text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
A Use Case for Local Class Declaration
Using local classes makes sense from an engineering point of view, but the principle of least surprise applies. Unless every team member is comfortable, don't use them.
Join the DZone community and get the full member experience.Join For Free
One of the first things one learns when starting with Java development is how to declare a class into its own file. Potential later stages include:
- Declaring multiple classes into the same file — with at most one of them
public
- Declaring
staticnested classes or inner classes
- Declaring anonymous (inner) classes
But this doesn’t stop there: the JLS is a trove full of surprises. I recently learned classes can be declared inside any block, including methods. This is called local class declaration (§14.3).
A local class is a nested class (§8) that is not a member of any class and that has a name. All local classes are inner classes (§8.1.3). Every local class declaration statement is immediately contained by a block. Local class declaration statements may be intermixed freely with other kinds of statements in the block.
The scope of a local class immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration. The scope of a local class immediately enclosed by in a switch block statement group (§14.11)is the rest of the immediately enclosing switch block statement group, including its own class declaration.
Cool, isn’t it? But using it just for the sake of it is not reason enough… until this week: I started to implement something like the Spring Boot Actuator in a non-Boot application, using Jackson to serialize the results.
Jackson offers several ways to customize the serialization process. For objects that require only to hide fields or change their names and which classes stand outside one’s reach, it offers mixins. As an example, let’s tweak serialization of the following class:
public class Person { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
Suppose the requirement is to have
givenName and
familyName attributes. In a regular Spring application, the mixin class should be registered during the configuration of message converters:(); jackson2HttpMessageConverter.getObjectMapper().addMixIn(Person.class, PersonMixin.class); converters.add(jackson2HttpMessageConverter); } }
Now, where does it make the most sense to declare this mixin class? The principle to declare something in the smallest possible scope applies: having it in a dedicated file is obviously wrong, but even a private nested class is overkill. Hence, the most restricted scope is the method itself:(); abstract class PersonMixin { @JsonProperty("givenName") abstract String getFirstName(); @JsonProperty("familyName") abstract String getLastName(); } jackson2HttpMessageConverter.getObjectMapper().addMixIn(Person.class, PersonMixin.class); converters.add(jackson2HttpMessageConverter); } }
While this way makes sense from a pure software engineering point of view, there is a reason not to design code like this: the principle of least surprise. Unless every member of the team is aware and comfortable with local classes, this feature shouldn’t be used.
Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/a-use-case-for-local-class-declaration | CC-MAIN-2021-17 | en | refinedweb |
#include <gromacs/selection/selection.h>
Provides access to information about a single selected position.
Each position has associated coordinates, and possibly velocities and forces if they have been requested and are available. It also has a set of atoms associated with it; typically the coordinates are the center-of-mass or center-of-geometry coordinates for that set of atoms. It is possible that there are not atoms associated if the selection has been provided as a fixed position.
After the selection has been compiled, but not yet evaluated, the contents of the coordinate, velocity and force vectors are undefined.
Default copy constructor and assignment operators are used, and work as intended: the copy references the same position and works identically.
Methods in this class do not throw.
Constructs a wrapper object for given selection position.
Asserts if
index is out of range.
Only for internal use of the library. To obtain a SelectionPosition object in other code, use Selection::position().
Returns total charge for this position.
Returns the sum of charges of atoms that make up this position. If there are no atoms associated or charges are not available, returns zero.
Returns force for this position.
Must not be called if Selection::hasForces() returns false.
Returns mapped ID for this position.
Returns ID of the position that corresponds to that set with Selection::setOriginalId().
If for an array
id,
setOriginalId(i, id[i]) has been called for each
i, then it always holds that
mappedId()==id[refId()].
Selection::setOriginalId() has not been called, the default values are dependent on type():
All the default values are zero-based.
Returns total mass for this position.
Returns the total mass of atoms that make up this position. If there are no atoms associated or masses are not available, returns unity.
Allows passing a selection position directly to neighborhood searching.
When initialized this way, AnalysisNeighborhoodPair objects return the index that can be used to access this position using Selection::position().
Works exactly like if AnalysisNeighborhoodPositions had a constructor taking a SelectionPosition object as a parameter. See AnalysisNeighborhoodPositions for rationale and additional discussion.
Returns reference ID for this position.
For dynamic selections, this provides means to associate positions across frames. After compilation, these IDs are consequently numbered starting from zero. For each frame, the ID then reflects the location of the position in the original array of positions. If SelectionOption::dynamicMask() has been set for the parent selection, the IDs for positions not present in the current selection are set to -1, otherwise they are removed completely.
Example: If a dynamic selection consists of at most three positions, after compilation refId() will return 0, 1, 2 for them, respectively. If for a particular frame, only the first and the third are present, refId() will return 0, 2. If SelectionOption::dynamicMask() has been set, all three positions can be accessed also for that frame and refId() will return 0, -1, 2.
Returns whether this position is selected in the current frame.
The return value is equivalent to
refid() == -1. Returns always true if SelectionOption::dynamicMask() has not been set.
Returns type of this position.
Currently always returns the same as Selection::type().
Returns velocity for this position.
Must not be called if Selection::hasVelocities() returns false. | https://manual.gromacs.org/current/doxygen/html-lib/classgmx_1_1SelectionPosition.xhtml | CC-MAIN-2021-17 | en | refinedweb |
SwiftyToggler alternatives and similar libraries
Based on the "Alert" category.
Alternatively, view SwiftyToggler alternatives based on common mentions on social networks and blogs.
SCLAlertView9.6 0.2 L2 SwiftyToggler VS SCLAlertViewAnimated Alert view.
SwiftMessages9.6 6.8 L2 SwiftyToggler VS SwiftMessagesA very flexible message bar for iOS written in Swift.
SwiftEntryKit9.5 4.6 SwiftyToggler VS SwiftEntryKitA simple and versatile pop-up presenter.
Alerts Pickers9.5 0.0 SwiftyToggler VS SwiftyToggler VS PopupDialogA simple, customizable popup dialog. Replaces UIAlertController alert style.
Whisper9.2 1.5 L4 SwiftyToggler VS WhisperMessages and in-app notification made easy.
XLActionController9.1 1.5 L4 SwiftyToggler VS XLActionControllerFully customizable and extensible action sheet controller written in Swift 2.
SweetAlert8.6 0.0 L3 SwiftyToggler VS SweetAlertAlert system.
PMAlertControllerPMAlertController is a great and customizable substitute to UIAlertController
Jelly8.5 0.0 L4 SwiftyToggler VS JellyJelly provides custom view controller transitions with just a few lines of code.
CDAlertView7.2 0.0 L4 SwiftyToggler VS CDAlertViewHighly customizable alert/notification/success/error/alarm popup
Queuer6.9 0.0 SwiftyToggler VS QueuerQueuer is a queue manager, build on top of OperationQueue and Dispatch (aka GCD).
SPAlert6.9 2.8 SwiftyToggler VS SPAlertNative popup from Apple Music & Feedback in AppStore. Contains Done & Heart presets.
Loaf6.6 1.0 SwiftyToggler VS LoafA simple framework for easy iOS Toasts.
StatusAlert6.4 1.5 SwiftyToggler VS StatusAlertDisplay Apple system-like self-hiding status alerts without interrupting user flow.
SwiftOverlays6.1 0.0 L4 SwiftyToggler VS SwiftOverlaysvarious popups and notifications.
GSMessage6.0 1.1 L2 SwiftyToggler VS GSMessageA simple style messages/notifications for iOS 7+.
Popup View5.8 3.6 SwiftyToggler VS Popup ViewToasts and popups library written with SwiftUI
CFNotify5.3 0.0 SwiftyToggler VS CFNotifyA customizable framework to create draggable alert views.
GoogleWearAlert5.2 0.0 L3 SwiftyToggler VS GoogleWearAlertGoogle Wear Alert style.
Hokusai5.2 0.0 L4 SwiftyToggler VS HokusaiA library for a cool bouncy action sheet.
EZAlertControllerEasy Swift UIAlertController.
Alertift4.1 2.0 SwiftyToggler VS AlertiftModern, easy UIAlertController wrapper.
Sheet4.0 0.0 SwiftyToggler VS SheetActionsheet with navigation features such as the Flipboard App.
CRNotifications3.1 0.0 L5 SwiftyToggler VS CRNotificationsCustom in-app notifications.
Zingle2.8 0.3 SwiftyToggler VS ZingleAn alert will display underneath your UINavigationBar.
FCAlertView2.8 0.0 L2 SwiftyToggler VS FCAlertViewA Flat Customizable AlertView for iOS.
AwaitToast2.8 0.0 SwiftyToggler VS AwaitToast🍞 An async waiting toast with basic toast. Inspired by facebook posting toast.
MaterialActionSheetControllerA Google like action sheet, easy to use and customizable.
Notie2.4 0.0 L5 SwiftyToggler VS NotieIn-app notification in Swift, with customizable buttons and input text field.
ALRT2.4 3.3 SwiftyToggler VS ALRTAn easier constructor for UIAlertController. Present an alert from anywhere.
Kamagari2.1 0.0 L5 SwiftyToggler VS KamagariSimple UIAlertController builder class in Swift.
HYAlertController2.0 0.0 L4 SwiftyToggler VS HYAlertControllerA simple and minimalist iOS AlertController written in Swift 3.
KRAlertController1.7 0.0 L4 SwiftyToggler VS KRAlertControllerA beautiful alert controller for your iOS.
AlertKit0.9 0.0 SwiftyToggler VS AlertKitAlert with a single line of Swift.
GSAlert0.7 0.0 L5 SwiftyToggler VS GSAlertIf you want to use UIAlertController, but still need to support iOS 7 this project is for you.
Indicate0.5 3.9 SwiftyToggler VS IndicateInteractive notification pop-over (aka "Toast) modeled after the iOS AirPods and Apple Pencil indicator.
SwiftAlertController0.3 0.0 L5 SwiftyToggleriftyToggler or a related project?
README
Requirements
- iOS 8.0+
- Xcode 8.1+
- Swift 3.1+
Installation
CocoaPods
Create a
Podfile file in the root of your application and the following content:
use_frameworks! target '<Your Target Name>' do pod 'SwiftyToggler', '~> 1.0.0' end
Then, run
pod install.
Carthage
Create a
Cartfile file in the root of your application and the following content:
github "MarcoSantarossa/SwiftyToggler" ~> 1.0.0
Then, run
carthage update to build the framework and drag the built
SwiftyToggler.framework into your Xcode project.
Swift Package Manager
Create a
Package.swift file in the root of your application and the following content:
import PackageDescription let package = Package( name: "YourApp", dependencies: [ .Package(url: "", “1.0.0”) ] )
Usage
Create A Feature
There are two ways to create a feature:
Implementing FeatureProtocol
The library provides the protocol
FeatureProtocol which you can implement:
class MyProtocol: FeatureProtocol { private let parentViewController: UIViewController private let featureViewController: UIViewController var isEnabled: Bool = false init(parentViewController: UIViewController) { self.parentViewController = parentViewController featureViewController = UIViewController() } // Main function of Feature. It's called when the future has been run. func main() { parentViewController.present(featureViewController, animated: true, completion: nil) } // It's called when the future has been disabled. func dispose() { featureViewController.dismiss(animated: true, completion: nil) } }
Extending Feature [Recommended]
The library provides the class
Feature<T> which you can extend. It has a generic property which is the payload of the feature. The payload is a clean way to manage the dependencies of your feature:
struct MyPayload { let parentViewController: UIViewController } class MyFeature: Feature<MyPayload> { private let featureViewController: UIViewController override init(payload: MyPayload?, isEnabled: Bool = false) { featureViewController = UIViewController() super.init(payload: payload, isEnabled: isEnabled) } override func main() { payload?.parentViewController.present(featureViewController, animated: true, completion: nil) } override func dispose() { featureViewController.dismiss(animated: true, completion: nil) } }
Add A Feature
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let featurePayload = MyPayload(parentViewController: self) let feature = MyFeature(payload: featurePayload) FeaturesManager.shared.add(feature: feature, name: "MyFeature", shouldRunWhenEnabled: true) } }
Remove A Feature
FeaturesManager.shared.remove(featureName: "MyFeature") // or FeaturesManager.shared.removeAll()
Run A Feature
do { let isRunning = try FeaturesManager.shared.run(featureName: "MyFeature") print("Is the feature running: \(isRunning)") } catch SwiftyTogglerError.featureNotFound { print("Feature not found") } catch {}
Enable/Disable A Feature
do { try FeaturesManager.shared.setEnable(true, featureName: "MyFeature") } catch SwiftyTogglerError.featureNotFound { print("Feature not found") } catch {}
Changes Observer
You can observer when a feature changes the value
isEnable:
class ViewController: UIViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) FeaturesManager.shared.addChangesObserver(self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) FeaturesManager.shared.removeChangesObserver(self) } } extension ViewController: FeatureChangesObserver { func featureDidChange(name: String, isEnabled: Bool) { } }
Present Features List
Modal
do { try FeaturesManager.shared.presentModalFeaturesList() } catch SwiftyTogglerError.modalFeaturesListAlreadyPresented { print("Features List already presented as modal") } catch {}
Child View Controller
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() FeaturesManager.shared.presentFeaturesList(in: self) } }
Advanced
shouldRunWhenEnabled
You can use this flag to run the feature as soon as it's enabled. You can set it with:
FeaturesManager.shared.add(feature: feature, name: "MyFeature", shouldRunWhenEnabled: true) // or do { try FeaturesManager.shared.update(featureName: "MyFeature", shouldRunWhenEnabled: true) } catch SwiftyTogglerError.featureNotFound { print("Feature not found") } catch {}
TODO
[ ] Add another example in example project.
[ ] Add feature dependencies.
[ ] Update features list table if a new feature is added when the table is visible.
[ ] Call
dispose() when a feature is removed.
[ ] Allow async call to feature
main() and
dispose().
Communication
- If you found a bug, open an issue.
- If you have a feature request, open an issue.
- If you want to contribute, submit a pull request.
Credits
SwiftyToggler is owned and maintained by Marco Santarossa. You can follow him on Twitter at @MarcoSantaDev.
License
SwiftyToggler is released under the MIT license. See LICENSE for details.
*Note that all licence references and agreements mentioned in the SwiftyToggler README section above are relevant to that project's source code only. | https://swift.libhunt.com/swiftytoggler-alternatives | CC-MAIN-2021-17 | en | refinedweb |
In this lesson, we'll cover some testing best practices - as well as go into a deeper dive regarding the differences between good and bad fails. Writing good fails instead of bad ones can really trip students up at first. And the implications of bad fails can be significant - extra time trying to find bugs, frustration, and less understanding about what's going wrong in the code. The implications get even bigger once we are out in the real world - for instance, if we don't test our code correctly, we might introduce breaking changes to production code, making our customers, coworkers, and employers upset. If possible, we don't want to do that. Unfortunately, in the real world, there are many companies that don't test their code - though it's not due to anyone arguing that untested code is better. Instead, tight deadlines, small staff, tight budgets, poor management practices, legacy code, and many other complications can lead to code that isn't fully tested - or tested at all.
At Epicodus, we're focused on testing best practices. Ideally, you'll eventually work at a company that has good testing practices. Even if the company doesn't have good practices, you can bring your newfound knowledge to the company and make a difference immediately. In fact, it's very common for junior developers to start learning a codebase by writing tests first. Adding testing to a codebase is something you can often start doing right away - even if you don't fully understand the code you're working with. And doing so can add tremendous value to your company.
Here are some testing best practices - as well as steps to make sure you get good fails - and in turn, good passes.
Write the test first, not the code. We've already covered many of the reasons why we should write our tests before we write any code. This is the cornerstone of TDD because it's test-driven, not code-driven. We won't reiterate all the reasons we should write tests first as we've covered that elsewhere.
Write just enough of a function or method to get the code to fail. We can't just write a test, run it, and move on. That would be a bad fail. If we are testing a function, for instance, we need to at least add the
function keyword and the name of the function. Our test should at least return how our expectation wasn't met - such as by stating the expected result and returning the actual result (such as
undefined because we haven't written a function body yet).
Keep the code in your test to a minimum. The more code you add to a test, the more likely you're going to have problems with that code. We want to isolate problems in our code - not create more problems by adding unnecessary code in our tests.
Read the Jest output for failing tests. It's easy to just run a test, see that it's red, and assume that it's a good fail. It's tempting to be in a rush to write the code, especially if we're excited about it or have an idea about how to implement it. But just because it's red doesn't mean it's a good fail.
Always fix bad fails before moving onto the code. TDD means having a good fail before writing the code. It doesn't mean writing a test, having a bad fail, and then writing some code. That is actually a recipe for disaster. We'll often see students looking for bugs in the wrong places when this happens - or just being utterly confused because their tests aren't pointing them in the right direction.
Always commit your code after each passing test. This is part of having a strong commit history. Also, if you break your code and can't get it working again, you can always return to a commit where all tests are passing.
Next, let's look at some examples of bad fails.
Here are some examples of bad fails based on the following tests:
import Example from '../src/example.js'; describe('Example', () => { test('should correctly demonstrate bad fails', () => { let example = new Example(); expect(example.data).toEqual("Bad fail!"); }); test('should correctly demonstrate bad fails', () => { let example = new Example(); expect(example.exampleFunction()).toEqual("This function returns a bad fail!"); }); });
The test won't run because it can't find a file. Let's say that when we run the test suite above, we get the following error:
Cannot find module '../src/example.js' from 'example.test.js'.
This means that the file doesn't exist or there's an error in the path or the file exists but there is an error in the file name.
This is a bad fail. Our test should always be able to correctly find the file it is looking for. We're not even correctly testing any code yet. All we've confirmed is that our tests can't find a file.
The test won't run because it can't find a function or constructor. So we realize that we don't have a
src/example.js file yet - or that it's named
src/exmple.js - or even that for some reason it's not in the
src directory. We fix that issue and run the test, only to get the following error:
TypeError: _example.default is not a constructor
This means that either we haven't added a constructor for
Example yet or there's a typo either in our test (such as
new Exmple()) or there's a typo in our constructor.
In the case of a missing function, we'll get an error like this:
TypeError: example.exampleFunction is not a function
These are both bad fails. Any functions or constructors that a test uses at the very least need to exist - and the test needs to be able to properly run or test the constructor.
The test won't run because there's an error that breaks all the tests in a suite. An error in a test file can blow up the whole suite - or it can cause an individual test to fail.
Here's an example that will blow up the entire suite:
Test suite failed to run SyntaxError: /Users/staff/Desktop/test_env/__tests__/example.test.js: Unexpected token, expected ";" (1:6) > 1 | impor Example from '../src/example.js'; | ^
Can you see the error? There's a typo in the import statement - it should be
import, not
impor. Any time you see
Test suite failed to run for any reason, it's a bad fail. It means the test isn't even correctly running. Don't you dare start writing your code yet if you're in this situation! Get the tests working first.
The test won't run because there's an error in an individual test. An error can also break just one test as well. Here's an example:
should correctly demonstrate bad fails ReferenceError: example is not defined 9 | 10 | test('should correctly demonstrate bad fails', () => { > 11 | expect(example.exampleFunction()).toEqual("This function returns a bad fail!"); | ^ 12 | });
Here we get the error
ReferenceError: example is not defined. Take a close look at the error, though, because it can be tempting to think it's because we haven't defined something in our code. In reality, it's because the line
let example = new Example(); has been removed from the test - and there's no variable named
example in our test's scope.
There are a million and one different errors that can occur in a test - but all of them are bad fails. The test needs to be running correctly and be error-free or it will be a bad fail. Once again, make sure you get this working correctly before writing any code.
The test fails because we wrote bogus data in our test. Let's say we've got all the code we need in our constructor to get the first test passing:
export default class Example { constructor() { this.data = "Bad fail!"; } }
However, for some reason we want to make sure that we get a fail before our test passes... perhaps because we did things out of order and wrote our code before we wrote the test. So we update our test to do the following:
test('should correctly demonstrate bad fails', () => { let example = new Example(); expect(example.data).toEqual("I'm sneaky! I'm gonna pretend this is a good fail!"); });
expect(received).toEqual(expected) // deep equality Expected: "I'm sneaky! I'm gonna pretend this is a good fail!" Received: "Bad fail!"
This is what is known as a test-based fail, not a code-based fail. The problem here is that we aren't actually testing to see if our code is working correctly - we're just breaking our test. What if we previously got our test passing but it was a false positive? Changing the test to try to get a good fail and then changing it back isn't going to suddenly stop the positive from being false. The test always needs to be a source of truth. If we've inserted errors into the test, it's no longer a source of truth - and it's no longer reliable for testing our code.
The test fails (or even passes) because we put too much code in our test. Let's say we want to test that our constructor automatically adds a
data property of
"Bad fail!" to an instance of
Example. This would be a truly horrible test:
// This is hideous. test('should instantiate an Example with a data property of Bad fail!', () => { let example = new Example(); const data1 = "Bad " const data2 = "fail" const data3 = "!" const newData = data1.concat(data2).concat(data3); example.data = newData; expect(example.data).toEqual("Bad fail!"); });
This test is actually going to pass if we at least correctly instantiate an
Example. But it's such a bad pass that it's truly a bad fail. What happens here is that we've written code in the test to get the test to artificially pass. But we're supposed to be testing our code and we're not actually testing that when an
Example is instantiated, a
data property with the right value is being created. Instead, we're writing the code manually in the test. If we were quality control elves in Santa's lab and our job was to inspect little toy cars being churned out of a machine and to make sure they are painted red, we can't just take a car that's painted blue, paint it red, and say the machine is working correctly. In this analogy, our code is the machine. Always test to make sure the machine works. Don't alter the results (the test) to fit what you're hoping for.
And here's the worst fail of all:
Test suite failed to run Your test suite must contain at least one test.
This means your suite doesn't even have any tests in it yet. Time to start adding some tests!
Before we're moving on, let's reiterate an example of a good fail. We can do the following to ensure a good fail:
undefined- don't write bogus code in either the function or your test to turn a good fail into a bad one.
Here's the error message on a good fail:
expect(received).toEqual(expected) // deep equality Expected: "This function returns a good fail!" Received: undefined
Here, we can see that the function was correctly called (and obviously our test was able to find the file as well). The function returns
undefined because we haven't added any code to the function body yet.
At this point, you should have a clear sense of the difference between good and bad fails. Ensuring your test has a good fail first is an important part of the process - and can help you isolate bugs in your code. In general, these testing practices apply no matter what language you are writing in - with a few small modifications depending on the language. From here on out, you should be applying these best practices as best as you can whether you are writing tests in JavaScript, Ruby, C#, or another language.
Lesson 29 of 48
Last updated April 8, 2021 | https://www.learnhowtoprogram.com/intermediate-javascript/test-driven-development-and-environments-with-javascript/testing-best-practices | CC-MAIN-2021-17 | en | refinedweb |
tensorflow::
ops:: BroadcastTo
#include <array_ops.h>
Broadcast an array for a compatible shape.
Summary]..)
Arguments:
- | https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/broadcast-to | CC-MAIN-2021-17 | en | refinedweb |
Smart items
Through the Builder, you can drag and drop smart items into a scene. These are items that have configurable parameters and actions that can be triggered, like doors that can be opened or levers that can be activated. There is a default collection of smart items in the Builder, but you can also create your own and import them.
Smart items are written using the same SDK code that you use for creating a scene, making use of entities, components and systems. This document assumes that you’re familiar with these concepts and will focus on how to encapsulate this code so that it interfaces with the scene and other smart items.
Smart item references
We recommend that you start working from an existing smart item, and use it as a template.
You can find the default collection of smart items that are in the builder in this repository:
You can also obtain the code of a smart item by using it in a scene in the Builder and then exporting that scene. The code for the smart item will be in a sub-folder of
src.
The asset manifest
Every smart item has an
asset.json file. This is a manifest that exposes how the item can be configured via the Builder UI, and how other items can activate it.
TIP: We recommend starting the development of your smart item from the manifest. There you can first define the item’s interface and configurable parameters, and then develop the supporting backend for that.
General item data
Name Refers to the name that this model will have in the Builder UI.
Note: Today, the item name that’s visible in the UI is taken directly from the name of the 3d model file. Don’t leave any spaces in the file name, use underscores to separate the words in it.
Model refers to the 3D model that is used as a placeholder when dragging the item into the scene in edit mode. This can be especially useful when the item is made up of several 3D models, as you’ll want to display an alternative placeholder model that includes all the meshes together. Make sure this placeholder model has the same size and orientation as the item that will be seen in the scene. Also make sure that the item isn’t displaced via code from its default location, unless the placeholder matches this.
Tags let you make the item easier to find when using the search.
Category places the item into a subcategory inside the asset pack, for example “nature” or “decorations”.
Parameters
The
asset.json file contains an array of parameters that can be configured via UI. The corresponding UI is generated in the Builder, automatically taking care of spacial arrangement and formatting of these menu items.
Every parameter must have:
- a
labelto display in the UI
- an
idby which its value can be used in your item’s code
- a
typethat determines the accepted values. The UI will change accordingly to match the type.
Parameters can also have a
default value, to help make the item easier to use out of the box.
{ "id": "distance", "label": "Distance", "type": "integer", "default": 10 },
The basic supported types for parameters are :
- text
- integer
- float
- boolean
Special types
Type actions refers to an action in this or another smart item. When this type is used, the field will present two dropdown menus. One selects a smart item, the other an action from that item.
{ "id": "onUse", "label": "When used", "type": "actions" },
Note: Decorators can use the plus sign to add as many actions as they want to one single actions field.
Type
entity refers to another item. When this type is used, the field will present a single dropdown to select a smart item.
{ "id": "target", "label": "Used on", "type": "entity" },
Note: Decorators can add a single entity in fields of type entity.
Type
textarea refers to a multi-line string, that appears in the UI as a text box.
{ "id": "text", "label": "Text", "type": "textarea", "default": "Some text" },
Type
slider exposes a draggable slider bar in the UI. This bar has a maximum and minimum value, and moves by fixed steps.
{ "id": "speed", "label": "Speed", "type": "slider", "default": 3, "max": 20, "min": 0, "step": 1 },
Type
options exposes a dropdown menu with a set of options you can list.
"parameters": [ { "id": "sound", "label": "Sound", "type": "options", "options": [ { "value": "Birds", "label": "Birds" }, { "value": "City", "label": "City" }, { "value": "Factory", "label": "Factory" }, { "value": "Field", "label": "Field" }, { "value": "Swamp", "label": "Swamp" }, { "value": "Town", "label": "Town" } ], "default": "Birds" } ]
Actions
Actions can be called by this item or others to trigger a specific behavior. These don’t appear in the item’s own UI, but all fields of type
actions list all of the actions available on all the items that are currently in the scene.
Actions have a
label that is shown in the dropdown menus, and an
id that lets you refer to this value in the item’s code.
"actions": [ { "id": "open", "label": "Open", "parameters": [] }, { "id": "close", "label": "Close", "parameters": [] }, { "id": "toggle", "label": "Open or Close", "parameters": [] } ]
Actions can also have
parameters that you can use to pass information with the action event. These parameters follow the same syntax, types and conventions as explained for the item parameters.
"actions": [ { "id": "changeText", "label": "Change Text", "parameters": [ { "id": "newText", "label": "New Text", "type": "textarea" } ] } ]
Item code
The
item.ts file is where you place the main logic for the item. This mainly includes creating an object that exposes at least an
init() and a
spawn() function.
Below is an example of the
item.ts of a door smart item:
export type Props = { onClick?: Actions onOpen?: Actions onClose?: Actions } export default class Door implements IScript<Props> { openClip = new AudioClip("sounds/open.mp3") closeClip = new AudioClip("sounds/close.mp3") active: Record<string, boolean> = {} init() {} toggle(entity: Entity, value: boolean, playSound = true) { if (this.active[entity.name] === value) return if (playSound) { const source = new AudioSource(value ? this.openClip : this.closeClip) entity.addComponentOrReplace(source) source.playing = true } const animator = entity.getComponent(Animator) const openClip = animator.getClip("open") const closeClip = animator.getClip("close") openClip.stop() closeClip.stop() const clip = value ? openClip : closeClip clip.play() this.active[entity.name] = value } spawn(host: Entity, props: Props, channel: IChannel) { const door = new Entity(host.name + "-button") door.setParent(host) const animator = new Animator() const closeClip = new AnimationState("close", { looping: false }) const openClip = new AnimationState("open", { looping: false }) animator.addClip(closeClip) animator.addClip(openClip) door.addComponent(animator) openClip.stop() door.addComponent(new GLTFShape("models/Door_Genesis.glb")) door.addComponent( new OnPointerDown(() => { channel.sendActions(props.onClick) }) ) this.active[door.name] = false // handle actions channel.handleAction("open", ({ sender }) => { this.toggle(door, true) if (sender === channel.id) { channel.sendActions(props.onOpen) } }) channel.handleAction("close", ({ sender }) => { this.toggle(door, false) if (sender === channel.id) { channel.sendActions(props.onClose) } }) channel.handleAction("toggle", ({ sender }) => { const newValue = !this.active[door.name] this.toggle(door, newValue) if (sender === channel.id) { channel.sendActions(newValue ? props.onOpen : props.onClose) } }) // sync initial values channel.request<boolean>("isOpen", (isOpen) => this.toggle(door, isOpen, false) ) channel.reply<boolean>("isOpen", () => this.active[door.name]) } }
Note: Keep in mind that external libraries aren’t supported in smart items, not even the
decentraland-esc-utilslibrary, so all of your item’s logic should be written using the SDK directly.
Item class setup
The
init() function is executed once the first time that a smart item of this kind is added to a scene.
It’s a great place to define elements that will be shared amongst all instances of the item, like materials, a system, etc.
Item instancing
The
spawn() function is executed every time a new instance of the smart item is added to the scene. This is where you should instance the entity and components of the item, as well as initiate all the action handlers.
spawn(host: Entity, props: Props, channel: IChannel)
The
spawn() function takes a host entity as a parameter. This host’s positioning will be applied to the positioning of the item in the scene. Instead of adding components like a shape, audiosource, etc directly to the host entity, create a new entity and set it as a child of the host.
The
props parameter will expose all the properties that are defined in the
asset.josn file, calling them by the
id specified for each in that file.
You should define a custom type for props, that includes the specific set of properties used by the item. You can then refer to these properties in the
spawn() function via the parameter’s id:
props.onClick.
The
channel parameter refers to the name of the channel of communication that will be used by this smart item. Smart items use the message bus to communicate between items and to sync state changes with other players. Having separate channels for each item avoids unwanted crosstalk between unrelated items.
Handling actions
In the spawn function you should also set up handlers to respond when another item calls this item to trigger an action.
For example, a door can have an ‘open’ action, that could be called by a button, a key, or even another door.
channel.handleAction("open", ({ sender }) => { this.toggle(door, true) if (sender === channel.id) { channel.sendActions(props.onOpen) } })
In the example above, each time an
open action arrives, the door runs the
toggle function to play its corresponding animation and sound and to change its state. Then it verifies that the
open action effectively came from this player instance and not from another player; if so, it will call any actions that were configured to be called on the item’s
OnOpen. If this check isn’t done, then the actions would be sent out multiple times, once for every player in the scene. This, besides being inefficient, can be quite disruptive when dealing with toggle-type actions.
TIP: As your item gets more complex, we recommend keeping the action handlers light, and keep most of the logic in external functions that can be called from these.
Testing your item
Use the
game.ts file to test out your item just as you would test a scene. Add an instance of your item to the
game.ts item, giving it a transform to position it and including all the required parameters inside an object.
import { Spawner } from "../node_modules/decentraland-builder-scripts/spawner" import Door, { Props } from "./item" const door = new Door() const spawner = new Spawner<Props>(door) spawner.spawn( "door", new Transform({ position: new Vector3(4, 0, 8), }), { onClick: [ { actionId: "toggle", entityName: "door", values: {}, }, ], } )
Then simply run
dcl start on the item’s folder, as you would for a normal scene. You’ll be able to interact with the item. The preview will hot-reload as you change your item’s code.
Try providing different values to the item’s properties, to make sure it functions as expected.
Importing into the Builder
When you’re ready to export the item, run
dcl pack on the item’s folder. This will generate an
item.zip file. Then import this file into a custom asset pack in the Builder.
You can then test it in a Builder scene. We recommend you do the following tests:
- Set different values in the item’s parameters
- Have its actions called by other items
- Call other items from it
- Add multiple instances of the item to make sure they don’t interfere with each other
If this all works then congratulations, you have a fully stable smart item!
Storing state data
Your item might need to store information at an instance level. For example, each door needs to keep track of if its open or closed, but other more complex items might keep track of more information about themselves.
The example above uses a list of booleans to represent the open/closed state of each door, where the entity name of each door is used as a key. For items with more information, it’s advisable to instead define a custom component that holds all of the data of the item.
When instancing an item in the
spawn() function, you should then add this component to new items.
TIP: We recommend defining the custom component in a separate file from
item.ts, to keep your code cleaner.
It’s important that you name your custom components with unique names that shouldn’t overlap with names used by other smart items. We recommend including the item name as part of the component name to avoid this. Otherwise, conflicting smart items in a same scene could interfere with each other in unexpected ways.
Custom systems
If you need your item to perform a gradual action that is executed frame by frame, like moving or rotating (not by animation), then you need to define systems to carry this out. Delaying an action also requires creating a system that waits x milliseconds.
NOTE: The
decentraland-ecs-utilslibrary can perform many of these actions in a scene’s code, but this library is not supported in smart items. Any transition needs to be explicitly written as a system.
As with custom components, systems need to have unique names that don’t overlap with those of other smart items used in the same scene. Again, we recommend using the item name as part of the system name to avoid this.
Note that besides defining the system, you also need to add an instance of it to the engine. The ideal place for that is in the
init() function of the smart item, which is executed once when the first item of this type is added.
TIP: We recommend defining systems in a separate file from
item.ts, to keep your code cleaner.
Multiplayer behavior
All the smart items that are available by default in the Builder have multiplayer capabilities. They achieve this by using the message bus to send peer to peer messages between players every time that something changes.
Since the state of the item is shared amongst peers, if all players leave the area of the scene, the state of the item is no longer stored anywhere, and it reverts to its initial state.
To keep the state of your smart item in sync between players, make sure that any relevant changes send out messages via the item’s channel for other instances to follow it.
When new players join the scene, the make sure that they obtain any relevant information from other players about the current state of the item. To do this, the door item sends out a
channel.request when spawning, and if there are any other players with instances of that door they will reply with a boolean indicating if the door is currently open.
// we send a request to all other players channel.request<boolean>("isOpen", (isOpen) => this.toggle(door, isOpen, false)) // we respond to this incoming request from other players channel.reply<boolean>("isOpen", () => this.active[door.name])
In some cases, you might not want the actions of a player affecting others. For example, when one player picks up a key, you don’t want all players to have that key equipped. To avoid this, you can filter the sender of a message and only react when it matches the channel id.
channel.handleAction("equip", (action) => { if (!this.isEquipped(key)) { // we only equip the key for the player who triggered the action if (action.sender === channel.id) { this.equip(key) channel.sendActions(props.onEquip) } // we remove the key from the scene for everybody this.hide(key) } }) | https://docs.decentraland.org/development-guide/smart-items/ | CC-MAIN-2021-17 | en | refinedweb |
I'm a software developer, hacker, and avid reader interested in all things tech
I added a lot more to my REST API than just the JSON responses. Borum Jot was the first project I tried seriously unit testing my code, encrypting the data, and documenting my back-end. In this article, I will discuss cybersecurity, software testing, and documentation of my REST API.
I encrypted my data using defuse/php-encryption. This library, claiming to be secure, unlike other libraries, did the encryption and decryption for me. To encrypt and decrypt, I needed my own key, which I generated by running:
$ composer require defuse/php-encryption $ vendor/bin/generate-defuse-key
Composer is a package manager for PHP applications. The key is 256 bits long and can be stored either in a file (unsecured) or in the environmental variables. Vercel has a built-in way of storing environmental variables, and was the best place, without extra tools, for me to store the key.
Truthfully, I stored the key in a text file in the
folder in the root directory because I didn't realize I could store it in thefolder in the root directory because I didn't realize I could store it in the
etc
at the time. This is highly insecure, so I am going to move this into a secure environmental variable soonat the time. This is highly insecure, so I am going to move this into a secure environmental variable soon
$_ENV
Then, at each request that updated or created data that I wanted to encrypt - task and note details - I loaded the key and called the encryption function. Similarly, for each request that fetched data that I encrypted, I loaded the key and decrypted before sending the response. This way, the front-ends never had to worry about encryption or decryption because I wrote everything on the backend, once.
To document my APIs, I got inspiration from the Stack Exchange API documentation. I used NextJS to make a static documentation site for the entire Borum ecosystem, including Borum Jot. Then, for each page, I specified the request method, request headers, query-string, request body (for POST, PUT, and DELETE requests), and response body.
Here is a given page of my developer documentation website, which is live, hosted by Vercel, and open-source on GitHub:
A sample Borum Jot endpoint API reference on my Borum Dev Documentation site
Because I am fluent in JavaScript, I did not have any trouble setting up the documentation site. I have a JSON file with data on each endpoint that I update whenever I update the Borum Jot REST API.
I suggest including the following as a bare minimum when documenting REST or other Web API's:
I used PHPUnit, a PHP unit-testing framework, and GuzzleHttp, a PHP HTTP client, to unit test my application. GuzzleHttp acts as a client to the REST API server, making requests and asserting information about the responses.
namespace BorumJot\Tests; use PHPUnit\Framework\TestCase; use GuzzleHttp\Client; class LoginTest extends TestCase { private $http; public function setUp() : void { $this->http = new Client(["base_uri" => ""]); } public function testPost() { $response = $this->http->post('login'); $this->assertEquals(200, $response->getStatusCode()); $contentType = $response->getHeaders()["Content-Type"][0]; $this->assertEquals("application/json; charset=UTF-8", $contentType); } }
The TestCase is a superclass in PHPUnit that indicates that the class contains test cases. The
method is called by PHPUnit before each test. GuzzleHttp'smethod is called by PHPUnit before each test. GuzzleHttp's
setUp()
class's "request-method methods" (likeclass's "request-method methods" (like
Client
andand
.get()
) provide information on the response, such as the headers and status code as shown above.) provide information on the response, such as the headers and status code as shown above.
First I had to run
to install the PHPUnit and GuzzleHttp packages.to install the PHPUnit and GuzzleHttp packages.
composer install phpunit/phpunit guzzlehttp/guzzle
I added the following to composer.json into the top-level object.
"scripts": { "test": "phpunit tests" }
This will substitute phpunit tests for composer test. It is a common practice to substitute the unit testing framework command for the package manager's command to have one command prefix to rule them all. However, this is not necessary, for you could simply run phpunit tests.
The last step is to configure phpunit to find the folder with all the unit tests. I put mine in the root directory and called it
, but you can call it and place it anywhere you would like, except maybe in auto-generated folders., but you can call it and place it anywhere you would like, except maybe in auto-generated folders.
tests
<?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="vendor/autoload.php"> <testsuites> <testsuite name="Borum Jot REST API Test Suite"> <directory suffix=".php">./tests/</directory> </testsuite> </testsuites> </phpunit>
Replace
with the path to the folder with the unit tests. The test suite is an arbitrary name you give to a group of tests to identify it.with the path to the folder with the unit tests. The test suite is an arbitrary name you give to a group of tests to identify it.
./tests/
And that's how I documented, tested, and encrypted the data of my first REST API. Have you ever documented your own API? What tools did you use? Share your own projects down below!
Create your free account to unlock your custom reading experience. | https://hackernoon.com/documenting-encrypting-and-unit-testing-my-first-rest-api-lz3c31ro | CC-MAIN-2021-17 | en | refinedweb |
Concept of Constant Pointers in C++
Hello Learners!
In this session, we will learn about some pointer variants. It is called Constant Pointers.
C++ adds the concepts of constant pointer and pointer to a constant. Mostly, these two are not used but are very conceptual topics that give more clarity and space for pointers to use if required. Let us get our hands on it.
Constant Pointers in C++
If one has a value in his/her program and it should not change throughout the program, or if one has a pointer and he/she doesn’t want it to be pointed to a different value, he/she should make it a constant with the const keyword. In simple words, a constant pointer is a pointer that cannot change the address it’s holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable. Although, we can change the value stored in it provided the address of the variable should not change. For example:
If we have initialized a constant pointer named i, then we could use it to point at a particular address which will be fixed throughout the program. It will be initialized in the following manner:
int a=10; int * const i= &a; //Syntax of Constant Pointer cout<<*i;
Here, a is the variable and i is the constant pointer which is pointing at the address of a. In the output screen, we will see the value 10. We can change the value stored in a and still pointer i will point the address a. This will be implemented something like this:
*i=99; cout<<*i;
Now, pointer i points to the same address but that address is having a value that is now converted from 10 to 99 and that’s what the output screen will show.
Let’s sum it up together and make it a full program for better understanding and good clarity.
#include<iostream> using namespace std; int main() { int a=10; int * const i= &a; cout<<"1st pointed value: "<<*i; *i=99; // value is getting changed of same address as before cout<<"\nModified value: "<<*i; return 0; }
Now, let us see the Output Screen:
1st pointed value: 10 Modified value: 99
The point to be taken care of is that if we ever try to change its address then it will definitely show an error. Let’s take an example :
int a=10,b=44; int * const i=&a; i=&b; //error cout<<*i;
This program has some serious issue and that is we are using the same pointer i to point to another address which is the address of variable b. That’s definitely not possible in the case of a constant pointer. Therefore, it will show a compilation error. | https://www.codespeedy.com/concept-of-constant-pointers-in-c/ | CC-MAIN-2021-17 | en | refinedweb |
Using Open-Zeppelin Library to build a basic capped ERC20 token sale.
Today, we are going to build a capped crowdsale with a mintable token using open-zeppelin library. (If you are a complete beginner, you should check out the previous tutorial on how to set up a solidity project and how to test a contract.) Open-zeppelin library provides basic building blocks to build an ERC20 Token on ethereum and will abstract away a lot of details for building an ERC20 token to get us up and running quicker.
Prerequisite
- Basic solidity concepts
- Understanding of ERC20 token standard and implementation
Things we will cover in the article:
- Definitions
- Open Zeppelin
- Building a crowdsale
Definitions
ERC20 Token
ERC20 is an ethereum standard for building a token. It defines a set of functions which a smart contract has to implement in order be ERC20 compliant. These standards are important to ethereum ecosystem and also helps you to make your contract robust, predictable and bug-free.
Crowdsale
A crowdsale is selling tokens to meet the financial requirements of the projects. Project share equity as a form of the token to contributors. In crypto world, crowd sales are called ICOs (Initial coin offering).
Capped Crowdsale
A project can have different types of constraints, one of them is capping. A capped crowdsale sets a limit on the total funding accepted and the number of tokens that will be distributed by the project. For example, we can cap on total ether contribution or if you want to put a cap on an investor for minimum contribution (let’s say 2 ether) and maximum contribution (let’s say 50 ether).
Benefits of a capped ICO
- A capped ICO helps investors to estimate value per token. It puts out the distribution structure and contributors get to know how many tokens are getting hold by the team and what are the plans to spend raised funds. It can also create a scarcity, thus increasing the value per token.
- Minimum and maximum contribution cap help to get more people to participate in the token distribution, you don’t want that all the token get bought by 100 people.
Mintable Token
In Mintable token, smart contract mint(create) tokens on the time of contribution. In this, you don’t permit tokens, so total supply gets decided based on total contributed ethers. Our contract will handle this logic too.
Building A Capped Crowdsale Token Using Open-Zeppelin Library
Open Zeppelin
We will use open zeppelin library to build our smart contract. Open zeppelin library provides basic building blocks to build an ERC20 Token on ethereum. It is a well-tested library and many projects use it on their production so it’s safe too.
Building a capped crowdsale contract
So let’s build a smart Capped ERC20 token. We will call our Token Example token. Below is code for ExampleToken and ExampleTokenCrowdsale.
ExampleToken.sol — Code for our Example token
ExampleTokenCrowdsale.sol — code for our crowdsale Contract
We are using open-zeppelin library which will abstract away a lot of details for building an ERC20 token and crowdsale contract. Feel free to ask questions on the comment section, if you don’t get something.
Installing OpenZeppelin Solidity
We need to install openZeppelin library using NPM.
npm install openzeppelin-solidity
Let’s go through our contracts on by one.
Our ERC20 Token — ExampleToken.sol
In this contract, we are defining ERC20 Token. One important thing to understand that open-zeppelin modularize many things, so don’t get overwhelmed with the so many file imports. If you come from the object-oriented background, then just see them as contracts inheriting interfaces and other contracts for their properties.
Let’s look at our imports, we are importing 3 contracts from the open-zeppelin library, we will go through them one by one. You can find all these files inside
node_modules under given path.
import "openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol";
DetailedERC20.sol
This contract itself importing
ERC20.sol which is simply the ERC20 interface. This will be used for initializing our token. As you can see, you need to set Token name, symbol and how many decimal point it will use. For example, ethereum uses 18 decimal point, where the smallest unit is wei (1 ether= ¹⁰¹⁸ wei).
pragma solidity ^0.4.24; import "./ERC20.sol"; contract DetailedERC20 is ERC20 {string public name;string public symbol;uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public {name = _name;symbol = _symbol;decimals = _decimals;}}
You can go on and check
ERC20.sol which is importing
ERC20Basic.sol and these two files combined have standard functions of an ERC20 token.
StandardToken.sol
This contract is a standard and well-tested implementation of ERC20 token methods. For the sake of simplicity, I am not adding contract code, you can check contract under the same path.
MintableToken.sol
This contract has our token minting logic. So let’s look at this contract closely. It’s importing
ownable and
StandardToken.
Ownable contract helps in putting access controls and managing ownership. It defines modifiers using which functions can be made owner accessible and It helps you to manage contract ownership.
Now, let’s look at out mint() function, It receives two parameters one is beneficiary account and another is a total number of tokens to be added. notice
mint() function, it’s increasing
total supply and
balances variable is available through inheriting
StandardTokencontract, which maintain the balance of every contributor.
This function will be called from
MintedCrowdsale contract (we will see that in the next part of this tutorial).
pragma solidity ^0.4.24; import "./StandardToken.sol";import "../../ownership/Ownable.sol"; contract MintableToken is StandardToken, Ownable {event Mint(address indexed to, uint256 amount);event MintFinished(); bool public mintingFinished = false; modifier canMint() {require(!mintingFinished);_;} modifier hasMintPermission() {require(msg.sender == owner);_;} function mint(address _to,uint256 _amount)publichasMintPermissioncanMintreturns (bool){totalSupply_ = totalSupply_.add(_amount);balances[_to] = balances[_to].add(_amount);emit Mint(_to, _amount);emit Transfer(address(0), _to, _amount);return true;} function finishMinting() public onlyOwner canMint returns (bool) {mintingFinished = true;emit MintFinished();return true;}}
Conclusion
In this part, we have created a Capped ERC20 token using open-zeppelin library. We have talked about different basic contracts provided by open-zeppelin library and how can we use them to build a capped ERC20 token.
In the next part, we will cover our ExampleTokenCrowdsale contract and will see how we can use different open-zeppelin library contracts to build our crowdsale smart contract.
On To Part 2 →
Notes & Suggestions
There are a lot of things which handled by open-zeppelin library and almost every basic functionality is provided by the library. If you don’t understand something, please comment.
If you have any problem while following through this tutorial, Check out my github code. | https://blog.crowdbotics.com/how-to-build-a-simple-capped-crowdsale-token-using-openzeppelin-library-part-1/ | CC-MAIN-2021-17 | en | refinedweb |
Introduction
Dictionary (also known as 'map', 'hash' or 'associative array') is a built-in Python container that stores elements as a key-value pair.
Just like other containers have numeric indexing, here we use keys as indexes. Keys can be numeric or string values. However, no mutable sequence or object can be used as a key, like a list.
In this article, we'll take a look at how to check if a key exists in a dictionary in Python.
In the examples, we'll be using this
fruits_dict dictionary:
fruits_dict = dict(apple= 1, mango= 3, banana= 4)
{'apple': 1, 'banana': 4, 'mango': 3}
Check if Key Exists using in Operator
The simplest way to check if a key exists in a dictionary is to use the
in operator. It's a special operator used to evaluate the membership of a value.
Here it will either evaluate to
True if the key exists or to
False if it doesn't:
key = 'orange' if key in fruits_dict: print('Key Found') else: print('Key not found')
Now, since we don't have an
orange in our dictionary, this is the result:
Key not found
This is the intended and preferred approach by most developers. Under the hood, it uses the
__contains__() function to check if a given key is
in a dictionary or not.
Check if Key Exists using get()
The
get() function accepts a
key, and an optional value to be returned if the
key isn't found. By default, this optional value is
None. We can try getting a key, and if the returned value is
None, that means it's not present in the dictionary:
key = 'orange' if fruits_dict.get(key) == None: print('Key not found') else: print('Key found')
This results in:
Key not found
Check if Key Exists using keys()
The
keys() function returns the keys from our dictionary as a sequence:
fruits_dict.keys()
This sequence contains:
dict_keys(['apple', 'mango', 'banana'])
Using this sequence, we can check if the key is present. You can do this through a loop, or better yet, use the
in operator:
key = 'orange' if key in fruits_dict.keys(): print('Key found') else: print('Key not found')
This also results in:
Key not found
Check if Key Exists using has_key()
Instead of manually getting the keys and running a check if the value we're searching for is present, we can use the short-hand
has_key() function:
key = 'orange' if fruits_dict.has_key(key): print('Key found') else: print('Key not found')
It returns
True or
False, based on the presence of the key. This code outputs:
Key not found
Handling 'KeyError' Exception
An interesting way to avoid problems with a non-existing key or in other words to check if a key exists in our dictionary or not is to use the
try and
except clause to handle the
KeyError exception.
The following exception is raised whenever our program fails to locate the respective key in the dictionary.
It is a simple, elegant, and fast way to handle key searching:
try: fruits_dict[key] except KeyError as err: print('Key not found')
This approach, although it may sound unintuitive, is actually significantly faster than some other approaches we've covered so far.
Note: Please note, exceptions shouldn't be used to alter code flow or to implement logic. They fire really fast, but recovering from them is really slow. This approach shouldn't be favored over other approaches, when possible.
Let's compare the performance of them to get a better idea of how fast they can execute.
Performance Comparison
import timeit code_setup = """ key = 'orange' fruits_dict = dict(apple= 1, mango= 3, banana= 4) """ code_1 = """ if key in fruits_dict: # print('Key Found') pass else: # print('Key not found') pass """ code_2 = """ if fruits_dict.get(key): # print('Key found') pass else: # print('Key not found') pass """ code_3 = """ if fruits_dict.__contains__(key): # print('Key found') pass else: # print('Key not found') pass """ code_4 = """ try: # fruits_dict[key] pass except KeyError as err: # print('Key not found') pass """ code_5 = """ if key in fruits_dict.keys(): # print('Key found') pass else: # print('Key not found') pass """ print('Time of code_1: ', timeit.timeit(setup = code_setup , stmt= code_1, number= 10000000)) print('Time of code_2: ', timeit.timeit(setup = code_setup , stmt= code_2, number= 10000000)) print('Time of code_3: ', timeit.timeit(setup = code_setup , stmt= code_3, number= 10000000)) print('Time of code_4: ', timeit.timeit(setup = code_setup , stmt= code_4, number= 10000000)) print('Time of code_5: ', timeit.timeit(setup = code_setup , stmt= code_5, number= 10000000))
This outputs:
Time of code_1: 0.2753713619995324 Time of code_2: 0.8163219139996727 Time of code_3: 0.5563563220002834 Time of code_4: 0.1561058730003424 Time of code_5: 0.7869278369998938
The most popular choice and approach, of using the
in operator is fairly fast, and it's also the intended approach for solving this problem.
Conclusion
In this article, we discussed multiple ways to check if a key exists in our dictionary or not. Then we made a performance comparison. | https://stackabuse.com/python-check-if-key-exists-in-dictionary/ | CC-MAIN-2021-17 | en | refinedweb |
Moving along through our .NET Exception Handling series, today we’ll dig into the
System.InvalidCastException. Put simply, a
System.InvalidCastException is thrown when trying to perform some type of conversion an object to an invalid type.
ga
In this article we’ll examine everything about the
System.InvalidCastException, including where it sits within the .NET exception hierarchy and by giving a few code examples to illustrate how this exception might come about. Let’s get going!
The Technical Rundown
- All .NET exceptions are derived classes of the
System.Exceptionbase class, or derived from another inherited class therein.
System.SystemExceptionis inherited from the
System.Exceptionclass.
System.InvalidCastExceptioninherits directly from
System.SystemException.
When Should You Use It?
There are a number of possible ways to throw a
System.InvalidCastException, so let’s just jump right into some example code to see exactly what this error means and how to deal with it.
Probably the most commonly used technique that could result in a
System.InvalidCastException is performing a
cast to convert one type to another type. In statically-typed languages like
C#, after a variable is declared, it typically cannot be declared again or used to store data that is incompatible with that particular type. By using a
cast, we’re able to tell the common language runtime (
CLR) that we want to convert from one type to another while acknowledging that there could be data loss in the process.
The
cast syntax is typically to precede the variable name with the type to be
cast into, which should be within bounded parentheses. For example, here we want to
cast an integer to a decimal:
int value = 10; decimal dec = (decimal)value; Logging.Log($"Cast succeeded from {value.GetType().Name} to {dec.GetType().Name}."); // Cast succeeded from Int32 to Decimal.
This works without a problem because .NET understands how to properly convert from an integer (whole number) to a decimal representation of that same number.
However, trouble can occur when trying to perform what is known as
downcasting: Trying to convert an instance of a base (parent) type to one of its derived (child) types. For example, here we have a simple
Book class with an
Author and
Titleproperty. We then inherit the
Book class to create the
PublishedBook class, which adds the
PublishedAt property:
public class Book { public string Title { get; set; } public string Author { get; set; } public Book(string title, string author) { Title = title; Author = author; } } public class PublishedBook : Book { public DateTime PublishedAt { get; set; } public PublishedBook(string title, string author, DateTime published_at) : base(title, author) { Title = title; Author = author; PublishedAt = published_at; } }
Let’s try to
cast an instance of of
Book to the derived type of
PublishedBook:
private static void CastToDerivedType() { try { var book = new Book("Sword in the Darkness", "Stephen King"); // Downcasting PublishedBook to base type of Book. var castBook = (PublishedBook)book; Logging.Log("Downcasting successful:"); Logging.Log(castBook); } catch (System.InvalidCastException exception) { Logging.Log("Downcasting failed."); Logging.Log(exception); } }
Sure enough, this fails and throws a
System.InvalidCastException:
Downcasting failed. [EXPECTED] System.InvalidCastException: Unable to cast object of type 'Airbrake.InvalidCastException.Book' to type 'Airbrake.InvalidCastException.PublishedBook'.
While
downcasting like this doesn’t work, let’s try
upcasting instead, in which we convert from a derived type “up” to a base type:
private static void CastToBaseType() { try { var publishedBook = new PublishedBook("It", "Stephen King", new DateTime(1986, 9, 1)); // Upcasting PublishedBook to base type of Book. var castBook = (Book)publishedBook; Logging.Log("Upcasting successful."); Logging.Log(castBook); } catch (System.InvalidCastException exception) { Logging.Log("Upcasting failed."); Logging.Log(exception); } }
The output shows us that
upcasting works just fine, since the
CLR knows how to “reduce” a more complex object and convert to its simpler, base type.
Upcasting successful. {Airbrake.InvalidCastException.PublishedBook} PublishedAt: 9/1/1986 Title: "It" Author: "Stephen King"
Another common action that could throw a
System.InvalidCastException is when trying to use the
cast operator syntax to convert to a string value. Here we’re attempting to convert our
age object to a string value via
casting:
private static void CastToString() { try { object age = 30; // Attempt cast to string. string convertedAge = (string)age; Logging.Log($"Converted age is: {convertedAge}."); } catch (System.InvalidCastException exception) { Logging.Log("String cast failed."); Logging.Log(exception); } }
Unfortunately, .NET isn’t pleased with this and fails while also throwing a
System.InvalidCastException:
String cast failed. [EXPECTED] System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
The recommended technique to use here is to call the
ToString() method on the object in question. Since
ToString() is defined by the
Object class (and thus is inherited by all derived objects therein), it’s always available and will work:
private static void CallToStringMethod() { try { object age = 30; // Convert via the ToString() method. string convertedAge = age.ToString(); Logging.Log($"Converted age is: {convertedAge}."); } catch (System.InvalidCastException exception) { Logging.Log("ToString() method conversion failed."); Logging.Log(exception); } }
This works just fine and outputs our converted age:
Converted age is: 30.
While there are a few others ways to incur a
sysex, the last technique we’ll cover here is when trying to call a primitive type’s
IConvertible implementation to perform a conversion to a type that isn’t supported. The
IConvertible interface can be used to provide a wide range of conversion methods, allowing the implementing type to convert to common language runtime types such as
Boolean,
String,
Int32, and so forth.
To see
IConvertible in practice, here we have a simple example where we’re trying to convert from a
bool to a
char type using
IConvertible's
ToChar() method:
private static void ConvertBoolToChar() { try { bool value = true; // Create an IConvertible interface. IConvertible converter = value; // Convert using ToChar() method. Char character = converter.ToChar(null); Logging.Log($"Conversion from Bool to Char succeeded."); } catch (System.InvalidCastException exception) { Logging.Log("Conversion failed."); Logging.Log(exception); } }
Unfortunately, there’s no way to convert from a
bool to
char so a
System.InvalidCastException is thrown:
Conversion failed. [EXPECTED] System.InvalidCastException: Invalid cast from 'Boolean' to 'Char'.
The only solution in cases like this is to ensure the types you’re working with are compatible with one another, meaning that the
CLR knows how to convert from one to the other. Here we’re trying to convert from an
int to to
Char, which should work just fine:
private static void ConvertIntToChar() { try { int value = 25; // Create an IConvertible interface. IConvertible converter = value; // Convert using ToChar() method. Char character = converter.ToChar(null); Logging.Log($"Conversion from int to Char succeeded."); } catch (System.InvalidCastException exception) { Logging.Log("Conversion failed."); Logging.Log(exception); } }
Sure enough, the
CLR knows how to convert from an intger to a character, so our conversion is successful:
Conversion from Int to Char succeeded.. | https://airbrake.io/blog/dotnet-exception-handling/invalidcastexception | CC-MAIN-2021-17 | en | refinedweb |
Hi!I'm trying to get working multisampled FBO on Samsung Galaxy S10+ with Mali-G76 (Android 10).Minimal example from spec fails with GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT (8D56) for me.Tried it with 256x256, 1024x768, 4 samples, GL_MAX_SAMPLES_EXT is 4.I'm building app with gl2.h and gl2ext.h and ndk-r19c.
OpenGL version: OpenGL ES 3.2 v1.r19p0-01rel0.###other-sha0123456789ABCDEF0### Compatibility profileMy desired setup is:- bind texture to COLOR_ATTACHMENT_0 (with glFramebufferTexture2DMultisampleEXT)
- bind d24s8 multisampled renderbuffer to both DEPTH_ATTACHMENT and STENCIL_ATTACHMENT (create with glRenderBufferStorageMultisample, bind with glFramebufferRenderBuffer)
Is there any detail I missed about using this extension?
Hi Ramil,
I notice you're using glRenderBufferStorageMultisample which is, confusingly, different to glRenderBufferStorageMultisampleEXT. I'd try switching to the EXT variant here and hopefully that helps.
Cheers,Christian
Thanks for reply, I actually use glRenderBufferStorageMultisamleEXT, sorry, my bad, that's a typo.
Ah, OK. :) Did I interpret it right you're using pretty much the same code as in the spec example? I can try to repro on my side; in general I know this functionality works (as there are games relying on it) -- but wondering if some obscure things is causing an issue with that specific code. (Eg GL_UNSIGNED_SHORT_4_4_4_4 jumps out to me as 'not common' -- so could try something different there.)
I'll let you know what I find; please shout if your code is different to the spec example.
Thank you!I've tried with GL_UNSIGNED_SHORT_4_4_4_4 when trying to do copy-paste from spec and GL_UNSIGNED_BYTE before that for our regular rgba8888 case.Anothing thing that came to my mind: I'm using EGL with EGL_SAMPLES, 4 for main backbuffer which maybe also uses this extension.If copy-pasted example from spec works fine for you - that will be very interesting to find out the truth! :)
I've tested the spec example on a few devices and drivers now, including a S10 with R19, but so far not been able to hit any problems (glCheckFramebufferStatus return GL_FRAMEBUFFER_COMPLETE). Is it possible to share a reproducer APK for this? Happy to have a look to try to debug what goes wrong.
Just for reference, here's a patch on top of the gles3jni example from (the same type of code works for the hello-gl2 sample as well) demonstrating how to load the right function pointers, plus how using the non-EXT glRenderbufferStorageMultisample can result in this error (see the #if for good vs non-working code):
diff --git a/gles3jni/app/src/main/cpp/RendererES3.cpp b/gles3jni/app/src/main/cpp/RendererES3.cpp
index df71a85..c7366a5 100644
--- a/gles3jni/app/src/main/cpp/RendererES3.cpp
+++ b/gles3jni/app/src/main/cpp/RendererES3.cpp
@@ -15,6 +15,8 @@
*/
#include "gles3jni.h"
+#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#define STR(s) #s
@@ -117,6 +119,55 @@ bool RendererES3::init() {
glVertexAttribPointer(OFFSET_ATTRIB, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), 0);
glEnableVertexAttribArray(OFFSET_ATTRIB);
glVertexAttribDivisor(OFFSET_ATTRIB, 1);
+#if 1
+ GLsizei width = 256;
+ GLsizei height = 256;
+ GLint samples;
+ glGetIntegerv(GL_MAX_SAMPLES_EXT, &samples);
+
+ PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisampleEXT = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)eglGetProcAddress("glRenderbufferStorageMultisampleEXT");
+ PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC glFramebufferTexture2DMultisampleEXT =(PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC)eglGetProcAddress("glFramebufferTexture2DMultisampleEXT");
+
+ /* Create multisampled depth renderbuffer */
+ GLuint depthbuffer;
+ glGenRenderbuffers(1, &depthbuffer);
+ glBindRenderbuffer(GL_RENDERBUFFER, depthbuffer);
+#if 0 // OK
+ glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples,
+ GL_DEPTH_COMPONENT16, width, height);
+#else // Fails
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples,
+ GL_DEPTH_COMPONENT16, width, height);
+#endif
+ glBindRenderbuffer(GL_RENDERBUFFER, 0);
+
+ /* Create RGBA texture with single mipmap level */
+ GLuint texture;
+ glGenTextures(1, &texture);
+ glBindTexture(GL_TEXTURE_2D, texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
+ GL_UNSIGNED_SHORT_4_4_4_4, NULL);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ /* Create framebuffer object, attach texture and depth renderbuffer */
+ GLuint framebuffer;
+ glGenFramebuffers(1, &framebuffer);
+ glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
+ GL_RENDERBUFFER, depthbuffer);
+ glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER,
+ GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0, samples);
+
+ /* handle unsupported cases */
+ if (glCheckFramebufferStatus(GL_FRAMEBUFFER) !=
+ GL_FRAMEBUFFER_COMPLETE)
+ {
+ ALOGE("FBO incomplete: %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
+ } else ALOGE("FBO OK");
+
+ checkGlError("FBO");
+#endif
ALOGV("Using OpenGL ES 3.0 renderer");
return true;
It might be good to double-check any function pointer loader you might be using isn't grabbing the wrong function.
I'll check it and answer tomorrow.Thank you a lot!
Hello.I copy-pasted retrieving glRenderbufferStorageMultisampleEXT pointer as PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC into example and it fixes my issue.The problem was in our engine macro GET_GL_FUNC(func_name, extSuffix) which first looks up function without suffix and only when it is not found looks up EXT version.Thank you for help!
Super, thanks for confirming this was the issue! :)
View all questions in Graphics and Gaming forum | https://community.arm.com/developer/tools-software/graphics/f/discussions/48989/struggling-with-ext_multisampled_render_to_texture-on-mali-g76 | CC-MAIN-2021-17 | en | refinedweb |
I am new to migrations and I can't find out what to do to get my changes onto the LiveDB.
So on dev when I add to my model I do
PM> add-migration <name> PM> update-database
But what do I do on live? I was HOPING that I could just publish\deploy to live and the migration would run and update the schema, but I guess not :)
The Live SQL server is off in its own world I have no access to it from my dev box to just change the connectionstring and doing an update-database again.
What do you guys do, where's the docs?
Thanks, Steve
Updated with sample for 3.0
The Core 3.0 approach is similar to 2.x, but now the generic host is used.
You will need to add
using Microsoft.Extensions.DependencyInjection; for the
CreateScope()
public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetService<ShortenerContext>(); db.Database.Migrate(); } host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Updated with better way for Core 2.0+
Migrations should be run in Program.cs due to tooling like the EF Core CLI tools running the Startup functions in normal execution.
Here is an example:
public class Program { public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetService<ShortenerContext>(); db.Database.Migrate(); } host.Run(); } public static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
One way to run migrations in 1.x is to just add something like this in app startup:
public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ShortenerContext db) { db.Database.Migrate(); //Rest omitted }
This will execute all pending migrations against the database on startup.
script-migration -From "last_migration_name" -To "current_migration_name"or
script-migration -idempotent | https://entityframeworkcore.com/knowledge-base/39796893/how-to-run-a-migration-in-production | CC-MAIN-2021-17 | en | refinedweb |
The 1602 LCD display is an alphanumeric display with 2 lines each containing 16 characters.
It finds application in a large number of scenarios, from vending machines to train stations.
This LCD display model is commonly included in Arduino kits, but those instructions work with any LCD display that has a 16 pins interface compatible with the Hitachi HD44780 LCD controller.
This controller is emulated via software by the
LiquidCrystal Arduino library.
In this post I will show the simplest possible usage of the display to print a
Hello, World!.
The LCD display has 16 input pins. From left to right:
VSSthe
-connection
VDDthe
+connection
VOadjusts the contrast (we connect that to a potentiometer in our project)
RSis connected to pin 7 of the Arduino
R/Wis connected to
-to set the LCD in “write mode”
Eis connected to pin 8 of the Arduino
D0-D7are data pins. We’ll just use
D4,
D5,
D6and
D7in this example.
Aand
Kcontrol the LED backlight. Connect
Ato
+via a 220Ω resistor,
Kto
-.
To print the
Hello, World! line I built this simple program and uploaded it to the Arduino:
#include <LiquidCrystal.h> LiquidCrystal lcd(7, 8, 9, 10, 11, 12); void setup() { lcd.begin(16, 2); lcd.print("Hello,"); lcd.setCursor(0, 1); lcd.print("World!"); } void loop() { }
There’s an initial configuration of the
lcd object, passing the pins of
RS,
R/W,
E, then
D4,
D5,
D6 and
D7 (see more details here).
Then we call the
lcd.begin() method, and we pass the key characteristics of the LCD display, number of columns and number of rows.
The
lcd.print() method prints the string, starting at the position
(0, 0).
We can move the cursor using
lcd.setCursor(), passing the index of the column and the index of the row we want to move to.
The circuit is built as follows:
And here’s the real-world implementation:
You can trim the potentiometer to apply a different contrast. Once you determine your perfect setting you can change that with a resistance.
More electronics tutorials:
- The Arduino Uno rev 3 board
- Electronic components: Analog Joystick
- Electronics Basics: Analog vs digital
- Electronic components: Diodes
- Electronic components: LEDs
- Electronics Basics: Vcc, ground, ...
- The Arduino MKR WiFi 1010
- Arduino: using libraries
- Arduino project: the analogWrite() function and PWM | https://flaviocopes.com/electronics-components-1602-lcd-display/ | CC-MAIN-2021-17 | en | refinedweb |
react-native-animateable-text
A fork of React Native's
<Text/> component that supports Animated Values as text!
Installation
yarn add react-native-animateable-text npx pod-install
Usage (Reanimated 2)
Use it the same as a
<Text/> component, except instead of passing the text as a child node, pass it using the
text props.
import AnimateableText from 'react-native-animateable-text'; const Example: React.FC = () => { const text = useSharedValue('World'); const animatedText = useDerivedValue(() => `Hello ${text.value}`); const animatedProps = useAnimatedProps(() => { return { text: animatedText.value, }; }); return ( <AnimateableText animatedProps={animatedProps} // same other props as Text component />; };
Usage (Reanimated 1)
import AnimateableText from 'react-native-animateable-text'; const Example: React.FC = () => { const text = useMemo(() => new Animated.Value('World'), []); const animatedText = useMemo(() => concat('Hello', text)); return ( <AnimateableText text={animatedText} // same other props as Text component />; };
OMG, why would you build this?
We want to animate numbers based on gestures as fast as possible, for example for charts displaying financial data. Updating native state is too slow and not feasible for a smooth experience. Using
createAnimatedComponent doesn't allow you to animate the text since the children of Text are separate nodes rather than just props.
The best way so far has been to use the
<ReText> component from react-native-redash, which allows you to render a string from a Reanimated Text node. However, under the hood, it uses a
<TextInput/> and animates it's
value prop.
This naturally comes with a few edge cases, for example:
Flicker: When changing values too fast, the text can be cut off and show an ellipsis. The problem gets worse the slower the device and the more congested the render queue is. Watch this GIF at 0.2x speed carefully:
Inconsistent styling: When styling a
TextInput, you need to add more styles to make it align with the rest of your text. (Behavior in screenshot happens only on Android)
Lack of full capabilities: Not all props are available. With Animateable Text, you can use props that you cannot use on a TextInput, such as
selectable,
dataDetectorType or
onTextLayout.
| https://reactnativeexample.com/a-fork-of-react-natives-text-component-that-supports-animated-values-as-text/ | CC-MAIN-2021-17 | en | refinedweb |
This Video Tutorial Explains what is Reflection and how to Implement it using Reflection API:
Reflection in Java is to inspect and change the behavior of a program at runtime.
With the help of this reflection API, you can inspect classes, constructors, modifiers, fields, methods, and interfaces at runtime. For Example, you can get the name of the class or you can get details of the private members of the class.
Read through our entire JAVA training series for more insight on Java concepts.
Here is a Video Tutorial on Java Reflection:
What You Will Learn:
- Reflection In Java
- Conclusion
Reflection In Java
We are aware that in a given class we can modify its properties and methods at compile time and it is very easy to do so. Whether the properties and methods are anonymous or have names, they can be changed at our will during compile time.
But we cannot change these classes or methods or fields at runtime on the fly. In other words, it is very difficult to change the behavior of various programming components at runtime especially for unknown objects.
Java programming language provides a feature called “Reflection” that allows us to modify the runtime behavior of a class or field or method at runtime.
Thus a Reflection can be defined as a “technique of inspecting and modifying the runtime behavior of an unknown object at run time. An object can be a class, a field, or a method.”
Reflection is an “Application Programming Interface” (API) provided by Java.
The “Reflection” process is depicted below.
In the above representation, we can see that we have an unknown object. Then we use the Reflection API on this object. As a result, we can modify the behavior of this object at runtime.
Thus we can use Reflection API in our programs for the purpose of modifying the object’s behavior. The objects can be anything like methods, interfaces, classes, etc. We inspect these objects and then change their behavior at runtime using reflection API.
In Java, the “java.lang” and “java.lang.reflect” are the two packages that provide classes for reflection. The special class “java.lang.Class” provides the methods and properties to extract metadata using which we can inspect and modify the class behavior.
We use Reflection API provided by the above packages to modify the class and its members including fields, methods, constructors, etc. at runtime. A distinguishing feature of Reflection API is that we can also manipulate the private data members or methods of the class.
The Reflection API is mainly used in:
- Reflection is mainly used in debugging tools, JUnit, and frameworks to inspect and change the behavior at runtime.
- IDE (Integrated Development Environment) E.g. Eclipse IDE, NetBeans, etc.
- Test Tools etc.
- It is used, when your application has third-party libraries and when you want to know about the classes and methods available.
Reflection API In Java
Using Reflection API, we can implement the reflection on the following entities:
- Field: The Field class has information that we use to declare a variable or a field like a datatype (int, double, String, etc.), access modifier (private, public, protected, etc.), name (identifier) and value.
- Method: The Method class can help us to extract information like access modifier of the method, method return type, method name, method parameter types, and exception types raised by the method.
- Constructor: Constructor class gives information about class constructor that includes constructor access modifier, constructor name, and parameter types.
- Modifier: Modifier class gives us information about a specific access modifier.
All the above classes are a part of java.lang.reflect package. Next, we will discuss each of these classes and use programming examples to demonstrate the reflection on these classes.
Let’s first start with the class java.lang.Class.
java.lang.Class Class
The java.lang.The class holds all the information and data about classes and objects at runtime. This is the main class used for reflection.
The class java.lang.Class provides:
- Methods to retrieve class metadata at run time.
- Methods to inspect and modify the behavior of a class at run time.
Create java.lang.Class Objects
We can create objects of java.lang.Class using one of the following options.
#1) .class extension
The first option to create an object of Class is by using the .class extension.
For example, if Test is a class, then we can create a Class object as follows:
Class obj_test = Test.class;
Then we can use the obj_test to perform reflection as this object will have all the information about the class Test.
#2) forName() method
forName () method takes the name of the class as an argument and returns the Class object.
For example, the object of the Test class can be created as follows:
class obj_test = Class.forName (“Test”);
#3) getClas () method
getClass() method uses object of a class to get the java.lang.Class object.
For example, consider the following piece of code:
Test obj = new Test (); Class obj_test = obj.getClass ();
In the first line, we created an object of Test class. Then using this object we called the “getClass ()” method to get an object obj_test of java.lang.Class.
Get Super Class & Access Modifiers
java.lang.class provides a method “getSuperClass()” that is used to get the superclass of any class.
Similarly, it provides a method getModifier() that returns the access modifier of the class.
The below example demonstrates the getSuperClass() method.
import java.lang.Class; import java.lang.reflect.*; //define Person interface interface Person { public void display(); } //declare class Student that implements Person class Student implements Person { //define interface method display public void display() { System.out.println("I am a Student"); } } class Main { public static void main(String[] args) { try { // create an object of Student class Student s1 = new Student(); // get Class object using getClass() Class obj = s1.getClass(); // get the superclass of Student Class superClass = obj.getSuperclass(); System.out.println("Superclass of Student Class: " + superClass.getName()); } catch(Exception e) { e.printStackTrace(); } } }
Output
In the above programming example, an interface Person is defined with a lone method ‘display ()’. Then we define a Student class implementing the person interface. In the main method, we use the getClass () method to retrieve the Class object and then access the parent or superclass of Student object using the getSuperClass () method.
Get Interfaces
If the class implements some interfaces, then we can get these interfaces names using the getInterfaces() method of the java.lang.Class. For this, we have to perform a reflection on the Java class.
The below programming example depicts the use of the getInterfaces () method in Java Reflection.
import java.lang.Class; import java.lang.reflect.*; //define Interface Animals and PetAnimals interface Animals { public void display(); } interface PetAnimals { public void makeSound(); } //define a class Dog that implements above interfaces class Dog implements Animals, PetAnimals { //define interface method display public void display() { System.out.println("This is a PetAnimal::Dog"); } //define interface method makeSound public void makeSound() { System.out.println("Dog makes sound::Bark bark"); } } class Main { public static void main(String[] args) { try { // create an object of Dog class Dog dog = new Dog(); // get class object Class obj = dog.getClass(); // get the interfaces implemented by Dog Class[] objInterface = obj.getInterfaces(); System.out.println("Class Dog implements following interfaces:"); //print all the interfaces implemented by class Dog for(Class citem : objInterface) { System.out.println("Interface Name: " + citem.getName()); } } catch(Exception e) { e.printStackTrace(); } } }
Output
In the above program, we have defined two interfaces i.e. Animals and PetAnimals. Then we define a class Dog, that implements both these interfaces.
In the main method, we retrieve the object of class Dog in java.lang.Class to perform reflection. Then we use the getInterfaces () method to retrieve the interfaces that are implemented by the class Dog.
Reflection: Get Field Value
As already mentioned the package java.lang.reflect provides the Field class that helps us to reflect the field or data members of the class.
Enlisted below are the methods provided by the Field class for Reflection of a field.
Given below are two reflection examples that demonstrate the reflection on the public and private field.
The Java program below demonstrates the reflection on a public field.
import java.lang.Class; import java.lang.reflect.*; class Student { public String StudentName; } class Main { public static void main(String[] args) { try{ Student student = new Student(); // get an object of the class Class Class obj = student.getClass(); // provide field name and get the field info Field student_field = obj.getField("StudentName"); System.out.println("Details of StudentName class field:"); // set the value of field student_field.set(student, "Lacey"); // get the access modifier of StudentName int mod1 = student_field.getModifiers(); String modifier1 = Modifier.toString(mod1); System.out.println("StudentName Modifier::" + modifier1); // get the value of field by converting in String String typeValue = (String)student_field.get(student); System.out.println("StudentName Value::" + typeValue); } catch(Exception e) { e.printStackTrace(); } } }
Output
In this program, we have declared a class “Student” having a public field StudentName. Then using the API interface of the Field class, we perform reflection on the field StudentName and retrieve its access modifier and value.
The next program performs reflection on a private field of the class. The operations are similar except that there is one extra function call made for the private field. We have to call setAccessible (true) for the private field. Then we perform reflection on this field in a similar manner as the public field.
import java.lang.Class; import java.lang.reflect.*; class Student { private String rollNo; } class Main { public static void main(String[] args) { try { Student student = new Student(); // get the object for class Student in a Class. Class obj = student.getClass(); // access the private field Field field2 = obj.getDeclaredField("rollNo"); // make the private field accessible field2.setAccessible(true); // set the value of rollNo field2.set(student, "27"); System.out.println("Field Information of rollNo:"); // get the access modifier of rollNo int mod2 = field2.getModifiers(); String modifier2 = Modifier.toString(mod2); System.out.println("rollNo modifier::" + modifier2); // get the value of rollNo converting in String String rollNoValue = (String)field2.get(student); System.out.println("rollNo Value::" + rollNoValue); } catch(Exception e) { e.printStackTrace(); } } }
Output
Reflection: Method
Similar to the fields of the class, we can also perform reflection on class methods and modify their behavior at run time. For this, we use the Method class of java.lang.reflect package.
Enlisted below are the functions provided by the Method class for Reflection of the class method.
The below example shows the reflection of class methods in Java using the above APIs.
import java.lang.Class; import java.lang.reflect.*; //declare a class Vehicle with four methods class Vehicle { public void display() { System.out.println("I am a Vehicle!!"); } protected void start() { System.out.println("Vehicle Started!!!"); } protected void stop() { System.out.println("Vehicle Stopped!!!"); } private void serviceVehicle() { System.out.println("Vehicle serviced!!"); } }class Main { public static void main(String[] args) { try { Vehicle car = new Vehicle(); // create an object of Class Class obj = car.getClass(); // get all the methods using the getDeclaredMethod() in an array Method[] methods = obj.getDeclaredMethods(); // for each method get method info for(Method m : methods) { System.out.println("Method Name: " + m.getName()); // get the access modifier of methods int modifier = m.getModifiers(); System.out.print("Modifier: " + Modifier.toString(modifier) + " "); // get the return type of method System.out.print("Return Type: " + m.getReturnType()); System.out.println("\n"); } } catch(Exception e) { e.printStackTrace(); } } }
Output
In the above program, we see that the method getDeclaredMethods returns the array of methods declared by the class. Then we iterate through this array and display the information of each method.
Reflection: Constructor
We can use the “Constructor” class of java.lang.reflect package to inspect and modify the constructors of a Java class.
The constructor class provides the following methods for this purpose.
The reflection example below demonstrates the reflection of constructors of a class in Java. Like method reflection, here also getDeclaredConstructors method returns an array of constructors for a class. Then we traverse through this constructor array to display information about each constructor.
import java.lang.Class; import java.lang.reflect.*; //declare a class Person with three constructors class Person { public Person() { } //constructor with no parameters public Person(String name) { } //constructor with 1 parameter private Person(String name, int age) {} //constructor with 2 parameters } class Main { public static void main(String[] args) { try { Person person = new Person(); Class obj = person.getClass(); // get array of constructors in a class using getDeclaredConstructor() Constructor[] constructors = obj.getDeclaredConstructors(); System.out.println("Constructors for Person Class:"); for(Constructor c : constructors) { // get names of constructors System.out.println("Constructor Name: " + c.getName()); // get access modifier of constructors int modifier = c.getModifiers(); System.out.print ("Modifier: " + Modifier.toString(modifier) + " "); // get the number of parameters in constructors System.out.println("Parameters: " + c.getParameterCount()); //if there are parameters, get parameter type of each parameter if(c.getParameterCount() > 0){ Class[] paramList=c.getParameterTypes(); System.out.print ("Constructor parameter types :"); for (Class class1 : paramList) { System.out.print(class1.getName() +" "); } } System.out.println("\n"); } } catch(Exception e) { e.printStackTrace(); } } }
Output
Drawbacks Of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to operate without using reflection, then it is preferable to avoid using it.
Enlisted below are few drawbacks of Reflection:
- Performance Overhead: Though reflection is a powerful feature, reflective operations still have slower performance than non- reflective operations. Hence we should avoid using reflections in performance-critical applications.
- Security Restrictions: As reflection is a runtime feature, it might require run-time permissions. So for the applications that require the code to be executed in a restricted security setting, then reflection may be of no use.
- Exposure of Internals: By using reflection, we can access private fields and methods in a class. Thus reflection breaks abstraction that might render code unportable and dysfunctional.
Frequently Asked Questions
Q #1) Why is Reflection used in Java?
Answer: Using reflection we can inspect classes, interfaces, constructors, fields, and methods at runtime, even if they are anonymous at compile time. This inspection allows us to modify the behavior of these entities at runtime.
Q #2) Where is Reflection used?
Answer: Reflection is used in writing frameworks that interoperate with user-defined classes, wherein the programmer doesn’t even know what the classes or other entities will be.
Q #3) Is Java Reflection slow?
Answer: Yes, it is slower than the non-reflection code.
Q #4) Is Java Reflection bad?
Answer: In a way, yes. First of all, we lose compile-time safety. Without compile-time safety, we might get run time errors that may affect end users. It will also be difficult to debug the error.
Q #5) How do you stop a Reflection in Java?
Answer: We simply avoid using reflection by writing non-reflection operations. Or maybe we can use some generic mechanisms like a custom validation with reflection.
More About Java Reflection
java.lang.reflect package has the classes and interfaces to do reflection. And the java.lang.class can be used as an entry point for the reflection.
How to get the class objects:
1. If you have instance of an object,
class c=obj.getclass();
2. If you know the type of the class,
class c =type.getClass();
3. If you know the class name,
Class c = Class.forName(“com.demo.Mydemoclass”);
How to get the class members:
Class members are fields (class variables) and methods.
- getFields() – Used to get all the fields except the private fields.
- getDeclaredField() – Used to get the private fields.
- getDeclaredFields() – Used to get the private and public fields.
- getMethods()– Used to get all the methods except the private methods.
- getDeclaredMethods() –Used to get the public and private methods.
Demo Programs:
ReflectionHelper.java:
This is the class where we are going to inspect using the reflection API.
class ReflectionHelper { private int age; private String name; public String deptName; public int empID; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } }
ReflectionDemo.java
public class ReflectionDemo { public static void main(String[] args) throws NoSuchFieldException, SecurityException { //get the class Class ReflectionHelperclass=ReflectionHelper.class; //get the name of the class String className = ReflectionHelperclass.getName(); System.out.println("className=="+className); System.out.println("getModifiers"+ReflectionHelperclass.getModifier s()); System.out.println("getSuperclass"+ReflectionHelperclass.getSupercla ss()); System.out.println("getPackage"+ReflectionHelperclass.getPackage()); Field[] fields =ReflectionHelperclass.getFields(); //getting only the public fields for(Field oneField : fields) { Field field = ReflectionHelperclass.getField(oneField.getName()); String fieldname = field.getName(); System.out.println("only the public fieldnames:::::"+fieldname); } //getting all the fields of the class Field[] privatefields =ReflectionHelperclass.getDeclaredFields(); for(Field onefield : privatefields) { Field field = ReflectionHelperclass.getDeclaredField(onefield.getName()); String fieldname = field.getName(); System.out.println("all the fieldnames in the class:::"+fieldname); } Method[] methods =ReflectionHelperclass.getDeclaredMethods(); for(Method m: methods) { System.out.println("methods::::"+m.getName()); } }}
Conclusion
This tutorial explained the Reflection API in Java in detail. We saw how to perform reflection of classes, interfaces, fields, methods, and constructors along with a few drawbacks of reflection.
Reflection is a relatively advanced feature in Java but should be used by programmers having a stronghold on the language. This is because it might cause unexpected errors and results if not used with caution.
Although reflection is powerful, it should be used carefully. Nonetheless, using reflection we can develop applications that are unaware of classes and other entities until runtime.
=> Take A Look At The Java Beginners Guide Here. | https://www.softwaretestinghelp.com/java/java-reflection/ | CC-MAIN-2021-17 | en | refinedweb |
Generics are great but in C# they seem to be limited in what they can do - specifically you can't have an operation that depends on the type actually used. However generic delegates provide a way of implementing type dependent operations in a generic method. This article takes a look at how this works using the Array as an example.
We all know and love arrays but .NET has some data structures and facilities that are just a touch more sophisticated than the simple array. What is often not realised is that the introduction of generics has changed the way that even simple things like arrays can be used. In this article we look at the way generic alternatives to the usual array methods are used. It also provides an interesting example of non-generic v generic approaches to coding simple things.
In particular it provides an example of how we can overcome one of the big problems in using generics - type specific operations. Using generic delegates you can implement a generic algorithm that uses operations which depend on the type specified when the generic is used.
The .NET array was already a fairly sophisticated construct compared to simple languages because it treats everything as an object. This means that arrays not only store data they also can have methods that do things. In most cases however these methods are provided by the static Array object.
For example:
int[] A = new int[50];//put some data into AArray.Sort(A);
results in the array A being sorted into ascending order using a QuickSort.
Thing are a little more sophisticated than the appear because you can see the order relation used in the sort. The point is that you can have an array of strongly typed objects and in this case you need to defined what a sorted order is.
To define the order relation used in the sort you need to implement an object with an IComparer interface. This defines a Compare method that returns –1, 0, or 1 depending on the result of the compare:
private class CMyCompare : IComparer{ int IComparer.Compare(Object x, Object y) {
The problem now is that we have to do the comparison between x and y but this is difficult without knowing what types they are. Without generics this is the only way you can define the interface.
The simplest solution is to cast to the type that you know is stored in the array and then use the type’s CompareTo method:
private class CMyCompare : IComparer{ int IComparer.Compare(Object x, Object y) { return (((int)y).CompareTo((int)x)); }}
Array.Sort(A, new CMyCompare());
The wider point being made is that without using generics this is the only way the job can be done. You need an interface to define the form of the function to be used and you have to cast to actually do the work that makes use of the nature of the objects actually being passed. This clearly isn't type safe at compile time as the casts cannot be checked but it can be made type safe at runtime by adding code to make sure the objects are of a type you can work with.
This is all good but it’s pre-generics which were introduced as long ago as .NET 2.0. Arguably generics provide a better way of implementing sorting methods that work with any type. The big problem with generics is that you can't use them to do things that are type specific. That is if you have two objects that are specified as generic you can't add them together even if in they support the operation. That is you can't write something like:
T x;T y;T z;z=x+y;
because the type of T isn't specified.
This seems to reduce the usefulness of generics. But this isn't always the case because you can define operations on generics using a generic delegate i.e. a method type with a generic signature. The concrete operation is then provided by a specific instance of the delegate that has a fully defined signature that fits the generic specification.
In .NET a number of new generic sort methods were introduced. For example:
public static void Sort<T> ( T[] array, Comparison<T> comparison)
This uses the generic Comparison delegate to supply the order relation used in the sort:
public delegate int Comparison<T> (T x,T y)
To implement the same sort as we did using IComparer all we have to do is write a Comparison function - no interfaces necessary:
public int MyCompare(int x, int y){return (((int)y).CompareTo((int)x));}
Now as long as we select the generic sort i.e. Sort<T> all we have to change is - well nothing much at all:
Array.Sort(A, MyCompare);
Notice this differs slightly from the use of generics we normally encounter. The MyCompare function simply has to have the correct signature and the system uses the type information to instantiate the generic within the Sort method.
This becomes slightly clearer if you write it out fully as:
Array.Sort<int>( A,new Comparison<int>(MyCompare));
which instantiates the Sort definition to:
public static void Sort ( int [] array, Comparison< int > comparison)
To understand what a generic definition actually produces it is often helpful to actually write out the result of setting the type parameters to particular values.
In turn the definition of Comparison is:
public delegate int Comparison (int x,int y)
This is, of course, the signature of the function that we are actually passing. Notice that the shorthand way of writing the function call saves specifying the data type twice and it also automatically creates the delegate using the “method group conversion” facility.
<ASIN:0470495995>
<ASIN:1430229799>
<ASIN:0262201755>
<ASIN:0596800959> | https://i-programmer.info/programming/c/2060-generics-and-arrays.html | CC-MAIN-2021-17 | en | refinedweb |
. If instead, you wish to combine a series of unsupported (or supported) TensorFlow operators into a single fused optimized custom operator, refer to operator fusing.
Using custom operators consists of four steps.
Create a TensorFlow Model. Make sure the Saved Model (or Graph Def) refers to the correctly named TensorFlow Lite operator.
Convert to a TensorFlow Lite Model. Make sure you set the right TensorFlow Lite converter attribute in order to successfully convert the model.
Create and register the operator. This is so that the TensorFlow Lite runtime knows how to map your operator and parameters in your graph to executable C/C++ code.
Test and profile your operator. If you wish to test just your custom operator, it is best to create a model with just your custom operator and use the benchmark_model program.
Let’s walk through an end-to-end example of running a model with a custom
operator
tf.sin (named as
Sin, refer to #create_a_tensorflow_model) which is
supported in TensorFlow, but unsupported in TensorFlow Lite.
Example: Custom
Sin operator.
Create a TensorFlow Model
The following code snippet trains a simple TensorFlow model. This model just
contains a custom operator named
Sin, which is a function
y = sin(x +
offset), where
offset is trainable.
import tensorflow as tf # Define training dataset and variables x = [-8, 0.5, 2, 2.2, 201] y = [-0.6569866 , 0.99749499, 0.14112001, -0.05837414, 0.80641841] offset = tf.Variable(0.0) # Define a simple model which just contains a custom operator named `Sin` @tf.function def sin(x): return tf.sin(x + offset, name="Sin") # Train model optimizer = tf.optimizers.Adam(0.01) def train(x, y): with tf.GradientTape() as t: predicted_y = sin(x) loss = tf.reduce_sum(tf.square(predicted_y - y)) grads = t.gradient(loss, [offset]) optimizer.apply_gradients(zip(grads, [offset])) for i in range(1000): train(x, y) print("The actual offset is: 1.0") print("The predicted offset is:", offset.numpy())
The actual offset is: 1.0 The predicted offset is: 1.0000001
At this point, if you try to generate a TensorFlow Lite model with the default converter flags, you will get the following error message:
Error: Some of the operators in the model are not supported by the standard TensorFlow Lite runtime...... Here is a list of operators for which you will need custom implementations: Sin.
Convert to a TensorFlow Lite Model
Create a TensorFlow Lite model with custom operators, by setting the converter
attribute
allow_custom_ops as shown below:
converter = tf.lite.TFLiteConverter.from_concrete_functions([sin.get_concrete_function(x)]) converter.allow_custom_ops = True tflite_model = converter.convert()
At this point, if you run it with the default interpreter, you will get the following error messages:
Error: Didn't find custom operator for name 'Sin' Registration failed.
Create and register the operator.
All TensorFlow Lite operators (both custom and builtin) are defined using a simple pure-C interface that consists of four functions:
typedef struct { void* (*init)(TfLiteContext* context, const char* buffer, size_t length); void (*free)(TfLiteContext* context, void* buffer); TfLiteStatus (*prepare)(TfLiteContext* context, TfLiteNode* node); TfLiteStatus (*invoke)(TfLiteContext* context, TfLiteNode* node); } TfLiteRegistration;
Refer to
common.h
for details on
TfLiteContext and
TfLiteNode. The former provides error
reporting facilities and access to global objects, including all the tensors.
The latter allows implementations to access their inputs and outputs.
When the interpreter loads a model, it calls
init() once for each node in the
graph. A given
init() will be called more than once if the op is used multiple
times in the graph. For custom ops a configuration buffer will be provided,
containing a flexbuffer that maps parameter names to their values. The buffer is
empty for builtin ops because the interpreter has already parsed the op
parameters. Kernel implementations that require state should initialize it here
and transfer ownership to the caller. For each
init() call, there will be a
corresponding call to
free(), allowing implementations to dispose of the
buffer they might have allocated in
init().
Whenever the input tensors are resized, the interpreter will go through the
graph notifying implementations of the change. This gives them the chance to
resize their internal buffer, check validity of input shapes and types, and
recalculate output shapes. This is all done through
prepare(), and
implementations can access their state using
node->user_data.
Finally, each time inference runs, the interpreter traverses the graph calling
invoke(), and here too the state is available as
node->user_data.
Custom ops can be implemented in exactly the same way as builtin ops, by defining those four functions and a global registration function that usually looks like this:
namespace tflite { namespace ops { namespace custom { TfLiteRegistration* Register_MY_CUSTOM_OP() { static TfLiteRegistration r = {my_custom_op::Init, my_custom_op::Free, my_custom_op::Prepare, my_custom_op::Eval}; return &r; } } // namespace custom } // namespace ops } // namespace tflite
Note that registration is not automatic and an explicit call to
Register_MY_CUSTOM_OP should be made. While the standard
BuiltinOpResolver
(available from the
:builtin_ops target) takes care of the registration of
builtins, custom ops will have to be collected in separate custom libraries. (see
below for an example)..
Register the operator with the kernel library
Now we need to register the operator with the kernel library. This is done with
an
OpResolver. Behind the scenes, the interpreter will load a library of
kernels which will be assigned to execute each of the operators in the model.
While the default library only contains builtin kernels, it is possible to
replace/augment it with a custom library op operators.
The
OpResolver class, which translates operator codes and names into actual
code, is defined like this:
class OpResolver { virtual TfLiteRegistration* FindOp(tflite::BuiltinOperator op) const = 0; virtual TfLiteRegistration* FindOp(const char* op) const = 0; virtual void AddBuiltin(tflite::BuiltinOperator op, TfLiteRegistration* registration) = 0; virtual void AddCustom(const char* op, TfLiteRegistration* registration) = 0; };
Regular usage requires that you use the
BuiltinOpResolver and write:
tflite::ops::builtin::BuiltinOpResolver resolver;
To add the custom op created above, you call
AddOp (before you pass the
resolver to the
InterpreterBuilder):
resolver.AddCustom("Sin", Register_SIN());
If the set of builtin ops is deemed to be too large, a new
OpResolver could be
code-generated based on a given subset of ops, possibly only the ones contained
in a given model. This is the equivalent of TensorFlow's selective registration
(and a simple version of it is available in the
tools directory)..
Test and profile your operator
To profile your op with the TensorFlow Lite benchmark tool, you can use the
benchmark model tool
for TensorFlow Lite. For testing purposes, you can make your local build of
TensorFlow Lite aware of your custom op by adding the appropriate
AddCustom
call (as show above) to
register.cc. | https://www.tensorflow.org/lite/guide/ops_custom?hl=hu | CC-MAIN-2021-17 | en | refinedweb |
1..
Integration Libraries
If you want to use a networking library such as OkHttp or Volley in your project for network operations, it is recommended you include the specific Glide integration for the library you are using (instead of the default one which bundles HttpURLConnection).
Volley
dependencies { compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.github.bumptech.glide:volley-integration:1.4.0@aar' compile 'com.mcxiaoke.volley:library:1.0.8' }
OkHttp
dependencies { // okhttp 3 compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar' compile 'com.squareup.okhttp3:okhttp:3.2.0' // okhttp 2 compile 'com.github.bumptech.glide:okhttp-integration:1.4.0@aar' compile 'com.squareup.okhttp:okhttp:2.2.0' }
You can visit the official Glide integration libraries guide for more information.
5. Add Internet Permission
Since Glide is going to perform a network request to load images via the internet, we need to include the permission
INTERNET in our AndroidManifest.xml.
<uses-permission android:
6. Create the Layout
We'll start by creating our
RecyclerView.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <android.support.v7.widget.RecyclerView android: </RelativeLayout>
Creating the Custom Item Layout
Next, let's create the XML layout that will be used for each item (
ImageView) within the
RecyclerView.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <ImageView android: </LinearLayout>
Now that we have created the layout, the next step is to create the
RecyclerView adapter for populating data. Before we do that, though, let's create our simple data model.
7. Create a Data Model
We are going to define a simple data model for our
RecyclerView. This model implements Parcelable for high-performance transport of data from one component to another. In our case, data will be transported from
SpaceGalleryActivity to
SpacePhotoActivity.
import android.os.Parcel; import android.os.Parcelable; public class SpacePhoto implements Parcelable { private String mUrl; private String mTitle; public SpacePhoto(String url, String title) { mUrl = url; mTitle = title; } protected SpacePhoto(Parcel in) { mUrl = in.readString(); mTitle = in.readString(); } public static final Creator<SpacePhoto> CREATOR = new Creator<SpacePhoto>() { @Override public SpacePhoto createFromParcel(Parcel in) { return new SpacePhoto(in); } @Override public SpacePhoto[] newArray(int size) { return new SpacePhoto[size]; } }; public String getUrl() { return mUrl; } public void setUrl(String url) { mUrl = url; } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public static SpacePhoto[] getSpacePhotos() { return new SpacePhoto[]{ new SpacePhoto("", "Galaxy"), new SpacePhoto("", "Space Shuttle"), new SpacePhoto("", "Galaxy Orion"), new SpacePhoto("", "Earth"), new SpacePhoto("", "Astronaut"), new SpacePhoto("", "Satellite"), }; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mUrl); parcel.writeString(mTitle); } }
8. Create the Adapter
We'll create an adapter to populate the RecyclerView with data. We'll also implement a click listener to open the detail activity—
SpacePhotoActivity—passing it an instance of
SpacePhoto as an extra. The detail activity will show a close-up of the image. We'll create it in a later section.
public class MainActivity extends AppCompatActivity { // ... private class ImageGalleryAdapter extends RecyclerView.Adapter<ImageGalleryAdapter.MyViewHolder> { @Override public ImageGalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View photoView = inflater.inflate(R.layout.item_photo, parent, false); ImageGalleryAdapter.MyViewHolder viewHolder = new ImageGalleryAdapter.MyViewHolder(photoView); return viewHolder; } @Override public void onBindViewHolder(ImageGalleryAdapter.MyViewHolder holder, int position) { SpacePhoto spacePhoto = mSpacePhotos[position]; ImageView imageView = holder.mPhotoImageView; } @Override public int getItemCount() { return (mSpacePhotos.length); } public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView mPhotoImageView; public MyViewHolder(View itemView) { super(itemView); mPhotoImageView = (ImageView) itemView.findViewById(R.id.iv_photo); itemView.setOnClickListener(this); } @Override public void onClick(View view) { int position = getAdapterPosition(); if(position != RecyclerView.NO_POSITION) { SpacePhoto spacePhoto = mSpacePhotos[position]; Intent intent = new Intent(mContext, SpacePhotoActivity.class); intent.putExtra(SpacePhotoActivity.EXTRA_SPACE_PHOTO, spacePhoto); startActivity(intent); } } } private SpacePhoto[] mSpacePhotos; private Context mContext; public ImageGalleryAdapter(Context context, SpacePhoto[] spacePhotos) { mContext = context; mSpacePhotos = spacePhotos; } } }
9. Loading Images From a URL
This is where we need Glide to do its job—to fetch images from the internet and display them in the individual
ImageViews, using our RecyclerView
onBindViewHolder() method as the user scrolls the app.
// ... @Override public void onBindViewHolder(MyViewHolder holder, int position) { Photo photo = mPhotoList.get(position); ImageView imageView = holder.mPhotoImageView; Glide.with(mContext) .load(spacePhoto.getUrl()) .placeholder(R.drawable.ic_cloud_off_red) .into(imageView); } // ...
Step by step, here are what the calls to Glide are doing:
with(Context context): we begin the load process by first passing our context into the
with()method.
load(String string): the image source is specified as either a directory path, a URI, or a URL.
placeholder(int resourceId): a local application resource id, preferably a drawable, that will be a placeholder until the image is loaded and displayed.
into(ImageView imageView): the target image view into which the image will be placed.
Be aware that Glide can also load local images. Just pass either the Android resource id, the file path, or a URI as an argument to the
load() method.
Image Resizing and Transformation
You can resize the image before it is displayed in the
ImageView with Glide's
.override(int width, int height) method. This is useful for creating thumbnails in your app when loading a different image size from the server. Note that the dimensions are in pixels not dp.
The following image transformations are also available:
fitCenter(): scales the image uniformly (maintaining the image's aspect ratio) so that the image will fit in the given area. The entire image will be visible, but there might be vertical or horizontal padding.
centerCrop(): scales the image uniformly (maintaining the image's aspect ratio) so that the image fills up the given area, with as much of the image showing as possible. If needed, the image will be cropped horizontally or vertically to fit.
10. Initializing the Adapter
Here we create our
RecyclerView with
GridLayoutManager as the layout manager, initialize our adapter, and bind it to the
RecyclerView.
// ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_images); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); ImageGalleryAdapter adapter = new ImageGalleryAdapter(this, SpacePhoto.getSpacePhotos()); recyclerView.setAdapter(adapter); } // ...
11. Creating the Detail Activity
Create a new activity and name it
SpacePhotoActivity. We get the
SpacePhoto extra and load the image with Glide as we did before. Here we are expecting the file or URL to be a
Bitmap, so we'll use
asBitmap() to makes that Glide receives a
Bitmap. Otherwise the load will fail and the
.error() callback will be triggered—causing the drawable resource returned from the error callback to be shown.
You could also use
asGif() if you wanted to ensure that your loaded image was a GIF. (I'll explain how GIFs work in Glide shortly.)
import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.graphics.Palette; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; public class SpacePhotoActivity extends AppCompatActivity { public static final String EXTRA_SPACE_PHOTO = "SpacePhotoActivity.SPACE_PHOTO"; private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo_detail); mImageView = (ImageView) findViewById(R.id.image); SpacePhoto spacePhoto = getIntent().getParcelableExtra(EXTRA_SPACE_PHOTO); Glide.with(this) .load(spacePhoto.getUrl()) .asBitmap() .error(R.drawable.ic_cloud_off_red) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(mImageView); } }
Note that we also initialized a unique cache for the loaded images:
DiskCacheStrategy.SOURCE. I'll explain more about caching in a later section.
The Detail Layout
Here's a layout to display the detail activity. It just displays a scrollable
ImageView that will show the full-resolution version of the loaded image.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <ScrollView android: <LinearLayout android: <ImageView android: </LinearLayout> </ScrollView> </LinearLayout>
12. Caching in Glide
If you watch closely, you'll see that when you revisit an image that was previously loaded, it loads even faster than before. What made it faster? Glide's caching system, that's what.
After an image has been loaded once from the internet, Glide will cache it in memory and on disk, saving repeated network requests and permitting faster retrieval of the image. So, Glide will first check if an image is available in either memory or on the disk before loading it from the network.
Depending on your application, though, you might want to avoid caching—for example if the images being displayed are likely to change often and not to be reloaded.
So How Do You Disable Caching?
You can avoid memory caching by calling
.skipMemoryCache(true). But be aware that the image will still be cached on the disk—to prevent that also, you use the
.diskCacheStrategy(DiskCacheStrategy strategy) method, which takes one of the following enum values:
DiskCacheStrategy.NONE: no data is saved to cache.
DiskCacheStrategy.SOURCE: original data saved to cache.
DiskCacheStrategy.RESULT: saves the result of the data after transformations to cache.
DiskCacheStrategy.ALL: caches both original data and transformed data.
To avoid both memory and disk caching altogether, just call both methods one after the other:
Glide.with(this) .load(spacePhoto.getUrl()) .asBitmap() .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) .into(imageView);
13. Request Listeners
In Glide, you can implement a
RequestListener to monitor the status of the request you made as the image loads. Only one of these methods will be called.
onException(): triggered whenever an exception occurs so you can handle exceptions in this method.
onResourceReady(): fired when the image is loaded successfully..
// ... @Override protected void onCreate(Bundle savedInstanceState) { // ... Glide.with(this) .load(spacePhoto.getUrl()) .asBitmap() .error(R.drawable.ic_cloud_off_red) .listener(new RequestListener<String, Bitmap>() { @Override public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) { onPalette(Palette.from(resource).generate()); mImageView.setImageBitmap(resource); return false; } public void onPalette(Palette palette) { if (null != palette) { ViewGroup parent = (ViewGroup) mImageView.getParent().getParent(); parent.setBackgroundColor(palette.getDarkVibrantColor(Color.GRAY)); } } }) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(mImageView); } // ...
Here you could also hide a progress dialog if you had one. With this last change, make sure to include the Palette dependency in your
build.gradle:
dependencies { // ... compile 'com.android.support:palette-v7:25.1.1' }
14. Testing the App
Finally, you can run the app! Click on a thumbnail to get a full-sized version of the image.
15. Animations
If you run the app, you will notice a crossfade animation that happens while the image is being displayed. Glide has this enabled by default, but you can disable it by calling
dontAnimate(), which will just cause the image to be displayed without any animation.
You can also customize the crossfade animation by calling
crossFade(int duration), passing the duration in milliseconds to either speed it up or slow it down—300 milliseconds is the default.
Animated GIFs
It's very simple to display an animated GIF in your app using Glide. It works the same as displaying an ordinary image.
ImageView gifImageView = (ImageView) findViewById(R.id.iv_gif); Glide.with(this) .load("") .asGif() .placeholder(R.drawable.ic_cloud_off_red) .error(R.drawable.ic_cloud_off_red) .into(gifImageView);
If you are expecting the image to be a GIF, call
asGif()—this makes sure that Glide receives a GIF, otherwise the load will fail and the
Drawable passed to the
.error() method will be shown instead.
Playing Video
Unfortunately, Glide does not support video loading and display via URL. Instead it can only load and display videos already stored on the phone. Show a video by passing its URI to the
load() method.
Glide.with(context) .load(Uri.fromFile(new File("your/video/file/path")) .into(imageView)
Conclusion
Great job! In this tutorial, you've built a complete image gallery app with Glide, and along the way learned how the library works and how you can integrate it in your own project. You've also learned how to display both local and remote images, how to show animated GIFs and videos, and how to apply image transformations like resizing. Not only that, but you've seen how easy it is to enable caching, error handling, and custom request listeners.
To learn more about Glide, you can refer to its official documentation. To learn more about coding for Android, check out some of our other courses and tutorials here on Envato T<< | https://code.tutsplus.com/tutorials/code-an-image-gallery-android-app-with-glide--cms-28207 | CC-MAIN-2021-17 | en | refinedweb |
Older versions of this plugin may not be safe to use. Please review the following warnings before using an older version:
A Jenkins Plugin to deploy configurations to Azure Container Service (AKS).
It also supports deployment to the legacy Azure Container Service (ACS) with the following orchestrator:
It also supports deployments on Azure Kubernetes Service.
It provides the following main functionality:
- Integration with ACS. Allow you to select existing ACS clusters and manages the authentication credentials.
- Unified configure interface for all the supported orchestrator.
- Variable substitution for configurations, which enables dynamic deployment in CI/CD.
- Docker login credentials management for pulling images from private repository.
Pre-requirements
AKS cluster, or an ACS cluster with the supported orchestrator
A Azure service principal that can be used to manage the ACS cluster
Configurations for the target ACS cluster orchestrator, this can be
- Kubernetes resource configurations of the following kinds:
- Deployment
- Replica Set
- Replication Controller - No rolling-update support. If that's required, consider using Deployment.
- Daemon Set
- Pod
- Job
- Service
- Ingress
- Secret - The plugin also provides secrets configuration.
- Marathon application configurations
- Docker compose configurations
In the context of container deployment, normally we should build a Docker image from the project artifacts, and push the image to a repository. This can be done with some existing plugins such as CloudBees Docker Build and Publish plugin.
Configure the plugin
- Within the Jenkins dashboard, Select a Job then select Configure
- Scroll to the "Add post-build action" drop down.
- Select "Deploy to Azure Container Service"
- Select the service principal from "Azure Credentials" dropdown. If no credentials are configured, create one.
- All resource group names will be loaded into the "Resource Group" dropdown. Select the one containing your ACS cluster.
- All the container service available in the selected resource group will be loaded into the "Container Service" dropdown. Select your target ACS cluster. (It's suggested that we use a standalone resource group to manage an ACS cluster, and do not add other resources or ACS clusters into the resource group.)
- Select the "Master Node SSH Credentials". This should be the credentials of type "SSH Username with private key", where username is the login name you specified when you create the ACS cluster (
azureuserby default), and private key is the one matching the public key you specified on the ACS cluster creation (by default that may be
$HOME/.ssh/id_rsaon Linux and
%USERPROFILE%\.ssh\id_rsaon Windows).
- Enter the "Config Files" path of the configurations you want to deploy, in the form of Ant glob syntax. Use comma (,) to separate multiple patterns.
- If you want to dynamically update the configurations on each build, for example, use the
$BUILD_NUMBERas the tag name of the image being pulled, you can tick the "Enable Variable Substitution in Config" option and the variables (in the pattern
$VARIABLEor
${VARIABLE}) in the configurations will be substituted with the corresponding value if they exists in the environment variables.
- If the configurations needs to pull images from private repository, click the "Docker Container Registry Credentials..." button and add them one by one.
For Kubernetes, you can enter the secret name and the namespace where the secret will be created based on the credentials configured. The credentials you provided will be consolidated into a Secret resource in your Kubernetes cluster with the name you provided. You can use that secret in your Kubernetes configuration.
You can use variables in the secret name (e.g.,
$BUILD_NUMBER), to generate a secret specific to a build. The name will be exposed as environment variable
KUBERNETES_SECRET_NAMEand you can use that in your Kubernetes resource configurations if the "Enable Variable Substitution in Config" option is turned on.
apiVersion: extensions/v1beta1 kind: Deployment metadata: name: sample-k8s-deployment spec: replicas: 1 template: metadata: labels: app: sample-k8s-app spec: containers: - name: sample-k8s-app-container image: <username or registry URL>/<image_name>:<tag(maybe, $BUILD_NUMBER)> ports: - containerPort: 8080 imagePullSecrets: - name: $KUBERNETES_SECRET_NAME
For Marathon on DC/OS, you can specify the "DC/OS Docker Credentials Path", the credentials you provided will be archived into a file
docker.tar.gz, and uploaded to the agent nodes in the path you filled. You can use it to construct the URI in your Marathon config:
file://<absolute_path_you_filled>/docker.tar.gz
If this path is left blank, a unique path will be generated under
$HOME/acs-plugin-dcos.docker.
The URI will be exported to the environment variable
MARATHON_DOCKER_CFG_ARCHIVE_URIwhich you can use in your Marathon configuration.
{ "id": "marathon-demo-app", "cmd": null, "cpus": 1, "mem": 512, "disk": 0, "instances": 1, "container": { "docker": { "image": "<username or registry URL>/<image_name>:<tag(maybe, $BUILD_NUMBER)>", "network": "BRIDGE", "portMappings": [ { "containerPort": 8080, "hostPort": 80, "protocol": "tcp", "name": "80", "labels": null } ] }, "type": "DOCKER" }, "acceptedResourceRoles": [ "slave_public" ], "uris": [ "$MARATHON_DOCKER_CFG_ARCHIVE_URI" ] }
Add a credentials entry for each of the private Docker registries involved in your configuration. If it is hosted on DockerHub, you can leave the URL as empty; otherwise for other private registries, you need to specify the "Docker registry URL".
- You may verify the static configuration by clicking "Verify Configuration". This will give you basic result of the configuration quality. You need to run a sample build to verify it works as some of the contents has to be loaded at build time.
Pipeline Support
To use the plugin in pipeline, go to the Pipeline Syntax page when you configure the pipeline job, and choose acsDeploy: Deploy to Azure Container Service from the Sample Step dropdown. You can configure it and click Generate Pipeline Scriptwhich will give you
acsDeploy(azureCredentialsId: '<azure-credential-id>', resourceGroupName: '<resource-group-name>', containerService: '<acs-name> | <acs-type>', sshCredentialsId: '<ssh-credentials-id>', configFilePaths: '<configuration-file-paths>', enableConfigSubstitution: true, // Kubernetes secretName: '<secret-name>', secretNamespace: '<secret-namespace>', // Docker Swarm swarmRemoveContainersFirst: true, // DC/OS Marathon dcosDockerCredentialsPath: '<dcos-credentials-path>', containerRegistryCredentials: [ [credentialsId: '<credentials-id>', url: '<docker-registry-url>'] ])
Data/Telemetry
Azure Container 1.0.0, 2019-08-14
- Bump Jenkins version to 2.60.3
- Upgrade Kubernetes cd plugin to 2.0.1
Version 0.2.4, 2019-04-09
- Fix exception in generic resource interface
Version 0.2.3, 2018-04-03
Version 0.2.2, 2018-02-09
- Abort the build flow if the deployment failed
Version 0.2.1, 2018-01-09
Version 0.2.0, 2018-01-05
- Support MSI
Version 0.1.5, 2017-11-27
- Fix typo in AI reporting
Version 0.1.4, 2017-11-07
- Support for Azure Kubernetes Service (AKS)
- Add Third Party Notice
Version 0.1.3, 2017-10-18
- Remove EULA
- Remove "Run On" check
Version 0.1.2, 2017-09-29
- Fixed a stream closed issue when variable substitution is disabled
Version 0.1.1, 2017-09-28
- Fixed an issue that plugin crashes on fastxml load
Version 0.1.0, 2017-09-27
- Initial release | https://plugins.jenkins.io/azure-acs/ | CC-MAIN-2021-17 | en | refinedweb |
Timing : are hurwitz_zeta values cached?
Dear all, It seems the values of hurwitz_zeta are cached in some way. This makes sense, but I couldn't find documentation on that issue, and in particular, on how to clear the cache: I want to time several instances of a script and need to start afresh each time. Here is an ECM:
import sys from timeit import default_timer as timer def ECM(prec): start, CF = timer(), ComplexField(prec) hurwitz_zeta(s = CF(2), x = CF(0.5)) end = timer() return end-start for i in range(0,20): ECM(3000) 0.10533331300030113 0.011018371998943621 0.011091479000242543 0.0118424979991687 etc...
Then start afresh, get a similar answer. I am pretty sure this system-caching mechanism is explained somewhere but my morning queries drew a blank --
Pointers would be appreciated! Best, Olivier | https://ask.sagemath.org/question/52806/timing-are-hurwitz_zeta-values-cached/ | CC-MAIN-2021-17 | en | refinedweb |
Amazon SNS Connector.
Prerequisites
To be able to use the Amazon SNS Connector, you must have the following:
Access to Amazon Web Services - SNS.
To access AWS with the connector, you need the credentials in the form of IAM.
Anypoint Studio version 7.0 (or higher) or Anypoint Design Center. Connector Global Element
To use the Amazon SNS connector in your Mule application, configure a global Amazon SNS element that can be used by all the Amazon SNS connectors in the application.
Configuring with Studio Visual Editor
Click the Global Elements tab at the base of the canvas.
In the Global Configuration Elements screen, click Create. Following window would be displayed.
In the Choose Global Type wizard, expand Connector Configuration and select Amazon SNS Configuration and click Ok. Following window would be displayed.
In the image above, the placeholder values refer to a configuration file placed in the
srcfolder of your project.
Configure the parameters according to instructions below.
You can either enter your credentials into the global configuration properties, or reference a configuration file that contains these values. For simpler maintenance and better reusability SNS.
Click OK to save the global connector configurations.
Configuring with XML Editor or Standalone
Ensure that you have included the Amazon SNS namespaces in your configuration file.
Create a global Amazon SNS configuration outside and above your flows, using the following global configuration code.
If you or your IAM users forget or lose the secret access key, you can create a new access key.
Using This Connector
Amazon SNS connector is an operation-based connector, which means that when you add the connector to your flow, you need to configure a specific operation for the connector to perform. The connector currently supports the following list of operations:, paste the namespace and schema into your Configuration XML.
Use Cases and Demos.
You can subscribe an Amazon SQS queue to an Amazon SNS topic using the AWS Management Console for Amazon SQS, which simplifies the process.
Create a new Mule Project in Anypoint Studio.
Add the below properties to
mule-artifact.propertiesfile to hold your Amazon SNS and SQS credentials and place it in the project’s
src/main/appdirectory.
Click on a Mule HTTP Connector and select Listener operation, drag it to the beginning of the flow and configure the following parameters:
Click on the Amazon SNS Connector and select the operation "Publish" and drag <sns:basic-connection <-details < > ReceiveMessages in the left side of the new flow and configure it according to the steps below:
Click the plus sign next to the Connector Configuration field to add a new Amazon SQS Global Element.
Configure the global element according to the table below:
Your configuration should look like this (Queue URL can be skipped if Queue Name is specified):
The corresponding XML configuration should be as follows:
<sqs:config
Make sure SQS-Queue that you mentioned in configuration should be subscribed to SNS-Topic. like:
<sqs:receivemessages
Add a Logger scope after the Amazon SQS connector to print the data that is being passed by the Receive operation in the Mule Console. Configure the Logger according to the table below.
Save and run the project as a Mule Application. Right-click the project in Package Explorer. Run As > Mule Application.
Open a web browser and check the response after entering the URL. The logger displays the published message ID on the browser and the received message on the mule console.
See Also
If you or your IAM users forget or lose the secret access key, you can create a new access key. More information about the keys in AWS documentation.
Subscribe Queue to Amazon SNS Topic. | https://docs.mulesoft.com/connectors/amazon-sns-connector | CC-MAIN-2018-30 | en | refinedweb |
Segment makes it easy to send your data to Kahuna (and lots of other destinations). Once you've tracked your data through our open source libraries we'll translate and route your data to Kahuna in the format they understand. Learn more about how to use Kahuna with Segment.
Getting Started
Segment makes it easy to send your data to Kahuna. Once you’re tracking data through our iOS, Android or server side libraries, we’ll translate and route your data to Kahuna in the format they can process.
If you have mobile apps, then Kahuna recommends using the Segment iOS and or Android library and bundling Kahuna (see Mobile section below).
If you are sending data from a server side library, please read the Server side section.
Be sure to enable Kahuna in your Segment destinations page and provide your Kahuna Secret Key, which can be found in the Settings page of the Kahuna Dashboard.
Mobile
In order to leverage the full capability of Kahuna’s Push Messaging and In-App features, you will have to bundle the Kahuna SDK while configuring your Segment mobile SDKs.
Android
Add this to your project gradle file:
allprojects { repositories { jcenter() maven { url "" } maven { url "" } } }
Add this to your app level gradle file:
compile ('com.kahuna.integration.android.segment:kahuna:+') { transitive = true }
Then, bundle Kahuna during your Segment Analytics initialization, with more details here:
Analytics analytics = new Analytics.Builder(this, "SEGMENT_KEY") .use(KahunaIntegration.FACTORY) .build();
iOS
Add the Kahuna pod dependency:
pod "Segment-Kahuna
Then, bundle Kahuna during your Segment Analytics initialization, with more details here:
#import <Segment-Kahuna/SEGKahunaIntegrationFactory.h> SEGAnalyticsConfiguration *config = [SEGAnalyticsConfiguration configurationWithWriteKey:@"YOUR_WRITE_KEY"]; [config use:[SEGKahunaIntegrationFactory instance]]; [SEGAnalytics setupWithConfiguration:config];
Push Notifications
To leverage the Push Notifications and In-App functionality provided by Kahuna, follow the steps in the Kahuna SDK destination guide:
For iOS, follow the steps in Enable Personalized Push in the iOS Get Started section.
For Android, follow the steps in Enable Personalized Push in the Android Get Started section.
Reset
If your app supports the ability for a user to logout and login with a new identity, then you’ll need to call
reset in your mobile app. Here we will call Kahuna’s logout implementation to ensure the user information remains consistent.
Server-Side
If you are using Segment’s iOS or Android libraries but have not bundled Kahuna’s SDK as described in the mobile section above, we will default to using the server side destination. It is recommended that you bundle the Kahuna’s SDK in order to use features such as Push Notifications and In-App features.
However, any data coming from sources other than mobile apps should be using the server side destination.
Batching
If you are using the server side destination for Kahuna, we recommend you set the Segment batching options as follows (note: these settings would apply to all of your Segment destinations):
- flushAt to 100
- flushAfter to 30 minutes (or 1800000 ms)
Identify
Our server-side destination supports the ability to register user information with Kahuna through our identify calls. This will allow you to organize and segment your Kahuna campaigns according to the user information that you have sent.
The first thing you’ll want to do is to
identify a user with any relevant information as soon as they launch the app. You record this with our
identify method.
Identify takes the
userId of a user and any
traits you know about them.
When you call
identify, we’ll set two Kahuna Credentials,
user_id and
user_info, which are User Attributes in Kahuna.
We will also send any relevant device information such as device token, app name and version, OS and browser name, etc.
Track
You can also use
track calls to send event data using Kahuna’s
Intelligent Events.
Whenever you call track, we’ll send an event to Kahuna with the event name and a unix timestamp. We will also pass through any properties of the event. If
properties.quantity and
properties.revenue are set, then we will send the event name as well as count and value. For value, we will first multiply
properties.revenue by
100 before sending to Kahuna since Kahuna tracks value in cents not dollars.
Note: We will flatten any compound objects such as nested objects or arrays. We will also strip any properties that have values of
null since Kahuna’s API does not support these values. Lastly, just like the
identify call, we will send any relevant device parameters we can send based off the context of the call.
Screen
When you call
screen in your mobile app, we send a screen view to Kahuna for mobile apps if trackAllPages is enabled for your Kahuna destination. If enabled, we track a Kahuna event with the format “Viewed
screen.name Screen”. If you want to enable sending
screenevents to Kahuna, simply check the box for: Track All Pages from your Segment Kahuna settings page.
E-Commerce
Segment supports a deeper Kahuna destination with e-commerce tracking in our mobile SDKs (NOT in server side). All you have to do is adhere to our
e-commerce tracking API and we’ll track Kahuna e-commerce specific user attributes.
Viewed Product Category
For
Viewed Product Category, we will track the Kahuna User Attributes “Last Viewed Category” and “Categories Viewed”. The value for Last Viewed Category will be taken from
properties.category, “None” if unspecified. The value of Categories Viewed will be a list of the last 50 unique categories the user viewed, also taken from
properties.category.
Viewed Product
For
Viewed Product, we will track the same Kahuna User Attributes as Viewed Product Category. We also will track another User Attribute called “Last Product Viewed Name” with the value taken from
properties.name.
Added Product
For
Added Product, we will track the Kahuna User Attributes “Last Product Added To Cart Name” taken from
properties.name and “Last Product Added To Cart Category” taken from
properties.category. If category is unspecified, we will track “None”.
Completed Order
For
Completed Order, we will track the Kahuna User Attributes “Last Purchase Discount” taken from
properties.discount. If
discount is unspecified, we will track 0.
Send Push Token via Server-Side
If you chose not to bundle the Kahuna Mobile SDK, then you will have to implement your own Push Message processors, and you won’t have access to Kahuna’s In-App feature.
If you decide to implement your own Push Message processors, then make sure you pass the Push Tokens to Kahuna via Server Side. You can do this by sending it inside
context.device.token. We will send this to Kahuna as
push_token..
Segment offers an optional Device-based Connection Mode for Mobile data with Kahuna. If you’d like to use those features that require client-based functionality, follow the steps above to ensure you have packaged the Kahuna SDK with Segment’s.
Settings
Segment lets you change these destination settings via your Segment dashboard without having to touch any code.
Secret Key
Specify the Secret Key from Kahuna (located in Kahuna’s dashboard’s settings).
Send data to production environment (default sandbox)
Check to send data to production account (default sandbox) once you are ready to pass data to Kahuna’s production namespace
Sender ID / Google API Project Number
If you are using our older mobile library (before v2 iOS or v3 Android) and have packaged Kahuna’s SDK, you can give us the sender ID. The sender ID is also called the project number in your Google API project. Make sure you have created a project by following instructions here, under ‘Enable Personalized Push’
If you have any questions or see anywhere we can improve our documentation, please let us know or kick off a conversation in the Segment Community! | https://segment.com/docs/destinations/kahuna/ | CC-MAIN-2018-30 | en | refinedweb |
to adopting listing standards requiring had purpose of the provision was to encourage high quality financial statements (The press release can be found here.)
The proposal would create new rule 10D-1, which would mandate the new listing standards, and amend Reg S-K to require disclosure of the policy and compliance with the recovery provisions. Companies that did not comply would be subject to delisting. The proposal addressed a number of questions that remained open under Dodd-Frank, and, in the view of the two dissenting commissioners, addressed them improperly.
Under the proposal, the clawback policy would apply to listed companies, including foreign private issuers, smaller reporting companies and emerging growth companies. In addition, the policy would be required to cover all current and former officers – as defined under Section 16 — who received incentive compensation during the three years preceding the date of the required restatement. The clawback policy would need to be filed as an exhibit to the Form 10-K. Compensation would be deemed to have been received in the fiscal period when the particular metric was attained, even if the compensation was actually paid at a later time. A restatement would be deemed to have been “required” upon the earlier of (1) the date the board (or committee) concluded (or reasonably should have concluded) that a restatement was required or (2) the date that a court or regulatory body directed the company to restate its financial statements. “Incentive compensation” would mean any compensation granted, earned or vested based wholly or in part on attainment of accounting metrics used in the financial statements (or derived from those metrics, including non-GAAP financial measures), or based on stock price or total shareholder return (TSR). Incentive compensation would not include salaries, awards that were earned or vested based solely on the passage of time or awarded wholly in the discretion of the board (such as a discretionary bonus) as well as non-equity incentive plan awards earned solely on the basis of satisfying one or more operational measures (e.g., opening a specified number of stores, completion of a project, increase in market share). With two exceptions, companies would be required to recover an amount of incentive-based compensation equal to the excess of the amount that was paid to the officer, in the three years preceding the date on which the company was required to prepare the restatement, over the amount that would have been paid to the officer based on the accurate financial data. No misconduct by the company or fault or responsibility by the officer affected would be required. Where the excess amount is not subject to calculation based on the restated financial statements (e.g., where the metric is stock price or TSR), the recovery amount would be based on reasonable estimates. Companies would be required to recover the excess amounts unless the board determined that the recovery was “impracticable”—meaning that a majority of independent directors had determined that the cost to recover would exceed the amount to be recovered – or, for foreign private issuers, where the company has obtained an opinion of foreign counsel that the recovery was not permitted under pre-existing home country laws. Before determining that recovery was impracticable, the company would need to make a reasonable attempt to recover the incentive-based compensation, document its attempts and provide that documentation to the exchange. To avoid circumvention of the rule, the proposal would prohibit indemnification by the company or payment of premiums by the company on insurance to cover the potential losses to officers.
The proposal would also amend Section 402 of Reg S-K to require certain disclosures where there was either a restatement during that last fiscal year that required a recovery of excess compensation or the existence of outstanding balances owed to the company under the policy. These disclosures would include the date the restatement was required, the estimates in the event stock- or TSR-based metrics were used, the aggregate dollar amount of excess incentive-based compensation attributable to the restatement and the aggregate dollar amount that remained outstanding at the end of the last completed fiscal year, the name of each person from whom the company decided not to pursue recovery, the amounts due from each of those persons, and a brief description of the reason the company decided not to pursue recovery. If amounts of excess compensation were outstanding for more than 180 days, the name of, and amount due from, each person at the end of the company’s last completed fiscal year. The information would be disclosed in proxy statements and Forms 10-K and data-tagged using XBRL.
Exchanges would be required to file their proposed amended listing standards within 90 days after publication of the SEC’s final rule in theFederal Register and listing rules would have to become effective within a year. Listed companies would be required to comply within 60 days after the effective date of the amended exchange rules and to recover all excess incentive-based compensation received on or after the effective date of the new rule that results from attaining a metric based on financial information for any fiscal period ending on or after the effective date of the new SEC rule.
None of the commissioners objected to the principles underlying the Dodd-Frank provision, although both Commissioners Gallagher and Piwowar voiced the criticism that the time spent developing proposals to implement the compensation-related provisions of Dodd-Frank represented a misallocation of SEC resources, particularly since Dodd-Frank did not include a deadline for this provision and the subject matter, in their view, had nothing to do with the financial crisis. Instead, the time would have been better spent on the disclosure review project or reevaluation of the shareholder proposal rules. If this all sounds vaguely familiar, it’s because it is. See this post. But, according to Commissioner Gallagher, the concept that executives should return compensation that was not really earned and that the policy might cause them to try harder to ensure accurate financial statements “made some sense.”
[Sidebar: Notably, Commissioner Gallagher opined that this provision of Dodd-Frank is not nearly as offensive as the pay-ratio provision, which, he said, the press is reporting will happen next month. So stay tuned.]
Nevertheless, he said, “the devil is in the details.” Both commissioners objected strenuously to the SEC’s proposed implementation of the provision. Commissioner Gallagher likened the proposal to a tortured and nightmarish Goya. For his statement, Commissioner Piwowar adopted a Yogi Berra leitmotif: it ain’t over till it’s over, the future ain’t what it used to be, etc. Both commissioners objected to the inclusion of all but the biggest companies under the rule’s ambit. Commissioner Gallagher preferred to experiment with larger companies that could more easily bear the costs and then ease in SRCs and ECGs; Commissioner Piwowar preferred to make compliance voluntary for these smaller companies.
Commissioner Gallagher also objected to use of the broad definition of “officer” as including persons fulfilling policy-making functions, a definition that he argued was not required by the statute. Similarly, he viewed the “no fault” nature of the proposal as likewise improper to infer from the language of statute and argued that the resulting strict liability, together with the broad definition of officer, created an injustice, especially for lower level officers who may have limited ability to influence events. He also had apparently advocated during the rulemaking process a broader relief valve that would have given the board broad discretion to decide not to pursue a recovery or to settle or otherwise pursue lower or alternative recoveries. The “baked-in” disclosure requirements would have acted, he argued, as a disciplining mechanism for the board. However, his alternative was excluded in favor of the narrower prescribed exclusions that, in his view, implied that boards were not to be trusted. In addition, Commissioner Gallagher found fault with the proposal’s inclusion of stock and TSR-based metrics as “incentive compensation.” Primarily, he observed that it was unclear how to calculate the recovery for these metrics and that they required event studies and analyses involving judgments and assumptions that typically produced a range of outcomes. As a result, the board would be inviting second-guessing by plaintiffs. However, he acknowledged that exclusion of these metrics would only a encourage a shift of compensation to the use of TSR, which he views as contributing to short-termism. Ultimately, he had no answer for this conundrum.
Commissioner Piwowar contended that the rule might have the type of unintended consequences that resulted from the adoption of IRC 162(m) — it’s deja vu all over again — in that the uncertainty that would be inherent in the compensation paid would cause executives to demand large increases in their compensation to cover the risk. He also voiced a process complaint because some of the provisions of the rule to which he objected were apparently added late in the process. He also protested the piecemeal adoption of XBRL and questioned whether it might not be better to consider its adoption as a whole.
Chair White contended that the proposal should increase accountability and improve the quality of financial reporting. She recognized that, although the idea of clawbacks is “simple,’ implementation of the statute was complex, and defended the proposal as “a carefully considered approach.” Commissioner Aguilar believed that the new rules were fair and should promote the creation of a “culture of compliance that results in accurate reporting of financial performance.” If executives were permitted to retain compensation based on inflated financial results, the purpose of incentive compensation — to align the interests of management and shareholders – would be undercut and the promised alignment would disappear. He argued that the use of TSR and other stock-based metrics was necessary, given that, as shown in a recent study, 51% of the top 200 companies used TSR-based metrics for their incentive compensation. He agreed with Commissioner Gallagher that excluding TSR would have created a “perverse incentive” for issuers to move executive compensation arrangements into stock- or TSR-based arrangements to avoid the clawback policy, thereby encouraging short-termism. In addition, he essentially disputed the notion that this provision of Dodd-Frank had no relation to the financial crisis, noting that various commissions examining the crisis found that incentive-based compensation promoted a focus on the short-term, which led to higher risk business decisions, and that clawback provisions “could help restore symmetry and a longer-term perspective to executive compensation systems.” Similarly, Commissioner Stein referred to a study showing that, in the financial crisis, long-term shareholders suffered substantial losses as a result of companies’ excessive risk-taking while executives were still able to profit. She argued that Dodd-Frank intended to “realign compensation arrangements and structures to concentrate on long-term performance.” | https://www.lexology.com/library/detail.aspx?g=87c0f480-54ec-4bfa-bca8-a52c010e1316 | CC-MAIN-2018-30 | en | refinedweb |
Java Reference
In-Depth Information
protected , and private ) and any return type. The two dots in the argument list match any number of
arguments.
execution(* com.apress.springenterpriserecipes.calculator.
➥
ArithmeticCalculator.*(..))
You can omit the package name if the target class or interface is located in the same package as
this aspect.
execution(* ArithmeticCalculator.*(..))
The following pointcut expression matches all the public methods declared in the
ArithmeticCalculator interface:
execution( public * ArithmeticCalculator.*(..))
You can also restrict the method return type. For example, the following pointcut matches the
methods that return a double number:
execution(public double ArithmeticCalculator.*(..))
The argument list of the methods can also be restricted. For example, the following pointcut
matches the methods whose first argument is of primitive double type. The two dots then match any
number of followed arguments.
execution(public double ArithmeticCalculator.*( double, ..))
Or, you can specify all the argument types in the method signature for the pointcut to match.
execution(public double ArithmeticCalculator.*( double, double))
Although the AspectJ pointcut language is powerful in matching various join points, sometimes
you might not be able to find any common characteristics (e.g., modifiers, return types, method name
patterns, or arguments) for the methods you want to match. In such cases, you can consider providing a
custom annotation for them. For instance, you can define the following annotation type (this annotation
can be applied to both method level and type level):
package com.apress.springenterpriserecipes.calculator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target( { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoggingRequired {
}
Then you can annotate all methods that require logging with this annotation. Note that the
annotations must be added to the implementation class but not the interface because they will not
be inherited.
Search WWH ::
Custom Search | http://what-when-how.com/Tutorial/topic-105fbg1u/Spring-Enterprise-Recipes-A-Problem-Solution-Approach-76.html | CC-MAIN-2018-30 | en | refinedweb |
Hello to all of you!
Recently i was working on a website for a huge pharmaceutical company and i got my hands on a product feed from one of their suppliers (csv file), with product name, description, price, categories and image link.
So i decided not to use that feed since i already had what i needed in my database, except the product images.
I decided to compile a list of the links and to download them on my hard drive...over 2000 of them.
After spending hours with python scripts that for whatever reasons needed tons of dependencies and wget crashing on my system or having issues with ssl certificates i just made my own, in c++.
The download part was copied from an old topic here on this forum, to save some time.Thanks go to Xander.
I know it may not be perfect, but maybe it can help someone!
The list file looks like this:
Here is the code:
#include <windows.h> #include <WinInet.h> #include <iostream> #include <conio.h> #include <fstream> #include <sstream> #include <vector> #pragma comment (lib, "WinInet.lib") #define WIN32_LEAN_AND_MEAN using namespace std; template<typename... Args> char *beautifulDupcat(const Args ... params) { int bytes = 0; for (auto o : { strlen(params)... }) { bytes += o; } char *ret = new char[bytes + 1]; memset(ret, 0, bytes); for (auto o : { strcat(ret,params)... }) { } return ret; } string getFileName(const string& s) { char sep = '//'; size_t i = s.rfind(sep, s.length()); if (i != string::npos) { return(s.substr(i + 1, s.length() - i)); } return(""); } void main() { char * destFolder = "C:\\Users\\Athenian\\Desktop\\save\\download"; char * linkList = "C:\\Users\\Athenian\\Desktop\\save\\images.txt"; cout << "Link image downloader" << endl; HINTERNET url; HINTERNET open; ifstream file(linkList); string linebuffer; FILE *saved; unsigned long buffer; char name[1000000]; std::vector<std::string> s; open = InternetOpen("ExampleDL", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); while (file && getline(file, linebuffer)) { if (linebuffer.length() == 0)continue; s.push_back(linebuffer); } for (std::vector<std::string>::iterator it = s.begin(); it != s.end(); ++it) { char * cat = beautifulDupcat(destFolder, "\\", getFileName(*it).c_str()); url = InternetOpenUrl(open, it->c_str(), NULL, 0, 0, 0); saved = fopen(cat, "wb"); while (InternetReadFile(url, name, sizeof(name), &buffer) && buffer != 0) { fwrite(name, sizeof(char), buffer, saved); name[buffer] = '\0'; } fclose(saved); } _getch(); }
Athenian out! | http://www.rohitab.com/discuss/topic/44012-c-list-downloader/ | CC-MAIN-2018-30 | en | refinedweb |
tom
The simplest way to get up and running will probably be to use an
sqlite3 database for the tutorial. Edit the
tutorial/settings.py file, and set the default database
"ENGINE" to
"sqlite3", and
"NAME" to
"tmp.db".
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'tmp.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }
We'll also need to add our new
snippets app and the
rest_framework app to
INSTALLED_APPS.
INSTALLED_APPS = ( ... 'rest_framework', 'snippets', )
We also need to wire up the root urlconf, in the
tutorial/urls.py file, to include our snippet app's URLs.
urlpatterns = [ url(r'^', include('snippets.urls')), ]
Okay, we're ready to roll.
Creating a model to work with
For the purposes of this tutorial we're going to start by creating a simple
Snippet model that is used to store code snippets. Go ahead and edit the
snippets app's',)
Don't forget to sync the database for the first time.
python manage.py syncdb django.forms import widgets from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): pk = serializers.Field() # Note: `Field` is an untyped read-only field. title = serializers.CharField(required=False, max_length=100) code = serializers.CharField(widget=widgets.Textarea, max_length=100000) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def restore_object(self, attrs, instance=None): """ Create or update a new snippet instance, given a dictionary of deserialized field values. Note that if we don't define this method, then deserializing data will simply return a dictionary of items. """ if instance: # Update existing instance instance.title = attrs.get('title', instance.title) instance.code = attrs.get('code', instance.code) instance.linenos = attrs.get('linenos', instance.linenos) instance.language = attrs.get('language', instance.language) instance.style = attrs.get('style', instance.style) return instance # Create new instance return Snippet(**attrs)
The first part of the serializer class defines the fields that get serialized/deserialized. The
restore_object method defines how fully fledged instances get created when deserializing data.
Notice that we can also use various attributes that would typically be used on form fields, such as
widget=widgets.Textarea. These can be used to control how the serializer should render when displayed as an HTML # {'pk': # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into Python native datatypes...
# This import will use either `StringIO.StringIO` or `io.BytesIO` # as appropriate, depending on if we're running Python 2 or Python 3. from rest_framework.compat import BytesIO stream = BytesIO(content) data = JSONParser().parse(stream)
...then we restore those native datatypes into to a fully populated object instance.
serializer = SnippetSerializer(data=data) serializer.is_valid() # True serializer.object # # [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u edit the
SnippetSerializer class.
class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style').
We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into
json.
Edit the
snippets/views.py file, and add the following.
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs).conf.urls import patterns, url from snippets import views urlpatterns = [ url(r'^snippets/$', views.snippet_list), url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail), ].4.3, using settings 'tutorial.settings' Development server is running at Quit the server with CONTROL-C.
In another terminal window, we can test the server.
We can get a list of all of the snippets.
curl [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
Or we can get a particular snippet by referencing its id.
curl {. | http://www.tomchristie.com/rest-framework-2-docs/tutorial/1-serialization | CC-MAIN-2018-30 | en | refinedweb |
I am posting a link to the talk I presented at PAKCON III, Pakistan’s Largest Underground Hacking Convention, at Pearl Continental, Karachi, on the evening of 26 July. The talk is titled How Attackers Go Undetected.
Month: July 2007
Uploading files via newforms in Django made easy.
I have already described creating custom fields with Django and shown how easy it can get. Today, I am going to show how to manage file uploading through newforms. I expended a good part of my morning and afternoon today reading up on Django and asking for help in #django on irc.freenode.net. Many thanks to the folks in #django for helping me out.
I will take the aid of code snippets as much as I can to describe the process. That way, you can not only grasp it quickly and place it all in a useful context, but can also use my code and apply it in applications.
First of all, I have Django configured on the development webserver that ships with it. Therefore, in order for Django to serve static contents, such as images, a couple of settings need be taken care of.
I have a directory, ‘static/’, in my root Django project folder in which I keep all the static content to be served. Within settings.py file, it is important to correctly define the MEDIA_ROOT and MEDIA_URL variables to point to that static/ directory. I have the two variables defined thusly:
ayaz@laptop:~$ grep 'MEDIA_' settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static/")
MEDIA_URL = ''
The structure of the static/ directory looks like the following:
ayaz@laptop:~$ ls -l static/
total 20
drwxr-xr-x 3 ayaz ayaz 4096 2007-06-28 15:34 css
drwxr-xr-x 3 ayaz ayaz 4096 2007-07-06 21:51 icons
drwxr-xr-x 3 ayaz ayaz 4096 2007-07-06 21:51 images
drwxr-xr-x 3 ayaz ayaz 4096 2007-07-21 15:57 license
drwxr-xr-x 3 ayaz ayaz 4096 2007-07-21 11:41 pictures
For Django to serve static content, it must be told via pattern(s) in URLconf at which URL path the static content is available. The following are relevant lines from urls.py (note that MEDIA_PATH is defined to point to the same directory as does MEDIA_ROOT in settings.py):
ayaz@laptop:~$ head -5 urls.py
MEDIA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static/")
urlpatterns = patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': MEDIA_PATH, 'show_indexes': True}),
That is all you need to do to enable Django to serve static content. Next up is the Model that I am using here as an example. I have the model DefaulProfile, which has two fields, the last of which is of interest here. The ‘picture’ field, as you can see below, is of type models.ImageField. Note the ‘upload_to’ argument (Consult the Model API for documentation on the various Model Fields and their supported arguments). It points to ‘pictures/’ which will, when Django processes it, be appended to the end of the path saved in MEDIA_ROOT. Also note that the ‘picture’ field is mandatory.
ayaz@laptop:~$ cat models.py
from django.db import models
from django.contrib.admin.models import User
class DefaultProfile(models.Model):
user = models.ForeignKey(User)
picture = models.ImageField("Personal Picture", upload_to="pictures/")
Now, let’s flock on to the views. I have already described the PictureField, so I will skip it.
ayaz@laptop:~$ cat views.py
from django import newforms as forms
from django.contrib.admin.models import User
from myapp.mymodel import DefaultProfile
‘UserForm’ is a small form model class, which describes the only field I am going to use, ‘picture’. Note the widget argument.
class UserForm(forms.Form):
picture = PictureField(label="Personal Picture", widget=forms.FileInput)
From now starts the meat of it all. Note request.FILES. When you are dealing with multipart/form-data in forms (such as in this case where I am trying to accept an image file from the client), the multipart data is stored in the request.FILES dictionary and not in the request.POST dictionary. Note that the picture field data is stored within request.FILES[‘picture’].
The save_picture() function simply retrieves the ‘filename’, checks to see if the multipart data has the right ‘content-type’, and then saves the ‘content’ using a call to the object’s save_picture_file() method (this method is documented here).
def some_view(request):
def save_picture(object):
if request.FILES.has_key('picture'):
filename = request.FILES['picture']['filename']
if not request.FILES['picture']['content-type'].startswith('image'):
return
filename = object.user.username + '__' + filename
object.save_picture_file(filename, request.FILES['picture']['content'])
post_data = request.POST.copy()
post_data.update(request.FILES)
expert_form = UserForm(post_data)
if expert_form.is_valid():
default_profile = DefaultProfile()
save_picture(default_profile)
default_profile.save()
If you look closely, you’ll notice I created a copy of request.POST first, and then updated it with request.FILES (the update() method is bound to dictionary objects and merges the key-value pairs in the dictionary given in its argument with the source dictionary). That’s pretty simple to understand. When an object of UserForm() is created, it is passed as its first argument a dictionary, which is usually request.POST. This actually creates a bound form object, in that the data is bound to the form. So when the method is_valid() is called against a bound form object, Django’s newforms’ validators perform field validation against all the fields in request.POST that are defined in the form definition, and raise ValidationError exception for each field which does not apparently have the right type of data in it. Now, if you remember, the picture field was created to be a mandatory field. If we didn’t merge the request.FILES dictionary with a copy of request.POST, the is_valid() method would have looked into request.POST and found request.POST[‘picture’] to be missing, and therefore, would have issued an error. This is a nasty, subtle bug, that, I’ve to admit, wasted hours trying to figure out — is_valid() is looking for the field ‘picture’ in request.POST when in reality, for multipart form-data forms, the ‘picture’ field is stored within request.FILES, but since request.FILES was never bound to the form object, and instead request.POST was, it would never find ‘picture’. So, when request.FILES and request.POST are merged together, the resultant object has all the required fields, and is_valid() correctly finds them and does not contain, provided there is no errant data in any of the fields.
I sure do hope the explanation is clear enough. Also, do take care the the “form” tag in the corresponding template has the enctype argument defined as “enctype=multipart/form-data”.
Slackware 12
Guys, Slackware 12 is out. Michiel van Wessem has written a neat review of Slackware 12, which is published on The Slack World, thanks to Mikhail Zotov.
3rd blogging anniversary. Three years ago, I wrote my first …
I hadn’t noticed. Today marks the passing of three tiresome years of my blogging epoch. The thought of celebrating, however modestly, the first anniversary had never crossed me, and I ended up shamelessly forgetting about it last year and year before. I may well not have remembered today either, were it not for the unexpected sidelong glance that fell on the post archive list and got stuck at “July 2004”. “July 2004” stood there, staring fiercely back at me, fuming, wanting to kill me if I didn’t notice it. It instantly made my ears stand up.
I am hardly happy over my memory, or at the fleeting nature of which. I suspect I could’ve blogged before July 7, 2004, but I have no proof to support that speculation. The oldest post I have intact dates back to July 7, 2004, which can be read here. It is a funny post. I wrote it to vent out anger and frustration that managed to bile up after the first ever semester project I did back at the University. I was a freshman then. I am a graduate now. Time flies.
In three years, I blogged decently. I maintained a balance between blogging because you love to write and blogging because you want to share information. I also kept my composure. A blog, I learned early, is not a personal diary. Anything you publish on the world wide web, perhaps, being a Security Engineer, it would do justice to say instead, anything you publish on the Internet, even when it is not published but kept seemingly hidden, is not personal. Or, it does not retain that status for long. People tend to write about everything on their blogs, from their likes to dislikes, grudges and crushes over someone, personal problems, depressing issues, joyous moments, et cetera. And it is very tempting to do so, too. But one has to remember that what they write, or more generally, make available on the Internet can be read by anyone at any time and tainted and used for any purposes, even, at times, to libel against the very person who wrote it. It is important to realise the importance and sensitive nature of what you make available on the Internet. In blogging, it is important to strike a balance between personal stuff and stuff that is OK for the public to read.
At odd times in my blogging history, I failed to maintain the balance, letting it fall to one side or the other. And, I regret it. However, all in all, what I’ve written has always been carefully screened by myself prior to getting published, and I’ve always made sure that, when droning on anything personal, I don’t let out too much, and when criticising someone or something, I don’t cross lines I am not supposed to cross.
In retrospect, I wrote about a lot of things. I have 159 posts today, the oldest dating back to July 7, 2004. However, of late, and as a good friend who tells me I inspired him to kick off his blogging career usually screams at me with a frown on his face, “You don’t write for your readers”, I’ve tipped the balance more on to the side of disseminating technical information and news. There are a couple of reasons for that, some of which I myself am not sure of. I am indulged in technical stuff more often than ever, plus with my career kicking off, I have hardly time for anything else. Another important reason, I believe, for my not writing about anything non-technical is abstinence. I am taking a lot of hits on the emotional front in my personal life, and I fear if I blog about it, I would trip over the line and go out and expose a lot of things I shouldn’t expose at all. And, no, I am not drinking, nor smoking, nor taking drugs, nor sleeping with anyone. Abstinence. If I blog, I know I will be tempted to write about it. To vent out. To cry. I avoid it, instead. Whatever little I write, it is purely technical. I regret my readers feel the need to leave the theatre a line too early, but, they’ll have to understand.
Blogging is fun. I love to write, so it have been even more fun. Blogging is a great way to fight writer’s block, too. But, again, you have to maintain a balance in what you write and what you should not write but still do out of temptation. When I look back, I can safely look at times when I badly wanted to lash out on someone, over something, but painfully resisted the urge. It was most important to contain the temptation, not only because it wouldn’t have been a nice thing to do, but also because over the years I’ve attracted a big reader base which includes people who are or may be my employees.
I don’t know what else to write. I am glad to have started blogging three years from now at this day, and I am glad to have kept blogging up till now. My blog alone has helped me in various ways. I am truly thankful.
I might celebrate quietly today. I already feel excited. Thank you very much for reading. :-)
Creating custom fields using Django’s newforms Framework
I simply adore Django’s newforms framework. Creating HTML forms and processing them, both of which, as any web developer would love to tell you with a grimace on their face, are extremely tedious and monotonous tasks, have never been easier with Django.
Part of the reason I like it is that each field in the form can be easily customised further. Take an example of a field in a form I created that accepts a picture. Instead of using one of the built-in fields provided by newforms, I extended newforms.Field, and created a custom PictureField which ensures the file specified has one of a couple of extensions. It raises a validation error otherwise, which automatically gets displayed on the page if the form object is first validated and then loaded into a template.
from django import newforms as forms
Within the form, I use it thusly:
class UserForm(forms.Form):
picture = PictureField(label="Personal Picture", required=False, widget=forms.FileInput)
It is nothing fancy, really, but, at least to me, being Pythonic all the way, it puts the fun back in web development. | https://ayaz.wordpress.com/2007/07/ | CC-MAIN-2018-30 | en | refinedweb |
System.Xml.LinqNamespace
The
System.Xml.Linq namespace exposes objects for creating, reading, and manipulating Xml documents. All objects inherit from
System.Xml.Linq.XObject. Table 28.1 summarizes and describes available objects.
Table 28.1 Objects Available in the
System.Xml.Linq Namespace
You create an Xml document declaring an instance of the
XDocument class:
Dim myDocument As New XDocument
When you have the instance you can add all acceptable objects mentioned in Table 28.1. The first required element is the Xml declaration that can be added as follows and that is mandatory:
myDocument.Declaration = New XDeclaration("1.0", "utf-8", "no") ...
No credit card required | https://www.safaribooksonline.com/library/view/visual-basic-2010/9780672331596/h4_720.html | CC-MAIN-2018-30 | en | refinedweb |
Java Reference
In-Depth Information
<context:exclude-filter
</context:component-scan>
</beans>
Because you have applied include filters to detect all classes whose name contains the word Dao or
Service , the SequenceDaoImpl and SequenceService components can be auto-detected even without a
stereotype annotation.
Naming Detected Components
By default, Spring will name the detected components by lowercasing the first character of the non-
qualified class name. For example, the SequenceService class will be named as sequenceService . You can
define the name for a component explicitly by specifying it in the stereotype annotation's value.
package com.apress.springenterpriserecipes.sequence;
...
import org.springframework.stereotype.Service;
@Service(" sequenceService")
public class SequenceService {
...
}
package com.apress.springenterpriserecipes.sequence;
import org.springframework.stereotype.Repository;
@Repository(" sequenceDao")
public class SequenceDaoImpl implements SequenceDao {
...
}
You can develop your own naming strategy by implementing the BeanNameGenerator interface and
specifying it in the name-generator attribute of the <context:component-scan> element.
1-6. Setting Bean Scopes
Problem
When you declare a bean in the configuration file, you are actually defining a template for bean creation,
not an actual bean instance. When a bean is requested by the getBean() method or a reference from
other beans, Spring will decide which bean instance should be returned according to the bean scope.
Sometimes you have to set an appropriate scope for a bean other than the default scope.
Search WWH ::
Custom Search | http://what-when-how.com/Tutorial/topic-105fbg1u/Spring-Enterprise-Recipes-A-Problem-Solution-Approach-52.html | CC-MAIN-2018-30 | en | refinedweb |
For the complete thread that led to this post, see the entire thread in the XML forum on ASP.NET.
I have played around with the Page.ParseControls method to add dynamically created controls to the page processing model before, but only really playing around. I never tried to fire a server-side event for a dynamically created control. I really haven’t found a great use for this technique, but I guess others have as I see a lot of posts on it in newsgroups.
I thought that adding server events should be simple enough: just add the OnServerClick attribute to the HTML, and you should be golden:
System.Web.UI.Control button = Page.ParseControl(“<input id=\”IDAHFUX\” name=\”IDAHFUX\” value=\”Click me!\” style=\”Z-INDEX:102;POSITION: absolute;TOP: 40px;LEFT: 10px\” type=\”button\” runat=\”server\”> OnServerClick=\”Button_Click\””);
Page.FindControl(“WebForm1”).Controls.Add(button);
System.Web.UI.Control button = Page.ParseControl(“<input id=\”IDAHFUX\” name=\”IDAHFUX\” value=\”Click me!\” style=\”Z-INDEX:102;POSITION: absolute;TOP: 40px;LEFT: 10px\” type=\”button\” runat=\”server\”> OnServerClick=\”Button_Click\””);
What I found was that the OnServerClick method is not used to generate the postback handling, instead it is rendered to the client. The client has no idea what “onserverclick” is, so nothing happens and the server-side Button_Click event never fires. So, you have to set the event delegate yourself. That should be simple enough, so I decided to use XSLT to generate the controls.
The XML document I used is very simple:
<root>
<foo/>
<foo/>
<foo/>
</root>
The XSLT to generate the controls is also pretty simple. The only 2 weird things might be the use of attribute value templates (AVT’s), noted by the “{ }” and the generate-id function. I could have used a bunch of xsl:attribute tags to create the attributes, but AVT’s are quite a bit shorter. The generate-id function is used to create a unique ID for each control (a requirement of ASP.NET), and 2 successive calls to generate-id for the same node context will return the same value. That means the value in the ID and NAME attributes will be identical for each distinct node in the result tree. I also used the node’s position to manipulate both the TOP and Z-INDEX attributes of the control.
<?xml version=”1.0″?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”“>
<xsl:output method=”html” version=”1.0″ />
<xsl:template match=”/root/foo”>
<input id=”{generate-id()}” name=”{generate-id()}” value=”Click me!” style=”Z-INDEX:{101 + position()};POSITION: absolute;TOP: {position() * 40}px;LEFT: 10px” type=”button” OnServerClick=”Button_Click” runat=”server”/>
</xsl:template>
</xsl:stylesheet>
There are a couple gotchas with the code. The first is using a foreach to enumerate over the parsedControl.Controls collection. If you replace the for loop with a foreach loop, you will receive an error that the collection has changed. This is because we are setting an eventhandler for items contained in the collection, causing the error. That explains the for loop instead of a foreach enumerator. The second non-obvious thing in the code is that you might try to optimize the page processing by checking IsPostBack. However, the controls will not be automatically added into the Page’s Controls collection so the loop has to be performed each time the page is loaded.
<%@ Page language=”c#”%>
<%@Import namespace=”System.Xml”%>
<%@Import namespace=”System.Xml.XPath”%>
<%@Import namespace=”System.Xml.Xsl”%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” >
<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<script language=C# runat=server>
private void Page_Load(object sender, System.EventArgs e)
{
XPathDocument doc = new XPathDocument(Server.MapPath(“xmlfile1.xml”));
XslTransform trans = new XslTransform();
trans.Load(Server.MapPath(“xsltfile1.xslt”));
System.IO.StringWriter writer = new System.IO.StringWriter();
trans.Transform(doc,null,writer);
writer.Flush();
System.Text.StringBuilder sb = writer.GetStringBuilder();
System.Web.UI.Control parsedControl = Page.ParseControl(sb.ToString());
HtmlForm form = (HtmlForm)Page.FindControl(“WebForm1”);
for (int i=0;i< parsedControl.Controls.Count;i++)
{
HtmlInputButton button = parsedControl.Controls[i] as HtmlInputButton;
if(null != button)
{
button.ServerClick += new System.EventHandler(this.Button_Click);
form.Controls.Add(button);
}
}
}
public void Button_Click(object sender, System.EventArgs e)
{
this.Label1.Text = “Button clicked at ” + System.DateTime.Now.ToLongTimeString();
}
</script>
<body MS_POSITIONING=”GridLayout”>
<form id=”WebForm1″ method=”post” runat=”server”>
<asp:Label id=”Label1″ style=”Z-INDEX: 101; LEFT: 444px; POSITION: absolute; TOP: 77px” runat=”server” Width=”497px”>Label</asp:Label>
</form>
</body>
</HTML>
By the way – I could have used code-behind for the Page_Load and Button_Click events, there is nothing special about this syntax. I chose this format for brevity.
<Kirk/>
Join the conversationAdd Comment
Is there solution for dynamic including User Control instead Web controls?
ParseControl can parse user control, but you have to include relevant @Register directive with the markup to be parsed.
This was very nice to read. I was interested in this because I just started a new position where the app has been designed like ibuyspy, using user controls dynamically added to screens. We have a default.aspx page, where all pages are created in, dynamically on the fly based on menu selections. I’m realy not sure how good an idea this is. One issue we have is that the ispostback is not able to be used inside the user controls as it appears that it is always a post back. I was thinking that we could handle an event, that the main page would fire, on ispost back, an if each user control handled that event, we could get that type of processing to work. Thanks for you ideas and posting. It was very helpful to see this processing.
Hi, How to generate the User Control dynamically in ASP.NET.
Thank you, I’ve been looking all over for the solution to adding event handlers for XSL/XML dynamic pages and you had the answer (more or less). Thanks a bunch!
The only difference is I’m calling my methods from OnInit() instead of Page_load. Additionally, I’m skipped the ParseControl section and went directly after the specific controls I need to add events for – using FindControl("cntlName") (i.e. Submit, ClearForm, etc..) | https://blogs.msdn.microsoft.com/kaevans/2003/02/22/dynamically-adding-web-controls-and-adding-event-delegates/ | CC-MAIN-2016-30 | en | refinedweb |
I recently received
this C# code snippet from a customer (my question follows):
//remove all instances of label “bad label” in the versions collection objVSSVersion
foreach(IVSSVersion
objVssVersion in myVssItem.get_Versions(0))
{
if (objVssVersion.Label == “Bad Label”)
objVssVersion.VSSItem.Label(“”,””);
}
Upon running
this code, the customer sees one of two errors:
· “A
history operation is already in progress”
· “File
VSSSERVERPATH\data\s\sfvaaaaa is already open”
Conundrum
There
appears to be another VSSVersions object instantiated. At present, you can have
only one at a time.
To work
around this limitation, we have to figure out how to finalize the existing object,
right? I have some idea about how to do this but would like to hear your thoughts.
How does one do this? Is it even possible in C#?
Have you
run into this problem with an IVSS… object before? If so, what was your workaround.
Related
Posts and Resources
++++++++++++++++++++++.
If it’s in the same process and it’s releasing the COM object you’re after I suggest using System.Runtime.InteropServices.Marshal.ReleaseComObject(objVssVersion) as the last line in the foreach. Ofcourse, I might be off beat on this one.
I’m not sure about releasing the COM object. I’ll have to try that.
I know this is a very sad solution, but here is what I found to work… (if there is a bettter way, please let me know.)
You have to loop through the entire iterator.
basically something like this:
IVSSItem badItem;
foreach(IVSSVersion objVssVersion in myVssItem.get_Versions(0))
{
if (objVssVersion.Label == "Bad Label")
badItem = objVssVersion.VSSItem;
}
//Now that the iterator is closed, you can label something.
badItem.Label("", "");
Good luck!!!
ReleaseCOMObject() was my initial guess but I haven’t gotten it to work….
Thanks for the workaround, Don. I’ll go try it now.
Craig Skibo dives into an explanation of this issue in his blog today (Reference counting, garbage collection, and zombies, oh my! [1]). Thanks Craig! Can we infer that it is possible to work around this IVSS limitation in C++ but not in C#? If so, does it have to be unmanaged C++ to work?
[1]
I’ve run into the same issue and agree with the analysis that a COM reference isn’t being freed unless foreach is allow to iterate through the entire collection. Looks like something undocumented is happening in the final iteration when MoveNext() returns false.
I couldn’t find a way to avoid iterating through the entire collection, but to reduce the amount of actual being done during iteration, I’ve used the following workaround:
using System.Collections;
…
String findLabel = "find me";
vssVersion = vssItem.get_Versions(…)
IEnumerator it = versions.GetEnumerator();
for (it.Reset(); it.MoveNext(); )
{
IVSSVersion version = it.Current as IVSSVersion;
if (version != null) {
String label = version.Label;
if (label == findLabel) {
while (it.MoveNext()) {};
}
}
} | https://blogs.msdn.microsoft.com/korbyp/2003/10/06/ivss-state-management-conundrum/ | CC-MAIN-2016-30 | en | refinedweb |
On one of our internal discussion aliases, someone asked why do we need a plus (+) the class name for FTP?
Typically, you would expect this to work [Net.WebRequestMethods.Ftp], but it doesn’t. The solution is [Net.WebRequestMethods+Ftp] and it has something to do with nested classes
In C#, a nested class looks something like
public class List
{
public class Node // Node is inside List
{
// Node stuff
}
// List stuff…
}
Usually, nested classes are used only by its container. In fact, its a design guideline to keep the nested class private
From – .NET Framework Developer’s Guide, Nested Types ()
• Avoid publicly exposed nested types. The only exception to this is when variables of the nested type need to be declared in rare scenarios such as subclassing or other advanced customization scenarios.
• Do not use nested types if the type is likely to be referenced outside of the declaring type.
So public/useful nested classes are rare, but some people will bump into them. Where does the plus sign come from?
The plus sign comes from .NET Reflection. If you do [Net.WebRequestMethods+Ftp].FullName you will see that fullname is “System.Net.WebRequestMethods+Ftp”
MSDN Documentation on Type.GetMethod has a fairly indepth discussion on the plus and other symbols
It says,
To Get : A parent class and a nested class
Use : Type.GetType(“MyParentClass+MyNestedClass”)
PowerShell is using .NET under the covers, .NET Reflection to be exact. We don’t want to redocument the .NET Type system, but in times where it causes confusion for PowerShell users, we’ll try to clarify things
.Net speed bumps,
Ibrahim Abdul Rahim [MSFT]
Join the conversationAdd Comment
I just ran into this issue. I wanted to get the value of a shell "Special Folder" The enum type is a nested type. Dot wasn’t working for me. Knowing reflection I guessed the plus.
I ran into another example of just this issue (see).
Thanks for explaining why the Plus sign is needed. | https://blogs.msdn.microsoft.com/powershell/2009/08/26/plus-in-net-class-names/ | CC-MAIN-2016-30 | en | refinedweb |
On Tue, Mar 13, 2012 at 9:10 AM, Vivek Goyal <vgoyal@redhat.com> wrote:> On Mon, Mar 12, 2012 at 04:04:16PM -0700, Tejun Heo wrote:>> On Mon, Mar 12, 2012 at 11:44:01PM +0100,.>>>> Yeah, the great pain of full hierarchy support is one of the reasons>> why I keep thinking about supporting mapping to flat hierarchy. Full>> hierarchy could be too painful and not useful enough for some>> controllers. Then again, cpu and memcg already have it and according>> to Vivek blkcg also had a proposed implementation, so maybe it's okay.>> Let's see.>> Implementing hierarchy is a pain and is expensive at run time. Supporting> flat structure will provide path for smooth transition.>> We had some RFC patches for blkcg hierarchy and that made things even more> complicated and we might not gain much. So why to complicate the code> until and unless we have a good use case.how about ditching the idea of an FS altogether?the `mkdir` creates and nests has always felt awkward to me. maybeinstead we flatten everything out, and bind to the process tree, butenable a tag-like system to "mark" processes, and attach meaning tothem. akin to marking+processing packets (netfilter), or maybe likesysfs tags(?).maybe a trivial example, but bear with me here ... other controllersare bound to a `name` controller ...# my pid?$ echo $$123# what controllers are available for this process?$ cat /proc/self/tags/TYPE# create a new `name` base controller$ touch /proc/self/tags/admin# create a new `name` base controller$ touch /proc/self/tags/users# begin tracking cpu shares at some default level$ touch /proc/self/tags/admin.cpuacct.cpu.shares# explicit assign `admin` 150 shares$ echo 150 > /proc/self/tags/admin.cpuacct.cpu.shares# explicit assign `users` 50 shares$ echo 50 > /proc/self/tags/admin.cpuacct.cpu.shares# tag will propogate to children$ echo 1 > /proc/self/tags/admin.cpuacct.cpu.PERSISTENT# `name`'s priority relative to sibling `name` groups (like shares)$ echo 100 > /proc/self/tags/admin.cpuacct.cpu.PRIORITY# `name`'s priority relative to sibling `name` groups (like shares)$ echo 100 > /proc/self/tags/admin.cpuacct.cpu.PRIORITY[... system ...]# what controllers are available system-wide?$ cat /sys/fs/cgroup/TYPEcpuacct = monitor resourcesmemory = monitor memoryblkio = io stuffs[...]# what knobs are available?$ cat /sys/fs/cgroup/cpuacct.TYPEshares = relative assignment of resourcesstat = some stats[...]# how many total shares requested (system)$ cat /sys/fs/cgroup/cpuacct.cpu.shares200# how many total shares requested (admin)$ cat /sys/fs/cgroup/admin.cpuacct.cpu.shares150# how many total shares requested (users)$ cat /sys/fs/cgroup/users.cpuacct.cpu.shares50# *all* processes$ cat /sys/fs/cgroup/TASKS1123[...]# which processes have `admin` tag?$ cat /sys/fs/cgroup/cpuacct/admin.TASKS123# which processes have `users` tag?$ cat /sys/fs/cgroup/cpuacct/users.TASKS123# link to pid$ readlink -f /sys/fs/cgroup/cpuacct/users.TASKS.123/proc/123# which user owns `users` tag?$ cat /sys/fs/cgroup/cpuacct/users.UID1000# default mode for `user` controls?$ cat /sys/fs/cgroup/users.MODE0664# default mode for `user` cpuacct controls?$ cat /sys/fs/cgroup/users.cpuacct.MODE0600# mask some controllers to `users` tag?$ echo -e "cpuacct\nmemory" > /sys/fs/cgroup/users.MASK# ... did the above work? (look at last call to TYPE above)$ cat /sys/fs/cgroup/users.TYPEblkio[...]# assign a whitelist instead$ echo -e "cpu\nmemory" > /sys/fs/cgroup/users.TYPE# mask some knobs to `users` tag$ echo -e "shares" > /sys/fs/cgroup/users.cpuacct.MASK# ... did the above work?$ cat /sys/fs/cgroup/users.cpuacct.TYPEstat = some stats[...]... in this way there is still a sort of heirarchy, but eachcontroller is free to choose:) if there is any meaning to multiple `names` per process) ... or if one one should be allowed) how to combine laterally) how to combine descendents) ... maybe even assignable strategies!) controller semantics independent of other controllerswhen a new pid namespace is created, the `tags` dir is "cleared out"and that person can assign new values (or maybe a directory is createdin `tags`?). the effective value is the union of both, and identicalto whatever the process would have had *without* a namespace (nodifference, on visibility).thus, cgroupfs becomes a simple mount that has aggregate stats andsystem-wide settings.recap:) bound to process heirarchy) ... but control space is flat) does not force every controller to use same paradigm (eg, "you mustbehave like a directory tree")) ... but orthogonal multiplexing of a controller is possible if thecontroller allows it) allows same permission-based ACL) easy to see all controls affect a process or `name` group with asimple `ls -l`) additional possibilities that didn't exist with directory/arbitrarymounts paradigmdoes this make sense? makes much more to me at least, and i thinkallow greater flexibility with less complexity (if my experience withFUSE is any indication) ...... or is this the same wolf in sheep's skin?-- C Anthony--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2012/3/13/419 | CC-MAIN-2016-30 | en | refinedweb |
Hi Ingo,As you probably know, we've been chasing a variety of performance issueson our SLE11 kernel, and one of the suspects has been CFS for quite awhile. The benchmarks that pointed to CFS include AIM7, dbench, and a fewothers, but the picture has been a bit hazy as to what is really the problem here.Now IBM recently told us they had played around with some schedulertunables and found that by turning off NEW_FAIR_SCHEDULERS, theycould make the regression on a compute benchmark go away completely.We're currently working on rerunning other benchmarks with NEW_FAIR_SLEEPERSturned off to see whether it has an impact on these as well.Of course, the first question we asked ourselves was, how can NEW_FAIR_SLEEPERSaffect a benchmark that rarely sleeps, or not at all?The answer was, it's not affecting the benchmark processes, but some noisegoing on in the background. When I was first able to reproduce this on my workstation, it was knotify4 running in the background - using hardly any CPU, butgetting woken up ~1000 times a second. Don't ask me what it's doing :-)So I sat down and reproduced this; the most recent iteration of the test programis courtesy of Andreas Gruenbacher (see below).This program spawns a number of processes that just spin in a loop. It also spawnsa single process that wakes up 1000 times a second. Every second, it computes theaverage time slice per process (utime / number of involuntary context switches),and prints out the overall average time slice and average utime.While running this program, you can conveniently enable or disable fair sleepers.When I do this on my test machine (no desktop in the background this time :-)I see this:./slice 16 avg slice: 1.12 utime: 216263.187500 avg slice: 0.25 utime: 125507.687500 avg slice: 0.31 utime: 125257.937500 avg slice: 0.31 utime: 125507.812500 avg slice: 0.12 utime: 124507.875000 avg slice: 0.38 utime: 124757.687500 avg slice: 0.31 utime: 125508.000000 avg slice: 0.44 utime: 125757.750000 avg slice: 2.00 utime: 128258.000000 ------ here I turned off new_fair_sleepers ---- avg slice: 10.25 utime: 137008.500000 avg slice: 9.31 utime: 139008.875000 avg slice: 10.50 utime: 141508.687500 avg slice: 9.44 utime: 139258.750000 avg slice: 10.31 utime: 140008.687500 avg slice: 9.19 utime: 139008.625000 avg slice: 10.00 utime: 137258.625000 avg slice: 10.06 utime: 135258.562500 avg slice: 9.62 utime: 138758.562500As you can see, the average time slice is *extremely* low with new fairsleepers enabled. Turning it off, we get ~10ms time slices, and aperformance that is roughly 10% higher. It looks like this kind of"silly time slice syndrome" is what is really eating performance here.After staring at place_entity for a while, and by watching the process'vruntime for a while, I think what's happening is this.With fair sleepers turned off, a process that just got woken up willget the vruntime of the process that's leftmost in the rbtree, and willthus be placed to the right of the current task.However, with fair_sleepers enabled, a newly woken up processwill retain its old vruntime as long as it's less than sched_latencyin the past, and thus it will be placed to the very left in the rbtree.Since a task that is mostly sleeping will never accrue vruntime atthe same rate a cpu-bound task does, it will always preempt anyrunning task almost immediately after it's scheduled.Does this make sense?Any insight you can offer here is greatly appreciated!Thanks,Olaf-- Neo didn't bring down the Matrix. SOA did. --soafacts.com/* * from agruen - 2009 05 28 * * Test time slices given to each process */#include <sys/time.h>#include <sys/resource.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <sys/stat.h>#include <signal.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>#undef WITH_PER_PROCESS_SLICESstruct msg { long mtype; long nivcsw; long utime;};int msqid;void report_to_parent(int dummy) { static long old_nivcsw, old_utime; long utime; struct rusage usage; struct msg msg; getrusage(RUSAGE_SELF, &usage); utime = usage.ru_utime.tv_sec * 1000000 + usage.ru_utime.tv_usec; msg.mtype = 1; msg.nivcsw = usage.ru_nivcsw - old_nivcsw; msg.utime = utime - old_utime; msgsnd(msqid, &msg, sizeof(msg) - sizeof(long), 0); old_nivcsw = usage.ru_nivcsw; old_utime = utime;}void worker(void) { struct sigaction sa; sa.sa_handler = report_to_parent; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGALRM, &sa, NULL); while (1) /* do nothing */ ;}void sleeper(void) { while (1) { usleep(1000); }}int main(int argc, char *argv[]){ int n, nproc; pid_t *pid; if (argc != 2) { fprintf(stderr, "Usage: %s <number-of-processes>\n", argv[0]); return 1; } msqid = msgget(IPC_PRIVATE, S_IRUSR | S_IWUSR); nproc = atoi(argv[1]); pid = malloc(nproc * sizeof(pid_t)); for (n = 0; n < nproc; n++) { pid[n] = fork(); if (pid[n] == 0) worker(); } /* Fork sleeper(s) */ for (n = 0; n < (nproc + 7)/8; n++) if (fork() == 0) sleeper(); for(;;) { long avg_slice = 0, avg_utime = 0; sleep(1); for (n = 0; n < nproc; n++) kill(pid[n], SIGALRM); for (n = 0; n < nproc; n++) { struct msg msg; double slice; msgrcv(msqid, &msg, sizeof(msg) - sizeof(long), 0, 0); slice = 0.001 * msg.utime / (msg.nivcsw ? msg.nivcsw : 1);#ifdef WITH_PER_PROCESS_SLICES printf("%6.1f ", slice);#endif avg_slice += slice; avg_utime += msg.utime; } printf(" avg slice: %5.2f utime: %f", (double) avg_slice / nproc, (double) avg_utime / nproc); printf("\n"); } return 0;} | http://lkml.org/lkml/2009/5/28/219 | CC-MAIN-2016-30 | en | refinedweb |
What kind of exception below Java program will throw?
class Test{
int i=10;
public void disp(){
System.out.println("i val is.."+i);
}
}
public class ExceptionDemo {
public static void main(String[] args) {
Test t=null;
t.disp();
}
}
It will not throw any exception, but it may give compile time error.
It will throw NullPointerException, which is a checked exception.
It will throw, NullPointerException, which is an un-checked exception.
it will print i val is..10
Here Test t=null; and we are trying to access t.disp() which is potentially doing null.disp() which will throw NullPointerException, and this is an un-checked exception, which we have to debug and fix rather than handling it by try-catch block.
Back To Top | http://skillgun.com/question/3014/java/exceptions/what-kind-of-exception-below-java-program-will-throw-class-test-int-i10-public-void-disp-systemoutprintlni-val-isi-public-class-exceptiondemo-public-static-void-mainstring-args-test-tnull-tdisp | CC-MAIN-2016-30 | en | refinedweb |
See also: IRC log
<trackbot> Date: 10 June 2009
<Ashok> scribe: Ashok Malhotra
<Ashok> scribenick: Ashok
Starting on Wednesday June 10, 2009
Resuming yesterday.s meeting
Bob: I sent out a mail about 'mode'
<Bob> my mail this am
Bob: I tried to define what were called 'problems' yesterday
First, compositipn on 'mode' ... it is done as an attribute
scribe: extensions were suggested
... proposal is that extensions could be named as QNames
Bob: Do we agree that this is a way forward?
No disagreement
Bob: So we agree that a list of QNames would be a way to handle composability
Second problem is scope of the extensions
scribe: extensions apply to parent and children of element
Asir: So, in general, put extension where it belongs
Bob: ... as child of the thing it extends
Geoff: I'm concerned about this ...
re.DeliveryMode
... you will agrue that all extensions go in NotifyTo or Subscribe and we don't need DeliveryMode
Bob: In aggregate the delivery mode you get is the result of the composition
<dug> <GB:Frog/>
Bob: that's the mode
Geoff: disagrees
... I accept that "we shd put things where they belong"
... I'm worried about the second-last problem
Bob: Let's wait till we get there
... Third, mode-not-supported fault ... what do we do abt that
... also the usecase 'I want to create a subcription only if all extensions are there"
... so I created boolean called 'strict' which says only create subscription if all extensions supported
Asir: I not sure all features you are
trying to realize are useful
... you are trying to tighten the faulting mechanism
Bob: Sorta like mustUnderstand
Gil: Strict does not allow you to say these extensions are vital and these are optional
Ashok: Policy can be used to say what's required and what's optional
Geoff: There is the fault business that returns all this stuff ... we need fault to say that a delivery mode is not supported
Bob: We agree that we want a fault
that the delivery mode cannot be supported
... we also agree there may be a usecase where a portion of the delivery mode is supported and that's acceptable
Asir: Differentiate between not understood and not accepted
Bob: You could use mustUnderstand faults in addition
Geoff: There is a concept of delivery
and a fault that say I did not agree with how you want it
delivered
... if we have lot's of delivery modes we must also have lot's of faults
... I did not understand how you wanted me to deliver stuff
Bob: We agree we need fault-tightening behaviour which also deals with composition problem
Wu: We want default of delivery mode as in the current spec
Tom: I'm trying to grasp the
requirements
... I hearing strong attachment to this concept called "delivery"
... I want a fault that gives you the info yiu want
... Does not matter if it not called delivery
Dug: All will agree with fault that
says 'I cannot meet yiur needs"
... but what is a dlivery need and what is a subscription need
c/dlivery/delivery/
scribe: why do you want a fault that
says 'cannot meet delivery needs' and not just cannot meet your
needs
... delivery need vs. subscription need
Dug: Do not classify faults .. we need we need a fault
Asir: Agree we ned to tighten faulting mechanism. We can define detailed faults later.
Bob: We also need to talk abt
contents subscribe/response
... need to specify waht you got
... Let's talk abt Delivery Mode
... may be affected by more than one extension
Bob draws Subscribe box with NotifyTo and EndTo children
Bob: The concept of delivering stuff is NotifyTo + extensions plus other extensions that affect delivery (Delivery Concept)
Dug: Filter can also be part of delivery mode
Bob: Is EndTo part of delivery mode
Dug: If you cannot tell me why subscription ended prematurely that part of delivery mode
Bob: Delivery concept is everything subscription mgr must know to fulfill its contract with you
Tom: Delivey is in the eyes of the beholder
Asir: 2 cycles ... subscribe then response and end subscription and response
Wu: Separate delivery from subscription
Gil: Trying to classify extension as delivery extension or subscription extension is not useful
<Wu> We can view WS-E with three semantics components: Event subscription, Event Generator and Delivery engine
Dug: Suppose we kept the
<delivery> element and decided that <frog> was a
delivery extension
... now we put <frog> outside delivery ... waht what happen ... would system fall apart
Asir: Folks said WS-MAN put in extensions here that there, we need better guidelines
Dug: We have extension points and can put extensions in different places
Bob draws generic diagram of event source
scribe: six boxes all involved in my
delivery
... do we need wrapper around extensions to each of the six bozes?
... Should it be possible to put an extsion at the subscribe level and affect everything?
Dug: Yes
Wu: Need to provide structure and
people add etensions in a strctured manner
... I like current spec. Each element has an extension point
Bob: Are talking abt delivery element
Dug: I diagree that elements inside
map to implementation bits
... need to tell what each extension applies to ... so put in appropriate element
Gil: We only talk abt EPR to EPR communication ... not abt implementation structure
Geoff: But we talk abt event source
and a subscription manager in spec. So we separate them
... 2 separate concepts
Bob: EndTo is not related to
delivery
... is there anything abt delivery concept not inherenetly connected to NotifyTo?
... is there any need to have an element associated with concept of delivery?
... NotifyTo EPR is essential
You specify 'push', 'push-with-acks' in the NotiFyTo EPR
Asir: Today PUSH is built into the
spec as default
... if something is specified then that's the delivery mode
... today you can ignore evrything other than the address of the EPR
... If we say delivery mode needs to be inferred we need to say whare it is inferred from
... today if you say mode='something' then you must understand the mode
Bob: Anything in the scope affects
its parent
... somesubset of the element you want to call a Delivery Concept
Asir: Delivery and NotifyTo
Geoff: Default is the 'push' mode. If we delete mode there is no way to say that
Bob shows how to do that ... put PUSH as final child of Subscribe
scribe: Format and Filter are
separate elements
... I don't think Delivery element it dangerous. May not be necessary
... Mode is dangerous
Gil questions need for delivery element
Dug: Cannot classify extensions
... is Format a Delivery extension or a Subscription extension
Asir: It's an implementation problem
Gil: Supports Dug
... cannot classify extensions ... distinction does not affect anything
Bob: Asks if the delivery wrapper elemnt is removed is that a lie-down-in-road issue?
Wu: Yes
Geoff: Yes
Bob: If delivery element is not removed is that a lie-down-in-road issue?
Dug, Gil, Tom: Yes
Mark: Yes
Asir: Maybe we shd focus on delivery element some more to try and get consensus
Geoff: Where shd people send slides
Bob: To the public list
<asir> His name is Hemal Shah
That's the speaker coming up
Josh_Cohen: In 2003 customers meet
with hardware vendores and asked for facilities to manage hardware
independent of specific hardware
... DMTF took on this challenge with SMASH and DASH
... Intial feeling was Web Services stack was too heavy
... We now have 3 specs with Web Services profiles and features
Hemal: I work for Broadcom
... I started with WS-MAN in 2005
... folks were sceptical because spec was heavyweight and resources limited
<dug> Prasad:
Hemal: Start with WS-Eventing issue
on removing 'mode'
... We are using 'mode'. We have defined several modes in WS-MAN
... If you remove mode you lose function which is in many implementations
Bob: As a single attribute is not
composable
... proposal to replace mode with a set of QNames so they cam be composed
... you look for an extension QName
... there would be a set of elements rather than one attribute
Josh: Are there other elements also? Asks scope question
Bob: The scope of extension is the
parent and its children
... the faulting behaviour needs to be tightened up
... it is optional so not reliable
... has unbounded list of elements and namespaces
... need to generate fault saying waht cannot be honored
... Folks divided in whether we need a delivery element and what shd be in it
... We have not decided on categories, whether we need them, what they are?
Hemal: We have implementations. If the info is in another element it will break the implementations.
Bob: Other changes we have agreed on will break wire protocols
Hemal: Keep the mode and also provide other facilities and allow both mechanisms
Bob: Mode as it is currently
non-composable
... you would add elements e.g. Push-with-acks
Jeff: You will have to change becuse namespace will change and there will be other changes
s/beuse/because/
scribe: we shd shift to how to
migrate
... you could map extensions to modes
<asir> we should not worry about namespace name changes because wire compat is not a requirement .. feature-wise backward compat is a requirement
Gil: Extensibility model in WS-Eventing has change. Now ignore what you don't recognize not fault
Bob: We have moved <format> out and moved it higher up
Hemal: What possible extensions?
Gil: Relaible messaging or security
for example
... argues composability requirements
Asir: We shd not talk abt security and reliability as extensions
Bob: Cannot anticipate extensions
... also need to be flexible abt scale of implementations
Hemal: If you add RM, and security that's not WS-Eventing.
Bob: We need to support composability
Hemal: People can extend values of mode attribute
Bob: E.g. push-with-acks is defined
as specific URI value that can be used as value of mode.
... equivalent is a push-with-acks element. This could combine with other features such as queue management
Wu: You several good points. We are still discussing.
Hemal: My concern is removal of
'mode'
... if you remove it I worry about existing implementations and transition path
Asir: Keep RM and Security out of mode discussion. They are different.
Bob: Disagrees
Jeff: Mode does not compose and MS has been pushing 'composable specifications'
Bob: I would like to hear all of Hemal's concerns
Jeff: We are trying to ensure reasonable clean migration path but we don't have an absolute requirement to have backwards compatibility
Tom: The mode that has been defined
is 'push'
... WS-Man has added others and they can define 'push-with-ack'
Hemal: Next point 6413 - T/RT
merge
... didn't completely understand proposal. Is it trying combine Enum functionality
Bob: Current proposal is to move
frgment support from RT and make that an optional party of T or
possibly a separate spec.
... or possibly another form of fragment support
... still open on details
... no agreement yet
Hemal: Fragment level transfer poses
signifact challenges in resource constrained envvironment
... more we can deal with this in headers the better
Bob: If frag level transfer is presented as a feature with a mustUnderstand type feature that would work for you?
Hemal: We can gennerate a fault
Bob: We are propsing it as an optional feature
Heaml: Is it going in body or header?
Dug: Currently in body but being worked on
Bob: You want to be able figure with minimal processing if you don't support it
Asir: We say it is optional but current proposal is not optional. We have raised an issue against the current proposal.
Moving to 6724
Geoff: Subscribe as a Resource
Hemal: You can get to instances once you have subscribe.
Bob: We will not remove GetStatus and Renew. Those are off the table
Dug: Eveting spec defines minimum function. Implementaions can extend
This would allow you get full properties of the subscription and even update subscription properties
Hemal: For the SIM case this will not provide any more information
Dug: Are you talking abt enumeration
instances?
... this allows you reterive subscription properties. GET may not give you back what you need.
Bob: Has SIM extended Transfer to get
this info
... what spec defines represenation of the subscription
Josh: With any SIM class you can manipulate subscription info
Bob: There is no conflict with that.
Josh: We want to make sure it is aligned with SIM or CIM can be put in it
Dug: I think we are talking abt something different. Please send mail so we don't lose your idea of possible conflict
Josh: We can followup with emal.
Bob: Someone shd open an issue. Very interested in follwing up with you.
END OF MORNING SESSION. BREAKING TILL 1PM PACIFIC
<Bob> link to Josh's slides
<Bob>
<PrasadY> scribe PrasadY
<PrasadY> scribeNick PrasadY
<PrasadY> Starting the afternnon session
<Bob> scribenick: PrasadY
<Bob> scribe: Prasad Yendluri
Bob: Doug sent his write up on 6712 to the list
<Bob>
Bob: That was the proposed resoloution to Issue 6712
[Body]/wst:Create@ContentDescription
Ashok: Why not call the "implied" value "default" value
Dug: I have seen both used but, ok
Geoff: What does the default/implied value mean?
Bob: As stated there is no way not to have a value
Agreement - Change the last sentence to say "no default value"
Asir: "Corretly" in 1st sentence should be dropped
Consensus: agreed
...
<Bob> ...resource representation or an instruction, but the attribute is not present or the URI is not known, then the service MUST generate an invalidContentDescriptionURI fault. There is no default value.
Asir: Name is contentDescription the fault also should be called the same (no URI in the end)
agreed
Asir: wants to name the attribute, contentDescriptionHint
Dug: Does not think the word Hint is needed. The description conveys that
Yves: Hint also means it is not trustable
Bob: Hints can be wrong
Ashok: Server can send a fault it
wants. It is explained in a complex way
... Say, "if the server does not understand the att, it may send a fault'
Dug: we need to call out the two
cases described explicitly
... if you needed the att to process the message
Ashok: does it matter to the client / user?
Dug: The spec needs to be clr on when the fault is generated
Gil: if you get a fault, you need to be able to look up the spec to understand when the fault is generated
Ashok: I am not going to make a big issue. Just i would have written that way
<asir> here is what we agreed yesterday
Dug: does not think hint is well-defined
Bob: In the version I have I have not added the Hint language
Asir: We agreed to it yesterday
Bob: I am happy to leave it as is, even though we used that word...
Dug: I already added the fault to spec. I will change it to match above
<Bob> ...resource representation or an instruction, but the attribute is not present or the URI is not known, then the service MUST generate an invalidContentDescription fault. There is no default value.
RESOLUTION: Issue-6712 resolved with text above along with parallel modifications to the associated fault
Bob: describes where we stand
in depth discussion on different ways to place the delivery bracket and if there is a value in having it or not
Bob: Suggests "stamp" element that qualifies the EPR (NotifyTo)
Wu: Stamp is equivalant to Delivery
Geoff: The Eventing spec saya there
is a difference between subscription and event source. The arh
boxes the concepts
... 2nd pt. Every one accepts push mode, yet we have no defined way to change it
Bob: We talked about Delivery.. Could you come-up with a concept of "Delivery"?
Dug: As an extension writer, I should be able to tell if it goes in Delivery or not
Geoff: accept that
<Geoff> the definition for delievery we should start with can be found in an email sent by Asir
<Geoff> the link is here:
Dug: does not think Pull fits the above (MEP part)
Asir: Thinks it does
Bob: Can we simply define: Delivery is rules for transportation of Notifications from source to sink
Dug: How about batching?
Asir/Bob: That is formatting not transportation
Delivery is rules for conveyance of Notifications from source to sink
Ashok: Suppose we agree on this, how does it change things?
Tom: The from and To would be part of this
Gil: Thinks it is hard for people outsite this room to figure out whether an extension goes with delivery or not
Bob: With this definition Notify:to comes back into the bracket
Dug: Does not solve the EndTo problem
Bob: If no more arguments, we are going to decide
Asir: Not all directional proposals from this am have translated into concrete proposals
Tom: Rules don't go into the "Stamp", the effects of rules do
Not all effects may go into stamp also
Bob: Within the subscribe Msg - a Yes vote supports the directional decision to define an element that acts as a container for all extension QNames defined by this spec or externally, and data necessary fro conveyance of Notfications from Source to Sink
Dug: This is an incomplete soultion does not address EndTo
<li> i'm on queue
Li: WS-Eventing is a pt to pt protocol - establishing a channel from source to sink
Subscription establishes 2 links, between source and sink and subscription manager and client
Bob: Any other concerns before wew vote on the directional proposal?
Asir: Want to account for EndTo?
Dug/Gil: No need. May raise as a separate issue
Bob: Vote Yes - to support the wrapper
Avaya - Yes
Fujitsu - Yes
Hitachi - No
IBM - No
MS - Yes
Oracle - No
Redhat - No
Software AG - Yes
W3C - Yes
Yes - 5
No - 4
<li> one link = one wrapper
Bob: yes carries => Directional
proposal
... We want to rest this and let it season for a bit
... Need a concrete proposal
Geoff: Will do in couple of weeks
Bob: Need it before 23rd so that
people can look at it
... I have received a notification that Redhat has given proxy to Oracle for the duration of the F2F
Gil: Recaps where we are
<Wu>
Wu: Issue, WSDL in WS-E does not confrom to WS-I BP
<Wu>
Dug sent the above in March
Wu: Using Policy to link out bound operations with source is a clean solution
<Wu>
Li: Two proposals from Gil, (1) BP compliant (2) Make WSDL <....>
You link Event Source WSDL with Notification WSDL
<gpilz>
Geoff: Your proposal is centered around wrapped mode. Pls address why wrapped mode changes things
Gil: Details his proposal at the above URL
Geoff: Why do need this rather than WSDL
Gil: WSDL msg types etc define notification type - other parts are for raw notifications
<Bob> ACTION: Geoff to write a concrete proposal to capture the decisions to-date on Issue-6692 [recorded in]
<trackbot> Created ACTION-70 - Write a concrete proposal to capture the decisions to-date on Issue-6692 [on Geoff Bullen - due 2009-06-17].
Dug: Describes why he found WSDL was not good enough
<Zakim> asir, you wanted to ask a question, what aspect of wrapped notifications did not fit into WSDL?
Asir: Wants concrete examples of why WSDL alone is not enough
Gil: Can provide
<dug>
Bob: Gil is ferminting[sic] the proposal and we have another proposal from Wu
Link to today's IRC log:
Bob: Recessed until tomorrow | http://www.w3.org/2002/ws/ra/9/06/2009-06-10.html | CC-MAIN-2016-30 | en | refinedweb |
In this section you will learn how to check whether a file or a directory exist or not. The " java.io " package provide a method exist() which return true or false. This method will return "true" if file or directory exist otherwise it returns "false". In the following program we will create a object of file class and check whether file or directory exist or not.
import java.io.File; public class DirectoryExist { public static void main(String args[]) { File file = new File("C://Documents and Settings//satya//Desktop//Temp"); if(file.exists()){ System.out.println("File Exists"); }else{ boolean check = file.mkdir(); if(check)System.out.println("Directory Created = "+file.getName()); else System.out.println("Sorry could not create directory"); } } }
Description : In the above code first we create an object of file class. Passing path as argument to the file class, will create a directory at the same position. The if condition checks for the file or directory existence in path by method exist(), that returns true if directory is already created and print "file Exist" to the console. If file is not there then exist() method will return false and control execute the else statement which create a directory by mkdir() method of file class and print the name of the directory to the console.
Output of the program :
If the Directory exist then the output will be as follows.: Checking if a file or directory exist
Post your Comment | http://roseindia.net/java/beginners/java-directory-exists.shtml | CC-MAIN-2016-30 | en | refinedweb |
Hi, I'm programming a code to generate a table of values with an operator and have to use pointers. I'm having a problem understanding how pointers work and how to use them in the function, even after reading chapters on the topic. If someone could help me out by maybe giving a brief explanation, it would be of great help.
2 Replies - 538 Views - Last Post: 08 March 2011 - 05:43 PM
#1
Writing a table in C but having a problem understanding how to use poi
Posted 08 March 2011 - 04:56 PM
Replies To: Writing a table in C but having a problem understanding how to use poi
#2
Re: Writing a table in C but having a problem understanding how to use poi
Posted 08 March 2011 - 05:02 PM
#3
Re: Writing a table in C but having a problem understanding how to use poi
Posted 08 March 2011 - 05:43 PM
Quote
If someone could help me out by maybe giving a brief explanation, it would be of great help.
A pointer is a variable that holds a memory address. This is very useful because a pointer can "refers to" or "point to" other data. To really make this useful you need to be able to "de-reference" the data, that is access the data at the memory address pointed to.
So:
int var = 10; // var is some data *somewhere* in memory int* ptr = &var; // &var returns the "address of" var and so now ptr is a pointer to var. *ptr = 2; //*ptr dereferences the address ptr and gives access to the data there cout << var << endl; // prints 2
So to access different locations in memory we can assign a value to a pointer and then dereference the pointer to access (read/write) the data at that memory location!
Example: Strings in C are a collection a chars with the last one equal to 0. Generally a pointer is used to point to the first char in the string.
#include <iostream> using namespace std; int main() { const char* aString = "I had a tiny turtle his name was Tiny Tim."; cout << "Address of aString's data in memory = " << (void*)aString << endl; cout << "value of aString's data in memory = \"" << aString << "\"" << endl; cout << "ADDRESS : ch : ASCII" << endl; for (const char* ptr = aString; *ptr !=0; ptr++) { cout << (void*)ptr << ": " << *ptr << " : " << hex << (int)*ptr << endl; } return 0; }OUTPUT:
> "C:\CProjects\Forum Help\ptrExample1.exe " Address of aString's data in memory = 00E89334 value of aString's data in memory = "I had a tiny turtle his name was Tiny Tim." ADDRESS : ch : ASCII 00E89334: I : 49 00E89335: : 20 00E89336: h : 68 00E89337: a : 61 00E89338: d : 64 00E89339: : 20 00E8933A: a : 61 00E8933B: : 20 00E8933C: t : 74 00E8933D: i : 69 00E8933E: n : 6e 00E8933F: y : 79 00E89340: : 20 00E89341: t : 74 00E89342: u : 75 00E89343: r : 72 00E89344: t : 74 00E89345: l : 6c 00E89346: e : 65 00E89347: : 20 00E89348: h : 68 00E89349: i : 69 00E8934A: s : 73 00E8934B: : 20 00E8934C: n : 6e 00E8934D: a : 61 00E8934E: m : 6d 00E8934F: e : 65 00E89350: : 20 00E89351: w : 77 00E89352: a : 61 00E89353: s : 73 00E89354: : 20 00E89355: T : 54 00E89356: i : 69 00E89357: n : 6e 00E89358: y : 79 00E89359: : 20 00E8935A: T : 54 00E8935B: i : 69 00E8935C: m : 6d 00E8935D: . : 2e > Process Exit Code: 0 > Time Taken: 00:00
So as I dereference each address I find that there is a printable ASCII char there and so this data is some text, not all data is text data though. Strings in C rely heavily upon pointers to access blocks of continuous memory containing text data. Rather than requireing a variable for each letter, I can refer to the address of the first character and mark the ending of the string with a '/0' char.
Part II: pointers know data size
Pointers are addresses and all addresses are is numbers. But pointers are kind of special because the know the "size" of the type they refer to in memory. So a char is typically 1 byte so when you add 1 to a char* the address goes up by 1 to get you to the next char. But an int is typically 32bits or 4 bytes so when you add 1 to an int* the address goes up by 4 bytes to get you to the next int in memory.
#include <iostream> using namespace std; int main() { int piDigits[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}; cout << "Address of piDigits's data in memory = " << piDigits << endl; cout << "ADDRESS : digit" << endl; for (int* ptr = piDigits; *ptr < sizeof(piDigits)/sizeof(*piDigits); ptr++) { cout << (void*)ptr << ": " << *ptr << endl; } return 0; }OUTPUT:
> "C:\CProjects\Forum Help\ptrExample2.exe " Address of piDigits's data in memory = 0026F98C ADDRESS : digit 0026F98C: 3 0026F990: 1 0026F994: 4 0026F998: 1 0026F99C: 5 > Process Exit Code: 0 > Time Taken: 00:00
note the addresses go up by 4: 0026F98C + 4 = 26F990
So when you add/subtract a number to a pointer it slides the address up/down by units of the size of that pointer's base type. char 1byte, short 2 bytes, int 4 bytes (these values are platform dependent).
So if we have int* ptr = 0x800000; (some random address) then ptr = ptr + 10 will be 0x800028 -- since 10*4 = 40 = 0x28
so the array access operator ptr[5] is the same as *(ptr + 5) -- which means that rather than doing a lot of pointer arrithmatic to access elements of a block of memory like a string we can use the array access operator [] to do it!
I hope this helps, sorry it was not as brief as I wanted.
Page 1 of 1 | http://www.dreamincode.net/forums/topic/220921-writing-a-table-in-c-but-having-a-problem-understanding-how-to-use-pointers/ | CC-MAIN-2016-30 | en | refinedweb |
XML Attributes
Introduction
One of XML strengths is its ability to describe data
with various options, using simple or complex elements. Although an
element can have a value as large as a long paragraph of text, an element
can have only one value. There are cases where you would like the same
element to be equipped with, or be able to provide, various values that
can also be easily distinguished or separate. To provide various types of information
to an XML element, you can use one or more attributes
Creating an Attribute
In C#, we are used to creating classes. Imagine that
you want to create one for employees. Such a class would appear as
follows:
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace CSharpLessons
{
class CEmployeeRecord
{
public string Username;
public string Password;
public Double Salary;
public char MaritalStatus;
}
class Program
{
static void Main(string[] args)
{
CEmployeeRecord emplRecord = new CEmployeeRecord();
emplRecord.Username = "kallar";
emplRecord.Password = "7hd47D89";
emplRecord.Salary = 20.12;
emplRecord.MaritalStatus = 'D';
Console.WriteLine("Username: {0}", emplRecord.Username);
Console.WriteLine("Password: {0}", emplRecord.Password);
Console.WriteLine("Marital Status: {0}", emplRecord.MaritalStatus);
Console.WriteLine("Hourly Salary: {0}", emplRecord.Salary);
Console.ReadLine();
}
}
}
This would produce:
Username: kallar
Password: 7hd47D89
Marital Status: D
Hourly Salary: 20.12
The members of such a class are said to describe the
class. When you instantiate the class (when you declare a variable of that
class), you can provide value for one or more member variables. Another
instance of the class can have different values.
In XML, a tag is like a variable of a C++ class,
except that you don't have to create the class but you must create the
tag. Inside of the start tag, you can provide one or more attributes that
mimic the member variables of a class.
An attribute is created in the start tag using the
formula:
<tag Attribute_Name="Value">Element_Value</tag>
Like the tag, the name of an attribute is up to you.
On the right side of the attribute, type its value in double-quotes. The
end tag doesn't need any information about any attribute. It is only used
to close the tag. Here is an example of a tag that uses an attribute:
<salary status="Full Time">22.05</salary >
In this example, status="Full Time" is
called an attribute of the salary element.
One of the good features of an attribute is that it
can carry the same type of value as that of an XML tag. Therefore, using
an attribute, you can omit giving a value to a tag. For example, instead
of creating the following tag with its value:
<movie>Coming to America</movie>
You can use an attribute to carry the value of the
tag. Here is an example:
<movie title="Coming to America"></movie>
In this case, you can still provide another or new
value for the tag.
You can create more than one attribute in a tag. To do
this, separate them with an empty space. Here is an example:
<movie title="Coming to America" director="John Landis" length="116 min">Nile Rodgers</movie>
If you create a tag that uniquely contains attributes
without a formal value, you can omit the end tag. In this case, you can
close the start tag as you would do for an empty tag. Here is an example:
<movie title="Coming to America" />
Practical Learning: Creating XML Attributes
<?xml version="1.0" encoding="utf-8"?>
<logininfo>
<credential username="belld" password="qwyIYw58" />
<credential username="democracy" password="2k!2hk3W" />
<credential username="autocrate" password="$*@#ywEy" />
<credential username="progress" password="36%y68F$" />
</logininfo>
private void Form1_Load(object sender, System.EventArgs e)
{
this.dataSet1.ReadXml("credentials.xml");
this.dataGrid1.DataSource = this.dataSet1;
this.dataGrid1.DataMember = "credential";
this.dataGrid1.CaptionText= "Login Credentials";
} | http://www.functionx.com/vcsharp2003/xml/attributes.htm | CC-MAIN-2016-30 | en | refinedweb |
Red Hat Bugzilla – Bug 462331
vino-server: fatal error in libgcrypt, file visibility.c, line 1197, function gcry_randomize: called in non-operational state
Last modified: 2008-10-01 17:36:40 EDT
With current Rawhide, vino-server crashes when I connect. The last thing it prints in ~/.xsession-errors is, "fatal error in libgcrypt, file visibility.c, line 1197, function gcry_randomize: called in non-operational state".
Downgrading from libgcrypt-1.4.2-1 to libgcrypt-1.4.0-3 makes this problem go away.
Perhaps this indicates that there is a bug in libgcrypt-1.4.2-1, or perhaps this indicates that there is a bug in vino which doesn't manifest itself with the older libgcrypt version because the older version is less strict. I leave this to the vino maintainer to figure out ;-).
I'm also encountering this problem. Haven't tried downgrading yet, but I've managed to get a backtrace which may be interesting for the package maintainer:
15/09/2008 21:24:58 Autoprobing TCP port
15/09/2008 21:24:58 Autoprobing selected port 5900
15/09/2008 21:24:58 Advertising authentication type: 'VNC Authentication' (2)
15/09/2008 21:24:58 Advertising security type: 'VNC Authentication' (2)
15/09/2008 21:28:04 Got connection from client xxxxxxxxxxxx
15/09/2008 21:28:04 other clients:
15/09/2008 21:28:04 Client Protocol Version 3.7
15/09/2008 21:28:04 Advertising security type 2
15/09/2008 21:28:04 Client returned security type 2
fatal error in libgcrypt, file visibility.c, line 1197, function gcry_randomize: called in non-operational state
Program received signal SIGABRT, Aborted.
0x00110416 in __kernel_vsyscall ()
Missing separate debuginfos, use: debuginfo-install e2fsprogs.i386 expat.i386 gtk-nodoka-engine.i386 keyutils.i386 krb5.i386 libXau.i386 libXcomposite.i386 libXcursor.i386 libXdmcp.i386 libXi.i386 libXinerama.i386 libXrandr.i386 libXrender.i386 libcap.i386 libpng.i386 libselinux.i386 libxcb.i386 openssl.i686 pixman.i386
(gdb) bt
#0 0x00110416 in __kernel_vsyscall ()
#1 0x001c2740 in raise (sig=<value optimized out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#2 0x001c4108 in abort () at abort.c:88
#3 0x04c29773 in _gcry_fips_noreturn () at fips.c:679
#4 0x04c21c42 in gcry_randomize (buffer=Could not find the frame base for "gcry_randomize".
) at visibility.c:1198
#5 0x0806448d in vncRandomBytes (bytes=0x80f0ae5 "") at vncauth.c:48
#6 0x08058b73 in rfbAuthProcessSecurityTypeMessage (cl=0x80f0ab8) at auth.c:275
#7 0x0805e2f8 in rfbProcessClientMessage (cl=0x80f0ab8) at rfbserver.c:370
#8 0x08053db8 in vino_server_client_data_pending (source=0x80d2dc0, condition=G_IO_IN, rfb_client=0x80f0ab8) at vino-server.c:334
#9 0x004091cd in g_io_unix_dispatch (source=<value optimized out>, callback=<value optimized out>, user_data=Could not find the frame base for "g_io_unix_dispatch".
) at giounix.c:162
#10 0x003d21f8 in g_main_dispatch () at gmain.c:2142
#11 IA__g_main_context_dispatch (context=<value optimized out>) at gmain.c:2694
#12 0x003d58a3 in g_main_context_iterate (context=<value optimized out>, block=<value optimized out>, dispatch=<value optimized out>, self=Could not find the frame base for "g_main_context_iterate".
) at gmain.c:2775
#13 0x003d5dc2 in IA__g_main_loop_run (loop=<value optimized out>) at gmain.c:2983
#14 0x04953fd9 in IA__gtk_main () at gtkmain.c:1172
#15 0x080512a0 in main (argc=Cannot access memory at address 0x5aa4
) at vino-main.c:110
I see we have libgrypt 1.4.3 in rawhide now.
Does this still happen ?
The problem is gone as of libgcrypt 1.4.3-1 | https://bugzilla.redhat.com/show_bug.cgi?id=462331 | CC-MAIN-2016-30 | en | refinedweb |
ComponentTray Class
Provides behavior for the component tray of the form designer. The component tray represents components that do not otherwise provide a visible surface at design time and provides a way for users to access and set the properties of those components.
For a list of all members of this type, see ComponentTray Members.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollableControl
System.Windows.Forms.Design.ComponentTray
[Visual Basic] Public Class ComponentTray Inherits ScrollableControl Implements IExtenderProvider [C#] public class ComponentTray : ScrollableControl, IExtenderProvider [C++] public __gc class ComponentTray : public ScrollableControl, IExtenderProvider [JScript] public class ComponentTray extends ScrollableControl implements IExtenderProvider
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Remarks.
Requirements
Namespace: System.Windows.Forms.Design
Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family
Assembly: System.Design (in System.Design.dll)
See Also
ComponentTray Members | System.Windows.Forms.Design Namespace | https://msdn.microsoft.com/en-us/library/system.windows.forms.design.componenttray(v=vs.71).aspx | CC-MAIN-2016-30 | en | refinedweb |
This action might not be possible to undo. Are you sure you want to continue?
Viet Nam: Vocational and Technical Education Project
Evaluation
Independent
Performance Evaluation Report April 2013
Viet Nam: Vocational and Technical Education Project
Reference Number: PPE: VIE 2013-03 Project Number: 25033 Loan Number: 1655 (SF) Independent Evaluation: PE-762
Note: In this report, “$” refers to US dollars.
Director-General Director Team leader Team member
V. Thomas, Independent Evaluation Department (IED) W. Kolkma, Independent Evaluation Division 1, IED H. H. Son, Principal Evaluation Specialist, IED M. Agapito, Evaluation Officer, IED I. Marquez, Senior Evaluation Assistant, IED
In preparing any evaluation report, or by making any designation of or reference to a particular territory or geographic area in this document, the Independent Evaluation Department (IED) does not intend to make any judgment as to the legal or other status of any territory or area. The guidelines formally adopted by IED on avoiding conflict of interest in its independent evaluations were observed in the preparation of this report. To the knowledge of the management of IED, there were no conflicts of interest of the persons preparing, reviewing, or approving this report.
Abbreviations
ADB AFD DACUM DOLISA EIRR GDVT IED IEM ILO JICA LMIS MOET MOLISA NDF PAS PCR PIU PPER RRP SDMP SERD TA TCS VCCI VTE – – – – – – – – – – – – – – – – – – – – – – – – – Asian Development Bank Agence Française de Développement Developing a Curriculum Department of labor, invalids, and social affair economic internal rate of return General Department of Vocational Training Independent Evaluation Department independent evaluation mission International Labour Organization Japan International Cooperation Agency labor market information system Ministry of Education and Training Ministry of Labor, Invalids, and Social Affairs Nordic Development Fund program accreditation system project completion report project implementation unit project performance evaluation report report and recommendation of the President Staff Development Master Plan Southeast Asia Department technical assistance technical certification system Viet Nam Chamber of Commerce and Industry vocational and technical education
Currency Equivalents
Currency Unit – dong (D) At Appraisal (9 November 1998) D1.00 = $1.00 = $0.000072 D13,898 At Project Completion (31 March 2008) $0.000062 D16,078 At Independent Evaluation (December 2012) $0.000048 D20,800
Contents
Page i ii iii 1 1 1 3 3 4 5 5 6 8 9 9 10 10 10 17 23 25 27 27 36 38 39 39 40 42
Acknowledgments Basic Data Executive Summary Chapter 1: Introduction A. B. A. B. C. D. E. F. G. H. A. B. C. D. E. A. B. C. A. B. C. Evaluation Purpose and Process Expected Results Formulation Rationale Cost, Financing, and Executing Arrangements Procurement, Construction, and Scheduling Outputs Consultants Loan Covenants Policy Framework Overall Assessment Relevance Effectiveness Efficiency Sustainability Impact ADB, Development Partners, and Borrower Performance Technical Assistance Issues Lessons Follow-Up Actions
Chapter 2: Design and Implementation
Chapter 3: Performance Assessment
Chapter 4: Other Assessments
Chapter 5: Issues, Lessons, and Follow-Up Actions
Appendixes: 1. 2. 3. 4. 5. 6. 7. 8. Summary Design and Monitoring Framework 44
Change in Vocational and Technical Education Structure in Vocational Training Law 2006 47 Rating Matrix for Core Evaluation Criteria Student Perception of Vocational Training Usefulness Economic Internal Rate of Return Reestimation Occupations and Training Levels of 15 Key Schools Average Monthly Income of Key School Graduates by Occupations in 2005 Skill Matching Among Key School Graduates 48 49 50 52 53 54
Acknowledgments
A team of staff and consultants from the Independent Evaluation Department (IED) contributed to this study by conducting analysis, desk reviews, interviews, research, survey, and data collection. The core team included Hyun H. Son (team leader), Grace Agapito (evaluation officer), and Imelda Marquez (senior evaluation assistant). The report benefited from the overall guidance of Vinod Thomas and Walter Kolkma. The team would like to acknowledge the valuable inputs of the consultants recruited for this evaluation exercise, Rizza Leonzon and Tu Chi Nguyen. The team would also like to thank Minh Nguyen, Thu Nguyen, and Thuy Nguyen for their assistance in organizing various meetings with the concerned government ministries, development partners, and project schools. The team is grateful to Asian Development Bank staff, school representatives, and the Government of Viet Nam for their hospitality, as well as assistance and participation in the interviews. Their insights on the vocational and technical education sector in Viet Nam proved to be extremely helpful in writing the report. The report was peer reviewed by Suganya Hutaserani and Raikhan Sabirova of IED. Valuable comments were also received on an earlier draft from ADB’s Southeast Asia Department and Viet Nam Resident Mission. The report was also shared with the Government of Viet Nam, which welcomed the findings and recommendations of the study.
Basic Data
Loan 1655: Vocational and Technical Education Project Program Preparatory/Institution Building TA No. TA Name Type
2671 3063 Technical Assistance to Viet Nam for the Technical Education Project Technical Assistance to Viet Nam for Capacity Building in Vocational and Technical Education PP
Personmonths
Amount ($‘000)
800.0 600.0
Approval Date
27 December 1996 3 September 1998
AD
AD = Advisory, PP = Project Preparatory, TA = Technical Assistance.
Key Project Data Key Project Data ($ million)
Total project cost ADB loan amount/utilization Loan 1655 ADB loan amount/cancellation Amount of cofinancing AFD JICA NDF
Per ADB Loan Documents
120.0 54.0 12.0 24.0 6.0
Actual
86.3 32.6 12.2 19.2 6.4
Key Dates Key Dates
Fact-finding mission Appraisal mission Inception mission Loan negotiations Board approval Loan agreement Loan effectiveness First disbursement Project completion Loan closing Months (effectiveness to completion)
Expected
9 December 1999 23 December 1999 October 2004 31 October 2004 58.5 months
20 April–12 May 1998 4–20 August 1998 18–22 October 1998 29–30 October 1998 11 December 1998 10 September 1999 17 December 1999 September 2008 23 October 2008 105.0 months
Actual
Borrower Executing Agency Type of Mission
Socialist Republic of Viet Nam Ministry of Labor, Invalids, and Social Affairs No. of Missions
15 1 1
Review Project completion review mission Independent evaluation mission
No. of Person-Days
118 18 30
ADB = Asian Development Bank, AFD = Agence Française de Développement, JICA = Japan International Cooperation Agency, NDF = Nordic Development Fund.
Executive Summary
In addressing labor requirements, vocational and technical education (VTE) is indispensable, especially for countries transitioning to market economies, such as Viet Nam. Following the 1986 economic reforms known as Doi Moi (Renovation), the demand for skilled workers and production technicians in Viet Nam has intensified. However, Viet Nam’s VTE system has failed to sufficiently meet labor demand given the country’s previously supply-driven, outdated, and low-quality VTE sector. To overhaul Viet Nam’s VTE system, the Asian Development Bank (ADB) supported a project that helped to (i) improve the market orientation of the VTE system; (ii) upgrade key schools by developing curricula and instructional materials and improving equipment and facilities; and (iii) strengthen the institutional capacity in the General Department of Vocational Training (GDVT) to implement VTE reforms, which included establishment of a labor market information system (LMIS), program accreditation system (PAS) and technical certification system (TCS), improved access for women and minority students, staff development, cost recovery, and private sector participation. The project was cofinanced by three other development partners. The project costs totaled $86.290 million, or 72% of the estimation at approval, of which ADB financed $32.57 million, Agence Française de Développement $12.22 million, Japan International Cooperation Agency1 $19.17 million, and Nordic Development Fund $6.35 million. The Government of Viet Nam provided $15.98 million. This project performance evaluation report (PPER) presents the findings of the performance evaluation of the Vocational and Technical Education Project in Viet Nam based on the criteria of relevance, efficiency, effectiveness, sustainability and impact. Overall, the project performance is rated successful. The project is found to be relevant, effective, less than efficient, and likely to be sustainable. In general, the project is deemed relevant. It is found to be responsive to Viet Nam’s increasing demand for skilled industry workers, and mostly aligned with the policies and strategies of the government and ADB. The loan modality was appropriate, but the project design was partly relevant to its objectives, with issues of student demand, teacher quality, and occupation selection inadequately addressed. Meanwhile, the project is regarded as effective, particularly in terms of developing a new curriculum methodology and providing modern training equipment at key schools. However, the LMIS, career guidance, production units, school–industry partnership, and program accreditation and technical certification were achieved but not effectively utilized. The project is assessed to be less than efficient. It took 4 years longer to complete than anticipated. Procurement of equipment suffered from delays and was not completed until 2006–2008. The economic rate of return, estimated at 18.7% in the report and recommendation of the President, was recalculated to 11.0% in this report, just below the ADB standard of 12.0%.
1
Government of Japan through the Japan International Cooperation Agency.
iv Viet Nam: Vocational and Technical Education Project
The project is rated likely to be sustainable. Reforms of the new curriculum development method and accreditation and certification systems internalized in the structure of the General Department of Vocational Training (GDVT) and VTE policies are likely to be sustained. On the other hand, the LMIS is no longer carried out since it is complex and resource driven. There was no funding set aside to ensure maintenance and continuity of key project outcomes such as training curricula and equipment. The project’s socioeconomic impact is deemed significant and the performance of ADB and the borrower satisfactory, while the contribution of the capacity building technical assistance (TA) moderate. It has helped to orient the VTE system toward a marketdriven approach without any known adverse environmental or social impact, but failed to account for the weak administrative and management capacity of the executing agency and project implementation unit. Five important lessons are drawn from the evaluation: (i) Management of VTE requires extensive coordination among different stakeholders. For the project, there was little collaboration and sharing of lessons among donors. There were also overlapping responsibilities for technical and professional education between the Ministry of Labor, Invalids, and Social Affairs (MOLISA) and the Ministry of Education and Training (MOET). (ii) Outcomes need to be integrated with the national system for them to be effectively utilized and sustained. The GDVT adopted the new curriculum development method and implemented it nationwide. In contrast, the LMIS, production units at key schools, and school– industry partnership have become rather inactive as sustaining these outputs requires a lot of resources. Strong management capacity should be a prerequisite to project implementation. The GDVT lacked experience and capacity to effectively implement the project. The GDVT is overwhelmed with an increasing number of vocational institutions, which may explain the delay in implementing the PAS and TCS nationwide. Establishing a market-driven VTE system is a long process and requires macro-level links with industry. Public vocational institutions are still financially and strategically dependent on the government. School– industry relations remain ad hoc.. Many students who enter vocational institutions are low-performing and unmotivated. At the same time, access to vocational education can be more equitable. The system attracts relatively few disadvantaged students such as women, ethnic minorities, and the poor.
(iii)
(iv)
(v)
Executive Summary v
Given these lessons, the PPER makes the following recommendations: (i) ADB’s Social Sectors Division of the Southeast Asia Department (SERD) should continue to engage with the GDVT and MOLISA to monitor the progress of the VTE system reforms, collaborate with other donors to share lessons, and coordinate assistance strategies. This can be done under the framework of the ongoing Skills Enhancement Project.2 (ii) MOLISA and the GDVT are advised to continue strengthening the macro-level linkages between the VTE system and the labor market. These agencies need to work closely with the Viet Nam Chamber of Commerce and Industry (VCCI) to facilitate this relationship and establish sector skills councils to match the skill requirements of the labor market with training. The Government of Viet Nam is advised to continue improving the focus and management of its VTE system. VTE management can be further streamlined to reduce overlapping duties among government ministries and agencies. The government needs to reconsider the balance between investments in vocational and academic institutions, and step up campaigns to familiarize secondary and high school students with the benefits of vocational training. SERD is advised to monitor the progress of these reforms under the framework of the follow-on Skills Enhancement Project as well as the next country partnership strategy.
(iii)
2
ADB. 2010. Report and Recommendation of the President: Proposed Loans to the Socialist Republic of Viet Nam for the Skills Enhancement Project. Manila.
CHAPTER 1
Introduction
A. Evaluation Purpose and Process
1. This project performance evaluation report (PPER) assesses the performance of the first project loan of the Asian Development Bank (ADB) to Viet Nam’s Ministry of Labor, Invalids, and Social Affairs (MOLISA) aimed at strengthening the quality and market orientation of the vocational and technical education (VTE) sector in the country. 1 The project is evaluated based on the project performance evaluation guidelines of ADB,2 according to four core evaluation criteria (relevance, effectiveness, efficiency, and sustainability) and two additional criteria (institutional development and impact). The PPER also analyzes the project’s inclusiveness and issues in the domestic labor market that may have affected project performance. It also assesses the roles of different stakeholders in the project. The lessons drawn from this evaluation will feed into the upcoming thematic evaluation study on ADB’s support for inclusive growth. 2. The project completion report (PCR) was prepared in December 2008.3 Overall, it rated the project successful based on ADB’s criteria of relevance, effectiveness, efficiency, and sustainability. The project was found to be highly relevant as it is considered consistent with major policy priorities under Viet Nam’s Education Development Strategy 2001–2010 and ADB’s lending strategy for the country. The project was also deemed effective in realizing most of the targeted outcomes and outputs, as well as efficient in terms of resource utilization at the 15 key schools. It was considered likely to be sustainable given the involvement of local industry in school management, generation of sizeable revenues in production units, and creation of a critical mass of teachers. In addition, the project was assessed to have largely achieved its intended impact of reforming the VTE system in support of the government’s market-oriented industrialization policy by supplying well-trained workers and production technicians for key occupations.
The PPER analyzes the project’s inclusiveness and issues in the domestic labor market that may have affected project performance
B.
Expected Results
3. The project’s objective was to reform the VTE system to better support the government’s market-oriented industrialization policy and supply well-trained skilled workers and production technicians for key occupations. The project’s intended outcomes were (i) improved market orientation of the VTE system; (ii) improved efficiency of VTE programs in key schools; and (iii) strengthened institutional capacity in
1
2
3
ADB. 1998. Report and Recommendation of the President to the Board of Directors: Proposed Loan to the Socialist Republic of Viet Nam for the Vocational and Technical Education Project. Manila. Independent Evaluation Department (IED). 2006. Guidelines for Preparing Performance Evaluation Reports for Public Sector Operations. Manila: ADB. ADB. 2008. Completion Report: Vocational and Technical Education Project in Viet Nam. Manila.
The project’s objective was to reform the VTE system to better support the government’s market-oriented industrialization policy and supply well-trained skilled workers and production technicians for key occupations
2 Viet Nam: Vocational and Technical Education Project
the General Department of Vocational Training (GDVT) to implement the VTE reforms effectively, which included establishment of a labor market information system (LMIS), program accreditation system (PAS), and technical certification system (TCS); improved access for women and minority students; staff development; cost recovery; and private sector participation. The main intended outputs that supported these outcomes included (i) improved market orientation of VTE, (ii) upgrade of key schools by developing curricula and instructional materials and improving equipment and facilities, and (iii) introduction of policy reforms in the VTE system through institutional capacity building. Through supporting the VTE system and key schools, the project aimed to benefit the vocational training students and potential employers as well as the labor market as a whole. A summary of the design and monitoring framework is presented in Appendix 1.
CHAPTER 2
Design and Implementation
A. Formulation
4. Project preparatory TA was requested by the Government of Viet Nam4 prior to formulating the project. The TA produced a well-written report analyzing the VTE system in Viet Nam, along with five background studies on the demand for technical education, procedures for setting up an accreditation system, and feasible options for restructuring the VTE system. Training was also provided to 120 staff from the Ministry of Education and Training (MOET)5 on English and computer skills, and the government was requested to produce a labor force demand survey. However, the TA’s staff training component was less useful since the loan project execution responsibility was transferred to a different ministry. The loan fact-finding mission visited Viet Nam from 20 April to 12 May 1998 and the appraisal mission took place on 3–21 August 1998. The project was approved on 11 December 1998 and became effective on 17 December 1999. 5. The project loan was complemented by separate advisory TA aimed at strengthening the executing agency’s (MOLISA) institutional capacity for planning, implementing, and evaluating VTE policy reforms.6 The GDVT was established in 1998 under MOLISA, taking over MOET’s duty of managing Viet Nam’s VTE system, whereas MOET focused more on long-term professional training. The TA facilitated the transfer of technical skills and knowledge on labor market monitoring, and curriculum and course material design to GDVT staff, officials of key schools, and MOLISA’s provincial offices. It also strengthened the capacity of the project implementation unit (PIU). The delay in the start-up of the loan project, however, weakened the momentum generated by the TA and several staff trained under the TA were not retained to work under the project. The TA also did not sufficiently focus on enhancing the administrative capacity of the GDVT, which then lacked experience in working with foreign-funded projects. 6. The project was cofinanced with three development partners—Agence
Française de Développement (AFD), Japan International Cooperation Agency (JICA), and Nordic Development Fund (NDF)—on a parallel basis. Coordinating the different funding agencies was challenging for the implementing agency (GDVT). The 15 key schools were divided among the development partners, with ADB funding six schools, AFD four schools, NDF three schools, and JICA two schools. Hence, the project was virtually divided into multiple subprojects, making it difficult to manage.
4
5 6
ADB. 1996. Technical Assistance to the Socialist Republic of Viet Nam for the Technical Education Project. Manila (TA 2671-VIE, for $800,000, approved on 27 December 1996). MOET was the main VTE authority at the time. ADB. 1998. Technical Assistance to the Socialist Republic of Viet Nam for the Capacity Building in Vocational and Technical Education. Manila (TA 3063-VIE, for $600,000, approved on 3 September 1998).
4 Viet Nam: Vocational and Technical Education Project B. Rationale
The project responded to the need to overhaul Viet Nam’s VTE system
7. The project responded to the need to overhaul Viet Nam’s VTE system. Following the economic reforms of 1986 known as Doi Moi (Renovation), Viet Nam transitioned from a centrally planned to a market economy, with an increasing demand for skilled workers and production technicians. Under Doi Moi, the government sought to create 1.2 million–1.3 million job opportunities starting in 2000. The proportion of trained workers was expected to increase from 10%–11% to 25% by 2000 and to 50% by 2010. At project appraisal, about 80% of the labor force was unskilled (with the highest concentration [77%] in rural areas) and only 10% had formal training. 8. The labor force was forecasted to grow to more than 42 million by 2003 as about 1 million workers joined the labor force annually in 1996. There would be nearly 19 million industrial and service workers by 2003, of whom 20% would be highly educated engineers with university degrees, 50% would be skilled workers and production technicians, and 30% would be unskilled or semiskilled workers. Despite this demand for labor, Viet Nam’s VTE system failed to keep up with the labor market’s shifting needs. As in most former communist economies, Viet Nam’s VTE system supported supply-driven economic and industrial planning. Technical schools were originally set up to provide staff for government offices and state-owned enterprises, and were managed by many different line ministries and government agencies. They were mandated to train an allotted number of skilled workers. In 1997, the technical education system only trained one-third of the estimated yearly demand of 1.5 million technicians. 9. In terms of quality, several issues were also observed. No career guidance services were provided to students, and the curricula were not regularly revised. Most facilities were rundown and inadequate for further use, as most training equipment was outdated and there was not enough if it. Most trainers were also underqualified. The standard cost of technical education (about $1,000 for a 3-year course student) was not reviewed against international standards ($650). About 30%–50% of students dropped out. There was no national accreditation system to inform students and parents of the quality of different providers. 10. ADB’s 1995 country operational strategy study for Viet Nam advocated dealing with changes in the economic structure and skill-mix requirements by addressing issues related to the education sector.7 It pointed out that there was a serious discrepancy between the skill composition of graduates of higher education and skills relevant to a more market-oriented economy. In Viet Nam, ADB’s VTE priorities were to (i) improve the capacity of secondary vocational and technical schools; (ii) enhance the quality of training outputs by introducing program accreditation and technical certification systems; (iii) engage employers in program planning to improve its relevancy; (iv) decentralize much of the decision making to the institutional administrators; and (v) reduce the public cost of training through the introduction of cost-recovery measures, such as charging tuition fees, offering training courses to employed workers on a fee basis, and selling goods and services. 11. On the government’s side, the 2nd Plenary Session of the 8th Congress of the Communist Party (December 1996) reinforced earlier declarations and pledged to establish a number of key schools to train workers and lead the reform process. The 4th Plenum of the Central Committee of the Communist Party (December 1997) adopted
7
ADB. 1995. Country Operational Strategy Study: Viet Nam. Manila.
Design and Implementation 5
educational development policies to expand VTE, rationalize the number and size of schools, and train highly skilled workers for export processing zones. The government’s Educational Development Strategy 2001–2010 also recognized the importance of VTE and sought to (i) ensure that 40% of the workforce has professional qualifications, of whom 26% should receive vocational training; and (ii) establish 40 high-quality institutions.
C.
Cost, Financing, and Executing Arrangements
12. At appraisal, the project’s total cost was estimated at $120.0 million, of which $72.0 million was foreign exchange cost—including the $1.5 million service charge— and $48.0 million was local currency cost. ADB approved a loan of $54.0 million. The project was also cofinanced on a parallel basis by AFD ($12.0 million), JICA ($24.0 million), and NDF ($6.0 million). The government’s share was $24.0 million. The actual cost of the project was $86.3 million, of which ADB financed $32.6 million, AFD $12.2 million, JICA $19.2 million, NDF $6.4 million, and the government $16.0 million. This was 72% of the original estimate, with substantial savings in ADB funding given savings from procurement, low actual implementation costs, cancellation of the second phase of staff development, and exchange rate variations. The capacity building TA was approved for $600,000 and cofinanced by the British Council ($20,000) for workshop support and the Korean International Cooperation Agency ($20,000) for CD-ROM course development. After 9 months of implementation, $578,640 was disbursed. 13. Since vocational training management was moved from MOET to MOLISA, MOLISA replaced MOET as the executing agency. The Project Steering Committee was established, with the vice-minister of MOLISA as chair and with members from the State Bank of Viet Nam, related ministries, Office of the Prime Minister, Viet Nam Chamber of Commerce and Industry (VCCI), and women’s and labor unions. The GDVT was the implementing agency, with the agency’s director-general leading as the project director until December 2006.8 The third and final project director was GDVT’s deputy director-general who was appointed in February 2007. Day-to-day activities were handled by PIU staff under the leadership of the project manager, who changed three times during the project. There were initially only a few full-time staff, thus the PIU recruited contractual staff, who worked elsewhere after gaining experience. The PIU eventually improved its management in the later part of implementation. Sub-PIUs were established in each key school, though the production unit in each key school was managed by a separate unit manager.
D.
Procurement, Construction, and Scheduling
14. The project suffered several delays for various reasons. The change in executing agency and redesign of the key school selection process caused a 1-year slippage prior to project effectiveness. Since this was MOLISA’s first foreign loan project, it required another year to prepare internal regulations and an organizational framework, and allocate authority for project implementation. Contract awards and disbursement also did not gain momentum until the fourth quarter of 2003. The project followed ADB’s requirement to open an imprest account on 22 November 1999 at a commercial bank—the Bank for Foreign Trade of Viet Nam. The first advance of $100,000 occurred in December 1999, followed by another advance of $1 million in December 2000. Disbursements were slow at the beginning because of delays in consultant selection
8
The project suffered several delays for various reasons
The project director was changed twice during this period as a result of the retirement of two GDVT directors-general.
6 Viet Nam: Vocational and Technical Education Project
and procurement, and the inexperience of the executing agency. As a result, the advance was cut from $1 million to $600,000 in April 2003. 15. At the midterm review in October 2003, the borrower requested extension of the loan closing date from 31 October 2004 to 30 September 2006. The Office of the Auditor General in 2004 conducted an investigation of allegations raised by an unsuccessful bidder regarding supply training equipment. The 7-month investigation dismissed the complaint, but halted project procurement and disbursements. As a result, the borrower requested a further 18-month extension, from 30 September 2006 to 31 March 2008. Minor delays were also encountered that slightly delayed the closing of the loan account. These include processing direct payments to local suppliers, which required the translation of invoices from Vietnamese to English, as well as staff development overseas programs, which were too small to attract international bidders. Complicated contracting processes and lengthy substitution processes also contributed to delays in consulting services contracting.
The project did not involve any major construction since only schools with sufficient facilities were selected as key schools
16. The project did not involve any major construction since only schools with sufficient facilities were selected as key schools. Nevertheless, the procurement process, which was mainly for training equipment, suffered various delays. There were setbacks in finalizing the list of equipment by key schools because of unfamiliarity of staff with modern equipment and unavailability of completed curriculum guides. There were also complications because of different requirements of the cofinanciers. The procurement of equipment under ADB and NDF financing mainly followed international competitive bidding procedures. At ADB-financed schools, the PIU signed contracts with successful bidders, and key schools were only recipients of equipment. In contrast, procurement and contracting responsibilities in NDF-funded schools were decentralized to key schools with support from the Department of Labor, Invalids, and Social Affairs (DOLISAs). Procurement at two JICA-funded schools was completed the earliest and on time (in 2005–2006) because JICA supplied the equipment directly from Japan. On the other hand, procurement at AFD-funded schools was completed only in 2008 because AFD required that at least 55% of equipment originate from France. Eventually, AFD allowed 55% of equipment to originate from the euro zone and delegated procurement and contracting responsibilities to key schools.
E.
Outputs
17. The project comprised three main components: (i) improvement in the market orientation of VTE, (ii) upgrading of key schools by developing curricula and instructional materials and improving equipment and facilities, and (iii) introduction of policy reforms in the VTE system through institutional capacity building. 18. Improvement in the market orientation of vocational and technical education. To help systematically assess the demands of enterprises and employers, the project developed a labor market information system (LMIS). The project also trained staff of key schools and DOLISAs to design and conduct four rounds of enterprises and student tracer surveys (2002–2005). The project also published career guidance and employment, and conducted career guidance training workshops for staff of key schools and DOLISAs. Finally, the project developed a methodology for formulating modern curriculum guides relevant to the skills requirements of employers. Ninety seven curriculum guides were developed—27 at the college level, 43 at the secondary level, and 27 for mobile training programs. Under the project, 48 curriculum development committees were established with key school teachers, managers, and outside production managerial staff. The project also developed textbooks and
Design and Implementation 7
teachers’ guides based on the new curriculum guides and 100 computer course products. In addition, the project developed and produced multimedia teaching and learning resources such as CD-ROMs, videos, and posters for mobile training programs and traditional occupations to make the delivery of new curriculum guides more effective. The project procured curricula, instructional materials, and audiovisual materials worth $6.34 million from abroad for key schools and translated them into Vietnamese for reference. 19. Upgrading of key schools by developing curricula and instructional materials and improving equipment and facilities. MOLISA designated 15 key schools as follows: Six ADB-financed key schools: Dien Bien Health Care Secondary School, Dien Bien; Agriculture and Forestry College, Bac Giang; Da Nang Technical Economic School, Da Nang (later upgraded to Vocational College); Central Highland Youth and Ethnic Minorities Vocational Training School, Dak Lak (later upgraded to Vocational College); Da Lat Technical School, Da Lat (later upgraded to Vocational College); and Can Tho Technical Worker’s School, Can Tho (later upgraded to Vocational College); Four AFD-financed key schools: Vietxo Technical Worker’s School No. I, Vinh Phuc (later upgraded to Construction Vocational College No. I); Hai Phong Industry Secondary School, Hai Phong (later upgraded to Hai Phong Industrial Vocational College); Technical Worker’s School No. 1, Ho Chi Minh City (later upgraded to Ho Chi Minh University of Industry); and Dong Nai Technical Worker’s School, Bien Hoa (later upgraded to Vocational College); Three NDF-financed key schools: Vinh Technical Teacher Training College, Vinh (later upgraded to University); Hue Technical Practical Worker’s School, Hue (later upgraded to Industrial College); and Vinh Long Technical Teacher Training College, Vinh Long; and Two JICA-financed key schools: Technical Worker’s School No.1, Ha Noi (later upgraded to Hanoi University of Industry); and Training School for Road Construction and Machinery, Ha Noi (later upgraded to Central Transport Vocational College 1). ADB, AFD, and the central and provincial governments financed the renovation or construction of classrooms and installation of equipment. ADB procured equipment worth $12.4 million for six key schools, as did NDF ($6.4 million) for three key schools, and AFD (€9.0 million) for four key schools. The procurement plan included 16 packages, comprising 7 packages under ADB financing, 5 under NDF financing, and 4 under AFD financing. The project spent $47.31 million on equipment and furniture. Civil works for the Vocational Science Research Center were not completed since the construction site was unavailable. The project also established 15 production units, one at each key school, to link training with practice and generate additional income for key schools. 20. Introduction of policy reforms in the VTE system through institutional capacity building. For program accreditation, the GDVT drafted the Viet Nam National Accreditation System for quality control of vocational training programs, which was introduced in all 15 key schools in 2003. Quality teams were established at key schools for self assessment. The project drafted a method for developing competency-based skills standards using job descriptions and skills requirements developed by competent industry people. After initially developing skills standards for two occupations, the project developed skills standards for 48 occupations. The project drafted a qualification framework for primary, secondary, and college levels that clearly defines the knowledge and skills to be attained at each level. MOLISA in turn established the
8 Viet Nam: Vocational and Technical Education Project
Vocational Accreditation Department and GDVT’s National Skills Testing and Certification Department. 21. To bolster access to vocational training, MOLISA and the GDVT on 11 December 2001 submitted to ADB an action plan to promote participation of women and minorities. In November 2002, the GDVT piloted a sewing program in Can Tho Technical Worker School, and nursing and midwifery in Dien Bien Health Care Secondary School. Similar programs for disadvantaged groups such as women, ethnic minorities, the poor, and disabled were instituted in key schools starting in December 2005. Three mobile training centers were established—at Dien Bien, Dak Lak, and Bac Giang. About 27 mobile training programs targeting 540 people were developed.9 The project also drafted a manual for and conducted training workshops on effective school–industry partnerships. A program–industry advisory committee was set up for each occupation. 22. The project also set out to build the capacity of managerial staff and improve institutional capacity. The project produced the Staff Development Master Plan (SDMP). At appraisal, more than 20,000 people were to be trained, but the target was unrealistic because there were not many teachers and administrators in Viet Nam’s VTE system at that time. The midterm review in October 2003 reduced the project target to 6,300 (later further reduced to 4,900), which led to cancelation of the second phase of the SDMP, saving $3.04 million. By completion, the project trained 4,709 participants (96% of the SDMP target), including policy makers across all levels of government and teachers, of whom 372 received external study tours (99% of the SDMP target), 186 received external fellowships (90% of the SDMP target), and 4,151 received local shortterm training (96% of the SDMP target).
F.
Consultants
23. The project used 261 person-months of international consultancy services and 442 person-months of national consultancy services. The TA engaged a team of four international and two national consultants for a total of 28.5 person-months to conduct a series of workshops and training sessions aimed at strengthening the technical and administrative capability of GDVT staff assigned to the project and faculty in key schools. Recruitment was carried out in accordance with ADB’s Guidelines on the Use of Consultants and other arrangements satisfactory to ADB on the engagement of national consultants. Consultants were contracted to assist the GDVT with establishment of the LMIS, curriculum revision, career guidance, private sector links, equipment installation, program accreditation, skills standards, testing and certification, and staff training. The consultants’ performance was generally satisfactory. However, the transfer of knowledge and technology from consultants to staff at the GDVT and key schools was weak, especially regarding equipment maintenance and use of the LMIS. In terms of managing consultants, the PIU did not actively discuss the mobilization plans for consultants with the consulting firms. As a result, many international consultants were mobilized when there was little implementation progress between September 2001 and December 2002. Once the project actually started, only a few person-months of international consultancy remained, which made it difficult for the PIU to implement professional activities. During the second extension period, from 30 September 2006 to 31 March 2008, ADB agreed to the recruitment of individual consultants, which was viewed by the PIU as effective and efficient.
9
Of 540 people, 78% were women and 76% were members of ethnic minorities.
Design and Implementation 9
G.
Loan Covenants
24. Thirty two of the 36 loan covenants were satisfactorily complied with. Three loan covenants—adoption of a decree to empower MOLISA to collect fees for providing career guidance, skills training, job placement, and business-related activities for the production units; introduction of program accreditation and technical certification systems for the VTE schools; and the action plan to attract more females and ethnic minority groups to vocational and technical schools—were complied with after delay. One covenant—establishing seven units in the GDVT—underwent a minor change, as the women, minorities, and handicapped unit was not established. No covenant was cancelled or significantly altered. The covenant on expanding technical certification and accreditation to other schools and sectors was not fully met upon project completion and even at the time of the PPER.
H.
Policy Framework
25. A major policy change during the project involved enactment of the Vocational Training Law in 2006, which defines institutions and qualification levels in Viet Nam's VTE system. The law reflected the experiences, findings, and recommendations of the various components of the project. Most notably, it acknowledged the new curriculum method and introduced the national PAS and TCS. In addition, it restructured the classification of VTE institutions, grouping them into three levels: primary, secondary, and college (Appendix 2), which helped change the status of some key schools.
CHAPTER 3
Performance Assessment
A. Overall Assessment
Overall, the project is rated successful
26. Overall, the project is rated successful. The overall assessment is based on equally weighted individual assessment criteria: relevance, effectiveness, efficiency, and sustainability (Table 1), and in accordance with the Guidelines for Preparing Performance Evaluation Reports for Public Sector Operations. This is the same as the rating of the PCR, but with differences in the individual ratings for relevance and efficiency (Appendix 3). The other criteria such as impact, ADB and borrower performance, and institutional development are discussed but not assessed because of difficulties in precise attribution and quantification. Table 1: Assessment of Project Performance
Criterion Relevance Effectiveness Efficiency Sustainability Impact ADB and Borrower Performance Technical Assistance Overall Rating 100 Weight (%) 25 25 25 25 Assessment Relevant Effective Less than efficient Likely to be sustainable Significant Satisfactory Moderate Successful 1.75 Rating Value 2 2 1 2 Weighted Rating 0.50 0.50 0.25 0.50
ADB = Asian Development Bank. Note: Highly successful > 2.7, Successful 2.7 > S > 1.6, Less than successful 1.6 > PS > 0.8, Unsuccessful < 0.8.
B.
Relevance
27. The project is rated relevant. As stated in the Rationale section (paras. 7–11), the project fits with the development path of Viet Nam since the time of approval. Countries at different stages of economic development require different mixes of skills. Viet Nam’s economic structure has been changing with increasing demand for skilled industry workers, and the project responded to this change. In 1997, 82% of productive employment was in agriculture, 12% in industry, and only 6% in service. The agriculture sector accounted for 65.3% of employment in 2000 and 51.7% in 2006. Meanwhile, employment in industry increased 7.8 percentage points from 2000 to 2006. As Table 2 shows, the share of skilled agriculture and fishery workers, as well as workers in elementary occupations, decreased between 2000 and 2008, replaced by an increasing share of craft and related trades workers, and plant and machine operators and assemblers.
Performance Assessment 11
Table 2: Change in Shares of Occupations in 2000–2008 (%)
ISCO-88 Occupations Country/ Economy Australia Cambodia Hong Kong, China Republic of Korea Malaysia Mongolia Nepal New Zealand Pakistan Philippines Singapore Thailand Viet Nam Period 2000–2008 2000-2008 2000-2008 2000-2008 2001-2009 2000-2008 1999-2001 2000-2008 2001-2008 2000-2008 2000-2008 2001-2007 2000-2004 1 (0.4) 0.1 2.6 0.1 0.2 (0.7) 0.5 0.8 1.7 2.7 1.1 0.2 0.1 2 0.6 0.4 1.4 2.8 1.4 1.9 2.1 3.9 (0.7) 0.0 5.5 0.2 1.1 3 0.8 0.3 1.9 1.0 2.3 0.0 (0.5) 0.3 1.1 0.0 1.0 0.7 0.3 4 (0.3) 1.0 (2.6) 3.0 0.5 0.2 0.9 0.2 0.0 0.5 (0.9) 0.4 0.1 5 1.3 0.1 1.5 (2.5) 3.4 8.1 2.7 (0.7) 0.3 1.1 (1.1) 1.4 0.2 6 (0.2) (1.2) (0.1) (3.3) (2.0) (10.7) (2.0) (2.6) (4.2) 0.0 (3.8) (0.8) 7 (0.5) 0.8 (3.0) (2.7) (2.0) (0.7) 3.4 (0.2) 0.2 (2.5) (2.4) 0.4 2.8 8 (1.9) (0.7) (2.1) 0.1 (4.4) (3.3) 0.3 (1.1) 0.7 (0.9) (3.7) 0.4 0.3 9 0.6 0.4 0.5 1.7 0.8 1.3 (1.3) (0.7) 3.4 0.8 0.2 (2.9)
Note: ISCO-88 occupation categories: 1 - legislators, senior officials, and managers; 2 - professionals; 3 - technicians and associate professionals; 4 - clerks; 5 - service workers and shop and market sales workers; 6 - skilled agriculture and fishery workers; 7 - craft and related trades workers; 8 - plant and machine operators and assemblers; and 9 - elementary occupations. Source: International Labour Organization. 2011. Key Indicators of the Labor Markets (7th ed.). Geneva; quoted from Maclean et al., eds. 2012. Skills Development for Inclusive and Sustainable Growth in Developing Asia-Pacific. Manila: ADB.
28. In addition, at the time of project implementation, Viet Nam had a significant proportion of its labor in low-skilled occupations compared to other countries (Figure 1). It therefore faced demands for skills upgrade, with growing needs for craft and/or trade and production workers. In 2002, 68% of the labor force had no or minimal training (Table 3). This percentage has decreased, but remains high. The ratio of trained workers in Viet Nam reached 31.55% in 2006, of which vocational trained workers make up 21.25%. 10 It was estimated that there would be demand for nearly 19.0 million industrial and service workers, of whom 9.5 million (50%) would be skilled workers and production technicians, mostly in construction, welding, mechanics, automatic machines and robotics, electrical and electronics, and hydraulics. A survey conducted by Austrade in 2012 points out that enterprises raised the issue of lack of skilled labor as one of their major operational constraints. 11 The project objective, therefore, is deemed appropriate to address the economic needs of Viet Nam at the time of project approval and remains relevant in the present context. It also fits with the lessons learned from other countries, e.g., People’s Republic of China, Japan, and Republic of Korea, which show that human resource development is key to a country’s growth.
Viet Nam had a significant proportion of its labor in lowskilled occupations compared to other countries
Viet Nam Chamber of Commerce and Industry. 2008. Viet Nam Business Annual Report 2007 – Labor and Human Resource Development. Hanoi. 11 Australian Education International. 2012. Vocational Education and Training in Viet Nam Background..
10
12 Viet Nam: Vocational and Technical Education Project
Figure 1: Shares of High-, Medium-, and Low-Skilled Occupations in Total Employment
(%)
90 80 70 60 Percent 50 40 30 20 10 0
High skilled
Medium skilled
Low skilled
AUS = Australia, BRU = Brunei Darussalam, PRC = People’s Republic of China, CAM = Cambodia, HKG = Hong Kong, China, INO = Indonesia, KOR = Republic of Korea, LAO = Lao People’s Democratic Republic, MAL = Malaysia, MON = Mongolia, NEP = Nepal, NZL = New Zealand, PAK = Pakistan, PHI = Philippines, SNG = Singapore, THA = Thailand, and VIE = Viet Nam. Note: Data for Brunei Darussalam and Nepal is for 2001; the PRC for 2005; Lao People’s Democratic Republic for 1995; Malaysia for 2009, and Viet Nam for 2004. For ISCO 88: higher-skilled (professionals, technicians and associate professionals, clerks), medium-skilled (craft and related trade workers, plant and machine operators and assemblers) and low-skilled (agriculture and elementary occupations). Source: International Labour Organization. 2011. Key Indicators of the Labor Markets (7th ed.). Geneva; quoted from Maclean et al., eds. 2013. Skills Development for Inclusive and Sustainable Growth in Developing Asia-Pacific. Manila: ADB.
Table 3: Distribution of Labor by Technical Skill Level in 2002 (%)
Technical Level Basic Level Primary Technical Worker without Degree Technical Worker with Degree Secondary College University Master PhD Total
Source: Labor Market Information System—Enterprise Survey.
All 23.69 2.22 42.59 19.94 4.36 1.53 5.64 0.03 0.01 100.00
Male 20.33 1.76 30.20 29.57 6.14 2.21 9.70 0.07 0.02 100.00
Female 25.82 2.50 50.41 13.84 3.23 1.09 3.06 0.01 0.00 100.00
The project is mostly relevant to the policies and strategies of the government and ADB
29. The project is mostly relevant to the policies and strategies of the government and ADB. It is aligned with the government’s policies, particularly the Educational Development Strategy 2001–2010 12 and Socio-Economic Development Plan 2001–
12
Socialist
Republic
of
Viet
Nam
Government
Web
Portal.
Performance Assessment 13
2005,13 which set out to increase the percentage of the workforce with skill training. ADB’s country operational strategy for Viet Nam in 1995 also acknowledged that human resource development is critical to economic growth.14 The project also fits with the trend of multilateral and bilateral assistance. Since the late 1990s, ADB, the International Labour Organization (ILO), and various bilateral development partners (Germany, Switzerland, the Republic of Korea, and Japan) have been actively providing official development assistance to improve the quality and market orientation of vocational training. During the late 1990s and early 2000s, bilateral assistance of $36.5 million was committed to the VTE subsector by more than a dozen countries. 15 Although there was no overlap between the project’s key schools and the schools supported by other development partners, there is also no evidence that coordination took place to avoid repetition in other areas, such as teacher training and curriculum development. Furthermore, the project is not included in the priority areas of ADB’s education sector strategy at the time of approval, as outlined in ADB's Education Policies and Strategies, which focuses on basic education, improving management and governance capacity of the government, and increasing private sector provision within vocational and technical education. 16 At the time of evaluation, ADB’s education strategy, in line with Strategy 2020, has shifted its priorities to postsecondary education, including VTE, to contribute to filling labor market gaps.17 The project is consistent with this new focus. 30. However, the project framework does not directly fit with the priorities within these strategies. The country operational strategy for Viet Nam in 1995 indicated that the secondary technical institutions offering 2–4 year programs experienced a sharp drop in enrollment (50%), whereas the number of trainees in short vocational programs tripled to 300,000 in 1993/94. At the same time, the strategy cautioned against efforts to “vocationalize” the secondary education program into a “two-track” system, since international evidence shows that vocational training in secondary schools has been less cost-effective than providing more “life skills” and practical activity in the general education program. If resources are not equitably distributed between vocational and general education, students in VTE may end up with low-quality training. As a result, it appears that enhancing relevance and practicality within the general secondary education system, combined with increased supply of short vocational courses close to the workplace, may be more appropriate for students’ demand and employers’ needs. Indeed, ADB stated in the country assistance plan 2001–2003 18 that support in the education sector would continue to focus on secondary education, given its importance in ensuring employment and socioeconomic improvements. 31. The loan modality is generally appropriate and responsive to the government’s efforts to reform the VTE system amid the transition to a market economy. As the project was one of the first initiatives to introduce market orientation to the VTE system, it was, therefore, client driven. Nevertheless, although relevant government agencies were involved in designing the project, other stakeholders—especially VTE institutions and industries—had little involvement. The project managed to leverage
portal/English/ strategies/strategiesdetails?categoryId=29&articleId=3064 Socialist Republic of Viet Nam Government Web Portal. portal/English/ strategies/strategiesdetails?categoryId=29&articleId=3065 14 ADB. 1995. Country Operational Strategy Study: Viet Nam. Manila. 15 Mori, et al. 2009. Skill Development for Viet Nam’s Industrialization: Promotion of Technology Transfer by Partnership between TVET Institutions and FDI Enterprises. Hiroshima: Hiroshima University. 16 ADB. 2002. Education Policies and Strategies . Manila. 17 ADB. 2010. Education by 2020: A Sector Operations Plan. Manila; ADB. 2008. Strategy 2020: The LongTerm Strategic Framework of the Asian Development Bank , 2008–2020. Manila. 18 ADB. 2000. Country Assistance Plan: Viet Nam, 2001–2003. Manila.
13
The loan modality is generally appropriate and responsive to the government’s efforts to reform the VTE system amid the transition to a market economy
14 Viet Nam: Vocational and Technical Education Project
The project managed to leverage funding from different development agencies, which was important as government financial capacity was low at that time
funding from different development agencies, which was important as government financial capacity was low at that time. It could have raised additional finance from the private sector but this would have been difficult considering that the private sector in the country was only emerging at the time. The associated TA projects were instrumental in identifying key issues within the VTE system and preparing staff capacity in managing the project. Nevertheless, the delay in the start of the loan project weakened the momentum generated by the TA projects. 32. The project design is partly relevant to its objectives. It addressed many key issues related to enhancing the quality and market orientation of the VTE system, i.e., developing labor market information, revising curriculum planning methods, improving training equipment, and introducing program accreditation and technical certification systems. However, the project underestimated the risks entailed in the project in terms of the low capacity of the borrower, which affected project implementation. The management capacity constraints within MOLISA and the GDVT—neither of which had ever administered a project before—were only partially addressed by the capacity building TA. This lack of capacity and experience on the borrower’s side caused delays and difficulties, especially during project inception. In addition, the project design did not sufficiently incorporate two issues that were critical to enhancing the quality of vocational training: low student demand for VTE, and low teacher quality. 33. The project paid little attention to resolving the lack of student demand for VTE. Similar to many countries, Viet Nam has been having difficulty in attracting students to vocational training. In a country that places high value on professional education, vocational training is valued less, both economically and socially, than university training. Most students in Viet Nam enter vocational training as a last resort after failing to enter public universities. Student enrollment in VTE institutions has further decreased in recent years as there have been more private universities that are willing to accept students who fail the public university exam. At the same time, many universities started to offer vocational training programs, attracting students away from VTE institutions. Indeed, in 2010, there were only 700,000 students enrolled in VTE (6.1% of the school-age population and 8% of total enrollment in secondary education). This is quite low compared to the world average proportion of secondary school students enrolled in VTE, which has been 11% since 1999, and the average in East Asia and the Pacific, which was 14% in 1999 and 17% in 2010. In countries such as the Republic of Korea, the figures were 11.5% of the school-age population and 12.0% of total enrollment in secondary education; and in the People's Republic of China 16.7% of the school-age population and 20.6% of total enrollment in secondary education. 19 Interviews with vocational institution representatives reveal that many students who enter vocational training schools are low-performing students from poor households who cannot get into public high schools or universities and cannot afford high tuition fees at private schools. This situation is not unique to Viet Nam. In 18 of 22 countries in the 2009 Program for International Student Assessment survey, students who entered vocational schools had, on average, lower socioeconomic status than their peers in general education. Pushing low-performing students into technical and vocational training may yield low-quality graduates and result in employers devaluing these programs (footnote 21). 34. The project also did not sufficiently address the issue of teacher quality. Developing a Curriculum (DACUM) may be an important tool for teachers but it does
19
Pushing lowperforming students into technical and vocational training may yield low-quality graduates and result in employers devaluing these programs
Developing a Curriculum (DACUM) may be an important tool for teachers but it does not help improve their pedagogy or expertise
United Nations Educational, Scientific and Cultural Organization. 2012. Education for All Global Monitoring Report: Youth and Skills—Putting Education to Work. Paris.
Performance Assessment 15
not help improve their pedagogy or expertise, which determine the quality of instruction. 20 During project implementation, not all teachers had a minimum of a bachelor’s degree and not many had advanced degrees (Table 4).21 Interviews with key and control schools suggest that attracting and retaining quality and experienced teachers is an issue in Viet Nam’s VTE system. This is primarily rooted in low salaries of teachers as mandated by the public sector salary level (Figure 2). Most teachers earn less than D2 million per month ($128 equivalent). 22 The project did recognize the importance of training teachers in key schools on (i) technological aspects of the equipment to be procured, (ii) teaching methodology using newly developed curricula and new equipment, and (iii) quality assessment and testing of new training programs. However, this type of training was provided only at four AFD-financed key schools using the savings under AFD financing. Table 4: Distribution of Teachers by Degrees Obtained 2003
Institution Agriculture and Forestry College Can Tho Vocational College Da Nang Vocational College Central Highland Youth and Vinh Technical Teacher Training University Vinh Long Technical Teacher Training College Total PostGraduate 18 0 3 4 3 1 5 122 132 6 3 0 0 30 10 337 University 95 47 58 83 35 62 35 517 162 42 17 35 29 121 64 1,402 College 1 12 7 4 10 10 2 38 18 19 5 43 38 24 36 267 Technical Worker 0 7 1 9 0 4 2 21 7 4 0 36 23 1 18 133 Vocational Secondary 18 1 0 2 0 2 1 0 0 0 3 29 3 0 0 59 Vocational Degree 0 18 0 7 6 2 40 16 7 0 0 79 15 5 0 195
Source: Labor Market Information System – School Survey.
20
It should be noted, however, that three of the key schools that the project support are devoted to training teachers for technical schools: Vinh Long Technical Teacher Training College, Vinh Technical Teacher Training University, and Ha Noi Industrial University. Nevertheless, the Impact section (paras. 58–73) will show that not many graduates from these schools chose teaching as an occupation. 21 This percentage has been increasing over the years and schools are aiming to have 100% of teachers with at least a university degree. 22 As a reference, according to the General Statistics Office of Viet Nam, the monthly average consumption expenditure per capita (excluding durable expenditure) in Viet Nam during project implementation is approximately D360,000 ($23 equivalent).
16 Viet Nam: Vocational and Technical Education Project
Figure 2: Teacher Monthly Salary 2003/04 (D‘000) Below 500 500‐750 750‐1,000 1,000‐1,250 1,250‐1,500 1,500‐2,000 2,000‐2,500 2,500‐3,000 3,000‐4,000 Above 4,000 0% 2.8% 11.8% 12.5% 25.7% 13.9% 22.9% 5.2% 2.4% 2.1% 0.7% 5% 10% 15% Percent of Teachers
Note: The top bar represents salary above D4 million and the bottom bar represents salary below D500,000. Source: Labor Market Information System—Teacher Survey.
Salaray Range (D'000)
20%
25%
30%
35. Finally, it is unclear how the 15 key schools were selected among the 418 vocational schools in the country in 1998 since the selection criteria were broad and the selection process was not described in detail. Interviews with PIU and GDVT staff reveal that the criteria include (i) strong record in student enrollment, (ii) representation of different regions, (iii) representation of different sectors (especially schools that offer occupations of high demand), (iv) management capacity and development strategy of the school, and (v) priority for schools with ethnic minorities. For the most part, these criteria were followed since the 15 key schools represent different regions and sectors in the country, and have strong record of student recruitment and management capacity. 36. Nevertheless, the occupations covered by the project at the 15 key schools only partly responded to the skill shortage and demand as raised by surveyed enterprises during the project and at the time of evaluation. At the early stage of the project, the formal enterprise survey as part of the second survey of the LMIS (2003) indicates that most labor demand among mid-level technical workers was in crafts (Table 5). The same survey also reveals that the majority of enterprises were in the processing industry (407 out of 700), of which 140 were in textile and shoe making and 75 were in food processing. The processing industry also had the highest percentage of labor (65.00% of total labor employed and 76.54% female labor). There were 40 enterprises in machinery and equipment. The sector with the second-highest number of enterprises was services (135 enterprises), with the majority in retail and repair (69) and hospitality (30). At the time of evaluation, a survey by Austrade shows that hospitality, waste treatment, and component manufacturing and assembly were among the most needed and deficient skills.23 On the other hand, none of the key schools offered training in hospitality services, and very few provided training in production and processing. Only at the Central Highland Youth Ethnic Minorities Vocational College did the project
23
See Australian Education International. 2012. Vocational Education and Training in Viet Nam Background. %20AEI%20website.pdf
Performance Assessment 17
focus on crafts training such as carpentry. Most programs concentrated on mechanics and technology (Table 6). Table 5: Additional Labor Demanded among Mid-Level Technical Workers, 2002
Occupation Groups Office Workers Sales and Restaurants Agriculture and Forestry Crafts Assembly and Operations Others Total Number of Missing Labor 655 483 565 31,597 6,422 849 40,571 % of Total Labor 3.3 4.6 3.4 10.1 10.4 0.7 6.8 % of Total Missing Labor 1.61 1.19 1.39 77.88 15.83 2.09 100.00
Source: Labor Market Information System – Enterprise Survey.
Table 6: Distribution of Students across Occupations Trained, 2005–2006
Occupations Trained Business and Management Computer Technology Production and Processing Construction and Architecture Agriculture and Forestry Vet Health Others Total Total 211 247 1,914 99 44 215 111 156 81 3,078 Technical Worker 156 1,429 64 44 23 111 62 42 1,931 Vocational Secondary 62 65 254 35 91 94 6 607 Vocational College 149 26 231
101
33 540
Source: Labor Market Information System – Survey of Key Schools.
C.
Effectiveness
37. The project is regarded as effective. According to the stakeholders interviewed, the most effective outcomes of the project include development of a new curriculum methodology and provision of modern training equipment at key schools. Some outcomes of the project were achieved but not effectively utilized, including the LMIS, career guidance, production units, school–industry partnership, and program accreditation and technical certification. A summary of the project’s outputs, outcomes, and impacts compared with its targets is presented in Appendix 1. This monitoring framework is based on the original design of the project, where indicators were not very well defined. In particular, provision of consulting services and equipment were considered outcomes when they should be inputs. Production of labor market surveys, curricula, and course material should be outputs but were included as outcomes. On the other hand, employment rates of graduates were listed as outputs although they could be impact. 38. Curriculum guides and instructional materials development. As part of the first component, the project helped set up curriculum development committees that yielded 48 curricula for 48 occupations. The instructional materials are well utilized by teachers at key schools to train students on new technology and use of modern machinery. Although these curricula and instructional materials may soon be outdated given changing technology and skill demands, the main success of this outcome is the
Most effective outcomes of the project include development of a new curriculum methodology and provision of modern training equipment at key schools
18 Viet Nam: Vocational and Technical Education Project
establishment of a process for developing market-driven curricula. Prior to implementation of the project, curricula were developed using a top-down government-mandated approach. The project introduced a more bottom-up approach—dubbed DACUM—that requires job market analysis and broader participation of various stakeholders. To ensure that the curricula respond to market needs, there is a designated committee tasked with developing the curriculum for each occupation with representation from teachers, research institutes, policy makers, and industries. The new curricula are also organized in modules, with each module corresponding to different skills required for the occupation. This helps enterprises better evaluate the skills of students based on the modules they complete. Such practice also gives more flexibility to students, allowing them to combine different training programs or transfer from one to another. The GDVT adopted DACUM to produce more than 200 curricula to be used nationwide. About 4,900 teachers and administrators in both project and nonproject schools were trained so as to raise their awareness on and enhance their capacity to adopt DACUM. 39. Facilities development and training equipment provision. In the second component, upgrading the facilities and equipment at 15 key schools was effective in facilitating students’ learning and familiarizing students with modern technology used in enterprises.24 The upgraded facilities also helped key schools obtain higher status and improve their reputation. Of the 15 key schools, 12 were upgraded from vocational secondary schools or technical worker schools to vocational colleges, and three were upgraded to universities. The change in status, together with the enhanced training quality from the project-financed facilities and equipment, helped to improve their reputation.
Some schools have faced a decrease in enrollments, which may be due to the unattractiveness of the occupations offered and impacts of the economic crisis
40. The PCR reported that total enrollment in key schools increased from 60,700 in 2001 to 107,000 in 2007, or a cumulative enrollment of 578,600 during the life of the project. Nevertheless, it is difficult to attribute this increase in student enrollment to the project. Although enhanced capacity and reputation helped key schools attract more students,25 the increase in student enrollment may also be ascribed to the introduction of new programs that are more relevant to students’ interests and market demands, such as economics, accounting, and finance. According to the data collected from key schools during the IEM, the increase in the number of students is not consistent across programs and years.26 This is probably because the school recruitment processes are subject to the mandate of the managing government entities and limited by the capacity of the schools. Furthermore, despite their enhanced reputation, schools continue to face competition from a growing number of vocational institutes and private universities. Recently, some schools have faced a decrease in enrollments, which may be due to the unattractiveness of the occupations offered and impacts of the economic crisis.27 41. Graduates seem to have valued their vocational training (Table 7). Two years after graduation, 81% of students rated both their theory and practical training to be
24
For example, visual media and computers in classrooms that support teachers in their teaching, sophisticated models of assembly chains that help students understand the production in a factory, and machines that help students design and produce machinery parts. 25 For example, Hanoi Industrial University has utilized these upgrades to produce outstanding marketing materials, which helps it recruit students, leverage resources from donors, and improve links with enterprises. 26 Data available upon request. 27 Programs that suffer from recent decreases in enrollment include Bac Giang Agricultural and Forestry College’s Planting, Breeding and Food Industry programs; and Hue Industrial College’s Household Electricity and Metal Cutting.
Performance Assessment 19
useful or very useful, decreasing from 96% when they were studying. More details about students’ ratings over the years and across occupations are included in Appendix 4. Table 7: Key School Student Evaluation of Training Usefulness before Graduation and 2 Years after Graduation in 2005
Level of Usefulness of Training for Future Work (before graduation) Not Very Very Not Useful Useful Useful Useful 118 91 19 11 1 240 119 93 16 11 1 240 56 106 22 17 16 217 58 105 21 16 17 217 1 12 1 2 0 16 1 11 2 2 0 16 0 1 0 0 1 2 0 1 0 0 1 2
Level of Usefulness of Training for Current Work (2 years after graduation) Theory Very Useful Useful Somewhat Useful Not Very Useful Not Useful Total Practice Very Useful Useful Somewhat Useful Not Very Useful Not Useful Total
Total 175 210 42 30 18 475 178 210 39 29 19 475
Source: Labor Market Information System—Tracer Survey.
42. Other outcomes, especially in the third component, are less successful. In terms of the first policy reform, outputs from the first component of labor market monitoring (i.e., the results from four rounds of survey as part of the LMIS) were turned into reports for VTE policy makers. However, it is unclear how these reports were used either by schools or the GDVT in developing VTE programs and strategies. Although the independent evaluation mission (IEM) team obtained data from the PIU, there was no staff capable of or responsible for managing these data. The second and third policy reforms—involving the introduction of program accreditation, skills standards, and technical certification qualification criteria—have not been fully achieved. It was anticipated that the program accreditation and skills certification systems would be implemented nationwide upon project completion. These systems were introduced and piloted at a few schools, however they have not been implemented nationwide at the time of this evaluation. 43. The fourth policy reform was to increase the access to VTE of disadvantaged students (females, ethnic minorities, 28 and the poor) to help reduce poverty and address social issues in skills training. Based on the action plan submitted to ADB in 2001, ethnic minorities were identified and specifically targeted in five schools in three regions—the Northwest, Central Highlands, and Mekong River Delta—where there are substantial ethnic minority populations. The five schools are the Dien Bien Health Care
28
The ethnic minorities form a big disadvantaged group in Viet Nam. In addition to the biggest ethnic group (Kinh), there are 53 ethnic minorities in Viet Nam, some with fewer than 200 members. They account for approximately 13% of the population. They tend to live in more remote highland areas, and some of them have migratory residential patterns linked to shifting cultivation. Remoteness often translates into more difficult access to education, health services, markets, and economic opportunity, leading to higher concentrations of poverty and poorer social indicators among these groups.
20 Viet Nam: Vocational and Technical Education Project
Secondary School in Northwest, the Central Highland Youth Ethnic Minorities Vocational College and the Da Lat Vocational Training Center in Central Highlands, and the Vinh Long Technical Teacher Training College No. 4 and the Can Tho Vocational Training School in the Mekong River Delta. In November 2002 the GDVT introduced two pilot programs: in Can Tho Technical Worker School for sewing, and in Dien Bien Health Care Secondary School for nursing and midwifery. 44. The GDVT conducted a policy workshop in February 2003 to prepare a proposal for a revised policy framework on access, including establishment of a disadvantaged persons unit in the GDVT. Based on this pilot program, the GDVT and the PIU implemented similar exercises in key schools for women and ethnic minorities from December 2005. For women, the project improved training opportunities by creating greater awareness of skills training programs for self-employment, which contributed to achieving almost equal remuneration for male and female graduates from VTE programs. For the poor and ethnic minorities, the project established a new mode of mobile training program to reach out to poor rural communities of mainly ethnic minorities. Three mobile training centers were established—in Dien Bien, Dak Lak, and Bac Giang—and 27 mobile training programs were delivered, targeting 540 people (of whom 78% were women and 76% members of ethnic minorities). The project also published and replicated curricula and audiovisual materials for circulation among other VTE schools using government funds. 45. Indeed, the share of female students seems to have increased, albeit by only a few percentage points, from around 17% in 2002 to 25% in 2005 (Figure 3). This increasing trend, however, is not so obvious in the data collected from 13 key schools during the IEM. The percentage of female students ranges from 0% at Hue Industrial College to 50% at Agriculture and Forestry College in Bac Giang. The nature of the training reflects traditional gender-focused domains. Men register in technical areas,29 whereas women enroll mainly in textile and economics courses. For example, women account for more than 70% in the textile program and 60% in computer business programs at the Central Highland Youth Ethnic Minorities Vocational College. Figure 3. Surveyed Students at Key Schools by Sex, 2002–2005 100%
% of Students
80% 60% 40% 20% 0% Round 1 Round 2 Round 3 Round 4
Survey Round
Female Male
The share of ethnic minority and poor students has not increased over the life of the project
Note: Each column denotes each of the four rounds of survey. The bottom bars are male and the top bars are female. Source: Labor Market Information System—School Survey.
46. The share of ethnic minority and poor students has not increased over the life of the project. The Central Highland Youth Ethnic Minorities Vocational College has the
29
Technical programs such as mechanics, electricity, electronics, and machinery account for most of the programs covered by the project at key schools.
Performance Assessment 21
highest proportion of minority students (up to 99% in 2002), understandably since the school is located in a region with a high concentration of ethnic minorities and is specifically devoted to ethnic youths. The Bac Giang Agricultural and Forestry College is another school where the proportion of minority students is relatively high and has been increasing. This is also the school where the mobile training program was implemented by the project (Figure 4). Similarly, the Central Highland Youth Ethnic Minorities Vocational College and Da Nang Vocational College are the two schools with the highest proportion of poor students (Figure 5). Figure 4. Percentage of Minority Students at Key Schools, 1998–2012
100% 90% 80% 70% 60% 50% 40% 30% 20% 10% 0%
Central Highland Youth Ethnic Minorities Vocational College Vinh Long Technical Teacher Training College Bac Giang Agricultural and Forestry College Can Tho Vocational College
Da Lat Vocational College
Year
Note: These are the five schools located in regions with ethnic minorities (Dien Bien Health Care Secondary School did not respond to the survey). The percentage is an average of three programs benefiting from the project at each school. Source: Data collected from key schools during the independent evaluation mission.
Figure 5. Percentage of Poor Students at Key Schools, 1998–2012
50% 45% 40% 35% 30% 25% 20% 15% 10% 5% 0%
Da Lat Vocational College Dong Nai Vocational College Central Highland Youth Ethnic Minorities Vocational College Vinh Long Technical Teacher Training College Hanoi University of Industry Hai Phong Industrial Vocational College Bac Giang Agricultural and Forestry College Hue Industrial College
Note: The percentage is an average of three programs benefiting from the project at each school. Students are considered poor when they belong to households below the national poverty line. Source: Data collected from key schools during the independent evaluation mission.
22 Viet Nam: Vocational and Technical Education Project
The project made efforts to reach out to disadvantaged students but much more is needed to increase their access to and participation in vocational education
47. The project made efforts to reach out to disadvantaged students (female, minority, and poor), but much more is needed to increase their access to and participation in vocational education. For example, the project could have supported schools’ policies to attract and support poor and ethnic minority students, including provision of scholarships, transportation and living cost subsidies, priority in housing arrangements, and extracurricular activities to help the students integrate. Local governments also offer scholarships to poor and ethnic minority students in their localities. As mentioned in previous sections, the government is paying much attention to the rural workforce, investing around $1.4 billion to train 1 million rural workers per year by 2015. These mobile training programs developed under the project could be an appropriate model for this objective. 48. In terms of the fifth policy reform area on cost recovery and sustainability of the project, schools were able to collect additional revenue from sources such as tuition, short-term training, and production units (Table 8). For example, the provision of equipment allowed schools to offer more short-term courses and production units to take on more production and service orders from enterprises. However, revenue from these sources is limited. Also, the majority of the funding for most schools continues to come from the government. Table 8: Distribution of School Revenue by Source, 2003 (%)
School Agriculture and Forestry College Can Tho Vocational College Da Nang Vocational College Central Highland Youth
Government 73.1 68.6 49.0 38.0 46.9 62.4 50.0 18.0 20.0 65.0 40.0 46.1 56.7
Tuition 13.1 8.9 6.3
Training Activities 0.0 31.3 3.0
Production Unit 0.2 2.4
Project 13.5 19.0 8.6 59.0
Other 0.9 4.9
2.7 11.6 25.0 71.0 45.0 16.0 8.0 44.5 8.3
44.6 3.5 13.0 0.0 15.0 1.0 0.0 4.3 0.2
0.0 1.2 0.0 11.0 4.0 0.0 0.0 5.1 16.3 2.0
0.0 21.3 8.0 0.0 15.0 9.0 36.0 13.7 43.0
5.4 0.0 4.0 0.0 0.5 9.0 16.0 4.8 4.6 22.0
Career service at school plays an important role in many circumstances thanks to direct relations between the school and enterprises
Vinh Technical Teacher Training 42.2 8.2 University Vinh Long Technical Teacher Training 76.0 2.0 College Note: Some rows do not exactly add up to 100% due to rounding. Source: Labor Market Information System—School Survey.
49. Finally, private sector participation remains ad hoc. As shown in Table 9, the main channel through which students obtained their jobs was personal relations (36.7%).30 Career service at school plays an important role (24.6% of students found jobs through this channel), in many circumstances thanks to direct relations between the school and enterprises. Nevertheless, these relations have yet to be scaled up to a
30
This is, however, lower than among graduates of 2002, 45% of whom found jobs through family and friends.
Performance Assessment 23
structural level despite the project’s effort to guide key schools in establishing school– industry advisory councils. For example, the Hanoi Industrial University manages to reach out to many large national and foreign enterprises given its extensive resources and reputation, while other key schools focus mainly on local enterprises. School– industry advisory committees also do not engage the Viet Nam Chamber of Commerce and Industry (VCCI), which is a large network organization of enterprises in Viet Nam. Similarly, there is little evidence that the publications on career guidance and job placement services produced under the project and distributed to schools were actually utilized. Schools appear to conduct career service and job placement activities on an ad hoc basis. 31 In particular, key schools have apprenticeship programs for students to help ensure their employment outcomes, but these are not explicitly promoted by either the project or the government. Table 9: Ways of Seeking Jobs among 2003 Graduates
Way of Seeking Job Career center at school Local job center Family and friends Advertisement Employer directly Government offices Others Total
Source: Labor Market Information System—Survey of Key Schools.
Number 257 89 383 47 111 94 62 1,043
Rate (%) 24.6 8.5 36.7 4.5 10.6 9.0 5.9 100.0
D.
Efficiency
50. The project is assessed to be less than efficient. The training equipment and facilities provided, which account for 71% of the project cost, seem to have been used well by the key schools to enhance the quality of their training and student outcomes. The PCR estimated the utilization of project facilities to be around 95%. Visits to some key schools reveal that all advanced students have the opportunity to practice with modern equipment to familiarize themselves with updated technology, which is useful in their jobs. 51. Nevertheless, the project suffered a long delay of 4 years (with actual completion date in 2008 rather than 2004 as originally planned). This was due to delay in project start-up as well as in procurement of equipment, which was not completed until 2006–2008 (as described in the Procurement section [paras. 14–16). On one hand, this means that most equipment remains new and has not required any major repair. On the other hand, this lengthened the project life and gave little time for the benefits of new equipment to be realized by project completion. Other factors also contributed to the significant amount of time and effort needed to set up the project implementation procedures: (i) The project was subject to many financial and accountability systems of different government and development partners, including four development partners (ADB, AFD, JICA, and NDF), five line ministries, and seven provincial people’s committees that manage the 15 key schools. (ii) The GDVT and the PIU were inexperienced and lacked administrative capacity, especially for an externally financed project.
31
A survey of 13 key schools conducted during the IEM reveals that not all schools offer career guidance services to their students.
24 Viet Nam: Vocational and Technical Education Project
(iii) Authority was not delegated to the project director until much later, which made it difficult to streamline the internal procedures of MOLISA. (iv) Selection of the 15 key schools was finalized only after project signing, and this affected advance actions and preparatory activities by key schools, delaying loan effectiveness and project implementation.
The student– teacher ratio has indeed decreased over time, which may help improve training quality
52. The data collected from 13 key schools during the IEM confirm some of the results of the PCR regarding internal and external efficiency at key schools, but they also reveal issues not discussed in the PCR. For example, the problem of dropping out still persists. Although not very high, 32 the drop-out rate varies across schools and programs, and is more than 20% in Hue, Can Tho, and Da Lat vocational schools.33 The cost per student does not differ much across schools, and averages around D4 million– D6 million during 1998–2012.34 However, the cost per student is much higher than the tuition fees that schools collect, which increased from an average of D480,000 in 1998 to D1.5 million in 2012. As the Effectiveness section points out (paras. 37–49), this means that schools remain dependent on government subsidies. At the time of the project, the government contributed 18%–76% of schools’ revenue (Table 8). The student–teacher ratio has indeed decreased over time, which may help improve training quality.35 53. In terms of external efficiency, the graduation and graduate employment rates are high, reaching an average of 90% for graduation and 84% for graduate employment during 1998–2012. 36 However, not all graduates managed to find employment within their field of training, as only 76% of jobs on average are in the same field.37 Average salaries have increased over the years, from an average of around D17 million in 1998 to D43 million in 2012, which suggests a high return to vocational education.38 54. As a result, the economic internal rate of return (EIRR) for the project needs to be adjusted from the calculation in the report and recommendation of the President (RRP) (as the EIRR was not calculated in the PCR). Several assumptions made during appraisal do not match the actual situation. For example, the RRP assumed that the graduate output of the key schools was about 12,500 annually for the long courses, 37,500 for the short courses, and 6,000 for the upgrading of enterprise workers. Yet, the PCR recorded that the total number of graduates across all courses ranges from
32
Not all graduates managed to find employment within their field of training
The PCR recorded an average drop-out rate of 4% during 2001-2007, while the school surveys conducted during the IEM show an average of 9% during 1998-2012. 33 According to interviews with schools, the main reasons students drop out are (i) difficulty in following the teaching and requirements of the program, since many students lack basic knowledge from previous studies; (ii) losing interest in the training; and (iii) transferring to professional education. 34 This is similar to but a bit higher than the PCR’s record of D2 million–D4 million during 2001–2007. 35 In the PCR, the student–teacher ratio in Viet Nam improved from 36:1 in 2001 to 30:1 in 2007. On the other hand, the trend in developed countries involves rising student–teacher ratios coupled with more efficient management, growth in information and communication technology delivery methods, and increase in short courses and work-based learning (Grootings, P; Nielsen, S., eds. 2005. ETF Yearbook 2005
high cost of training, Viet Nam’s schools can explore ways to keep high student–teacher ratios while maintaining high internal efficiency and quality of teaching. 36 Data collected from 13 key schools during the IEM. This is consistent with the record from the PCR. 37 Data collected from 13 key schools during the IEM. This should be treated with caution, however, as they are based on the estimates of schools and not actual tracer data since schools do not formally track the outcomes of their graduates. 38 Data collected from 13 key schools during the IEM. This should also be treated with caution since they are based on schools’ estimates. These are much higher than the records of the PCR, which show an average of approximately D8 million in 2001 and D13 million in 2007.
– Teachers and Trainers: Professionals and Stakeholders in the Reform of Vocational Education and Training. Turin: European Training Foundation). Given the low supply of quality teachers and the relative
Performance Assessment 25
19,622 in 2001 to 38,900 in 2007. The estimated incremental earnings of the graduates were assumed to be $600 and were expected to increase 5% per year, which is higher than the premium of $366 on average as calculated in the Impact section (paras. 58–73). The assumed employment rate of 95% in years 2–4 and 100% in year 5 is much higher than what actually prevailed, which is 84% and has not changed much over time. This analysis has not included revenue generated from production units and career guidance service fees, but these are minimal. On the other hand, the actual project cost was lower than planned (72% of the original estimate), mostly because of the cancellation of the second phase of staff development, which reduced the project scope. Based on these, the EIRR has been revised from 18.7% in the RRP to 11.0% in this report (Appendix 5).
E.
Sustainability
55. The project is rated likely to be sustainable. With the new curriculum development method and the accreditation and certification systems internalized in the GDVT’s structure and VTE policies (the Vocational Training Law of 2006), it is likely that these policy reforms will be sustained. The 4,900 teachers and administrators trained in the new method created a critical mass that promoted this market-driven and bottomup approach. The curriculum development committees set up by the project remain functional and have set a structure for future planning activities in the VTE system. Many of the curricula developed by the project were approved by the GDVT and were set to be applied nationwide. The equipment provided continues to be in use by the key schools, with the schools providing their own resources for maintaining the equipment.39 These facilities are also shared with some other nonproject schools for their research and study tours. Other schools have also adopted the success model of some key schools (e.g., Hanoi Industrial University), hence enhancing the project’s effect. Some key schools have also leveraged on the enhanced infrastructure and capacity provided by the project to attract support from the government, the private sector, and development partners.40 Of the 15 key schools, 12 were upgraded from technical secondary school to vocational college or from vocational college to university. Schools have been able to collect some additional revenue for cost-recovery from their production units and short-term training courses. 56. Most importantly, the project influenced the thinking of the government on vocational training, which continues to put emphasis on improving the quality and market orientation of VTE. The government started the National Rural Vocational Education program in 2009, investing around $1.4 billion to train 1 million rural workers per year by 2015 to improve agricultural productivity and promote off-farm activities. The government also established the Renewal and Development of Vocational Training System by 2020 project to (i) expand and improve the VTE system to provide 90% of its eligible population (approximately 25 million) with vocational training by 2020 through establishing 230 vocational colleges and 310 vocational secondary schools, and (ii) train 40,000 vocational trainers. The project directed the government
Teachers and administrators trained in the new method created a critical mass that promoted this market-driven and bottom-up approach
The project influenced the thinking of the government on vocational training
39
40
However, it should be noted that schools may not have the resources and expertise to maintain the modern equipment provided. Since most of the equipment is still new, none has yet to be replaced or significantly repaired. Interviews with key schools indicate that schools are only capable of minor repairs and will have to rely on national or foreign enterprises for major work. Furthermore, some machines run on very costly batteries. For example, Hanoi Industrial University continues to receive financial and technical support from JICA through two new projects from 2010 to 2016, aiming to enhance skill training and institutional capacity at the university. Construction Vocational College No. 1 continues to attract investment from the Ministry of Construction, building on the facilities provided by the project.
26 Viet Nam: Vocational and Technical Education Project
in the right direction and Viet Nam’s VTE system needs more of such investment and attention. 57. On the other hand, the LMIS is no longer carried out by the key schools because it is too complex and resources demands are too high. Most of the local staff involved in the system were either hired short-term or have moved out. There is little institutional memory regarding the LMIS remaining at either the PIU or the GDVT.41 Institutional experience could be lost due to high staff turnover and the fact that the PIU was not integrated into the GDVT’s operational structure. Meanwhile, as pointed out previously, the sustainability of schools’ performance depends on government subsidies. This not only undermines schools’ autonomy but also puts a strain on government budget. Although vocational training is an important area that deserves government investment, more could be done to attract resources from the private sector—an area of reform that the project aims to address—to reduce the burden on government and increase schools’ connection with industry.
Although vocational training is an important area that deserves government investment, more could be done to attract resources from the private sector
41
The LMIS model, however, is appreciated by the GDVT, which plans to incorporate it into other development partner projects.
CHAPTER 4
Other Assessments
A. Impact
58. The project’s impact is assessed significant. In general, it helped to orient the VTE system toward a market-driven approach. There was no known adverse environmental or social impact. The PCR stated that the project raised environmental awareness by incorporating instruction on environmental protection measures such as safe disposal of hazardous waste, conservation of energy and nonrenewable resources, and recycling of used materials and equipment in curriculum guides and training programs. There was also no resettlement conducted as project facilities were built in existing locations. Graduates from the key schools are the direct beneficiaries of the project, benefiting from the updated curricula and technology and improved training quality. The PCR reported that by 2008 the project trained 108,000 skilled workers and production technicians. 42 According to the PCR, there were a total of 210,060 graduates from all courses in key schools during 2001–2007,43 but not all graduates directly benefited from the project (Appendix 6 lists the 48 occupations that received assistance from the project in terms of revised curricula, multimedia instructional materials, and equipment). A survey of 13 key schools conducted during the IEM recorded approximately 120,000 graduates from programs involved in the project during 2001–2012. 59. The employment rate of graduates from key schools is an important indicator of the project’s impact. The survey of 13 key schools conducted during the IEM shows that the majority of graduates from key schools managed to find jobs, varying from around 50% for Hue Industrial College’s electricity and metal cutting programs to almost 100% for Hai Phong Industrial Vocational College and Construction Vocational College No. 1. At each school and program, the job-finding rate changes over time but there seems to be no increasing trend, except for Central Highland Youth Ethnic Minorities Vocational College and Dong Nai Vocational College’s electricity-refrigeration program, which show a consistent increasing trend from 1998 to 2012. On the other hand, Vinh Technical Teacher Training University shows a decreasing trend over the years. There were some increases at several schools and programs (e.g., Hai Phong Industrial Vocational College and Can Tho Vocational College) during the course of the project until 2007, followed by a decrease.44 There is no sharp break in the job-finding rate before and after the project. Thus, based on these data, it cannot be concluded that the project has contributed to the employability of students.45
It cannot be concluded that the project has contributed to the employability of students
42 43
More than 37,500 workers and technicians were targeted at appraisal. See the project benefit monitoring and evaluation in the PCR. 44 The recent difficulty for graduates to find employment has been attributed to the economic crisis. Indeed, around 110,000 enterprises in Viet Nam went bankrupt in 2011-2012 as a consequence of low demand, reduced foreign investment, and raised interest rate (Viet Nam Chamber of Commerce and Industry). 45 Survey of 13 key schools conducted during the IEM (data available upon request).
28 Viet Nam: Vocational and Technical Education Project
60. In conducting a more detailed review of the employment impact, the fourth round of the LMIS (2005) shows that the unemployment rate among key school graduates is low. A large percentage of graduates managed to find a job, either through opening their own business, working in their family businesses, or in wage employment (Table 10). Among the graduates of 2004, 13% had not found a job 1 year after graduation, but this percentage may decrease as these students found employment in later years. After 2–3 years of graduation, only 4.1%–6.2% of students were unemployed. Yet, the percentage of graduates doing domestic work is relatively high (3%–6%), which can be considered a form of unemployment. Students tend to join family business right after graduation, but 2–3 years later move on to start their own businesses, become self-employed, or become wage employees. Quite a few students chose to continue studying (around 8%–9%), most of whom enrolled in universities or colleges since these schools recognized some of the credits they obtained from technical training. Table 10: Employment Situation of 2002–2004 Key School Graduates in 2005 (%)
Employment Situation Continuing study Self-employment Family business Wage employee Working and studying Unemployed and job searching Domestic work Others
Source: Labor Market Information System—Tracer Survey.
2002 7.2 7.2 1.9 68.0 3.4 4.1 2.9 5.5
2003 8.0 4.3 2.7 61.0 6.0 6.2 6.2 5.3
2004 8.9 4.2 3.5 57.6 3.5 13.0 3.4 5.9
61. Among the wage employees, a large number of graduates entered the public sector (government agencies in their localities or state-owned enterprises) (Table 11). The trend, however, is that recent graduates tended to work more for private enterprises (both national and foreign-funded); this percentage increased from 43% among 2002 graduates to 56% among 2004 graduates. This is probably because of the growing private sector, which attracts more students because of higher salaries. Table 11: Type of Wage Employment of 2002–2004 Key School Graduates in 2005
2002 Item National government Local government State-owned enterprises Collectives SMEs Joint-stock companies Joint-venture companies 100% foreign-funded companies Farms/crafts workshops Total Number 11 105 237 1 61 125 42 43 9 634 Percentage 1.7 16.6 37.4 0.2 9.6 19.7 6.6 6.8 1.4 100.0 Number 13 148 200 5 87 209 72 77 15 826 2003 Percentage 1.6 17.9 24.2 0.6 10.5 25.3 8.7 9.3 1.8 100.0 Number 10 201 197 10 161 259 54 96 30 1,018 2004 Percentage 1.0 19.7 19.4 1.0 15.8 25.4 5.3 9.4 2.9 100.0
SME = small and medium-sized enterprise. Source: Labor Market Information System—Tracer Survey.
Other Assessments 29
62. In terms of occupations, most graduates of technical worker degrees46 became skilled craftsmen (64.4%) or assembly and operation workers (15.5%). Many secondary graduates (51.1%) and college degree graduates (42.6%) managed to become midlevel technicians, although many still worked in crafts (around 30.0%). Those with college degrees also tended to take on more office work (18.0%) (Table 12). Not many graduates worked in agriculture or service, probably because of the small percentage of students studying these trades among the key schools. Table 12: Occupations of 2004 Key School Graduates in 2005 by Degree Level (%)
Occupation Mid-level technician Office worker Service and sales staff Agriculture and forestry Skilled crafts Machinery assembly and operation Simple labor Total 17.6 6.7 4.7 1.4 55.4 11.4 2.8 Technical Worker 5.8 4.8 3.8 1.8 64.4 15.5 3.8 Secondary 51.1 8.4 6.7 0.4 32.0 0.9 0.4 31.5 College 42.6 18.5 7.4
Source: Labor Market Information System—Tracer Survey.
63. In addition, the project could also have had some impact on teacher training since three of the key schools—Vinh Technical Teacher Training College, Vinh Long Technical Teacher Training College, and Ha Noi Industrial University—provide courses that train VTE teachers. Despite this, many graduates from these programs chose not to become vocational teachers (80% after 1 year of graduation and 70% after 2–3 years). Those who chose to become teachers mainly worked in government training institutions. Even before graduation, only 43% of students in these programs already planned to go into teaching. This could be due to the low salary of teachers, as discussed in the Relevance section (paras. 27–36). 64. The impact of vocational training on students in terms of earnings is significant. The survey of 13 key schools during the IEM reveals that, overall, graduate incomes increased over time, with incomes among graduates from vocational secondary schools lower than from vocational colleges. Graduates from Central Transport Vocational College 1, Vinh Long Technical Teacher Vocational College, Da Nang Vocational College, and Can Tho Technical Worker College have the highest incomes; those who graduated from Agriculture and Forestry Vocational College in Bac Giang and Minority Youth Vocational School in Dak Lak had the lowest incomes. It must be noted that these are also the schools located in rural areas and with the highest proportion of minority students. 65. The salary differential between vocational secondary and college degrees is aligned with findings from the LMIS (Table 13). In general, the salary of graduates increased over time as workers gained more experience. Mid-level technicians (graduates of vocational secondary degrees) often earned around D900,000–D1 million per month, and a majority earned at least D1 million per month. In comparison, college-level technicians had an average salary of D1.1 million–D1.3 million, with a
46
The impact of vocational training on students in terms of earnings is significant
Equivalent to primary level or short-term training after the Vocational Training Law became effective in 2007.
30 Viet Nam: Vocational and Technical Education Project
large percentage earning at least D1.5 million. Since a technical worker’s degree (equivalent to vocational primary) is a short certificate course, graduates from these courses tend to already have working experience and earn more than graduates of vocational secondary degrees. Very few graduates earned less than D500,000. Their salary was higher relative to the salary of labor that required only basic skills, which was around D500,000–D750,000. It could therefore be estimated that the premium of a secondary degree over no qualification is around D150,000–D500,000 (equivalent to $10–$32 at 2005 exchange rate) and the premium of a college degree over a secondary degree is around D100,000–D400,000 (equivalent to $6–$25 at 2005 exchange rate). Table 13: Average Monthly Salary of Key School Graduates by Degree Level in 2005 (D)
Item Technical Worker Secondary College Total 2002 Graduates 1,275,767 957,908 1,326,575 1,228,536 2003 Graduates 1,256,806 1,011,058 1,352,512 1,227,705 2004 Graduates 1,161,880 918,732 1,103,746 1,109,483
Source: Labor Market Information System—Tracer Survey.
Salary breakdown by occupation also shows that there was high demand for largeconstructionmachinery operators and crane drivers, who had relatively high salaries
66. In terms of occupation, graduates who worked as skilled craftspeople (production and processing) and machine operators earned the most (Table 14) while graduates working in agriculture or doing simple manual work had the lowest salary.47 Technical workers did not earn as much as other occupation groups, except for electricians and mechanics (see Appendix 7 for a detailed breakdown of salary by occupations). Office workers (accountants and procurement specialists) and those who worked in sales and services (restaurants), especially those with college degrees, earned relatively well. This is aligned with the salary comparison across sectors (Table 15). Tracing 2004 graduates 1 year after graduation, the survey found that those who entered processing or construction industries had the highest income on average. The salary breakdown by occupation also shows that there was high demand for largeconstruction-machinery operators and crane drivers, who had relatively high salaries (at least D1.3 million). Table 14: Average Monthly Salary of Key School Graduates by Occupation Groups in 2005 (D)
Item Management High-level technician Mid-level technician Office worker Sales and services Agriculture, forestry, and aquaculture Skilled craftsperson Machinery assembly and operation Simple work Total 700,000 1,023,333 1,017,236 1,158,418 1,080,595 717,338 1,340,559 1,385,565 910,588 Technical Worker 700,000 1,500,000 1,073,174 948,712 1,115,593 770,000 1,358,087 1,400,517 784,286 Secondary College
...
937,500 876,760 1,134,500 720,000 541,800 1,125,652 1,168,750 1,000,000
...
1,300,000 1,093,543 1,322,300 1,415,000
...
1,508,865
...
1,750,000
47
These are also the occupation groups with the highest demand in the labor market.
Other Assessments 31
Item Total Total 1,227,993 Technical Worker 1,263,712 Secondary 989,603 College 1,350,296
... = data not available. Source: Labor Market Information System—Tracer Survey.
Table 15: Average Monthly Salary of 2004 Key School Graduates by Sector in 2005 (D)
Sector Agriculture, forestry, and aquaculture Extractive industry Processing industry Electricity, gas, and water Construction Services Total Total 699,158 1,103,200 1,223,261 1,187,027 1,247,211 957,986 1,110,450 Male 763,411 1,103,200 1,254,726 1,178,333 1,251,655 1,024,394 1,173,136 Female 538,525
...
969,366 1,500,000 925,000 851,538 858,609
... = data not available. Source: Labor Market Information System—Tracer Survey.
67. The salary variation also depends on the type of employers that graduates had (Table 16). Wage employment in state-owned or private enterprises generated the highest income, which explained the popularity of these workplaces among graduates. Although the salary was low, local government offices attracted many students, probably because of other benefits such as tenure and social security. Not many students chose self-employment because the income was relatively low. This, however, was still a better option than family business or farm work for those who could not obtain wage employment. Table 16: Average Monthly Salary of 2004 Key School Graduates by Employer in 2005
Employer Self-employed Family business National government Provincial/local government State-owned enterprise Collective Small or medium-sized enterprise Joint-stock enterprise Joint-venture enterprise 100% foreign-funded enterprise Farm/crafts workshop Total
Source: Labor Market Information System—Tracer Survey.
The salary variation also depends on the type of employers that graduates had
Number of Graduates 67 65 10 201 197 10 161 259 54 96 30 1,150
Salary (D) 984,627 839,692 982,000 773,846 1,375,939 800,000 1,103,665 1,194,494 1,307,556 1,318,333 890,000 1,109,483
68. There is, however, a wage differential between males and females (Table 17). The income of female graduates was, on average, 20%–30% lower than male graduates. According to the LMIS, around 80% of female workers earned less than D1 million, compared with 70% among male workers. This salary gap is the biggest among
Salary gap is the biggest among technical workers and smallest among college graduates, which indicates that education and training could help narrow the gap between males and females
32 Viet Nam: Vocational and Technical Education Project
technical workers and smallest among college graduates, which indicates that education and training could help narrow the gap between males and females. Table 17: Average Monthly Salary of 2004 Key School Graduates by Gender in 2005 (D)
Training Level Technical worker Secondary College Total 1,161,880 918,732 1,103,746 1,109,483 Male 1,202,830 1,025,094 1,126,997 1,172,087 Female 849,368 762,733 1,069,927 857,698
Graduates of academic colleges and universities tended to have higher incomes than graduates of vocational colleges, which may explain why the academic track still attracts more students than the vocational track
Total
Source: Labor Market Information System—Tracer Survey.
69. An analysis of the broader labor market in 2010 confirms these earnings differentials across educational level (Table 18). In general, vocational college degree holders earned more than vocational secondary degree holders if they were also high school graduates. Vocational secondary degree holders who left academic education after secondary school actually earned more than those who went to high school, probably because they had more years of work experience, but the sample size of the former group is too small to be conclusive. Vocational graduates earned more on average than professional graduates. Most importantly, graduates of academic colleges and universities tended to have higher incomes than graduates of vocational colleges, which may explain why the academic track still attracts more students than the vocational track. Those who had wage employment (public or private employers) often earned more than those who worked on their own farms or were self-employed. Table 18: Average Monthly Salary by Educational Level in 2010 (D ‘000)
Technical Degree None General Education No qualification Primary Secondary High school College University Master Vocational Primary Primary Secondary High school College University Vocational Secondary Professional Education Secondary High school Secondary High school Total Monthly Salary 1,522 1,690 1,789 2,020 3,000 4,384 7,703 2,538 2,459 2,742 2,635 3,606 2,798 2,783 1,790 2,524 Observations 973 1,818 1,964 851 280 854 45 63 192 188 3 20 51 256 31 564 Monthly Wage Salary 1,615 2,030 1,962 2,253 2,995 4,440 7,496 2,534 2,577 2,976 2,693 3,655 3,113 2,884 2,111 2,530 Observations 166 448 755 523 268 833 45 38 132 137 2 17 35 227 21 529
Other Assessments 33
Total Monthly Salary 2,796
Technical Degree Vocational College
General Education High school
Observations 37
Monthly Wage Salary 2,762
Observations 35
Note: Total salary = earnings in the last 30 days of those who work full time (at least 20 days); wage salary = restricted to those who work for an employer (excluding farm work and self-employment). Vocational primary is equivalent to technical worker certificate (short-term courses). The qualification to enter a vocational secondary program is at least a general secondary degree and for vocational college is a high school degree. Source: Viet Nam Household Living Standard Measurement Survey 2010—a national representative survey of 36,756 households across the country. The sample is restricted only to individuals who worked in the last 30 days.
70. There is, however, the issue of mismatch between skills and employment among graduates. The tracer survey of key school graduates shows a high percentage of those who did not work in jobs that matched their training (Figure 6). The share of nonmatching jobs ranged from 10% to 45% and varies across survey rounds and degrees. Among the three degrees (technical worker, vocational secondary school, and vocational college), graduates from vocational secondary schools had the highest rate of nonmatching jobs. Of the 570 graduates who were traced in both the second and third rounds of survey and who had a job at the time of survey, 13.9% worked in jobs that did not match their skills in round 2, and 9.1% in round 3. Between the two rounds, 45.6% of those who had nonmatching jobs in round 2 managed to find a job that matched their skills in round 3. Among those who graduated from technical worker degrees, all of those who studied construction machinery obtained jobs that matched their skills. The rate is also high for those who studied construction and food processing. In contrast, those who studied computer technology or information technology had the highest rate of nonmatching jobs as the majority of them ended up working in electronic appliance shops (Appendix 8 summarizes a breakdown of matching by occupation and degree level). Figure 6: Matching between Occupations and Training Program of Key School Graduates
There is, however, the issue of mismatch between skills and employment among graduates
Technical Worker Secondary College
Round 2 Round 3 Round 4 Round 2 Round 3 Round 4 Round 2 Round 3 Round 4 0% 20% 40% 60% Matching 80% 100%
Not Matching
Note: The bottom group of bars represents graduates of technical worker’s degree, the middle of secondary degree, and top of college degree. In each group, the bottom bar is results from the second round of survey (2003), the middle from the third round (2004), and the top from the fourth round (2005). In each bar, the left shades represent nonmatching and the right matching. Source: Labor Market Information System—Tracer Survey.
34 Viet Nam: Vocational and Technical Education Project
Mismatch between labor supply and demand can lead to underutilization of human resources and constrain economic growth
71. Mismatch between labor supply and demand can lead to underutilization of human resources and constrain economic growth. When labor supply does not match labor demand, it can result in unfilled vacancies, unemployment, underemployment, or reduced productivity. Therefore, the importance of skills supplied by both vocational and general education institutions cannot be understated. To meet the demand for skills in various occupations in the labor market, it is imperative that educational institutions identify the type of skills required by different occupations. Skill shortage and mismatch, however, remains an issue in Viet Nam’s labor market. Under the project preparatory TA it was estimated that Viet Nam required 9.98 million skilled workers and technicians by 2003, yet the supply could only meet less than half of that, resulting in a shortage of 5.19 million workers (Table 19). Table 19: Projected Labor Demand and Supply of Skilled Workers and Technicians (million)
Item A. Labor force demand 1. Agriculture 2. Nonagriculture a. Engineers b. Skilled workers and technicians B. Supply of skilled workers and technicians C. Shortage of skilled workers and technicians 1998 Number % 37.80 24.60 13.20 2.65 6.63 3.94 (2.69) 65.0 35.0 7.0 17.5 2000 Number % 40.20 24.90 15.30 3.06 7.65 4.28 (3.37) 62.0 38.0 7.6 19.0 2003 Number % 43.90 24.00 19.90 3.99 9.98 4.79 (5.19) 55.0 45.0 9.1 22.7
This shortage is due to both the lack of people with skill training and irrelevance of skill training to the skills demanded by employers
Source: ADB. 1996. Technical Assistance to the Socialist Republic of Viet Nam for the Technical Education Project. Manila (TA 2671–VIE, for $800,000, approved on 27 December 1996).
72. This shortage is due to both the lack of people with skill training and irrelevance of skill training to the skills demanded by employers. The National Survey Assessment of Vietnamese Youth in 2003, covering a national representative sample of 7,584 people aged 14–25 years living in households across Viet Nam, indicated that only 19.0% were involved in vocational training with 13.4% having completed training and 5.6% in the process of being trained. Of those who had received vocational training, 67% found a job with the skills they were provided whereas the rest could not find the job for which they had received training.48 73. The mismatch issue is prevalent even among those who managed to obtain jobs within their field. According to the enterprise survey as part of the LMIS, enterprises in general value the vocational training of students, as 76% rated the theory and practice training quality to be good. However, 50% considered other aspects of training to be lacking (e.g., "soft" skills).49 Private enterprises tended to have a lower opinion of the quality of training than public enterprises. Among foreign-owned
48
Dang, Nguyen Anh, et al. 2005. Youth employment in Viet Nam: Characteristics, Determinants and Policy Responses. Employment Strategy Papers. Geneva: ILO. 49.
Other Assessments 35
enterprises, 40% thought that the theory and practice training was not satisfactory. In addition, a survey conducted by the VCCI jointly with the ILO in 2008 among 243 enterprises from Ho Chi Minh City and Hanoi shows that a large percentage of employers appeared not to value very highly the skills training provided by the public education and qualification system or by domestic training providers, as opposed to skills training conducted by foreign-funded institutions or overseas (Table 20). Respondents also felt that coaching and mentoring of younger workers by other staff within the organizations was the most effective training method (with over 85% either agreeing or strongly agreeing). Apprenticeships taken before formal recruitment were also seen as largely effective by around two-thirds of the respondents. Meanwhile, a significant proportion of respondents disagreed with the statement that training courses offered by external centers were effective, perhaps reflecting a desire to keep training in-house to ensure the skills developed by the individuals relate to the work of the organization.50 Table 20: Ratings of Enterprises on Training of Workers Aged 16–25 Years (%)
Item Trained by ourselves Trained abroad, including exported laborers Available in large numbers Of good quality Have an appropriate proportion of
50
Strongly Disagree 12.4 3.6 3.1 3.1 10.5 6.7 7.9 7 8.3 5.6 3.8 5.2 10.7 7.4 6.8 11.6 15.1 7.9 8.5
Disagree 15.1 10.4 8.8 5.8 15.1 17.4 14.6 16.3 18.5 16.1 20.1 17.4 22.7 6.1 9.5 13.7 30.9 12.2 14.2
Neutral 34.1 40.4 34.7 33.5 30.8 48.3 51.1 47.7 39.5 58.4 52.8 54.8 43.3 31.1 40.5 40.4 30.9 28.8 33.3
Agree 21.6 30.6 34.2 39.3 24.4 21.9 18 23.3 24.2 17.4 20.1 20 16.7 39.9 35.1 26.7 15.8 33.8 32.6
Strongly Agree 16.8 15.0 19.2 18.3 19.2 5.6 8.4 5.8 9.6 2.5 3.1 2.6 6.7 15.5 8.1 7.5 7.2 17.3 11.3
Trained by state-owned vocational training institutions without foreign Investment
Trained by private vocational training institutions without foreign investment
Trained by Viet Nam-based vocational training institutions with foreign investment
VCCI and ILO. 2009. Youth Employment in Viet Nam: Report of Survey Findings. Centre for Labour Marker Studies, University of Leicester, UK for Viet Nam Chamber of Commerce and Industry (VCCI)/International Labour Organization (ILO). Hanoi: VCCI.
36 Viet Nam: Vocational and Technical Education Project
Item required skills Are cost effective Attracted from competitors Available in large numbers Of good quality Have an appropriate proportion of required skills Are cost effective 14.0 3.0 3.8 3.8 25.5 10.3 11.9 11.5 40.1 46.7 41.9 29.5 15.3 33.3 33.8 37.2 5.1 6.7 8.8 17.9 N=156–165
Source: VCCI and ILO. 2009. Youth Employment in Viet Nam: Report of Survey Findings. Centre for Labor Marker Studies, University of Leicester, UK for Viet Nam Chamber of Commerce and Industry/International Labour Organization. Hanoi: VCCI.
Strongly Disagree 14.7
Disagree 19.9
Neutral 33.8
Agree 20.6
Strongly Agree 11
B.
ADB, Development Partners, and Borrower Performance
Project preparation and approval documents show ADB’s substantial understanding of the major issues in Viet Nam’s VTE system
74. ADB performance is rated satisfactory. Project preparation and approval documents show ADB’s substantial understanding of the major issues in Viet Nam’s VTE system. ADB seems to have provided sufficient consulting services to support the executing agency in implementing the project. There was adequate supervision in terms of review missions and timely responses to the executing agency’s requests for the project’s extensions. The midterm review and project completion review were also timely. At the same time, it should be noted that ADB underestimated the management capacity of the executing agency and did not accordingly adjust the project design in keeping up with the project’s transfer from MOET to MOLISA. The selection of 15 key schools was not supervised closely. The LMIS was not used effectively to monitor the progress of the project. Currently, only Hanoi Industrial University continues to receive support, and hence is monitored by JICA. The progress of the other key schools is not systematically monitored and students are no longer traced after graduation. Without efforts to track the project beneficiaries, it is difficult to assess the impact of the project. ADB also did not provide clear guidance on which procurement process to follow when there was conflict between the guidelines of ADB, the development partners, and MOLISA. There could also have been better effort by ADB to coordinate with cofinanciers to incorporate them under the same implementation structure and exchange lessons learned. 75. The performance of the borrower is assessed satisfactory. The executing agency was successful in meeting key project performance indicators and complying with a majority of the loan covenants. The project also received high-level support and its recommendations were incorporated into important policy reforms, i.e., the Vocational Training Law 2006. However, project performance was complicated by the fact that Viet Nam’s VTE system is supervised by many different government agencies. With the establishment of the GDVT under MOLISA, responsibility for VTE was transferred to MOLISA. However, MOET still maintains responsibility over professional education institutions, which also provide technical training, albeit with more focus on theory (Appendix 2). As a legacy of the command economy, VTE schools are established and operated by individual line ministries to meet their own staffing needs. These line ministries serve as governing bodies, providing funding and guidance in terms of
The executing agency was successful in meeting key project performance indicators and complying with a majority of the loan covenants
Other Assessments 37
personnel and strategy.51 At the same time, all schools that provide VTE programs are subject to the Law on Vocational Training under the supervision of MOLISA. If a school provides academic or professional education, it is also subject to the Education Law under the responsibility of MOET. Recognizing this overlapping authority, the project set up a project steering board committee, with representatives from relevant government agencies (MOET, MOLISA, VCCI, and labor and women’s unions). When JICA proposed to separate its two key schools and directly work with the two line ministries governing them (i.e., the Ministry of Industry and Trade and Ministry of Transport), the project decided to include the two ministries in the Project Steering Committee. However, no other governing agency of the other key schools was included. 76. Coordination among government agencies during project implementation was weak. The Project Steering Committee only met a few times and had little authority over the implementation of the project. The project was mainly executed by the PIU with guidance from the GDVT. Other government offices were involved only indirectly as governing bodies of key schools. There was also limited communication between MOET and MOLISA, although the two ministries have overlapping responsibilities over the VTE agenda. The transfer of responsibility over VTE from MOET to MOLISA in 1998 illustrates this disconnection. Such transfer partly caused a 1-year delay at the beginning of the project. Prior to 1998, VTE was managed by the Vocational Education and Training Office under MOET, but the staff capacity was limited.52 The establishment of the GDVT under MOLISA in 1998 to take over the VTE agenda was expected to facilitate the transition to a demand-based training system as MOLISA has closer connections with private sector employers. The project also foresaw little risk involved with institutional capacity if the entire department and relevant staff of MOET were to be transferred to MOLISA. This change, however, did not include the proper transfer of staff or documents, which caused initial confusion at the PIU as it took over a project designed under another ministry. 77. On top of this complicated governing structure, the project also faced the complexity of dealing with four different development partners. There was a lack of collaboration among these agencies as each focused on its own funded schools. Interviews with development partner representatives reveal that lessons learned at each key school or by each development partner were not actively shared with one another during project implementation. This is unfortunate because some development partners may have important success stories that could have benefited others. For example, JICA followed its own implementation model and built a long-term relationship with Hanoi Industrial University by establishing the Viet Nam–Japan Training Center, which then led to JICA’s subsequent engagements with the school. JICA published an evaluation of its collaboration with the two schools, but only at the end of the project. Furthermore, the administrative and accountability requirements of development partners were different from, and at times conflicted with, each other, causing confusion and challenges for the PIU. Finally, the fact that schools received different levels of funding from different development partners53 also means that the project’s impact on key schools varied.
51
Coordination among government agencies during project implementation was weak
On top of this complicated governing structure, the project also faced the complexity of dealing with four different development partners
The 15 key schools are supervised by seven different line ministries and five provincial people’s committees. For example, Hanoi Industrial University and Ho Chi Minh City University of Industry are governed by the Ministry of Industry and Trade, Agriculture and Forestry College in Bac Giang is under the Ministry of Agriculture and Rural Development, while Hai Phong Industrial Vocational College is under the Hai Phong People’s Committee. 52 The office had only three staff. 53 AFD provided $12 million for four schools, the NDF provided $6 million for three schools, while JICA provided $24 million for two schools.
38 Viet Nam: Vocational and Technical Education Project
C.
Technical Assistance
The effectiveness of the associated capacity building TA is considered
The capacity building TA was important to train staff on the market-driven approach to VTE and help them learn from international experience
78.
moderate. The capacity building TA was important to train staff on the market-driven
approach to VTE and help them learn from international experience. Considering that the project was the first foreign-funded project of the then newly established GDVT and PIU, the TA was important to prepare staff on project implementation. Through the project, the TA also helped government agencies to streamline their strategies for VTE. Starting with 40 staff and six divisions, the GDVT has expanded to 10 divisions, most prominently with the addition of the Department of Vocational Accreditation and Department of Skills Testing and Certification upon the project’s recommendations. Moreover, the project contributed to the drafting of the Law on Vocational Training, effective in 2007. However, the TA would have been more effective if its scheduling was better aligned with the project. The delay in the start-up of the project weakened the momentum generated under the TA and some staff trained under the TA had already moved out. The PCR reports that the TA should have focused more on improving administrative capacity rather than technical capacity. 79. Indeed, the TA did not account for the weak administrative and management capacity of the executing agency and PIU, which posed some risks to project performance. The first 2 years of project implementation was slow because of lack of both capacity and staff assigned to work on the project. Hence, outsourcing was resorted to outside of MOLISA and GDVT to relieve the staffing pressure. Frequent personnel movement also affected the performance and retention of institutional memory. The PIU had few staff, had a high turnover rate, relied on consultants, and had difficulty attracting and retaining quality staff given the public sector salary. Finally, the initial projection for staff development, which included upper secondary teachers in schools administered by MOET, was not immediately adjusted after the project was transferred from MOET to MOLISA, and this affected the planning of this component.
80. This evaluation also notes the weak monitoring and evaluation of the project. Data on schools were available only intermittently, which made it difficult to adjust activities and monitor the progress of the project. The LMIS set up by the project helped establish an information system for schools and the GDVT to understand market demands and trace graduates. However, the system was not continued and utilized, partly because of the complexity and high cost of the survey,54 and partly because of the lack of emphasis on building capacity at the GDVT to process the survey data. The surveys were outsourced to international consultants and the Vocational Training Research Center without retaining the knowledge within the GDVT.
54
The survey has seven modules and requires that thousands of enterprises, workers, teachers, school administrators, and graduates are interviewed.
CHAPTER 5
Issues, Lessons, and FollowUp Actions
A. Issues
81. The project has identified and attempted to address many issues in Viet Nam’s VTE system that constrain the supply of relevant and quality labor, which may consequently affect economic growth. Yet, this evaluation shows that the country’s VTE sector remains beset with many challenges. First, the VTE system has a complex structure. The project focused on modernizing the strategy of the system, but the weak and overlapping management of the government could undermine this effort. In particular, although the capacity of the GDVT may have been improved with the assistance of the project, it still does not match the current influx of VTE institutions. The number of vocational institutions almost doubled, from 224 in 2006 to 429 in 2010, in addition to 804 vocational centers.55 This may explain why the PAS and TCS have yet to be implemented nationwide. The GDVT piloted them in a few schools and encouraged other schools to conduct self-assessment, but has not been able to conduct a systematic qualification evaluation. As explained earlier, these institutions are also subject to different governing bodies and financing mechanisms so their policies and quality vary. The overlapping responsibility of MOLISA and MOET over technical and professional education should also be addressed. Although MOLISA has more expertise with the labor market, it has less experience in terms of education and training. Better coordination between the two ministries overseeing academic and vocational institutions may help ensure a more effective response toward challenges in the VTE system, such as assessing the skill level of the entire workforce. 82. Second, although the project oriented the VTE system toward a market-driven approach, the system remains largely supply driven. The recruitment of students is based on a top-down mandate given by the managing government agency. Although there is a strong desire to connect with industry, collaboration remains limited and ad hoc. The delay in implementing the TCS has resulted in a lack of skills standards that link specific competencies to labor market needs. The project laid the groundwork for a curriculum development approach that responds to market needs, yet the curricula will need to be revised regularly to remain relevant to the changing economy. This, however, will put a large financial burden on the government. Similarly, training equipment and teachers' skills will need to be periodically updated to match the curricula and new technologies in the job market, which will also require a lot of resources. Given these factors, the project could have set up an endowment fund to ensure sufficient resources for the continuity and update of project outcomes such as training curricula and equipment.
This evaluation shows that the country’s VTE sector remains beset with many challenges
55
GDVT. 2011. Report of Vocational Activities 2006-2010. Hanoi: MOLISA.
40 Viet Nam: Vocational and Technical Education Project
83. Finally, the project did not set out to adequately address the issue of access to and participation in VTE. As elaborated upon earlier, VTE remains an unpopular track for students; academic degrees are considered to be more socially and economically valuable. The National Survey Assessment of Vietnamese Youth in 2003 revealed that a high proportion of university graduates were still looking for jobs and only half of them were engaged in a job with the training they received. 56 Thus, there may be an oversupply of university graduates who could be oriented toward vocational education that needs more and better-quality students. If VTE institutions mostly attract lowperforming and unmotivated students, they may suffer from high drop-out rates, which means wastage to the system and could lead to low-quality skills that are not valued by employers. 84. The project is succeeded by another ADB loan aiming to address some of these weaknesses. The Skills Enhancement Project with MOLISA intends to address skills shortages in key occupations by improving the quality and management of VTE programs in 15 public and 5 private vocational colleges in economic zones offering programs for occupations in high demand in priority industries. 57 Nevertheless, reforming Viet Nam’s VTE system requires long-term and coherent investments. ADB will therefore need to continue its engagement and collaboration with other development partners to ensure that efforts are comprehensive and well coordinated.
B.
Lessons
Risks that may undermine project implementation should be identified and planned to be addressed in advance
85. The experience of the project gives some important lessons for Viet Nam’s VTE system in particular and for ADB’s vocational training sector in general. According to the PCR, the following are important lessons learned from the project: (i) an adequate project management structure should be in place before the project starts, (ii) the scope of project coordination work should be in line with the capacity of the implementing agency, and (iii) operation and maintenance cost should be adequately addressed and provided. 86. In addition to these, this evaluation has identified other lessons. First, risks that may undermine project implementation should be identified and planned to be addressed in advance. For this project, such risks include weak and overlapping management of the VTE system, detachment of training from industry needs, and poor social image of VTE. A streamlined system that is closely linked with the market will help ensure smooth school-to-work transition for students, which could then improve the perception of vocational training. Furthermore, the project should have focused on strengthening the administrative and management capacity of the executing agency and PIU to avoid unnecessary delays. 87. Second, an efficient information system is important not only to monitor the progress of the project but also to provide real-time data critical for policy making. The LMIS was the first attempt of the VTE system to trace students after graduation and collect systematic information on enterprise demand. However, its complexity made the system costly and unsustainable. A more integrated and less complex system would be useful so that schools can have the resources and capacity to collect information. Schools should also be given incentives to carry out these types of survey.
An efficient information system is important not only to monitor the progress of the project but also to provide real-time data critical for policy making
56
N. A. Dang et al. 2005. Youth employment in Viet Nam: Characteristics, Determinants and Policy Responses. Employment Strategy Papers. Geneva: ILO. 57 ADB. 2010. Report and Recommendation of the President: Proposed Loans to the Socialist Republic of Viet Nam for the Skills Enhancement Project. Manila.
Issues, Lessons, and Follow-Up Actions 41
88. Third, linkage with enterprises is important in assisting students find jobs and lowering the burden among training providers. Enterprises are a key beneficiary of skilled labor and hence have direct interest in skills training. Yet, they are often skeptical of the quality of training provided by public VTE institutions because of the disconnection between the two. Without good relations with employers, schools will find it difficult to provide students with job information or align their training to employers’ needs. Some employers are actually keen on providing their own training to ensure that the skills are relevant. Although firm-specific training may not replace general skill training, schools can collaborate with enterprises to organize in-house training or recruit their employees to be the trainers for some specific skills and modules. This can benefit both the schools and the enterprises, as teachers and students are updated with new technologies, and enterprises can partner with a school to certify and upgrade skills for their workers. Together with technical training, schools should also pay attention to enhancing students’ work ethics, knowledge about their rights and responsibilities, and labor laws, as such "soft" skills are valued by employers and beneficial for the students. Furthermore, linking schooling with work-based programs through apprenticeship has the potential to help students practice their learning and obtain practical problem-solving skills. Because apprenticeships often lead to employment, they can also motivate young people to stay in school and complete their education. Apprenticeship has proven particularly successful in some contexts. In Viet Nam, schools find apprenticeship to be very important for students to find jobs after graduation (Cooking and Hotel Business Vocational Secondary School). The German dual system, which combines structured training within a company and parttime classroom, has become a model for many countries. In France, going through an apprenticeship increases the likelihood of being employed 3 years after completion.58 Cooking and Hotel Business Vocational Secondary School
The Cooking and Hotel Business Vocational Secondary School stood out as one of the schools with a consistently high job-finding rate (almost 100%) over the years. This is partly because it has very good connections with restaurants and hotels in surrounding areas. The school was the first to know when a position opened up. It also maintains a feedback loop with these employers to update the skills that they train, rather than focusing on skills that may be less costly. The school also has a mandatory apprenticeship program of 4-6 months with these enterprises. Students gain a lot of experience during the apprenticeship and are often kept as employees afterwards. As a result, almost 100% of students managed to obtain jobs within 3 months of graduation and they also work in the same field as their training.
Source: Interview and data collected during the independent evaluation mission.
Linkage with enterprises is important in assisting students find jobs and lowering the burden among training providers
89. Finally, a qualification and certification system is critical to ensuring the quality of skills and facilitating labor mobility. Governments in over 100 countries are designing, implementing, or considering national qualification frameworks or are involved with regional qualifications frameworks. The idea is that all qualifications can (and should) be expressed in terms of outcomes.59 Students can be tested based on their competency and certified accordingly, regardless of their learning pathways. This will help assure employers of the skills of their workers. At the same time, it will allow workers to move across sectors, as well as to other countries if the national qualification framework is aligned with regional and international frameworks. Workers
UNESCO. 2012. Education for All Global Monitoring Report: Youth and Skills—Putting Education to Work. Paris. 59 S. Allais. 2010. The Implementation and Impact of National Qualifications Frameworks: Report of a Study in 16 Countries. Geneva: ILO.
58
A qualification and certification system is critical to ensuring the quality of skills and facilitating labor mobility
42 Viet Nam: Vocational and Technical Education Project
can also move in and out of education to leverage on the knowledge they gain in the workplace. 90. The follow-on Skills Enhancement Project (footnote 57) recognizes these lessons and adopts some of them in its design. In particular, the selection of key schools was completed prior to project approval and through a transparent process. Based on a labor market survey, specific programs were identified in advance to ensure a focus on the most in-demand occupations. This follow-up project also promotes more effective sector leadership to ensure smooth project operation, implements skills standards and strengthens skills testing and certification to increase the relevance of skill training, and increases the teaching skills of instructors through in-service training. The project is particularly supportive of a national social marketing campaign to improve the poor social image of VTE and the gradual shifting of VTE funding from the public to the private sector, piloting the campaign on five private vocational institutions.
C.
Follow-Up Actions
91. The evaluation recommends that the Social Sectors Division of the Southeast Asia Department (SERD) continue to engage with the GDVT and MOLISA to monitor the progress of the VTE system reforms, particularly the implementation of the Vocational Training Law and the nationwide adoption of the PAS and TCS. The division also needs to be more active in collaborating with other development partners to share lessons and coordinate assistance strategies. This can be done under the framework of the follow-on Skills Enhancement Project, which is important to continuing the momentum of the project and covering unaddressed issues. The division can also consider whether more of such engagement is necessary if VTE continues to be a priority of the education sector. 92. MOLISA and the GDVT need to strengthen the macro-level linkage between the VTE system and the labor market. The GDVT should work with the VCCI to facilitate this relationship, e.g., by establishing sector skills councils to match the skill requirements of the labor market with training. Systematic skills training planning frameworks will not only help minimize skills mismatches but also support the country’s competitiveness. In addition, it will be necessary to encourage, if not enforce, apprenticeship and emphasize employment services and job counseling for students before graduation. However, the GDVT should provide incentives for schools to create local networks, particularly with enterprises in surrounding areas rather than have the government mandate this. Experience of schools suggests that local enterprises are the main employers of graduates and they will also be the ideal places for apprenticeship. 93. The government should streamline VTE management to reduce existing overlapping responsibilities among government ministries and agencies. It should also balance the investment between vocational and academic institutions, and subject them to one coherent management framework. The government can take the lead in providing information and guidance to students in secondary and high schools about the benefits of vocational training to help change their attitude about, and increase their demand for, VTE. SERD can monitor the progress of these recommendations by the GDVT, MOLISA, and the government under the framework of the follow-on Skills Enhancement Project as well as the next country partnership strategy.
Appendixes
APPENDIX 1: SUMMARY DESIGN AND MONITORING FRAMEWORK
Design Summary a 1. Impact Reform the Vocational and technical education (VTE) system to support the government’s market-oriented industrialization policy and supply well-trained skilled workers and production technicians for key occupations Performance Indicators and Targets Introduce demand-based VTE programs to increase external efficiency Train 37,500 skilled workers and production technicians Increase the efficiency of VTE programs at 15 key schools Introduce quality assurance systems PCR/PPER Update Sustainability This impact is sustainable, but the graduates’ skills can be better utilized if they are properly certified.
Market orientation of
120,000 skilled workers
VTE programs improved
2. Outcome 2.1 Improve the market orientation of the VTE system
Conduct four labor market
surveys Develop 100 VTE programs Prepare 500 sets of instructional materials Develop 100 sets of computer course materials Designate 15 key schools Increase the size of schools Procure equipment Establish 15 production units
2.2 Develop key schools to improve the internal efficiency of VTE programs
Provide consulting services Train school staff,
instructors, and GDVT administrators
and production technicians trained during 2001–2012 Employment rates of the graduates ranged from 82% to 86% during 2001–2012 Vocational accreditation and national skills testing and certification introduced but not yet implemented Four annual labor market surveys conducted and results published 48 curricula developed with the new method 97 curriculum guides developed: 27 at college level, 43 at secondary level, and 27 for mobile training programs 100 computer course products developed MOLISA designated 15 key schools Schools expanded with new training programs, but enrollment fluctuated Procurement of equipment included 16 packages, which were financed by ADB for $12.4 million for six key schools (seven packages), NDF for $6.4 million for three key schools (five packages), and by AFD for €9.0 million equivalent for four key schools (four packages) 15 production units established 261 person-months of international consultancy and 442 person-months of national consultancy
The labor market surveys Curricula and equipment
need to be regularly updated to reflect changing labor market needs. Schools should gain resources and expertise to maintain equipment. Production units add minimal revenue to schools.
are no longer conducted.
TVET institutions still
struggle to attract and retain quality teachers
Summary Design and Monitoring Framework 45
Performance Indicators and Targets
Design Summary a
2.3 Strengthen institutional capacity of GDVT to implement VTE reforms effectively
Develop program
accreditation system Introduce technical certification system
3. Outputs 3.1 Improve market orientation
Change supply-driven VTE
system into a marketoriented system Develop highly relevant VTE programs
3.2 Develop key schools
Improve 15 key schools up
to international standard Operate self-sustainable production units
PCR/PPER Update were used in instructional design; curriculum and multimedia development; skills standards, testing, and certification; and school– industry partnership 4,700 staff, instructors, and administrators received training MOLISA adopted the Viet Nam National Accreditation System for the quality control of training programs MOLISA introduced technical certification system GVDT established Vocational Accreditation Department and National Skills Testing and Certification Department MOLISA established 12 national curriculum appraisal boards to assist MOLISA in appraising curriculum guides New curriculum development method (DACUM) introduced 48 curriculum development committees established for 48 occupations Program–industry advisory committees and school–industry advisory councils established in all key schools 12 out of 15 key schools upgraded from technical secondary school to vocational college, or from vocational college to university 15 production units operational
Sustainability
The PAS and TCS are
only on paper and still in pilot phase. GDVT needs to enhance its capacity to implement the two systems nationwide.
Program–industry
advisory committees and school–industry advisory councils are not very active. School–industry relations remain ad hoc.
Key schools have not yet
3.3. Introduce policy reforms and strengthen institutional capacity
Provide consulting services
on VTE reform Provide staff training to improve institutional capacity
261 person-months of
international consultancy and 442 person-months of national consultancy were used
been accredited. Quality of schools varies. Schools are yet to be financially autonomous and have to compete for limited government funding, which constrains their activities. Administrators should also be given administrative and management training to streamline the VTE
46 Viet Nam: Vocational and Technical Education Project
Design Summary a Performance Indicators and Targets Introduce policy reforms PCR/PPER Update Sustainability system. Vocational Training Law is still in the process of being implemented.
4,700 staff, instructors,
4. Inputs
and administrators received training Vocational Training Law passed by National Assembly in 2006 and became effective on 1 June 2007
A. Base Costs
Staff Development Consultant Services Surveys and Studies Instructional Materials Equipment and Civil Works Implementation Taxes and duties
Total Base Cost B. Contingencies C. Service Charge Total Cost
a
$10.1 million $7.7 million $0.5 million $12.5 million $56.0 million $8.3 million $7.8 million $4.8 million
$6.44 million $6.26 million $0.33 million $6.34 million $47.31 million $14.21 million $1.65 million $2.90 million
$85.45 million $0 $0.84 million $86.29 million
Furniture
$107.7 million $10.8 million $1.5 million $120.0 million
Report and Recommendation of the President: Proposed Loan to the Socialist Republic of Viet Nam for the Vocational and Technical Education Project. Manila.
The design summary and performance targets/indicators were taken from ADB. 2008. Project Completion Report: Vocational and Technical Education Project in Viet Nam. Manila; ADB. 1998. Report and Recommendation of the President: Proposed Loan to the Socialist Republic of Viet Nam for the Vocational and Technical Education Project. Manila. The impact, outcome, and outputs were the goal, objectives, and components of the project framework in the Report and Recommendation of the President. Note: ADB = Asian Development Bank, AFD = Agence Française de Développement, DACUM = developing a curriculum, GDVT = General Department of Vocational Training, JICA = Japan International Cooperation Agency, MOLISA = Ministry of Labor, Invalids and Social Affairs, NDF = Nordic Development Fund, PAS = Program Accreditation System, PCR = project completion report, PPER = project performance evaluation report, TCS =Technical Certification System; TVET = technical and vocational education and training, VTE = vocational and technical education. Source: ADB. 2008. Project Completion Report: Vocational and Technical Education Project in Viet Nam. Manila; ADB. 1998.
APPENDIX 2: CHANGE IN VOCATIONAL AND TECHNICAL EDUCATION STRUCTURE IN VOCATIONAL TRAINING LAW 2006
MOET = Ministry of Education and Training, MOLISA = Ministry of Labor, Invalids and Social Affairs, TVET = technical and vocational education and training. Source: Mori et al. 2009. Skill Development for Viet Nam’s Industrialization: Promotion of Technology Transfer by Partnership between TVET Institutions and FDI Enterprises. Hiroshima: Hiroshima University.
APPENDIX 3: RATING MATRIX FOR CORE EVALUATION CRITERIA
Table A3.1: Rating Matrix for Core Evaluation Criteria
Ratings Relevance PCR Highly Relevant PPER Relevant Reasons for Disagreements/Comments Agreed with the PCR’s assessment on project’s alignment with government and ADB strategies. However, there are some misalignments between the project’s design and skills needs in the labor markets. Project did not adequately address issue of student demand and teacher quality. The EIRR is 11.0% rather than 18.7% as predicted in the RRP. Project completion was delayed by 4 years. Project cost was reduced together with project scope. Some project facilities, such as LMIS, career guidance services, and school industry councils were not well utilized. It should be noted that the LMIS is no longer conducted; the production units generated minimal income for key schools; school–industry advisory councils are mostly inactive; there was no funding set aside for maintaining and updating several key outcomes, such as curricula and equipment; and institutional memory is weak because of regular staff transition.
Effectiveness in Achieving Outcomes Efficiency in Achieving Outcomes and Outputs
Effective Efficient
Effective Less than Efficient
Preliminary Assessment of Sustainability
Likely
Likely
Overall Assessment Impact ADB and Borrower Performance Technical Assistance Quality of PCR
Successful Not Rated Not Rated Not Rated
Successful Significant Satisfactory Moderate Satisfactory
ADB = Asian Development Bank, EIRR = economic internal rate of return, LMIS = Labor Market Information System, PCR = project completion report, PPER = project performance evaluation report. Source: Independent Evaluation Department Study Team.
Table A3.2: Core Evaluation Criteria Rating Values
Rating Value 3 2 1 0 Relevance Highly relevant Relevant Partly relevant Irrelevant Effectiveness Highly effective Effective Less than effective Ineffective Efficiency Highly efficient Efficient Less than efficient Inefficient Sustainability Most likely Likely Less than likely Unlikely
Source: IED. 2006. Guidelines for Preparing Performance Evaluation Reports for Public Sector Operations. Manila: ADB.
APPENDIX 4: USEFULNESS
STUDENT
PERCEPTION
OF
VOCATIONAL
TRAINING
Table A4.1: Key School Student Evaluation of Training Usefulness across Graduation Groups in 2005 (%)
Item Very useful Useful Partly useful Useless 2002 Graduates 31.6 31.6 29.5 7.4 2003 Graduates 38.3 44.0 12.6 5.1 2004 Graduates 31.1 39.2 22.2 7.5 2005 Graduates 52.9 43.6 3.3 0.2
Source: Labor Market Information System –Tracer Survey.
Table A4.2: Assessments on Training Program by Graduates of 2002 in Middle-Skill Level (%)
Sector Theoretical Aquaculture Mining Processing and manufacturing Electricity, water, and gas production Construction Services Total Practical Aquaculture Mining Processing and manufacturing Electricity, water, and gas production Construction Services Total Very relevant 5.9 0.0 20.5 17.2 7.2 27.8 16.9 11.8 0.0 21.2 20.7 7.7 30.0 18.0 Relevant 35.3 85.7 31.6 27.6 64.4 28.2 42.7 29.4 85.7 36.1 31.0 55.9 29.1 41.7 Relatively relevant 29.4 14.3 23.3 37.9 25.3 25.1 24.8 29.4 14.3 19.0 27.6 16.0 22.0 18.9 Little relevant 11.8 0.0 16.0 10.3 1.8 8.8 9.3 11.8 0.0 14.7 13.8 3.6 9.3 9.5 Irrelevant 17.6 0.0 8.4 6.9 1.0 9.7 6.1 17.6 0.0 8.4 6.9 0.5 9.3 5.9
Source: Labor Market Information System – Tracer Survey.
APPENDIX 5: ECONOMIC INTERNAL RATE OF RETURN REESTIMATION
This analysis follows the same framework as in the report and recommendation of the President (RRP) (Table A5.1). It takes into account only the direct benefits of the project—i.e., the incremental salary of the vocational and technical education (VTE) graduates—since it is difficult to quantify other benefits (e.g., teacher and staff training). The number of graduates during 2001–2007 is obtained from the project completion report (PCR). The number of graduates in later years is assumed to increase by 5% per year. The percentage of employed graduates is assumed to be 84% based on the labor market information system (LMIS). The RRP assumed the incremental income of graduates to be $600, increasing by 5% per year. This rate, however, is too high because the return to vocational education estimation in the impact section of the main text (paras. 58–73) shows that the premium of a vocational secondary degree is $10–$32 per month, and of a college degree $16–$51 per month, which translates to a premium of $120–$612 per year. This analysis uses the average ($366) and keeps the assumption of 5% annual increase. All the project costs except the technical assistance (TA) funds, taxes and duties, and price contingencies are included. This analysis uses the actual project costs, and assumes that investment costs include surveys, instructional materials, equipment, and civil work, and they occur during 2000–2006 when procurement and surveys were conducted. Recurrent costs include implementation, staff development, and consultant services. Similar to the RRP, the time horizon of the analysis is assumed to be 15 years. The dollar value has been estimated in constant 1998 prices. The analysis yields an economic internal rate of return (EIRR) of 11% (Table A5.2) Table A5.1: Economic Analysis in Report and Recommendation of the President ($ ‘000)
Project Costs Project Benefits Income of Workers Skills Upgrading 0.00 960.00 1,920.00 2,880.00 2,880.00 9,720.00 9,720.00 9,720.00 9,720.00 9,720.00 9,720.00 9,720.00 9,720.00 9,720.00
Year 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Investment 2,625.92 9,951.25 54,459.45 25,073.41 5,006.81 128.10 1,387.20 39,000.00 15,000.00 0.00 128.10 0.00 128.10 1,387.20
Recurrent 1,260.40 1,260.40 1,330.20 1,342.20 1,357.20 1,357.20 1,357.20 1,357.20 1,357.20 1,357.20 1,357.20 1,357.20 1,357.20 1,357.20
Total 3,886.32 11,211.65 55,789.65 26,415.61 6,364.01 1,485.30 2,744.40 40,357.20 16,357.20 1,357.20 1,485.30 1,357.20 1,485.30 2,744.40
Income of STS Leavers 0.00 6,240.00 10,848.00 15,193.60 15,616.00 15,616.00 15,616.00 15,616.00 15,616.00 15,616.00 15,616.00 15,616.00 15,616.00 15,616.00
Total 0.00 7,200.00 12,768.00 18,073.60 18,496.00 25,336.00 25,336.00 25,336.00 25,336.00 25,336.00 25,336.00 25,336.00 25,336.00 25,336.00
Net Benefit (3,886.32) (4,011.65) (43,021.65) (8,342.01) 12,131.99 23,850.70 22,591.60 (15,021.20) 8,978.80 23,978.80 23,850.70 23,978.80 23,850.70 22,591.60
Economic Internal Rate of Return Re-estimation 51
Project Costs Project Benefits Income of Workers Skills Upgrading 9,720.00
Year 15
Investment 0.0
Recurrent 1,357.20
Total 1,357.20
Income of STS Leavers 15,616.00
Total 25,336.00
Net Benefit 23,978.80 $18,967.69 18.70%
NPV@12% IRR
IRR = internal rate of return, NPV = net present value, STS = short term school. Note. Investment costs include contingencies. Source: ADB. 1998. Report and Recommendation of the President to the Board of Directors: Proposed Loan to the Socialist Republic of Viet Nam for the Vocational and Technical Education Project. Manila.
Table A5.2: Revised Economic Analysis ($ ‘000)
Project Costs Year 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 NPV12% IRR
IRR = internal rate of return, NPV = net present value.
Investment 0.00 9,741.43 9,741.43 9,741.43 9,741.43 9,741.43 9,741.43 9,741.43 0.00 0.00 0.00 0.00 0.00 0.00 0.00
Recurrent 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67 956.67
Total 956.67 10,698.10 10,698.10 10,698.10 10,698.10 10,698.10 10,698.10 10,698.10 956.67 956.67 956.67 956.67 956.67 956.67 956.67
Project Benefits Graduate Graduates Income 0 0.00 0 19,622 20,911 28,838 30,789 33,844 37,156 38,900 40,845 42,887 45,032 47,283 49,647 52,130 0.00 5,924.58 6,386.76 8,978.90 9,319.41 9,931.97 10,660.25 10,820.54 9,691.02 9,976.05 10,099.72 9,380.74 9,244.90 9,111.03
Net Benefit (956.67) (10,698.10) (4,773.52) (4,311.33) (1,719.19) (1,378.69) (766.13) (37.84) 9,863.88 8,734.36 9,019.39 9,143.06 8,424.08 8,288.23 8,154.36 ($1,130.90) 11%
APPENDIX 6: OCCUPATIONS AND TRAINING LEVELS OF 15 KEY SCHOOLS
Source: ADB. 2008. Completion Report: Vocational and Technical Education Project in Viet Nam. Manila.
APPENDIX 7: AVERAGE MONTHLY INCOME OF KEY SCHOOL GRADUATES BY OCCUPATIONS IN 2005
Occupation Average Technical Worker Electricity Mechanics Agri-Forestry Vet Pharmacy Nursing Teaching Office Worker Accounting Procurement Others Sales and Services Waiter/Waitress Sales Agriculture, Forestry, and Aquaculture Processing Civil Electricity Welding, Metal Cutting Metal Processing Mechanics, Tools Mechanics, Vehicles Mechanics, Production Machinery Mechanics, Electrical Appliances Electronic Appliances Food Processing Machinery Assembly and Repair Machinery Control Large Construction Machinery Crane Driver Simple Work
... = data not available. Source: Labor Market Information System—Tracer Survey.
Graduates in 2002 (D) 1,231,559 1,091,362 1,465,854 1,186,047 585,453 622,857 1,268,889 975,000 990,143 1,229,974 1,357,654 1,034,714 827,733 1,194,444 … 1,222,500 685,080 1,305,446 1,396,104 1,663,636 1,845,833 1,513,889 1,235,000 1,128,571 1,312,500 1,053,846 825,057 1,303,175 1,316,667 1,348,276
Graduates in 2003 (D) 1,250,938 957,144 1,320,000 1,243,000 609,543 670,000 807,625 965,217 900,000 1,054,460 1,410,000 1,281,250 1,222,200 1,026,667 783,333 978,750 737,500 1,364,825 1,383,186 1,774,359 1,416,250 1,611,429 1,298,684 1,150,000 1,095,833 1,431,250 791,667 1,470,656 1,292,308 1,636,842 2,175,000 878,667
Graduates in 2004 (D) 1,109,978 872,001 1,433,333 1,312,500 652,784 614,804 770,408
...
766,153 1,084,183 1,387,788 1,062,500
...
893,922 920,000 895,428 823,529 1,221,553 1,355,827 1,309,444 1,535,000 1,511,111 1,089,561 1,180,916 1,056,667 1,314,000 657,142 1,183,160 1,079,273 1,214,607 1,800,000 718,875
...
1,150,000
APPENDIX 8: SKILL MATCHING AMONG KEY SCHOOL GRADUATES
Table A8.1: Skill Matching among Graduates from Technical Worker’s Degree
Item Computer, IT Welding Machinery Repair Metal Processing Electricity Electronics Construction Machinery Textile Construction Round 2 (2003) Not Matching Matching 7 6 13 28 9 29 1 64 18 71 17 45 0 99 3 17 1 21 Round 3 (2004) Not Matching Matching 8 7 5 39 2 36 0 65 14 84 11 53 0 99 2 15 0 22 Round 4 (2005) Not Matching Matching 22 20 5 50 7 71 6 145 0 23 12 174 0 94 4 21 0 20
IT = information technology. Source: Labor Market Information System—Tracer Survey.
Table A8.2: Skill Matching among Graduates from Vocational Secondary Degree
Item Accounting Business Management Computer Welding and Mechanics Electricity Electronics Husbandry Pharmacy Round 2 (2003) Not Matching Matching 4 3 1 1 4 4 0 0 2 0 2 8 4 2 5 19 Round 3 (2004) Not Matching Matching 2 6 5 1 1 3 3 0 7 1 2 4 8 3 7 17 Round 4 (2005) Not Matching Matching 1 2 3 23 14 7 10 0 10 2 4 8 6 6 7 81
Source: Labor Market Information System—Tracer Survey.
Table A8.3: Skill Matching among Graduates from Vocational College Degree
Round 2 (2003) Item Accounting Computer Welding and Mechanics Electricity Electronics Not Matching 3 2 4 7 1 Matching 5 1 7 3 5 Round 3 (2004) Not Matching 1 4 0 2 0 Matching 7 2 9 8 3 Round 4 (2005) Not Matching 1 1 2 3 1 Matching 12 12 18 7 3
Source: Labor Market Information System—Tracer Survey.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview. | https://www.scribd.com/document/138064817/Viet-Nam-Vocational-and-Technical-Education-Project | CC-MAIN-2016-30 | en | refinedweb |
Search: Search took 0.12 seconds.
- 24 Aug 2010 3:43 AM
FT, problem resolved!
but i donnt know why
at the beginning i used ext-base-debug.js
now i change to ext-base.js
so it run well
evan
what difference with these two file?
i thought -debug can...
- 23 Aug 2010 9:14 PM
when use router i implement a class extend DirectHandler like
public class GridHandler : DirectHandler
and follow two method:
public override string ProviderName
{
get...
- 9 Aug 2010 7:54 PM
- Replies
- 8
- Views
- 4,981
i got it
use Ext.Ajax.request replace JSONP to implement
js code
Ext.ux.ComboExample = {
init: function() {
this.photoTemplate = new Ext.Template([
'<a...
- 9 Aug 2010 2:38 PM
- Replies
- 8
- Views
- 4,981
sorry everyone
class jsonp aim to load remote domain Script and get data back
i just find the data that return
code before is wrong
- 9 Aug 2010 7:19 AM
- Replies
- 8
- Views
- 4,981
still question with code like this:
Ext.ux.JSONP.request('../webcontrols/tree/ProRecGet.ashx', {
//callbackKey: 'jsoncallback',
params: {
...
- 27 Jul 2010 6:20 AM
it's so wonderful work
thanks evan
- 26 Jul 2010 11:41 PM
- Replies
- 8
- Views
- 4,981
yes thanks
i got it
but i dont want insert comment in my aspx page
'cause i think this will make aspx page load slow? is that true?
i want an ajax method to load data,when loaded then add...
- 26 Jul 2010 8:07 PM
- Replies
- 8
- Views
- 4,981
code as follow fetch comment from api.flickr.com with jsonp
Ext.ux.JSONP.request('', {
callbackKey: 'jsoncallback',
params: {
format: 'json',...
- 25 Jul 2010 11:50 PM
- Replies
- 8
- Views
- 4,981
thanks for help
i have less exprience of javascript and should learn more
- 23 Jul 2010 10:51 PM
- Replies
- 8
- Views
- 4,981
i like this example
but i donnt want a menu to control photo data load
as a carousel of a main page it should load data auto
so i modified the html example sicript code as follow:
...
- 23 Jul 2010 5:13 PM
- Replies
- 3
- Views
- 3,352
How to implement this?
i set up a carousel and a jsonstore to get things like{url:"",title:""},and i init a template
but it doesn't work
i'm newbie, and just can use these items seperetely
can i...
Results 1 to 11 of 11 | https://www.sencha.com/forum/search.php?s=0ebd2a37fbd9caf67c5f1691725df1e6&searchid=17053246 | CC-MAIN-2016-30 | en | refinedweb |
I have a program which runs slightly slower than I would like it to run.
I profiled it, and it spends almost 100% of the time in 1 subroutine which
is not surprising, as this is the only subroutine which is reading text input.
Below is the subroutine, and a demonstration of the size of the input.
# returns the $limit largest files from the flist file,
# full path to file in $name
sub process_flist {
my ($name, $limit) = @_;
my ($nlines, $total, @lines, @size);
open(my $fh, '<', $name) or die("Error opening file `$name': $!\n");
while (<$fh>) {
my @f = split / /;
# skip files that have a space or other whitespace
# characters in their name
next if @f > 10;
# store file size in bytes and the full path to the file
push @lines, $f[4] . '/' . $f[1];
}
$nlines = scalar @lines;
{
# disable warnings because the array to be sorted has
# the following format "12345/path/to/file"
# Perl would complain this is not a number
# but the <=> comparison operator will handle such
# input properly
# this is needed so the files can be sorted
# with a single pass through
# the flist file
no warnings 'numeric';
$total = sum(@lines);
$limit = min($limit, $nlines);
@lines = (sort {$b <=> $a} @lines)[0 .. ($limit - 1)];
}
# returns the number of files, their cumulative size,
# and the $limit largest files
return ($nlines, $total, @lines);
}
[download]
find /tgt -type f -name input | xargs wc -l
197898 .../input
213267 .../input
240331 .../input
194063 .../input
191862 .../input
179495 .../input
218041 .../input
1434957 total
[download]
51 opt/src/t.tar 100444 1247464676 290119680 283320 NA 1 0xbe2d 0x4000
+0006
[download]
The program runs for around 40 seconds with this input - 7 input files, but with 100 input files of similar size it runs for around 25 minutes.
I have 2 pictures of the profiler output -
Can the runtime be reduced ? I am not proficient in interpreting the output of the profiler, so I can't really figure out whether it can be improved, or it is simply
so I/O intensive that not much can be done. The input files represent a list of files backed up from a particular client, and they are not ordered in any
meaningful way.
Below code is apparently faster (at the cost of some readability) than split/if
...
while (<$fh>) {
next unless m/^[0-9]+ ([^ ]+) [0-9]+ [0-9]+ ([0-9]+)/;
push @lines, $2 . '/' . $1;
}
...
[download]
What happens if you return an array reference instead of an array at the end of this function? (Depending on how large $limit is, you might cause Perl to copy a lot of data.)
What happens if, instead of reading the whole file into an array and then sorting it, you keep track of the largest n lines you've seen and read the file line by line?
Improve your skills with Modern Perl: the free book.
The latter suggestion is more promising.
Looking at the timings, the bulk of the time is in the split (20.4 s) and the push @lines (16.2s)
Ah, I didn't see there was a second image. Good catch.]
I'm clutching at straws here, but if a lot of the filenames contain multiple whitespace characters, then you might get a very slight improvement doing this:
my @f = split / /, $_, 11;
# skip files that have a space or other whitespace
# characters in their name
next if @f > 10;
[download]
The third parameter to split tells it not to keep looking for split points once it's found. | http://www.perlmonks.org/?node_id=1001087 | CC-MAIN-2016-30 | en | refinedweb |
This article describes simple ways to query an in-memory collection or “table” using LINQ query expressions. The focus will be on a particular part of a query expression called a query operator. Query operators such as select, where, join and groupby are the primary engine driving LINQ queries. Hence the explanation of query operators found in this post provides you with the keys to the LINQ kingdom. Once you understand the basics of how to use query operators in query expressions, you will be ready to begin serious and useful work with LINQ.
NOTE: This is the third in a series of posts on LINQ. An index to this series is available in my blog. The code for this post is available for download.
Rather than directly access a database server, I will show how to use a new feature called collection initializers to quickly create an in-memory collection that will act just like a database table. By working with an in-memory “table” you can see how the syntax for querying a database works without having to connect directly to a database server. You will also begin to see how you can use the same syntax to query a database table or a different type of data structure such as a collection.
The “table” found in this post’s example program will contain one row of data for each of the 48 query operators you can use in the May LINQ CTP. A CTP, or Community Technical Preview, is a kind of pre-beta, offering a sneak peak at upcoming technology.
In this post you will get a chance to use a few query operators, and to view the names of all the query operators. By the time you are done reading, you should have a sense of the important role that query operators play in the LINQ technology. Please remember that we are working with pre-release code. It is therefore possible that a few of the details of how LINQ works will change before the product ships.
The query operators are declared in a static class called System.Query.Sequence. They are stored in an assembly called System.Query.dll.
Collection Initializers
Collection initializers provide a shorthand for creating a collection or List<>. The example found in Listing One shows how to create a list of pre-initialized instances of the class called Operator. The custom Operator class is defined at the beginning of the listing.
Listing One: A Collection Initializer creates a collection from a set of literals.
1: class Operator
2: {
3: public int OperatorID;
4: public string OperatorName;
5: public string OperatorType;
6: }
7:
8: private List<Operator> OperatorList;
9:
10: private void CreateLists()
11: {
12: // Collection initializer
13: OperatorList =
14: new List<Operator>
15: {
16: { OperatorID = 1, OperatorName = "Where",
17: OperatorType = "Restriction" },
18: { OperatorID = 2, OperatorName = "Select",
19: OperatorType = "Projection" },
20: { OperatorID = 3, OperatorName = "SelectMany",
21: OperatorType = "Projection" }
22: }
23: }
You can see that Operator has three fields called OperatorId, OperatorName, and OperatorType. All three fields are initialized in this example. The end result is a list containing three instances of the Operator class.
Query Operators
The operators under examination here are the query operators that are part of the LINQ API. If you download the source for this example, you will see that there are actually 48 different query operators available in the May CTP. In Listing One, I only initialize three operators. I do this to keep the example simple and easy to read. The source, however, is considerably longer and shows not three operators, but 48.
The example we are building in this post will provide a means of querying this in-memory table, or collection. My general goal is to provide examples of how to query either in-memory objects, or a real database. One of the great benefits of LINQ is that it uses nearly identical code to query a real database and a collection.
Simple Queries
In this post I’m going to show you three simple queries, shown in Listing Two. The query expressions that form the heart of this code are found on lines 3 and 4, lines 14 and 15, and lines 25, 26 and 27.
Listing Two: Three simple ways to query the data in the OperatorList
1: public void ShowOperatorObjects(System.Collections.IList list)
2: {
3: var s = from p in OperatorList
4: select p;
5:
6: foreach (var a in s)
7: {
8: list.Add(a);
9: }
10: }
11:
12: public void ShowOperatorNames(System.Collections.IList list)
13: {
14: var s = from p in OperatorList
15: select p.OperatorName;
16:
17: foreach (var a in s)
18: {
19: list.Add(a);
20: }
21: }
22:
23: public void ShowOperatorGeneration(System.Collections.IList list)
24: {
25: var s = from p in OperatorList
26: where p.OperatorType.Equals("Generation")
27: select p.OperatorName;
28:
29: foreach (var a in s)
30: {
31: list.Add(a);
32: }
33: }
The example program I am using is a Windows Forms application that uses a ListBox to display data, as shown in Figure One. Since I’m working with a ListBox, I pass in an IList to each of these methods. By passing in this list, I can ensure that the data found in our query expressions will be displayed in the ListBox:
queryData.ShowOperatorObjects(listBox1.Items);
NOTE: I need to fully qualify IList with the System.Collections namespace because I don’t want to confuse the System.Collections.Generic.IList interface with the System.Collections.IList interface used by the ListBox class. The necessity of adding this rather verbose qualification is an unfortunate, but unavoidable, exercise.
Figure One: Some of the data returned by running the ShowOperatorObjects method found in Listing Two.
The ShowOperatorObjects query is found on lines 3 and 4 of Listing Two. It produces the output shown in Figure One.
This query expression asks the compiler to “select all the items from the OperatorList.” In the discussion of collection initializers, we saw that in this program these items will be instances of the Operator class.
As you learned in the previous posts in this series, the code on lines 3 and 4 is interesting because it demonstrates how to use a simple, type-safe, native-to-C#, declarative, SQL-like syntax for querying data. In short, it shows how to use LINQ.
The data we are querying is stored not in a database, but in a collection of type List<>. Had the data been stored in a database we could have used identical syntax to query the table.
The string “QueryLister.QueryData+Operator“ is the output from the ToString() method of the Operator class. Why does the ToString() method return this rather odd looking string? Take a look at Listing Three. This is another view of the same class shown in Listing Two. You can see that the Operator class is sub-class of a class called QueryData which is declared in a namespace called QueryLister.
Listing Three: This second view of the code excerpts shown in Listing One gives you a sense of the scoping of the Operator class.
1: namespace QueryLister
2: {
3: class QueryData
4: {
5: class Operator
6: {
7: public int OperatorID;
8: public string OperatorName;
9: public string OperatorType;
10: }
11:
12: // lots of code omitted here
13: }
14: }
The var Keyword
The code shown on lines 1 through 9 of Listing Two could have been written like this:
Listing Four: Here both instances of the var keyword have been removed from the ShowOperatorObjects method.
1: public void ShowOperatorObjects(System.Collections.IList list)
2: {
3: IEnumerable<Operator> s =
4: from p in OperatorList
5: select p;
6:
7: foreach (Operator a in s)
8: {
9: list.Add(a);
10: }
11: }
Either version of the ShowOperatorObjects method will compile, and both produce the same output. In fact, they both are asking the compiler to do more or less the same thing.
On line 3 of Listing Four you can see that I have replaced the declaration var s with IEnumerable<Operator> s. These are really two ways of saying the same thing. In LINQ, however, the var syntax is preferred in part because it makes programming simpler, and in part because it plays an important role in LINQ programming.
In later posts, you will see that there are syntactical constructs called anonymous types that are used in LINQ programs. I’ll talk about these anonymous types in more depth in later posts. For now, you only need to know that anonymous types have no name and no explicit type. If you don’t know the type of a variable, then you can’t declare it. To avoid putting a developer in this awkward situation, LINQ uses the var type. The var type is a “typeless” type that can, for instance, stand for any data that is returned by a query expression. It can even stand for an anonymous type that is never explicitly declared in your program!
If all this business about anonymous types sounds confusing, then just ignore it. All you really need to know is that the var type makes LINQ programming simple. The code shown in Listing Four is simpler than the code in Listing Two. It is easier to write var than it is to write IEnumerable<Operator>. In LINQ, query expressions can almost always be declared to return a var type, and you generally don’t have to worry about exact type that is being returned.
The var type is simple, clean, and easy to use. Don’t worry, be happy. var is easy to use. Rejoice! It makes your life simpler!
Slightly More Complex Query Expressions
The output from the code in the ShowOperatorNames method is shown in Figure Two. This latter method is just slightly more sophisticated than the code in the ShowOperatorObjects method.
Figure Two: The output from the ShowOperatorNames method gives you a complete list of all the operators found in the May LINQ CTP.
I will show you the ShowOperatorNames method once again. The code shown here is identical to the code in Listing Two, but I am repeating it so that you don’t have to scroll back and forth in your browser:
1: public void ShowOperatorNames(System.Collections.IList list)
2: {
3: var s = from p in OperatorList
4: select p.OperatorName;
5:
6: foreach (var a in s)
7: {
8: list.Add(a);
9: }
10: }
This method is similar to the ShowOperatorObjects method. In this case, however, we qualify the select statement by asking specifically for the OperatorName field from the Operator class. It is this difference that makes the output in Figure Two so much more useful than that in Figure One. In the first figure, we see the output from the ToString method of the whole Operator class. In figure two, however, we see the actual OperatorName from the Operator class.
As explained in previous posts, the variable p is called a range variable and it is never specifically declared. In this simple query we know that p is of type Operator. We know this because OperatorList contains instances of the Operator class. Furthermore, we know that that the Operator class has OperatorName as one of its fields. The compiler is also privy to this information. Thus the field OperatorName is type checked.
Let’s take a moment to consider the importance of what is happening here. When you wrote a SQL expression in the bad old days, you had to write a string literal such as “SELECT OperatorName FROM OperatorList“. These string literals were not checked at compile time. If you accidentally typed OperatorsName instead of OperatorName, your query would fail, but you would not know of the problem until you compiled and ran your program. With LINQ, errors like this are caught at compiler time!
LINQ is giving you two big advantages you didn’t have before:
- A native C# query language that gives you compile time type checking
- The ability to use a single, unified query language whether you are querying databases, xml, or in-memory data structures such as the OperatorList in this example.
The Where Query Operator
Let’s take a look at the Where operator found in the ShowOperatorGeneration method. This method produces the output shown in Figure Three.
Figure Three: The output from the ShowOperatorGeneration method gives you a list of all the operators of type Generation.
Here is the code from the ShowOperatorGeneration method:
1: public void ShowOperatorGeneration(System.Collections.IList list)
2: {
3: var s = from p in OperatorList
4: where p.OperatorType.Equals("Generation")
5: select p.OperatorName;
6:
7: foreach (var a in s)
8: {
9: list.Add(a);
10: }
11: }
This code is similar to that in the ShowOperatorNames method, except we have added a where clause that uses the where operator.
The OperatorList collection is a table-like structure with rows that look like this:
There are 48 rows in the table, but here I show just 8 sample rows. As you can see, in this poorly normalized table the OperatorType sometimes repeats. This is because the OperatorType is used to categorize the various kinds of operators. For instance, the “Generation” type has three members called Range, Repeat and Empty.
I take advantage of the current simple “table” structure to show how to use the where operator to query this collection. In particular, the program asks to see “the OperatorName from all the instances of the Operator class in the collection that have their OperatorType set to the word ‘Generation.'” The result is the data shown in Figure 3.
Summary
In this post you were introduced to query operators. We saw a listing and some program output that revealed the names of a number of these operators. We also had a chance to use two of the operators, called select and where.
Future posts in this series will continue to explore these query operators. You will get a chance to see many of them in working code, and I will provide tables listing all of the operators. This exploration of query operators will be a key building block in our study of LINQ.
You’ve been kicked (a good thing) – Trackback from DotNetKicks.com
This is the fourth in a series of articles on LINQ . This article focuses on an important operator from.
Bipolar and lexapro. Side effects of lexapro. Lexapro. Interactions between ephedrine and lexapro. Lexapro and drinking. | https://blogs.msdn.microsoft.com/charlie/2006/11/11/the-linq-farm-query-operators/ | CC-MAIN-2016-30 | en | refinedweb |
I believe I'm looking at the current version. (It's a file called snapshot.zip with no version-specific identifying info that I can find.) The sre module changed one line in _fixflags from the CVS version. def _fixflags(flags): # convert flag bitmask to sequence assert flags == 0 return () The assert flags == 0 is apparently wrong, because it gets called with an empty tuple if you use sre.search or sre.match. Also, assuming that simply reverting to the previous test "assert not flags" fix this bug, is there a test suite that I can run? Guido asked me to check in the current snapshot, but it's hard to tell how to do that correctly. It's not clear which files belong in the Python CVS tree, nor is it clear how to test that the build worked. Jeremy | https://mail.python.org/pipermail/python-dev/2000-May/004328.html | CC-MAIN-2016-30 | en | refinedweb |
Named Scope Caching
When working on high-traffic Rails sites, it often becomes necessary to find ways to improve performance with caching. One place we’ve found this is most convenient and easy-to-do is by caching an ActiveRecord result set for models that change rarely or not at all. An easy example of this is a Category model.
Often times, you have a categorization hierarchy that will never or rarely change over the life of an application. Ideally you would fetch the results once from the database and never have to again. So how do we go about caching this? First let’s look at our model and create a
named_scope for it:
class Category < ActiveRecord::Base acts_as_tree named_scope :find_top_level, :conditions => 'categories.parent_id IS NULL', :order => 'categories.name' end
Next, we need to create create a method that fetches the results for our new scope and caches it in a class variable. It should also only do caching if in production environment (alternatively or additionally, we could use the ActionController.perform_caching config value), as this can cause problems in tests.
def self.top_level unless ('production' == RAILS_ENV) && ActionController.perform_caching @@top_level_cache = self.find_top_level else @@top_level_cache ||= self.find_top_level end end
Finally, we need to create a method to invalidate our cache when records are saved or deleted. Since we know this isn’t happening often (if at all), this should rarely be performed but is a good safeguard so we know our cache is current.
after_save :reset_cached_finder after_destroy :reset_cached_finder def reset_cached_finder @@top_level_cache = nil end
This is something that we could easily see doing in a number of models for a number of finders. Since this involves a lot of similar code, it would be great if we could create some meta code that would allow us to define these caches with a simple one liner.
Maybe with syntax like
cache_scopes :cached_method_name => :scope_name.
For example:
cache_scopes :top_level => :find_top_level
Well here’s the code that does that:
Suggestions for improvement are encouraged, which is easily done with GitHub’s new gist.
Enjoy and have fun caching! | https://www.viget.com/articles/named-scope-caching | CC-MAIN-2016-30 | en | refinedweb |
This chapter leads you through the process of creating a very small working test suite quickly and easily by following step-by-step instructions. To simplify the process, conceptual information is generally not provided but is available in later chapters.
The test suite you create here can serve as the basis for your entire test suite. If your tests have no special requirements that the Standard Test Finder and Standard Test Script cannot accommodate, you may be able to create your product test suite by simply adding additional tests and creating a configuration interview to gather the information required to execute your tests.
Notes:
The instructions in this chapter assume that you have completed the tutorial in Chapter 2 and that you have read Chapter 3.
The instructions also assume that you are familiar with basic operating system commands on your system.
In the examples, path names are given using the "
\" file separator. If your system uses a different file separator, please substitute it where appropriate.
This chapter describes how to:
Create a test suite directory
Create a
testsuite.jtt file
Copy
javatest.jar to the test suite
lib directory
Add appropriate classes to the
classes directory
Create a test
Run the test suite
Other issues of interest regarding test suite creation are discussed at the end of the chapter.
To create a test suite, follow the steps in these simple tasks.
Create a Test Suite Directory
Create the testsuite.jtt File
Set Up the
classes Directory
Use a Simple Test Template
Create and Compile a Simple Test Example
Create the directory and sub-directories for your test suite.
Create the top-level test suite directory.
Create the directory somewhere convenient in your file system. This directory is referred to as ts_dir for the remainder of this chapter.
Under ts_dir, create sub-directories named
tests,
lib, and
classes.
As described in Chapter 3, the JavaTest harness reads the
testsuite.jtt file to find out information about your test suite. The following steps describe how to create the
testsuite.jtt file for this test suite.
Make ts_dir the current directory.
Create the
testsuite.jtt file.
Enter the following information into a text editor:
# Test Suite properties file for DemoTCK test suite # with tag-style tests name=My Test Suite id=1.0 finder=com.sun.javatest.finder.TagTestFinder script=com.sun.javatest.lib.StdTestScript interview=com.sun.javatest.interview.SimpleInterviewParameters
You can substitute your own string values for the
name and
id properties.
Save the file as ts_dir
\testsuite.jtt.
javatest.jar
The test suite works best if there is a copy of the
javatest.jar file in the
lib directory of the test suite; this enables the JavaTest harness to automatically locate the test suite.
Copy
javatest.jar from jt_install
\examples\javatest\simpleTags\demotck\lib to ts_dir
\lib.
classesDirectory
In order to execute, tests must have access to some of the classes contained in
javatest.jar. Extracting these classes eliminates the need for each test to have
javatest.jar on its class path. The the most convenient location to place these classes is the ts_dir
\classes directory.
Make ts_dir
\classes the current directory.
Verify that the Java SE platform (version 1.6 or later) is in your path.
At a command prompt, enter:
C:\>
java -version
From
javatest.jar, extract the classes required to run the tests.
Use the following command line:
jar -xvf ..\lib\javatest.jar com\sun\javatest\Test.class
com\sun\javatest\Status.class
The following instructions describe how to create a very simple test to add to your test suite. For more detailed instructions about writing TCK tests, see the Test Suite Developers Guide.
Make ts_dir
\tests the current directory.
Enter the test code into your favorite text editor.
The following template can be used as the basis for writing simple tests:
import java.io.PrintWriter;
import com.sun.javatest.Status;
import com.sun.javatest.Test;
/** @test* @executeClass MyTest * @sources MyTest.java **/
public classMyTest
implements Test{
public static void main(String[] args) {
PrintWriter err = new PrintWriter(System.err, true);
Test t = newMyTest
();
Status s = t.run(args, null, err);
s.exit();
}
public Status run(String[] args, PrintWriter log1, PrintWriterlog2) {
Status result;// your test code here ...
return result;
}
}
Note that the section delimited with the
/**
**/ characters is the test description portion of the test. It must be present for the JavaTest harness to locate and recognize the test. You will change all instances of
MyTest, and replace the line
// your test code here... with your own code. The following table describes the test description entries recognized by the Standard Test Script:
You can create simple tests by replacing the comment:
// your test code here ...
with code that tests your API. Note that the test must return a
Status object as a result.
The following sample is a very simple test you can use to get started.
Save the following file as
MyTest.java.
Be sure to copy the entire file, including the test description delimited with the
/**
**/ characters
import java.io.PrintWriter; import com.sun.javatest.Status; import com.sun.javatest.Test; /** @test * @executeClass MyTest * @sources MyTest.java **/ public class MyTest implements Test { public static void main(String[] args) { PrintWriter err = new PrintWriter(System.err, true); Test t = new MyTest(); Status s = t.run(args, null, err); s.exit(); } public Status run(String[] args, PrintWriter log1, PrintWriter log2) { Status result; if (1 + 1 == 2) result = Status.passed("OK"); else result = Status.failed("Oops"); return result; } }
Compile
MyTest.java.
Use the following command on WIN32 systems:
C:\> javac -d
..
\classes -classpath
..
\classes MyTest.java
Use the following command on Solaris or Linux systems:
% javac -d ../classes -classpath ../classes MyTest.java
MyTest.class is created in the ts_dir
\classes directory. As you add more and more tests you should organize them hierarchically in subdirectories.
You are now ready to run the test suite.
Make ts_dir the current directory.
Start the JavaTest harness.
At a command prompt enter:
c:\> java -jar lib\javatest.jar -newdesktop
Run the tests the same way you ran the tests in Chapter 2.
The configuration interview for this test suite contains a question not included in the tutorial configuration interview. Use the following information to answer the question:
This section takes a closer look at the components that make up a typical test suite and how they are organized. In addition, the various class paths required to run the JavaTest harness, the agent, and tests classes are discussed.
Note that much of the organization described here is optional; however, experience has shown that it works well for most test suites.
The top-level test suite directory generally contains the following files and directories:
All of the components you create for the test suite should be delivered to the user in a single JAR file installed in the
lib directory of the test suite. The JAR file is added to the class path in the
testsuite.jtt file as described in Chapter 8. Experience has shown that it is best to organized the JAR file with the following directory structure:
com\ your_company\ your_product\ Interview class files and resource files, More Info help
For example, the JAR file for the demo TCK test suite:
jt_install
\examples\javatest\simpleTags\demotck\jtdemotck.jar
is organized like this:
com\ sun\ demotck\ Interview class files and resource files, More Info help
If you provide a large number of components, you can further organize them into sub-packages:
com\ your_company\ your_product\ Interview class files and resource files, More Info help lib\ Everything else (TestSuite, Script, Finder, etc.)
When you create a test suite, it is important to keep in mind the three potential class paths that are involved:
JavaTest class path
Agent class path
Test class path
Two of the ways described in the following sections in which you can set a class path are through a
CLASSPATH environment setting or through a
-classpath flag in the command line. The
CLASSPATH environment setting is generally a safe way to set the classpath, although setting it as an environment variable is less explicit than using the
-classpath flag.
The
-classpath flag to the particular software development kit tool (such as
java and
javac) is generally the best way to set the class path if you know it explicitly. The main disadvantage of using the
-classpath flag is that it overrides the
CLASSPATH environment setting.
Shell example:
% CLASSPATH=otherclasses javac -classpath classes -d out foo/
In this example, only classes set by
-classpath are on the classpath. The otherclasses set by the
CLASSPATH environment setting are dropped.
Shell example:
% CLASSPATH=otherclasses javac -classpath $CLASSPATH:classes d out foo/
In this example, the environment setting is added to the
-classpath argument. The resulting classpath is otherclasses
:classes.
This is the class path that the JavaTest harness uses to access its classes, libraries, and your plug-in classes. The JavaTest class path can be set by means of:
The
CLASSPATH environment variable
The
-classpath option to the Java runtime
The
-jar option to the Java runtime (this is the standard)
In addition, each test suite can use the
classpath entry in the
testsuite.jtt file to extend the class path. The
classpath entry is used to add custom plug-in components and interviews that you create.
Often you must run tests on a system other than one on which the JavaTest harness runs. In this case you use an agent (such as the JavaTest Agent) to run the tests on that system. The agent class path is used by the agent to access its classes, libraries, and any plug-in classes. The class path can be set by means of:
The
CLASSPATH environment variable
The
-classpath option to the Java runtime
The
-jar option to the Java runtime
Some other platform-specific mechanism
This is the class path used by the tests during execution. It is normally the responsibility of the configuration interview and/or test script to set the class path for each test in the test environment command entry (see Command Strings). Test classes are normally located in the ts_dir
\classes directory, you normally include this on the test class path. You can also put any classes that your tests require in ts_dir
\classes and they will be found.
ng HTML relocated | http://docs.oracle.com/javame/test-tools/javatest-45/html/createts.htm | CC-MAIN-2016-30 | en | refinedweb |
A DataSource that holds a fixed size array, using the types::carray class. More...
#include <rtt/internal/DataSources.hpp>
A DataSource that holds a fixed size array, using the types::carray class.
Definition at line 324 of file DataSources.hpp.
Create and allocate an Array of a fixed size.
In case you create an empty/default ArrayDataSource, you can assign it an array size later-on with newArray( size )
Definition at line 120 of file DataSources.inl.
Creates an ArrayDataSource and initializes the array with the contents of another carray.
A deep copy is made from odata.
Definition at line 126 of file DataSources.inl.
Return a shallow clone of this DataSource.
This method returns a duplicate of this instance which re-uses the DataSources this internal::DataSource holds reference to. The clone() function is thus a non-deep copy.
Implements RTT::internal::AssignableDataSource< T >.
Definition at line 149 of file DataSources.inl.
Create a deep copy of this internal::DataSource, unless it is already cloned.
Places the association (parent, clone) in alreadyCloned. If the internal::DataSource is non-copyable (for example it represents the Property of a Task ), this may be returned.
Implements RTT::internal::AssignableDataSource< T >.
Definition at line 157 of file DataSources.inl.
Force an evaluation of the DataSourceBase.
Implements RTT::base::DataSourceBase.
Reimplemented in RTT::internal::ActionAliasAssignableDataSource< T >, RTT::internal::ActionAliasDataSource< T >, RTT::internal::AliasDataSource< T >, RTT::internal::FusedMCallDataSource< Signature >, RTT::internal::FusedFunctorDataSource< Signature, Enable >, RTT::internal::InputPortSource< T >, and RTT::internal::DataObjectDataSource< T >.
Definition at line 52 of file DataSource.inl.
Referenced by RTT::Property< bool >::Property(), RTT::scripting::CommandDataSourceBool::readArguments(), RTT::scripting::EvalCommand::readArguments(), RTT::internal::ReferenceDataSource< ds_type >::setReference(), and RTT::internal::AssignableDataSource< T >::update().
Get a (const) reference data source to a member of the structure of this data source.
You must call getMember() in turn on the returned member to access sub-members.
Definition at line 124 of file DataSource.cpp.
References RTT::types::TypeInfo::getMember(), and RTT::base::DataSourceBase::getTypeInfo().
Same as above, but with run-time lookup of the member to use.
Also takes an optional offset argument which can be used to offset the member in memory. This is necessary when using sequences of sequences. DataSources which are a sequence/offset member themselves must override this function to let the returned member take the offset into account.
Definition at line 130 of file DataSource.cpp.
References RTT::types::TypeInfo::getMember(), and RTT::base::DataSourceBase::getTypeInfo().
Returns the names of all members of the structure contained in this data source, or an empty list if none.
If this data source is a sequence, it will not return the allowed index numbers.
Definition at line 134 of file DataSource.cpp.
References RTT::types::TypeInfo::getMemberNames(), and RTT::base::DataSourceBase::getTypeInfo().
Returns the top level data source that contains the full data structure this data source refers to.
Defaults to returning this.
Definition at line 138 of file DataSource.cpp.
Returns a const pointer to the sample contained in this data source, if there is any.
Returns 0 otherwise
Reimplemented from RTT::base::DataSourceBase.
Definition at line 59 of file DataSource.inl.
Returns true if this object can be cast to an AssignableDataSource.
When this method returns true, all update functions below will return as well when valid input is given.
Reimplemented from RTT::base::DataSourceBase.
Definition at line 216 of file DataSource.hpp.
Clears the array of this data source and creates a new one.
Note that all references to this array will become invalid (types::carray may make shallow copies!) so only use this if you are sure no other object has a reference to the contained array.
Definition at line 133 of file DataSources.inl.
Referenced by RTT::types::CArrayTypeInfo< T, has_ostream >::buildVariable().
Get a const reference to the value of this DataSource.
You must call evaluate() prior to calling this function in order to get the most recent value of this attribute.
Implements RTT::internal::DataSource< T >.
Definition at line 378 of file DataSources.hpp.
Get a reference to the value of this DataSource.
Getting a reference to an internal data structure is not thread-safe.
Implements RTT::internal::AssignableDataSource< T >.
Definition at line 373 of file DataSources.hpp.
Returns a const shared_ptr to a DataSourceBase living on the stack.
Make sure that the const_ptr does not outlive the stacked element.
Definition at line 74 of file DataSource.cpp.
References RTT::base::DataSourceBase::ref().
Returns a shared ptr to a DataSourceBase living on the stack.
Make sure that the shared_ptr does not outlive the stacked element.
Definition at line 69 of file DataSource.cpp.
References RTT::base::DataSourceBase::ref().
Get the contents of this object as a string.
Definition at line 98 of file DataSource.cpp.
Update the value of this internal::DataSource with the value of an other DataSource.
Update does a full update of the value, adding extra information if necessary.
Reimplemented from RTT::base::DataSourceBase.
Definition at line 78 of file DataSource.inl.
References RTT::types::TypeInfo::convert(), RTT::internal::DataSource< T >::evaluate(), RTT::internal::DataSourceTypeInfo< T >::getTypeInfo(), and RTT::internal::DataSource< T >::value().
Generate a ActionInterface object which will update this internal::DataSource with the value of another internal::DataSource when execute()'ed.
Reimplemented from RTT::base::DataSourceBase.
Definition at line 94 of file DataSource.inl.
References RTT::types::TypeInfo::convert(), and RTT::internal::DataSourceTypeInfo< T >::getTypeInfo().
Return the result of the last evaluate() function.
You must call evaluate() prior to calling this function in order to get the most recent value of this attribute.
Implements RTT::internal::DataSource< T >.
Definition at line 366 of file DataSources.hpp.
Stream the contents of this object.
Definition at line 91 of file DataSource.cpp.
We keep the refcount ourselves.
We aren't using boost::shared_ptr, because boost::intrusive_ptr is better, exactly because it can be used with refcounts that are stored in the class itself. Advantages are that the shared_ptr's for derived classes use the same refcount, which is of course very much desired, and that refcounting happens in an efficient way, which is also nice :)
Definition at line 88 of file DataSourceBase.hpp.
Referenced by RTT::base::DataSourceBase::deref(), and RTT::base::DataSourceBase::ref(). | http://www.orocos.org/stable/documentation/rtt/v2.x/api/html/classRTT_1_1internal_1_1ArrayDataSource.html | CC-MAIN-2016-30 | en | refinedweb |
01 November 2012 11:30 [Source: ICIS news]
By Nigel Davis
?xml:namespace>
Dow Chemical won an award for pushing the boundaries of polymer science with its INFUSE olefin block co-polymers. Rhodia was acknowledged for a fascinating approach to tackling the problem of rare earth element availability, by creating, in effect, an ‘urban mine’.
The overall winner was Swiss specialty chemical producer Clariant which has developed a process for dyeing denim, one of the most ubiquitous of clothing materials, that could save an astonishing amount of water.
Clearly, sustainability lies behind the awards but they demonstrate that companies are putting new ideas to good and profitable use.
Innovation underpins chemicals manufacture in many ways, from the core process technologies developed, used or licensed by manufacturers, through new product ideas to different, more cost-effective, approaches to business.
It was noteworthy that this year no award was given in the ‘Best Business Innovation’ category. This was introduced into the awards to reflect the fact that innovation is not just about products and processes but also encompasses the way companies do business. Previous winners include BioAmber, Huntsman Advanced Materials and DSM.
“Coming up with new business solutions should be as important as technological or product development. Business innovation can add value and drive the right solutions to customers, and the industry,” says Alexander Farina of sponsor Shell Chemicals.
There were two strong short-listed contenders for award, Genomatica and Solazyme, but the judges felt that neither entry met the criteria for the category.
Often small-step business innovations can deliver great results as can a more collaborative, or partnership approach to innovation.
“This is a much more successful route,” said BMS head of sustainability Richard Northcote, in a recent edition of ICIS Chemical Business. “In the past, we have come up with clever technology but the market was often not ready,” he added.
“If you look at some of the recent product innovations we have delivered, they are often done in partnership. Solar Impulse or the BMS-
The solar driven plane, Solar Impulse, is proving to be a testbed for the successful application of lightweight materials. The aircraft has already flown continuously for 24 hours and crossed between continents, flying from Europe to
The main partners for the project are Solvay, which now incorporate Rhodia, watch-maker Omega, Deutsche Bank and elevator provider Schindler. BMS is one of the project partners while a number of suppliers and aeronautical and other institutions collaborate in the project.
BMS polyurethane and polycarbonate technologies are being used in the Solar Impulse planes and research done for the project has already found a place in the market. This, Northcote says, demonstrates that some of the solutions that manufacturer are seeking to develop lighter and stronger materials are not unique.
The annual ICIS Innovation Awards have shown that while chemical product markets are not necessarily becoming more complex, the processes for finding new product solutions perhaps | http://www.icis.com/Articles/2012/11/01/9609689/insight-innovation-and-collaboration-help-drive-results.html | CC-MAIN-2014-10 | en | refinedweb |
PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1)
perldata - Perl data types
Variable names Perl has three built-in data types: scalars, arrays of scalars, and associative arrays of scalars, known as "hashes". A scalar is a single string (of any size, limited only by the available memory), number, or a reference to something (which will be discussed in perlref). Normal arrays are ordered lists of scalars indexed by number, starting with 0. begin- ning run- time. expres- sion are saved under names containing only digits after the "$" (see perlop and perlre). In addition, several special variables that provide windows into the inner working of Perl have names containing punctuation characters and con- trol perl v5.8.8 2006-06-30 1 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) :-). Every variable type has its own namespace, as do several non-variable identifiers. This means that you can, without fear of conflict, use the same name for a scalar variable, an array, or a hash--or, for that matter, for a filehandle, a directory handle, a subroutine name, a format name, or a label. This means that $foo and @foo are two different variables. It also means that $foo[1] is a part of @foo, not a part of $foo. This may seem a bit weird, but that's okay, because it is weird. Because variable references always start with '$', '@', or '%', the "reserved" words aren't in fact reserved with respect to variable names. They are reserved with respect to labels and filehandles, however, which don't have an ini- tial the appropriate type. For a description of this, see perlref. Names that start with a digit may contain only more digits. Names that do not start with a letter, underscore, digit or a caret (i.e. a control character) are limited to one char- acter, e.g., $% or $$. (Most of these one character names have a predefined significance to Perl. For instance, $$ is the current process id.) perl v5.8.8 2006-06-30 2 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) Context The interpretation of operations and values in Perl some- times depends on the requirements of the context around the operation or value. There are two major contexts: list and scalar. Certain operations return list values in contexts wanting a list, and scalar values otherwise. If this is true of an operation it will be mentioned in the documenta- tion evalu- ates- routines do not need to bother, though. That's because both perl v5.8.8 2006-06-30 3 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) scalars and lists are automatically interpolated into lists. See "wantarray" in perlfunc for how you would dynamically discern your function's calling context. Scalar values All data in Perl is a scalar, an array of scalars, or a hash of scalars. A scalar may contain one single value in any of three different flavors: a number, a string, or a reference. In general, conversion from one form to another is tran- sparent. con- sidered. There are actually two varieties of null strings (sometimes referred to as "empty" strings), a defined one and an unde- fined enough to test it against both numeric 0 and also lexical "0" (although this will cause noises if warnings are on). That's because strings that perl v5.8.8 2006-06-30 4 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) aren't numbers count as 0, just as they do in awk: if ($str == 0 && $str ne "0") { warn "That doesn't look like a number"; } That).. How- ever, this isn't the length of the array; it's the subscript of the last element, which is a different value since there is ordinarily a 0th element. Assigning to $#days actually changes the length of the array. Shortening an array this way destroys intervening values. Lengthening an array that was previously shortened does not recover values that were in those elements. (It used to do so in Perl 4, but we had to break this to make sure destructors were called when expected.) You can also gain some minusc an array; perl v5.8.8 2006-06-30 5 PERLDATA(1) Perl Programmers Reference Guide PERLDATA as to leave nothing to doubt: $element_count = scalar(@whatever); exam- ple, buckets to the next power of two: keys(%users) = 1000; # allocate 1024 buckets Scalar value constructors Numeric (only numbers, begins with 0). perl v5.8.8 2006-06-30 6 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1)') or hash slices. (In other words, names beginning with $ or @, followed by an optional bracketed expression as a subscript.) The following code segment prints out "The price is $100." $Price = '$100'; # not interpolated print "The price is $Price.\n"; # interpolated There is no double interpolation in Perl, so the $100 is left as is. perl v5.8.8 2006-06-30 7 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) automatically. But anything more complicated in the sub- script will be interpreted as an expression. This means for example that "$version{2.0}++" is equivalent to "$ver- sion{2}++", not to "$version{'2.0'}++". Version Strings Note: Version Strings (v-strings) have been deprecated. They will not be available after Perl 5.8. The marginal benefits of v-strings were greatly outweighed by the poten- tial for Surprise and Confusion. A literal of the form "v1.20.300.4000" is parsed as a string composed of characters with the specified ordinals. This form, known as v-strings, provides an alternative, more readable way to construct strings, rather than use the some- what less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}". This is useful for represent- ing Unicode strings, and for comparing version "numbers" using the string comparison Such literals are accepted by both "require" and "use" for doing a version check. The $^V special variable also con- tains the running Perl interpreter's version in this form. See "$^V" in perlvar. Note that using the v-strings for IPv4 addresses is not portable unless you also use the inet_aton()/inet_ntoa() routines of the Socket package. Note that since Perl 5.8.1 the single-number v-strings (like "v65") are not v-strings before the "=>" operator (which is usually used to separate a hash key from a hash value), instead they are interpreted as literal strings ('v65'). They were v-strings from Perl 5.6.0 to Perl 5.8.0, but that caused more confusion and breakage than good. Multi-number v-strings like "v65.66" and 65.66.67 continue to be v-strings always. Special Literals. perl v5.8.8 2006-06-30 8 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1)".. Barewords "use warn- ings" pragma or the -w switch, Perl will warn you about any such words. Some people may wish to outlaw barewords entirely. If you say use strict 'subs'; then any bareword that would NOT be interpreted as a subrou- tine call produces a compile-time error instead. The res- triction lasts to the end of the enclosing block. An inner block may countermand this by saying "no strict 'subs'". Array Joining Delimiter Arrays and slices are interpolated into double-quoted strings by joining the elements with the delimiter specified in the $" variable ($LIST_SEPARATOR if "use English;" is specified), space by default. The following are equivalent: $temp = join($", @ARGV); system "echo $temp"; perl v5.8.8 2006-06-30 9 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) List values are denoted by separating individual values by commas (and enclosing the list in parentheses where pre- cedence requires it): (LIST) In a context not requiring a list value, the value of what appears to be a list literal is simply the value of the final element, as with the C comma operator. For example, @foo = ('cc', '-E', $bar); assigns the entire list value to array @foo, but $foo = ('cc', '-E', $bar); assigns the value of variable $bar to the scalar variable $foo. Note that the value of an actual array in scalar con- text is the length of the array; the following assigns the value 3 to $foo: @foo = ('cc', '-E', $bar); $foo = @foo; # $foo gets 3 You may have an optional comma before the closing parenthesis of a list literal, so that you can say: @foo = ( 1, 2, 3, ); perl v5.8.8 2006-06-30 10 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) To use a here-document to assign an array, one line per ele- ment, you might use an approach like this: @sauces = <<End_Lines =~ m/(\S.*\S)/g; normal tomato spicy tomato green chile pesto white wine End_Lines LISTs do automatic interpolation of sublists. That is, when a LIST is evaluated, each element of the list is evaluated in list context, and the resulting list value is interpo- lated into LIST just as if each individual element were a member of LIST. Thus arrays and hashes lose their identity in a LIST--the list (@foo,@bar,&SomeSub,%glarch) contains all the elements of @foo followed by all the ele- ments of @bar, followed by all the elements returned by the subroutine named SomeSub called. A list value may also be subscripted like a normal array. You must put the list in parentheses to avoid ambiguity. For example: # Stat returns list value. $time = (stat($file))[8]; # SYNTAX ERROR HERE. $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES perl v5.8.8 2006-06-30 11 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) # Find a hex digit. $hexdigit = ('a','b','c','d','e','f')[$digit-10]; # A "reverse comma operator". return (pop(@foo),pop(@foo))[0]; Lists may be assigned to only when each element of the list is itself legal to assign to: ($a, $b, $c) = (1, 2, 3); ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00); An exception to this is that you may assign to "undef" in a list. This is useful for throwing away some of the return values of a function: ($dev, $ino, undef, undef, $uid, $gid) = stat($file); List assignment in scalar context returns the number of ele- ments produced by the expression on the right side of the assignment: $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2 $x = (($foo,$bar) = f()); # set $x to f()'s return count This is handy when you want to do a list assignment in a Boolean context, because most list functions return a null list when finished, which when assigned produces a 0, which is interpreted as FALSE. It's also the source of a useful idiom for executing a func- tion or performing an operation in list context and then counting the number of return values, by assigning to an empty list and then using that assignment in scalar context. For example, this code: $count = () = $string =~ /\d+/g; will place into $count the number of digit groups found in $string. This happens because the pattern match is in list context (since it is being assigned to the empty list), and will therefore return a list of all matching parts of the string. The list assignment in scalar context will translate that into the number of elements (here, the number of times the pattern matched) and assign that to $count. Note that simply using $count = $string =~ /\d+/g; would not have worked, since a pattern match in scalar con- text will only return true or false, rather than a count of perl v5.8.8 2006-06-30 12 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) matches. The final element of a list assignment may be an array or a hash: ($a, $b, @rest) = split; my($a, $b, %rest) = @_; You can actually put an array or hash anywhere in the list, but the first one in the list will soak up all the values, and anything after it will become undefined. This may be useful in a my() or local(). A hash can be initialized using a literal list holding pairs of items to be interpreted as a key and a value: # same as map assignment above %map = ('red',0x00f,'blue',0x0f0,'green',0xf00); While literal lists and named arrays are often interchange- able, that's not the case for hashes. Just because you can subscript a list value like a normal array does not mean that you can subscript a list value as a hash. Likewise, hashes included as parts of other lists (including parame- ters simple identifier ("=>" doesn't quote compound identifiers, that contain double colons).', }; perl v5.8.8 2006-06-30 13 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) or for using call-by-named-parameter to complicated func- tions: order- ing. Subscripts An array is subscripted by specifying a dollar sign ("$"), then the name of the array (without the leading "@"), then the subscript inside square brackets. For example: @myarray = (5, 50, 500, 5000); print "Element Number 2 is", $myarray[2], "\n"; The array indices start with 0. A negative subscript retrieves its value from the end. In our example, $myar- ray[-1] would have been 5000, and $myarray[-2] would have been 500. Hash subscripts are similar, only instead of square brackets curly brackets are used. For example: %scientists = ( "Newton" => "Isaac", "Einstein" => "Albert", "Darwin" => "Charles", "Feynman" => "Richard", ); print "Darwin's First Name is ", $scientists{"Darwin"}, "\n"; Slices A common way to access an array or a hash is one scalar ele- ment at a time. You can also subscript a list to get a sin- gle element from it. $whoami = $ENV{"USER"}; # one element from the hash $parent = $ISA[0]; # one element from the array $dir = (getpwnam("daemon"))[7]; # likewise, but with list perl v5.8.8 2006-06-30 14 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1): perl v5.8.8 2006-06-30 15 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) sel- dom pass filehandles into a function or to create new filehandles. If you need to use a typeglob to save away a filehandle, do it this way: $fh = *STDOUT; or perhaps as a real reference, like this: perl v5.8.8 2006-06-30 16 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) $fh = \*STDOUT; See perlsub for examples of using these as indirect filehan- d'" perl v5.8.8 2006-06-30 17 PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1) forbids such practice. Another way to create anonymous filehandles is with the Sym- bol module or with the IO::Handle module and its ilk. These modules have the advantage of not hiding different types of the same name during the local(). See the bottom of "open()" in perlfunc for an example.
See perlvar for a description of Perl's built-in variables and a discussion of legal variable names. See perlref, perlsub, and "Symbol Tables" in perlmod for more discussion on typeglobs and the *foo{THING} syntax. perl v5.8.8 2006-06-30 18. | https://www.mirbsd.org/htman/sparc/man1/perldata.htm | CC-MAIN-2014-10 | en | refinedweb |
generator-closure
Generator for Closure Library
npm install generator-closure
Closure Library Generator
Create a fully working Closure Library project in seconds.
Getting Started
The Library Version
There is a Library version of the generator:
yo closure:lib
The Library version is for closure libraries that have no web output. The location of your project's base changes to
lib/ instead of the default one
app/js/.
What you get
- A fully working installation of closure compiler.
- A battle-tested folder scaffolding for your closure application.
- A skeleton sample application.
- A third-party dependencies loader.
- A set of helper and boilerplate code to speed up your time to productive code.
- A Full Behavioral and Unit testing suite using Mocha with Chai.js and Sinon.js.
- 52 BDD and TDD tests both for your development and compiled code.
- Full open source boilerplace (README, LICENSE, .editorconfig, etc).
- Vanilla and a special edition Closure Compiler that strips off all
loggercalls from your production code. (The special edition is used).
- Sourcemap file for your compiled code.
- A set of Grunt Tasks that will:
- Manage your dependencies.
- Compile your code.
- Run a static webserver with livereload.
- Test your code on the CLI & the browser.
Table Of Contents
- Grunt Tasks
- Your Closure Application
- Third-Party Dependencies
- The Test Suites
- About
Grunt Tasks
Tasks Overview
grunt serverStart a static server
gruntor
grunt depsCalculate Dependencies
grunt buildCompile your code
grunt testRun tests on the command line
grunt server:testRun tests on the browser
Tasks In Detail
grunt server
The
grunt server task will do quite a few things for you.
- A static server will listen on port 9000 (or anything you'd like, with:
--port=8080).
- A live reload server will be launched.
- All your codebase will be wathed for changes and trigger livereload events
- Finally, your browser will open on the project page:
- Temporary folder
tempis cleared.
- All the defined third-party dependencies are minified using uglify. The output can be found in
temp/vendor.js.
- Closure Compiler will compile your closure codebase using ADVANCED_OPTIMIZATIONS. The output can be found at:
temp/compiled.js
- Produce the final file by concatenating the vendor and compiled files to:
app/jsc/app.js
Configure build options var ENTRY_POINT = 'app';
Third-Party Libraries
Read about Configuring Third-Party dependencies for your build.
EXTERNS_PATH
Define the folder that will be scanned for externs files. The Closure Generator comes packed with these externs for you:
- jQuery 1.9
- Angular
- Facebook Javascript SDK
- When.js 1.8
ENTRY_POINT
The entry point is the top-most namespace level of your application. In the included sample application that namespace is
app.
Advanced Build Configuration.get.
Your Closure Application...
Folder Layout.provide('app.SomeClass'); goog.require('app.Module'); /** * @constructor * @extends {app.Module} */ app.SomeClass = function() { goog.base(this); /** .. */ }; goog.inherits(app.SomeClass, app.Module);.
Your Application Folders
Create new folders as you see fit. In the generator the folder
app/ is included which contains a skeleton app.
Third-Party Dependencies.
Configure Third-Party for Development
You need to edit the third-party library file which is located at:
app/js/libs/vendor.loader.js.
/** * EDIT THIS ARRAY. * * @type {Array} define the 3rd party deps. */ ssd.vendor.files = [ 'when.js', 'jQuery-1.9.1.js' ];
Add or remove strings in the array as you see fit.
Configure Third-Party Building
To define what third-party files will get bundled with your production file you need to edit the Gruntfile. At the top of the Gruntfile the
vendorFiles Array is defined:
// define the path to the app var APP_PATH = 'app/js'; // the file globbing pattern for vendor file uglification. var vendorFiles = [ // all files JS in vendor folder APP Suites
The test suite uses Mocha with Chai.js and Sinon.js. Two seperate types are included, Behavioral and Unit tests.
Behavioral Driven Development
Test Drive Development
Tests on the CLI
grunt test
'nough said.
Common Browser Pitfalls.
Contributing
Closure is so vast and we need to have a common place to document all the techniques and best practises used today.
The
ssd Namespace
The
ssd namespace that's included in some libraries stands for SuperStartup Development. It is the development namespace used by the Superstartup library.
Release History
- v0.1.15, 10 Jan 2014
- v0.1.13, 06 Jan 2014
- Force create
temp/folder.
- Updated
grunt-closure-toolspackage to
~0.9.0, latest.
- v0.1.12, 05 Dec 2013
- Updated all dependencies to latest.
- v0.1.9, 14 Oct 2013
- Allow overriding hostname and port of grunt server.
- Fix generator
greenbug.
- Enables defining closure-library location using the
CLOSURE_PATHenv var closureplease/generator-closure#3
- v0.1.8, 8 Jun 2013
- Fix event handling so it works with recent closure changes.
- v0.1.7, 3 Jun 2013
- Bug fix for library generation
- v0.1.6, 1 May 2013
- v0.1.5, 07 May 2013
- Renamed
component.jsonto
bower.json
- Linted Gruntfile
- Minor color tweaks
- v0.1.4, 14 Apr 2013
- Added Closure Linter task, thanks @pr4v33n
- v0.1.3, 14 Apr 2013
- Minor bugs
- v0.1.2, 21 Mar 2013
- Added Library generator
- Added Bower support
- Instruction changes
- v0.1.1, 20 Mar 2013
- Added Source Map option
- Minor typo fixes
- v0.1.0, Mid Mar 2013
- Big Bang
License | https://www.npmjs.org/package/generator-closure | CC-MAIN-2014-10 | en | refinedweb |
-------------------------------------------------------------------------- {- | Module : Control.Concurrent.STM.MonadIO Copyright : (c) 2010 Galois, Inc. License : BSD-style (see the file libraries/base/LICENSE) Maintainer : John Launchbury, john@galois.com Stability : experimental Portability : concurrency, requires STM Overloads the standard operations on TVars, and TMVars as defined in Control.Concurrent.STM. TVars and MVars are often thought of as variables to be used in the STM monad. But in practice, they should be used just as frequently (if not more so) in any IO-like monad, with STM being used purely when a new atomic transaction is being defined. Thus we reverse the naming convention, and use the plain access names when in the IO-like monad, and use an explicit STM suffix when using the variables tentatively within the STM monad itself. TMVars are particularly valuable when used in an IO-like monad, because operations like readTMVar and modifyTMvar can guarantee the atomicity of the operation (unlike the corresponding operations over MVars). The standard operations on 'TVar' and 'TMVar' (such as 'writeTVar' or 'newEmptyTMVar') are overloaded over the 'MonadIO' class. A monad @m@ is declared an instance of 'MonadIO' by defining a function > liftIO :: IO a -> m a It also overloads the 'atomically' function, so that STM transactions can be defined from within any MonadIO monad. -} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Control.Concurrent.STM.MonadIO ( STM , atomically , always , alwaysSucceeds , retry , orElse , check , catchSTM , S.TVar , newTVar , readTVar , writeTVar , registerDelay , modifyTVar , modifyTVar_ , newTVarSTM , readTVarSTM , writeTVarSTM , S.TMVar , newTMVar , newEmptyTMVar , takeTMVar , putTMVar , readTMVar , swapTMVar , tryTakeTMVar , tryPutTMVar , isEmptyTMVar , modifyTMVar , modifyTMVar_ , newTMVarSTM , newEmptyTMVarSTM , takeTMVarSTM , putTMVarSTM , readTMVarSTM , swapTMVarSTM , tryTakeTMVarSTM , tryPutTMVarSTM , isEmptyTMVarSTM ) where import Control.Monad.STM hiding (atomically) import qualified Control.Concurrent.STM as S import Control.Concurrent.MonadIO import GHC.Conc (readTVarIO) ------------------------------------------------------------------------- -- | The atomically function allows STM to be called directly from any -- monad which contains IO, i.e. is a member of MonadIO. atomically :: MonadIO io => STM a -> io a atomically m = liftIO $ S.atomically m ------------------------------------------------------------------------- type TVar = S.TVar newTVar :: MonadIO io => a -> io (TVar a) newTVar x = liftIO $ S.newTVarIO x readTVar :: MonadIO io => TVar a -> io a readTVar t = liftIO $ readTVarIO t writeTVar :: MonadIO io => TVar a -> a -> io () writeTVar t x = atomically $ writeTVarSTM t x registerDelay :: MonadIO io => Int -> io (TVar Bool) registerDelay n = liftIO $ S.registerDelay n -- | 'modifyTVar' is an atomic update operation which provides both -- the former value and the newly computed value as a result. modifyTVar :: MonadIO io => TVar a -> (a -> a) -> io (a,a) modifyTVar t f = atomically $ do x <- readTVarSTM t let y = f x seq y $ writeTVarSTM t y return (x,y) modifyTVar_ :: MonadIO io => TVar a -> (a -> a) -> io () modifyTVar_ t f = atomically $ do x <- readTVarSTM t let y = f x seq y $ writeTVarSTM t y ---------------------- newTVarSTM :: a -> STM (TVar a) newTVarSTM x = S.newTVar x readTVarSTM :: TVar a -> STM a readTVarSTM t = S.readTVar t writeTVarSTM :: TVar a -> a -> STM () writeTVarSTM t x = S.writeTVar t x ------------------------------------------------------------------------- type TMVar a = S.TMVar a newTMVar :: MonadIO io => a -> io (TMVar a) newTMVar x = liftIO $ S.newTMVarIO x newEmptyTMVar :: MonadIO io => io (TMVar a) newEmptyTMVar = liftIO $ S.newEmptyTMVarIO takeTMVar :: MonadIO io => TMVar a -> io a takeTMVar t = atomically $ takeTMVarSTM t putTMVar :: MonadIO io => TMVar a -> a -> io () putTMVar t x = atomically $ putTMVarSTM t x readTMVar :: MonadIO io => TMVar a -> io a readTMVar t = atomically $ readTMVarSTM t swapTMVar :: MonadIO io => TMVar a -> a -> io a swapTMVar t x = atomically $ swapTMVarSTM t x tryTakeTMVar :: MonadIO io => TMVar a -> io (Maybe a) tryTakeTMVar t = atomically $ tryTakeTMVarSTM t tryPutTMVar :: MonadIO io => TMVar a -> a -> io Bool tryPutTMVar t x = atomically $ tryPutTMVarSTM t x isEmptyTMVar :: MonadIO io => TMVar a -> io Bool isEmptyTMVar t = atomically $ isEmptyTMVarSTM t -- modifyTMVar is an atomic update operation which provides both -- the former value and the newly computed value as a result. modifyTMVar :: MonadIO io => TMVar a -> (a -> a) -> io (a,a) modifyTMVar t f = atomically $ do x <- takeTMVarSTM t let y = f x seq y $ putTMVarSTM t y return (x,y) modifyTMVar_ :: MonadIO io => TMVar a -> (a -> a) -> io () modifyTMVar_ t f = atomically $ do x <- takeTMVarSTM t let y = f x seq y $ putTMVarSTM t y ---------------------- newTMVarSTM :: a -> STM (TMVar a) newTMVarSTM = S.newTMVar newEmptyTMVarSTM :: STM (TMVar a) newEmptyTMVarSTM = S.newEmptyTMVar takeTMVarSTM :: TMVar a -> STM a takeTMVarSTM = S.takeTMVar putTMVarSTM :: TMVar a -> a -> STM () putTMVarSTM = S.putTMVar readTMVarSTM :: TMVar a -> STM a readTMVarSTM = S.readTMVar swapTMVarSTM :: TMVar a -> a -> STM a swapTMVarSTM = S.swapTMVar tryTakeTMVarSTM :: TMVar a -> STM (Maybe a) tryTakeTMVarSTM = S.tryTakeTMVar tryPutTMVarSTM :: TMVar a -> a -> STM Bool tryPutTMVarSTM = S.tryPutTMVar isEmptyTMVarSTM :: TMVar a -> STM Bool isEmptyTMVarSTM = S.isEmptyTMVar | http://hackage.haskell.org/package/monadIO-0.9.2.0/docs/src/Control-Concurrent-STM-MonadIO.html | CC-MAIN-2014-10 | en | refinedweb |
#include "libavutil/lfg.h"
#include "ac3.h"
#include "get_bits.h"
#include "dsputil.h"
#include "fft.
Definition at line 66 of file ac3dec.h.
Referenced by ff_eac3_decode_transform_coeffs_aht_ch().
Definition at line 64 of file ac3dec.h.
Referenced by ac3_decode_frame(), and decode_audio_block().
Definition at line 62 of file ac3dec.h.
Referenced by ac3_decode_transform_coeffs_ch(), calc_transform_coeffs_cpl(), decode_audio_block(), decode_transform_coeffs(), ff_eac3_parse_header(), and remove_dithering().
Definition at line 68 of file ac3dec.h.
Referenced by synth_frame().
Definition at line 69 of file ac3dec.h.
Referenced by ff_eac3_apply_spectral_extension().
Downmix the output to mono or stereo.
Definition at line 655(). | http://www.ffmpeg.org/doxygen/0.6/ac3dec_8h.html | CC-MAIN-2014-10 | en | refinedweb |
Awesome! Hearing not a peep from the list, I moved that to: so I could integrate it with content already at: It would be useful for novices to know if the stock Fedora kernels support this behavior, or if they have to custom-compile one. Thanks, Beland On Mon, 2009-03-16 at 15:45 +0000, "Jóhann B. Guðmundsson" wrote: > Sysrq.txt which has been with us for ages has finally been wikified with > minor editing > > Now testers and others can read > > > Until we find a place for it some were under QA namespace. | http://www.redhat.com/archives/fedora-test-list/2009-March/msg00944.html | CC-MAIN-2014-10 | en | refinedweb |
RadGroupBox control is a group box control with advanced styling options.
The primarily usage of this control is to hold a single radio buttons group. The control does not support
scrolling which is however supported by RadPanel. The control never gets focus being a container for other controls which can get focus.
You need to include Telerik.WinControls.UI namespace in your application.
The most important RadGroupBox layout styling options include the following:
GroupBoxStyle - there are two defined styles: Standard and Office.
The styles are defined in RadGroupBoxStyle enumeration.
HeaderAlignment - header alignment options are defined in HeaderAlignment enumeration: Near,
Center, and Far.
HeaderPosition - header position options are defined in HeaderPosition enumeration:
Top, Left, Bottom, and Right.
HeaderMargin - defines the header margin.
FooterVisibility - defines the footer visibility. Its default value is Collapsed.
The most important Headerand Footer styling options include the following ones:
HeaderImage
FooterImage
HeaderImageAlignment
FooterImageAlignment
HeaderText
FooterText
HeaderTextAlignment
FooterTextAlignment
HeaderTextImageRelation
FooterTextImageRelation
Please refer to ImageAndTextLayoutPanel documentation section about further details of those properties.
All these properties can be set in Visual Style Builder. Furthermore, the control can be customized on a very
fine-grained level using the Visual Style Builder to set any other property in the control hierarchy.
Please refer to RadGroupBox TPF structure section for more details. | http://www.telerik.com/help/winforms/panels-and-labels-groupbox-overview.html | CC-MAIN-2014-10 | en | refinedweb |
Nonlinear, stochastic Galerkin ModelEvaluator. More...
#include <Stokhos_SGModelEvaluator.hpp>
Nonlinear, stochastic Galerkin ModelEvaluator.
SGModelEvaluator is an implementation of EpetraExt::ModelEvaluator that generates a nonlinear problem from a stochastic Galerkin expansion.. For dealing with the W matrix two methods are supported: forming a fully-assembled SG matrix and a "matrix free" method. The choice is selected by setting the "Jacobian Method" parameter of the parameter list supplied to the constructor, which can be either "Fully Assembled" or "Matrix Free". In the first case, the W operator of the underlying model evaluator must be an Epetra_CrsMatrix. In the second case, a preconditioner for the mean block must also be supplied via the "Preconditioner Factory" parameter of this list. This preconditioner factory must implement the Stokhos::PreconditionerFactory interface also supplied in this file. Currently using a preconditioner for the mean is the only option available for preconditioning the SG system when using the matrix-free method.
Get indices of SG responses.
These indices determine which response vectors support SG
Get indices of SG parameters.
These indices determine which parameter vectors support SG | http://trilinos.sandia.gov/packages/docs/r10.12/packages/stokhos/doc/html/classStokhos_1_1SGModelEvaluator.html | CC-MAIN-2014-10 | en | refinedweb |
16 May 2012 05:40 [Source: ICIS news]
SINGAPORE (ICIS)--Saudi petrochemical major SABIC has raised its June monoethylene glycol (MEG) Asia Contract Price (ACP) nomination by $50/tonne (€40/tonne) from a month ago in view of improved supply and demand situation in ?xml:namespace>
“We set our June MEG ACP at $1,200/tonne CFR (cost & freight)
The company has earlier decided to extend the shutdown at its 700,000 tonne/year No 1 unit at Jubail by another month to end-May or early June.
The plant was shut in early April, initially for 10 days of maintenance, but the shutdown was prolonged twice because of mechanical issues.
Total MEG production loss from the two-month shutdown is estimated at around 120,000 tonnes, according to a source close to the company.
“The nomination is higher than we expected,” a major Zhejiang-based polyester maker said.
Uncertainties in the macroeconomic environment and persistently weak polyester demand have been weighing on the Asian MEG market.
Spot MEG prices stood at $960-980/tonne on Tuesday, down by $45-52/tonne from early May, according | http://www.icis.com/Articles/2012/05/16/9560082/saudis-sabic-hikes-june-meg-acp-nomination-by-50tonne.html | CC-MAIN-2014-10 | en | refinedweb |
ember
Ember - JavaScript Application Framework
npm install ember
Ember for Node
Ember.js is a framework for building ambitious client-side applications on the web. Now you can use the same Ember tools in node code and in node-based asset pipelines like Convoy.
Using This Package
Just add ember as a requirement to your package.json:
"dependencies": { ... "ember": "~0.9" }
In your code, you can load the entire Ember stack by just requiring the package. This will add Ember to the global namespace in your application.
require('ember'); MyApp = Ember.Application.create({ hi: function() { console.log('Hi! I'm an app!'); } });
If you don't want to use the entire Ember stack, you can just require the specific module that you want. For example, a lot of server side code just needs States for statecharting:
require('ember/states'); MyState = Ember.State.create({ });
Using Ember with Convoy
Building an Ember application in the browser is very easy when using Convoy. Just require ember in your main application file.
// In some JS module included by convoy: require('ember'); // <- convoy will automatically pull in all of Ember. UserView = Ember.View.extend({ template: Ember.Handlebars.compile('{{firstName}} {{lastName}}') });
If you want to store your Handlebars templates in a separate file, Ember for Node has a HandlebarsCompiler that will precompile the templates for you. Here is an example Convoy pipeline configuration:
pipeline = convoy({ 'app.js': { packager: 'javascript', compilers: { '.hbr': require('ember/packager').HandlebarsCompiler } } }); app = express.createServer(); app.use(pipeline.middleware());
This will now make
.hbr files available as modules. In your app code, you
can load the template via a normal require:
// user_view.js require('ember/views'); UserView = Ember.View.extend({ template: require('./user_template') // template in user_template.hbr });
For a fully functioning example of an application, check out the examples folder.
Building From Source
This project checks out the ember source and builds compiled copies for use in the released version. If you want to rebuild this from source, here is what you need to do:
- Make sure you have node.js and Jake installed globally. Once you have node.js installed you can install jake with the command
[sudo] npm install -g jake
- Also make sure you have Ruby 1.9.3 or later installed as well as bundler. Once you have ruby installed you can install bundler with
[sudo] gem install bundler
- Clone the node-ember repo
- From the repo directory run
jake vendor:setup. This should checkout the correct versions of ember and ember-data and set them up to build
- Run
jake dietto actually build the assets.
Note that you only need to run
vendor:setup once the first time you install the report or anytime the version of ember or ember-data changes. Afterwards, you should be able to run
dist just to rebuild.
ember and ember-data are linked into this project as git submodules. To update to a newer (or older) version of ember or ember-data, cd into the vendor directory and checkout the version you want. Then cd back to the top level of the repo and commit the updates into git. Once completed, run
jake vendor:setup again to update the contents.
IMPORTANT: The dist command will checkout whichever version of ember or ember-data are set in the submodule, so you must commit to git before rebuilding. | https://www.npmjs.org/package/ember | CC-MAIN-2014-10 | en | refinedweb |
#include <sensors.h>
Every hardware module must have a data structure named HAL_MODULE_INFO_SYM and the fields of this data structure must begin with hw_module_t followed by module specific information.
Definition at line 894 of file sensors.h.
Definition at line 895 of file sensors.h.
Enumerate all available sensors. The list is returned in "list".
Definition at line 901 of file sensors.h. | https://source.android.com/devices/reference/structsensors__module__t.html | CC-MAIN-2014-10 | en | refinedweb |
The VelocityECSLayout has been deprecated in Turbine 2.3.
See: VelocityOnlyLayout Howto
Writing Directly To ServletOutputStream
On March 19, 2003, Peter Courcoux wrote to turbine-dev:
"Hi all,
I have recently changed from using turbine 2.2-b3 to 2.2.1 and from using VelocityECSLayout to VelocityOnlyLayout.
One of my actions which extends VelocitySecureAction handles a file download by obtaining the HttpServletResponse setting the headers and then obtaining and writing directly to the ServletOutputStream.
Before the changes outlined above this caused no problem. Having made the changes the following Exception occurs after the completion of the download and closing the ServletOutputStream.
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at
org.apache.catalina.connector.ResponseBase.getWriter(ResponseBase.java:750)
at
org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:165)
at
org.apache.turbine.services.rundata.DefaultTurbineRunData.getOut(DefaultTurbineRunData.java:1013)
at
org.apache.turbine.modules.layouts.VelocityOnlyLayout.doBuild(VelocityOnlyLayout.java:120)
at org.apache.turbine.modules.Layout.build(Layout.java:91)
at org.apache.turbine.modules.LayoutLoader.exec(LayoutLoader.java:123)
at
org.apache.turbine.modules.pages.DefaultPage.doBuild(DefaultPage.java:169)
at org.apache.turbine.modules.Page.build(Page.java:90)
at org.apache.turbine.modules.PageLoader.exec(PageLoader.java:123)
at org.apache.turbine.Turbine.doGet(Turbine.java:563)
at org.apache.turbine.Turbine.doPost(Turbine.java:658)"
He later contributed a solution:
"I have solved this by creating a DirectResponseLayout class which does :nothing except check that declareDirectResponse() has been called on RunData. I then call
data.setLayout("DirectResponseLayout");
in my Action class.
Source of DirectResponseLayout :-
{{{ public class DirectResponseLayout extends Layout { {{{ /** Method called by LayoutLoader. public void doBuild( RunData data ) throws Exception { } }}} }}}
package com.whatever.modules.layouts;
// Turbine Classes
import org.apache.turbine.modules.Layout;
import org.apache.turbine.util.RunData;
/**
{{{ * This layout allows an action to manipulate the
* ServletOutputStream directly. It requires that
* data.declareDirectResponse() has been called to
* indicate that the OutputStream is being
* handled else an Exception is thrown
*
* @author <a href="mailto:peter@courcoux.biz">Peter Courcoux</a>
*/
} }}}
}
public class DirectResponseLayout extends Layout { {{{ /**
Method called by LayoutLoader.
- /
public void doBuild( RunData data ) throws Exception {
- if (!data.isOutSet())
- {
- throw new Exception(
- "data.declareDirectResponse() has not been called");
}
}}} }}}
One drawback is that it calls data.isOutSet() which is deprecated.
Questions.
1. Is there a better way?
2. If not, would it be worth including the DirectResponseLayout class in the turbine distribution.
3. Is there a case for removing the deprecation of RunData.isOutSet()?
4. Is this worth documenting. At least one other user appears to be doing something similar."
I have committed { { { DirectResponseLayout } } } to cvs - it will come with future releases of Turbine (2.3.1 and 2.4) whenever those are released. -- ScottEade 2003-10-17
CategoryJakartaTurbine2HowTo | http://wiki.apache.org/jakarta/JakartaTurbine2/VelocityOnlyLayout?highlight=DirectResponseLayout | CC-MAIN-2014-10 | en | refinedweb |
How to Test Everything
[This post also appears on Dustin's github blog].
I recently had a Membase user point out a sequence of operations that led to an undesirable state. I’ve got a lot of really good engine tests I’ve written, but not this case:
The bug is pretty straightforward – expiry is lazy and it turns out I’m not checking for expiry in this case. It was pretty easy to write this test, but immediately made me think about what other cases weren’t being run.
Now, I know there are countless tools out there to aid in testing. I’ve written another one. I probably spent an hour or so writing a framework to write and run all of the tests I needed. The difference between what I’m describing here and, for example, quick check is that I want something very simple to express actions that expect their environment to be in a particular state and will leave the environment in another state. Then I want to hit every possible arrangement of these actions to ensure they don’t interfer with each other in unexpected ways.
This blows up very quickly – specifically the number of tests generated for a test sequence of
n actions from
a possible actions is approximately
an.
Consider three defined actions permuted into sequences of two. That blows out to nine possibilites as shown in the diagram on the right.
The actions in the diagram are defined with memcached semantics on a single key, so
add has a prerequisite that the item must not exist and
del has a prerequisite that the item must exist.
The generated test expects success at each white box, failure at each red box, and tracks the expected state mutations to build assertions.
My first test… um, test ran with
11 actions in sequences of
4 actions. I have more actions to go, but
4 is a pretty good length, so the chart at the left is going to demonstrate my growth rate.
The awesome part is that it pointed out the original bug quite easily and another couple of bugs with limited effort.
How Do I Use This?
The API is so far pretty simple and composable. There are basically five classes (three are shown in the image on the right).
Condition
A
Condition is a simple callable that is used for preconditions and postconditions. A given class doesn’t care which one it’s used for, and in many cases will be used for both.
For example, consider my implementation of
DoesNotExist:
def __call__(self, state):
return TESTKEY not in state
Effect
An
Effect changes our view of the state (and depending on the driver, may actually cause something in the world to change with it). For example, the
StoreEffect works as follows:
def __call__(self, state):
state[TESTKEY] = '0'
Action
An
Action brings an
Effect and one or more
Condition classes as pre and post conditions. For example, we’ll look at two actions, an
Add action and a
Set action:
effect = StoreEffect()
postconditions = [Exists()]
class Add(Action):
preconditions = [DoesNotExist()]
effect = StoreEffect()
postconditions = [Exists()]
The interesting part of this is that Set and Add have different semantics, but are expressed as different compositions of the same conditions and effects.
Driver
Driver is kind of a larger part (seven defined methods!). It does enough that I can do anything from generate a C test suite for memcached engines all the way to actually executing tests across a remote protocol.
I won’t describe the entire thing here since it’s documented in the source. I will however, close the loop by showing you some example code that it generated that demonstrated the error we failed to find in the first place:
ENGINE_HANDLE_V1 *h1) {
add(h, h1);
assertHasNoError(); // value is "0"
add(h, h1);
assertHasError(); // value is "0"
delay(expiry+<span class="mi">1);
assertHasNoError(); // value is not defined
add(h, h1);
assertHasNoError(); // value is "0"
checkValue(h, h1, "0");
return SUCCESS;
}
</span>
That demonstrates how much information you know at each step of the way. From there, we can do all kinds of stuff with our stubs (delay above is implemented with the memcached testapp “time travel” feature, for example).
From here, it’s less exciting. We provide constraints, it writes tests, and makes sure that there’s another area that it’s impossible for users to encounter something we haven’t seen before. | https://blog.couchbase.com/how-test-everything | CC-MAIN-2014-10 | en | refinedweb |
#include <NOX_Solver_LineSearchBased.H>
Inheritance diagram for NOX::Solver::LineSearch": | http://trilinos.sandia.gov/packages/docs/r7.0/packages/nox/doc/html/classNOX_1_1Solver_1_1LineSearchBased.html | CC-MAIN-2014-10 | en | refinedweb |
.
Second, the PEP defines the one official way of defining namespace packages, rather than the multitude of ad-hoc ways currently in use. With the pre-PEP 382 way, it was easy to get the details subtly wrong, and unless all subpackages cooperated correctly, the packages would be broken. Now, all you do is put a * start.
Eric Smith (who is the 382 BDFOP, or benevolent dictator for one pep), Jason Coombs, and I met once before to sprint on PEP 382, and we came away with more questions than answers. Eric, Jason, and I live near each other so it's really great to meet up with people for some face-to-face hacking. This time, we made a wider announcement, on social media and.
So, what did we accomplish? Both a lot, and a little. Despite working from about 4pm until closing, we didn't commit much more than a few bug fixes (e.g. an uninitialized variable that was crashing the tests on Fedora), a build fix for Windows, and a few other minor things. However, we did come away with a much better understanding of the existing code, and a plan of action to continue the work online. All the gory details are in the wiki page that I created.
One very important thing we did was to review the existing test suite for coverage of the PEP specifications. We identified a number of holes in the existing test suite, and we'll work on adding tests for these. We also recognized that importlib (the pure-Python re-implementation of the import machinery) wasn't covered at all in the existing PEP 382 tests, so Michael worked on that. Not surprisingly, once that was enabled, the tests failed, since importlib has not yet been modified to support PEP 382. by removing all the bits that could be re-implemented as PEP 302 loaders, specifically the import-from-filesystem stuff. The other neat thing is that the loaders could probably be implemented in pure-Python without much of a performance hit, since we surmise that the stat calls dominate. If that's true, then we'd be able to refactor importlib to share a lot of code with the built-in C import machinery. This could have the potential to greatly simplify import.c so that it contains just the PEP 302 machinery, with some bootstrapping code. It may even be possible to move most of the PEP 382 implementation into the loaders. At the sprint we did a quick experiment with zipping up the standard library and it looked promising, so Eric's going to take a crack at this.
This is briefly what we accomplished at the sprint. I hope we'll continue the enthusiasm online, and if you want to join us, please do subscribe to the import-sig!
Wednesday, June 22, 2011
PEP 382 sprint summary
Posted by Barry Warsaw at 1:12 PM
Thanks for the report, awesome work guys.) | http://www.wefearchange.org/2011/06/pep-382-sprint-summary.html | CC-MAIN-2014-10 | en | refinedweb |
livestats / README.md
LiveStats - Online Statistical Algorithms for Python
LiveStats solves the problem of generating accurate statistics for when your data set is too large to fit in memory, or too costly to sort. Just add your data to the LiveStats object, and query the methods on it to produce statistical estimates of your data.
LiveStats doesn't keep any items in memory, only estimates of the statistics. This means you can calculate statistics on an arbitrary amount of data.
Example usage
When constructing a LiveStats object, pass in an array of the quantiles you wish you track. LiveStats stores 15 double values per quantile supplied.
from livestats import LiveStats from math import sqrt import random test = LiveStats([0.25, 0.5, 0.75]) data = iter(random.random, 1) for x in xrange(3): for y in xrange(100): test.add(data.next()*100) print "Average {}, stddev {}, quantiles {}".format(test.mean(), sqrt(test.variance()), test.quantiles())
Easy.
How accurate is it?
Very accurate. If you run livestats.py as a script with a numeric argument, it'll run some tests with that many data points. As soon as you start to get over 10,000 elements, accuracy to the actual quantiles is well below 1%. At 10,000,000, it's this:
Uniform: Avg%E 1.732260e-12 Var%E 2.999999e-05 Perc%E 1.315983e-05 Expovar: Avg%E 9.999994e-06 Var%E 1.000523e-05 Perc%E 1.741774e-05 Triangular: Avg%E 9.988727e-06 Var%E 4.839340e-12 Perc%E 0.015595 Bimodal: Avg%E 9.999991e-06 Var%E 4.555303e-05 Perc%E 9.047849e-06
That's percent error for the cumulative moving average, variance, and the average percent error for four different random distributions at three quantiules, 25th, 50th, and 75th. Pretty good.
More details
LiveStats uses the P-Square Algorithm for Dynamic Calculation of Quantiles and Histograms without Storing Observations and other online statistical algorithms. I also wrote a post on where I got this idea. | https://bitbucket.org/scassidy/livestats/src/1ec0dffe5386/README.md | CC-MAIN-2014-10 | en | refinedweb |
Machine learning is broadly split into two camps, statistical learning and non-statistical learning. The latter we’ve started to get a good picture of on this blog; we approached Perceptrons, decision trees, and neural networks from a non-statistical perspective. And generally “statistical” learning is just that, a perspective. Data is phrased in terms of independent and dependent variables, and statistical techniques are leveraged against the data. In this post we’ll focus on the simplest example of this, linear regression, and in the sequel see it applied to various learning problems.
As usual, all of the code presented in this post is available on this blog’s Github page.
The Linear Model, in Two Variables
And so given a data set we start by splitting it into independent variables and dependent variables. For this section, we’ll focus on the case of two variables,
. Here, if we want to be completely formal,
are real-valued random variables on the same probability space (see our primer on probability theory to keep up with this sort of terminology, but we won’t rely on it heavily in this post), and we choose one of them, say
, to be the independent variable and the other, say
, to be the dependent variable. All that means in is that we are assuming there is a relationship between
and
, and that we intend to use the value of
to predict the value of
. Perhaps a more computer-sciencey terminology would be to call the variables features and have input features and output features, but we will try to stick to the statistical terminology.
As a quick example, our sample space might be the set of all people,
could be age, and
could be height. Then by calling age “independent,” we’re asserting that we’re trying to use age to predict height.
One of the strongest mainstays of statistics is the linear model. That is, when there aren’t any known relationships among the observed data, the simplest possible relationship one could discover is a linear one. A change in
corresponds to a proportional change in
, and so one could hope there exist constants
so that (as random variables)
. If this were the case then we could just draw many pairs of sample values of
and
, and try to estimate the value of
and
.
If the data actually lies on a line, then two sample points will be enough to get a perfect prediction. Of course, nothing is exact outside of mathematics. And so if we were to use data coming from the real world, and even if we were to somehow produce some constants
, our “predictor” would almost always be off by a bit. In the diagram below, where it’s clear that the relationship between the variables is linear, only a small fraction of the data points appear to lie on the line itself.
An example of a linear model for a set of points (credit Wikipedia).
In such scenarios it would be hopelessly foolish to wish for a perfect predictor, and so instead we wish to summarize the trends in the data using a simple description mechanism. In this case, that mechanism is a line. Now the computation required to find the “best” coefficients of the line is quite straightforward once we pick a suitable notion of what “best” means.
Now suppose that we call our (presently unknown) prediction function
. We often call the function we’re producing as a result of our learning algorithm the hypothesis, but in this case we’ll stick to calling it a prediction function. If we’re given a data point
where
is a value of
and
of
, then the error of our predictor on this example is
. Geometrically this is the vertical distance from the actual
value to our prediction for the same
, and so we’d like to minimize this error. Indeed, we’d like to minimize the sum of all the errors of our linear predictor over all data points we see. We’ll describe this in more detail momentarily.
The word “minimize” might evoke long suppressed memories of torturous Calculus lessons, and indeed we will use elementary Calculus to find the optimal linear predictor. But one small catch is that our error function, being an absolute value, is not differentiable! To mend this we observe that minimizing the absolute value of a number is the same as minimizing the square of a number. In fact,
, and the square root function and its inverse are both increasing functions; they preserve minima of sets of nonnegative numbers. So we can describe our error as
, and use calculus to our heart’s content.
To explicitly formalize the problem, given a set of data points
and a potential prediction line
, we define the error of
on the examples to be
Which can also be written as
Note that since we’re fixing our data sample, the function
is purely a function of the variables
. Now we want to minimize this quantity with respect to
, so we can take a gradient,
and set them simultaneously equal to zero. In the first we solve for
:
If we denote by
this is just
. Substituting
into the other equation we get
Which, by factoring out
, further simplifies to
And so
And it’s not hard to see (by taking second partials, if you wish) that this corresponds to a minimum of the error function. This closed form gives us an immediate algorithm to compute the optimal linear estimator. In Python,
avg = lambda L: 1.0* sum(L)/len(L) def bestLinearEstimator(points): xAvg, yAvg = map(avg, zip(*points)) aNum = 0 aDenom = 0 for (x,y) in points: aNum += (y - yAvg) * x aDenom += (x - xAvg) * x a = float(aNum) / aDenom b = yAvg - a * xAvg return (a, b), lambda x: a*x + b
and a quick example of its use on synthetic data points:
>>> import random >>> a = 0.5 >>> b = 7.0 >>> points = [(x, a*x + b + (random.random() * 0.4 - 0.2)) for x in [random.random() * 10 for _ in range(100)]] >>> bestLinearEstimator(points)[0] (0.49649543577814137, 6.993035962110321)
Many Variables and Matrix Form
If we take those two variables
and tinker with them a bit, we can represent the solution to our regression problem in a different (a priori strange) way in terms of matrix multiplication.
First, we’ll transform the prediction function into matrixy style. We add in an extra variable
which we force to be 1, and then we can write our prediction line in a vector form as
. What is the benefit of such an awkward maneuver? It allows us to write the evaluation of our prediction function as a dot product
Now the notation is starting to get quite ugly, so let’s rename the coefficients of our line
, and the coefficients of the input data
. The output is still
. Here we understand implicitly that the indices line up: if
is the constant term, then that makes
our extra variable (often called a bias variable by statistically minded folks), and
is the linear term with coefficient
. Now we can just write the prediction function as
We still haven’t really seen the benefit of this vector notation (and we won’t see it’s true power until we extend this to kernel ridge regression in the next post), but we do have at least one additional notational convenience: we can add arbitrarily many input variables without changing our notation.
If we expand our horizons to think of the random variable
depending on the
random variables
, then our data will come in tuples of the form
, where again the
is fixed to 1. Then expanding our line
, our evaluation function is still
. Excellent.
Now we can write our error function using the same style of compact notation. In this case, we will store all of our input data points
as rows of a matrix
and the output values
as entries of a vector
. Forgetting the boldface notation and just understanding everything as a vector or matrix, we can write the deviation of the predictor (on all the data points) from the true values as
Indeed, each entry of the vector
is a dot product of a row of
(an input data point) with the coefficients of the line
. It’s just
applied to all the input data and stored as the entries of a vector. We still have the sign issue we did before, and so we can just take the square norm of the result and get the same effect as before:
This is just taking a dot product of
with itself. This form is awkward to differentiate because the variable
is nested in the norm. Luckily, we can get the same result by viewing
as a 1-by-
matrix, transposing it, and multiplying by
.
This notation is widely used, in particular because we have nice formulas for calculus on such forms. And so we can compute a gradient of
with respect to each of the
variables in
at the same time, and express the result as a vector. This is what taking a “partial derivative” with respect to a vector means: we just represent the system of partial derivates with respect to each entry as a vector. In this case, and using formula 61 from page 9 and formula 120 on page 13 of The Matrix Cookbook, we get
Indeed, it’s quite trivial to prove the latter formula, that for any vector
, the partial
. If the reader feels uncomfortable with this, we suggest taking the time to unpack the notation (which we admittedly just spent so long packing) and take a classical derivative entry-by-entry.
Solving the above quantity for
gives
, assuming the inverse of
exists. Again, we’ll spare the details proving that this is a minimum of the error function, but inspecting second derivatives provides this.
Now we can have a slightly more complicated program to compute the linear estimator for one input variable and many output variables. It’s “more complicated” in that much more mathematics is happening behind the code, but just admire the brevity!
from numpy import array, dot, transpose from numpy.linalg import inv def bestLinearEstimatorMV(points): # input points are n+1 tuples of n inputs and 1 output X = array([[1] + list(p[:-1]) for p in points]) # add bias as x_0 y = array([p[-1] for p in points]) Xt = transpose(X) theInverse = inv(dot(Xt, X)) w = dot(dot(theInverse, Xt), y) return w, lambda x: dot(w, x)
Here are some examples of its use. First we check consistency by verifying that it agrees with the test used in the two-variable case (note the reordering of the variables):
>>> print(bestLinearEstimatorMV(points)[0]) [ 6.97687136 0.50284939]
And a more complicated example:
>>> trueW = array([-3,1,2,3,4,5]) >>> bias, linearTerms = trueW[0], trueW[1:] >>> points = [tuple(v) + (dot(linearTerms, v) + bias + noise(),) for v in [numpy.random.random(5) for _ in range(100)]] >>> print(bestLinearEstimatorMV(points)[0]) [-3.02698484 1.03984389 2.01999929 3.0046756 4.01240348 4.99515123]
As a quick reminder, all of the code used in this post is available on this blog’s Github page.
Bias and Variance
There is a deeper explanation of the linear model we’ve been studying. In particular, there is a general technique in statistics called maximum likelihood estimation. And, to be as concise as possible, the linear regression formulas we’ve derived above provide the maximum likelihood estimator for a line with symmetric “Gaussian noise.” Rather than go into maximum likelihood estimation in general, we’ll just describe what it means to be a “line with Gaussian noise,” and measure the linear model’s bias and variance with respect to such a model. We saw this very briefly in the test cases for the code in the past two sections. Just a quick warning: the proofs we present in this section will use the notation and propositions of basic probability theory we’ve discussed on this blog before.
So what we’ve done so far in this post is describe a computational process that accepts as input some points and produces as output a line. We have said nothing about the quality of the line, and indeed we cannot say anything about its quality without some assumptions on how the data was generated. In usual statistical fashion, we will assume that the true data is being generated by an actual line, but with some added noise.
Specifically, let’s return to the case of two random variables
. If we assume that
is perfectly determined by
via some linear equation
, then as we already mentioned we can produce a perfect estimator using a mere two examples. On the other hand, what if every time we take a new
example, its corresponding
value is perturbed by some random coin flip (flipped at the time the example is produced)? Then the value of
would be
, and we say all the
are drawn independently and uniformly at random from the set
. In other words, with probability 1/2 we get -1, and otherwise 1, and none of the
depend on each other. In fact, we just want to make the blanket assumption that the noise doesn’t depend on anything (not the data drawn, the method we’re using to solve the problem, what our favorite color is…). In the notation of random variables, we’d call
the random variable producing the noise (in Greek
is the capital letter for
), and write
.
More realistically, the noise isn’t chosen uniformly from
, but is rather chosen to be Gaussian with mean
and some variance
. We’d denote this by
, and say the
are drawn independently from this normal distribution. If the reader is uncomfortable with Gaussian noise (it’s certainly a nontrivial problem to generate it computationally), just stick to the noise we defined in the previous paragraph. For the purpose of this post, any symmetric noise will result in the same analysis (and the code samples above use uniform noise over an interval anyway).
Moving back to the case of many variables, we assume our data points
are given by
where
is the observed data and
is Gaussian noise with mean zero and some (unknown) standard deviation
. Then if we call
our predicted linear coefficients (randomly depending on which samples are drawn), then its expected value conditioned on the data is
Replacing
by
,
Notice that the first term is a fat matrix (
) multiplied by its own inverse, so that cancels to 1. By linearity of expectation, we can split the resulting expression up as
but
is constant (so its expected value is just itself) and
by assumption that the noise is symmetric. So then the expected value of
is just
. Because this is true for all choices of data
, the bias of our estimator is zero.
The question of variance is a bit trickier, because the variance of the entries of
actually do depend on which samples are drawn. Briefly, to compute the covariance matrix of the
as variables depending on
, we apply the definition:
And after some tedious expanding and rewriting and recalling that the covariance matrix of
is just the diagonal matrix
, we get that
This means that if we get unlucky and draw some sample which makes some entries of
big, then our estimator will vary a lot from the truth. This can happen for a variety of reasons, one of which is including irrelevant input variables in the computation. Unfortunately a deeper discussion of the statistical issues that arise when trying to make hypotheses in such situations. However, the concept of a bias-variance tradeoff is quite relevant. As we’ll see next time, a technique called ridge-regression sacrifices some bias in this standard linear regression model in order to dampen the variance. Moreover, a “kernel trick” allows us to make non-linear predictions, turning this simple model for linear estimation into a very powerful learning tool.
Until then! | http://jeremykun.com/tag/variance/ | CC-MAIN-2014-10 | en | refinedweb |
I.
#include <stdlib.h> #include <stdio.h> #include <fcntl.h> int main(int argc, char **argv) { char path[100]; int i, n, fh; if (argc != 3) { fprintf(stderr, "Usage: %s n dir\n", argv[0]); return -1; } n = atoi(argv[1]); for (i = 0; i < n; i++) { snprintf(path, 100, "%s/%d", argv[2], i); fh = open(path, O_CREAT | O_TRUNC | O_WRONLY); if (fh == -1) return -2; close(fh); if (i % 1000 == 0) printf("%d\n", i); } return 0; } | http://leaf.dragonflybsd.org/mailarchive/users/2008-07/msg00092.html | CC-MAIN-2014-10 | en | refinedweb |
sec_rgy_plcy_set_info-Sets the policy for an organization
#include <dce/policy.h> void sec_rgy_plcy_set sets the registry's policy data.
- policy_data
A pointer to the sec_rgy_plcy_t structure containing the authentication policy. This structure contains the minimum length of a user's password, the lifetime of a password, the expiration date of a password, the lifetime of the entire account, and some flags describing limitations on the password spelling.
Output
- status
A pointer to the completion status. On successful completion, the routine returns error_status_ok. Otherwise, it returns an error.
The sec_rgy_plcy_set_info() routine sets the authentication policy for a specified organization. If no organization is specified, the registry's policy data is set.
Policy data can be returned or set for individual organizations and for the registry as a whole.
Permissions RequiredThe sec_rgy_plcy_set_info() routine requires the m (mgmt_info) permission on the policy object or organization for which the data is to be set.
The policy set on an account may be less restrictive than the policy set for the registry as a whole. In this case, the changes in policy have no effect, since the effective policy is the most restrictive combination of the organization perform this operation.
- sec_rgy_object_not_found
The registry server could not find the specified organization.
- sec_rgy_server_unavailable
The DCE Registry Server is unavailable.
Functions:
sec_rgy_plcy_get_effective(), sec_rgy_plcy_get_info(). | http://pubs.opengroup.org/onlinepubs/9696989899/sec_rgy_plcy_set_info.htm | CC-MAIN-2014-10 | en | refinedweb |
How to download and install Tomcat?
How to download and install Tomcat? Hi,
How to download and install Tomcat?
Share me the url to learn Tomcat.
Thanks
Hi,
Please check the tutorial: Guide to download and install Tomcat 6.
Thanks
Guide to download and install Tomcat 6
Guide to download and install Tomcat 6
... of the JRE folder and click on the Install button. This will install the Apache tomcat...
To configure the Apache Tomcat Manager, Users will have
to follow the follwing
Download and Install Java
Download and Install Java
.... This
section enables you to download JDK and teaches you the steps to install... applications.
Download and Install JDK (Java Development
Kit)
The latest
Download Tomcat
Downoad
How To Install Tomcat
To install tomcat first download the tomcat...Download Tomcat
In this section we will discuss about downloading tomcat... what is Tomcat, tomcat components how to download Tomcat, tomcat releases, how
Download and Installing Struts 2
;
In this section we will download and install the Struts 2.0 on the latest
version of Tomcat container. We will first download tomcat and configure it
as our development server. Then we will download Struts 2.0 and install the
struts
Sysdeo Tomcat Launcher Plugin
This plugin does not contain Tomcat.
(Download and install Tomcat before using..., and Struts
Tomcat
Tutorial: HelloWorld for Complete Fools
...
Sysdeo Tomcat Launcher Plugin
servlets and jsp - JSP-Servlet
FOR ME,IN ADVANCE THANK U VERY MUCH. TO Run Servlets in Compand prompt.. you have to creat the following directory structure in your Tomcat folder where u have installed Tomcat.Generaaly in C drive we will install tomcat
C
Tomcat Books
and Servlets, then explains how to install and administer the Tomcat server... with Java servlets and JavaServer Pages.
Tomcat
Book Information and Code Download
Tomcat is an open source web server that processes JavaServer
Installation, Configuration and running Servlets
to install a WebServer, configure it and finally run servlets using this server... Tomcat Server is free software available for download...
Installation, Configuration and running Servlets
Servlets
{
^
6 errors
Do you have servlet-api.jar in your apache tomcat lib
Working with Tomcat Server
of the
applications. Tomcat is the official reference of implementation of
java Servlets and java Server Pages. Tomcat is very easy to install
and configure. ... the description on how to run
example with tomcat.
Deploying Servlets On
Using MYSQL Database with JSP & Servlets.
Using MYSQL Database with JSP & Servlets.
... download it from.
It is available for both Linux... database. We will use tomcat
web server to run over web application which
display Helloworld through servlets using jboss
display Helloworld through servlets using jboss I'm beginner,Can You please Write the code for this.Including WEB.INF
Please visit the following link:
Tomcat Configuration For Eclipse Server
Tomcat Server?
I am using Tomcat 6.0v
Thanks In Advance
Install tomcat on eclipse
1)First download the tomcat and install it on your hard drive.
2... button.
8)After above step, you have configured tomcat with Eclipse and can use
Tomcat
Tomcat I am using UBUNTU and I want to install tomcat to run servlet programs
How to download, compile and test the tutorials using ant.
;
In this section we will learn how to download and run Struts 2.1.8 examples
discussed here.
You will have to install ant... the application on tomcat:
Download the code and then extract it using
WinZip
Install Dojo
Install Dojo
In this section we will learn how to download and install Dojo in your web....
This section covers:
Download and install for new development
Download and install
Tom
tomcat
the following links:
code and specification u asked - Java Beginners
();
display.dispose();
}
}
so i have sent u the code...code and specification u asked you asked me to send the requirements... can build in java are extensive and have plenty of capability built in.
We Java
process of downloading and Installing Java Hi,
How easy is the process of downloading and Installing Java? I have windows 7 machines. Can anyone tell me how to download and install Java?
Thanks
install jdk 6 - Java Beginners
install jdk 6 sir i have installed my jdk1.6 but dont know how... the following link:
Thanks
Servlets
Servlets how to connect tomcat with me eclipse
When i click on Monitor Tomcat, it shows
When i click on Monitor Tomcat, it shows To run servlet i have seen the tutorial from
Hello i followed each and every step same to same as given, i have
tomcat installation - Java Beginners
tomcat installation How to install the apache-tomact server on my...,
To install the tomcat server,please visit the following link:
Then set
Servlets
Servlets Java Servlet technology You have set....
Anyways, please visit the following links:
servlets
servlets Hi
what is pre initialized servlets, how can we achives?
When servlet container is loaded, all the servlets defined... to be initialized when context is loaded, you have to use a concept called pre
servlets
implementing filter using apache tomcat in servlets can you explain in short how do you go about implementing filter using apache tomcat
Please visit the following links:
Logging Filter Servlet Example
servlets
servlets How do u display the list of employee object in JSP page
Servlets - JSP-Servlet
Servlets Hello !
I have the following error when i try to run Java... is due to "mysql-connector-java-5.0.6-bin.jar" not available.
So,it can be download and save into tomcat/lib folder and set the classpath.
For more information
FileUpload and Download
be download with its full content...can you please help me... im in urgent i have... for File upload and Download in jsp using sql server,that uploaded file should...;td><b>You have successfully upload the file by the name of:</b>
servlets
servlets hi i am using servlets i have a problem in doing an application.
in my application i have html form, in which i have to insert on date value, this date value is retrieved as a request parameter in my servlet
How to install and Configure the Tomcat Server
How to install and Configure the Tomcat Server
.... This will install the Apache tomcat at the specified location... and configuration process for Tomcat 6.0.10 are illustrated
below:
Step 1: Installation
Installing JSF 1.1 in TOMCAT 5.5.23
comfortable
installing the tomcat. There is nothing much to do to install JSF if you have
already installed and configured tomcat 5.5.23. We require
Jdk1.6.0...Installing JSF 1.1 in TOMCAT 5.5.23
Download Struts 2.1.8, Downloading and installing
to download and then install Struts 2.1.8.
The latest version of Struts 2.1.8 can... struts2-blank-2.1.8.1.war on tomcat 6 server:
Install the blank application on Tomcat simple...
Download Struts 2.1.8, Downloading and installing Struts 2.1.8
tomcat server - Java Server Faces Questions
install
INFO: Processing Context configuration file URL file:E:\tomcat\conf... application at context path /servlets-examples from URL fil
e:E:\tomcat\webapps... org.apache.catalina.core.StandardHostDeployer install
INFO: Installing web application at context path /tomcat-docs from execution - JSP-Servlet
servlets execution the xml file is web.xml file in which the servlet name,servlet class,mapping etc which has to be done.
What u want correctly mention? Hi Saziya,
Hello
HelloWorld
install jdk1.6
install jdk1.6 hello sir pls help me ,i wanna install jdk1.6.0 0n win 7 and i have tried it but i can't do this pls help me
tomcat problem - JSP-Servlet
tomcat problem Hi! Rose India Team,
I am unable to install the tomcat server.
It stops at this stage during installation .......c:\program files... installed several times and worked successfully on tomcat but this time it stops
Spring Framework Install
libraries and then install in our development environment.
Extracting Spring download...
Spring Framework Install
Spring Framework Install - a quick tutorial to install
Spring
Servlets Books
are to browsers. Unlike applets, however, servlets have no graphical user interface... environment or protocol. Servlets have become most widely used within HTTP...
Servlets Books
Install Java
Install Java Hi,
I have purchased a new computer and installed windows 7. Now I want to learn Java to make career in Java programming language.
I want to learn how to Install Java? Where can I find tutorial to learn Java
servlets
) and creates really ugly URLs.
doPost allows you to have extremely dense forms
Servlets
; I have already told you can't run servlet on console. It is always run
Servlets
have modified your code.
import java.io.*;
import java.sql.*;
import
Tomcat Quick Start Guide
Tomcat Quick Start Guide
... application using JSP, Servlets and JDBC technologies. In this quick and very fast tomcat jsp tutorial, you will learn all the essential steps need to start
jsp and servlets
.
Developing a website is generic question you may have to find out the usage... where u can use Struts, Spring framework.
Chandraprakash Sarathe
Creating Web application on tomcat server
Create your first Tomcat Web application
... application
using Servlet on the tomcat server.
We first make a
class named as HelloWorld that extends the abstract HttpServlet class. The code written
Deployment on apache tomcat 7.0.14.0
, on port 8084.
but I have one another apache tomcat with what I deply others apps that I download, or something like that.
But,this tomcat use port 8080.
so, when I...Deployment on apache tomcat 7.0.14.0 Hi guys,
Sorry but im
JAVA S/W download
; Hi !
u can download JAVA from... for your PC only.
Download and Install Java...JAVA S/W download Hi
I'm new to JAVA, I want to download JAVA S/W - JSP-Servlet
the entire Student Project in Tomcat/Webapps.
can u plzz explain me what...servlets hi deepak,
u had replied to me as
First in Student... an application using Servlets or jsp make the directory structure given below link
Java Free download
Java Free download Hi,
What is the url for downloading Java for free? Is java Free? Can I get the url to download Java without paying anything? Actually I am student and learning Java. I have to download and install Java on my
Tomcat Environment Setup - Java Beginners
Tomcat Environment Setup Kindly explain how to set path in tomcat.., i have install tomcat 6 version. Hi Friend,
Set the following...-server/tomcat/install-configure.shtml
Thanks
Free JSP download Books
to install and use the Tomcat software for running servlets
and JSPs on your own...Free JSP download Books
Java Servlets and JSP
free download books
Download Search Engine Code its free and Search engine is developed in Servlets
Installation Instruction
Download...;
Compile search.java file and install
the servlet on you... engine should work.
Download Search
Tomcat For Eclipse
Tomcat For Eclipse
How To Install... It:
Create a java project
In the java project properties select 'Tomcat
Apache Axis2 Tomcat: Installing Apache Axis2 on Tomcat
:
Download and install Apache Tomcat on your computer.
Step 3:
If you want to develop...:
Now you can download and install the Apache Axis2 engine on Tomcat
server. Read... to install Apache Axis2 Web
service engine on the Tomcat server.
After
Downloading and Installing Apache Axis2
such as winzip or winrar.
Installing Axis2 engine on Tomcat
Download and install Tomcat 6 or above. Now to install the Axis2 engine copy
axis2.war into Tomcat...;
Downloading and installing Apache Axis2
In this section we will download and install
Tomcat installation problem - JSP-Servlet
Tomcat installation problem Hello
I have installed Tomcat...://
Thanks... tomcat homepage ""..I am awaiting for response..Thanks
install junit - JUNIT
install junit How to install Junit? Download it from here
Download full code of JSF, Spring and Hibernate based Registration program
directory to tomcat
webapps directory. This will install application on tomcat...Download full code of JSF, Spring and Hibernate based Registration program...;
From this page you can download the source code of the
application
connect jsp with tomcat - JSP-Servlet
already set)
->tomcat 6.0.18 (c:/tomcat/tomcat6.0/)
I have my site folder...:// jsp with tomcat hello friends,
i have severe problem
servlets - Servlet Interview Questions
answer plz).thank u in advance. Hi friend,
ServletContext... to all the components. Remember that each servlet will have its own ServletConfig... servlet and are unknown to other servlets.
The ServletContext parameters
install mysql - JDBC
friend,
MySQL is open source database and you can download and install it on your... understand how to Download and Install MySQL. Please visit the following link :
http...install mysql i want to connect with mysql database.can i install jfreechart in netbeans.
how to install jfreechart in netbeans. I have successfully installed jfreechart in eclipse IDE.but I am unable to install the same in netbeansIDE... procedure to install it in netbeans 6.7.1
Please reply asap.Its urgent
Merve Tomcat Launcher Eclipse Plugin
Merve Tomcat Launcher Eclipse Plugin
... applications with Apache
Tomcat.
Merve includes already Tomcat Embedded.
Alternatively use your own preinstalled Tomcat version.
Merve supports
Configuring Struts DataSource Manager on Tomcat 5
DataSource in action class.
Downloading and Installing Tomcat 5.5.9
Download jakarta-tomcat-5.5.9 from.
Install it on your machine. Run and test the pages that comes with the tomcat.
Download Struts
Download
Accessing Database from servlets through JDBC!
in html formats.
Java
Servlets have a number of advantages...
Java Servlets - Downloading and Installation
Java
Servlets are server
install - Java Beginners
install Dear Sir,
How to install java on Windows 98
Or What... the following link:
After installing set the path from the command prompt
install
install How to install Tomcat7.05 in windowXP
path setting for tomcat to java for Desktop PC - JDBC
://
http...path setting for tomcat to java for Desktop PC Hi sir,
I.... So my problem here is i dont know how to set path setting for that can u please
How to Install WAMP Server on XP and Windows
How to Install WAMP Server on XP
WAMP stands for Windows Apache MySQL PHP.... Search on Google
If you don't have Wamp so you
can search on google and download from there.
2. Download Wamp
You can download wamp from
java servlets
java servlets please help...
how to connect java servlets with mysql
i am using apache tomcat 5.5
Tomcat 6.
Tomcat 6. hi......I have problem like
windows could not start the Apache Tomcat 6 on Local Computer.
for more information ,review theSystem Event Log.
If this is a non-Microsoft service,contact the service vendor,
and refer
how to execute jsp and servlets with eclipse
how to execute jsp and servlets with eclipse hi
kindly tell me how to execute jsp or servlets with the help of eclipse with some small program... and installing tomcat server into it.
file download
file download I uploaded a file and saved the path in database. Now i want to download it can u plz provide code
jsp -servlets
jsp -servlets i have servlets s1 in this servlets i have created emplooyee object, other servlets is s2, then how can we find employee information in s2 servlets
How to download JDK source code?
as well as the source
code of the JDK. You can download and install the JDK...How to download JDK source code?
This articles explains you how you can download the source code of JDK. You
will learn how to download JDK source code
HelloWorld in PHP
to send within parenthesis. echo also has a shortcut syntax, where you have to use
Tomcat & Struts - Struts
Tomcat & Struts How a install and configure struts version 1.3.8 and Tomcat version 4.0
JAVA SERVLETS ? An Overview
JAVA SERVLETS ? An Overview
... programming in general and Java Servlets in particular. In addition... a Web Server such as an Apache Tomcat Server. It also guides the student
How to download java software for Java Programming
How to download java software for Java Programming Hi,
How to download java software for Java Programming? I have purchased a computer....
Thanks
Hi,
Its very easy to download and install the software
Downloading and Installing "SimpleHelloByEnteringName" JSF Example
example. In this, we will show
you how you can quickly download and install... a folder
named "SimpleHelloByEnteringName".
Download tomcat... self.
STEPS-
Download zip file of the "SimpleHelloByEnteringName"
install jdk 6 - Java Beginners
install jdk 6 sir i have installed my jdk1.6 but dont know how to run, could you please help me i | http://www.roseindia.net/tutorialhelp/comment/14621 | CC-MAIN-2014-10 | en | refinedweb |
... of Action classes for your project. The latest version of struts provides classes... action. In this article we will see how to achieve this. Struts provides four
struts---problem with DispatchAction
with struts 1.3.10....I have created an application which uses DispatchAction..I hav configured struts-extras 1.3.10 jar but still i'm getting the following... an exception
root cause
java.lang.NoClassDefFoundError: org/apache/struts-problem With DispatchAction Class
DispatchAction..I'm using Eclipse ide..I hav configured struts-extras 1.3.10 jar but still...: org/apache/struts/actions/DispatchAction
Can any one help me with this problem...Struts-problem With DispatchAction Class hi this is Mahesh...i'm
DispatchAction class? - Struts
DispatchAction class? HI, Which is best and why either action class or dispatch class. like that Actionform or Dynactionform . I know usage.../understandingstruts_action_class.shtml
no action mapped for action - Struts
no action mapped for action Hi, I am new to struts. I followed...: There is no Action mapped for action name HelloWorld
Struts Dispatch Action Example
Struts Dispatch Action Example
Struts Dispatch Action... function. Here in this example
you will learn more about Struts Dispatch Action
servlet action not available - Struts
servlet action not available hi
i am new to struts and i am....
Struts Blank Application
action
org.apache.struts.action.ActionServlet
config
/WEB-INF/struts-config.xml
2
action
*.do
Action Or DispatchAction - Development process
Action Or DispatchAction
Hi, Action class has execute() only where as dispatchaction class has multiple methods. plz tell me when to use action and dispatchaction.can we use multiple actions in Action class. Thanks Prakash
Actions - Struts
Action struts 2 Please explain the Action Script in Struts
Actions Threadsafe by Default - Struts
Actions Threadsafe by Default
Hi Frieds,
I am beginner in struts, Are Action classes Threadsafe by default. I heard actions are singleton , is it correct
Struts dispatch action - Struts
Struts dispatch action i am using dispatch action. i send....
but now my problem is i want to send another value as querystring for example... not contain handler parameter named 'parameter'
how can i overcome
Action Configuration - Struts
Action Configuration I need a code for struts action configuration in XML
action tag - Struts
action tag Is possible to add parameters to a struts 2 action tag? And how can I get them in an Action Class. I mean: xx.jsp Thank
Login Action Class - Struts
Login Action Class Hi
Any one can you please give me example of Struts How Login Action Class Communicate with i-batis
Action in Struts 2 Framework
Actions
Actions are the core basic unit of work in Struts2 framework. Each action provides the processing logic for a specific URL with which it is linked. Actions are mostly associated with a HTTP request of User.
The action class
Understanding Struts Action Class
Understanding Struts Action Class
In this lesson I will show you how to use Struts Action... if necessary, and finally
calls execute method.
To use the Action, we need Action Chaining
Struts Action Chaining Struts Action Chaining
Implementing Actions in Struts 2
Implementing Actions in Struts 2
Package com.opensymphony.xwork2 contains.... Actions the contains the
execute() method. All the business logic is present in this method. When an
action is called the execute method is executed. You can Class
Struts Action Class What happens if we do not write execute() in Action 2 Actions
request.
About Struts Action Interface
In Struts 2 all actions may implement...
Struts 2 Actions
In this section we will learn about Struts 2 Actions, which is a fundamental
concept in most of the web
Struts MappingDispatchAction Example
of the Built-in Actions provided along with the struts framework... an implementation for the
execute() method because DispatchAction... in the struts-config.xml
Here, we need to create multiple independent actions
Struts MappingDispatchAction Example
;
Struts MappingDispatch Action...() method because DispatchAction class itself
implements this method...
Developing the Action Mapping in the struts-config.xml
Here, we
Struts LookupDispatchAction Example
;
Struts LookupDispatch Action... for the execute() method because DispatchAction class itself implements this method... the request to one of the methods of the derived Action class. Selection of a method
Struts
Writing Actions
Writing Actions
The Action is responsible for controlling of data flow within an application.
You can make any java class as action. But struts have some... using struts you can either user Action interface or
use ActionSupport class
Test Actions
Test Actions
An example of Testing a struts Action is given below using the junit. In this
example the execute method is being test.
HelloAction.java... {
// TODO Auto-generated method stub
return SUCCESS
Struts Forward Action Example
Struts Forward Action Example
...). The ForwardAction is one of the Built-in Actions
that is shipped with struts framework.....
Here in this example
you will learn more about Struts Forward Action
struts - Struts
is the structure we hav to follow in struts whn and application has to run
4. where...-config.xml
Action Entry:
Difference between Struts-config.xml...struts hi,
what is meant by struts-config.xml and wht are the tags
struts - Struts
Struts dispatchaction vs lookupdispatchaction What is struts dispatchaction and lookupdispatchaction? And they are used to combined what? Hi,Please check easy to follow example at
defined actions in struts config still getting a HTTP 404 - Struts
defined actions in struts config still getting a HTTP 404 Hi guys,
I am getting an Invalid Path requested error.
Heres the code snippet from... exist and so do the Action classes.
Still whenever I pass the .do action
Java - Struts
in DispatchAction in Struts.
How can i pass the method name in "action" and how can i map at in struts-config.xml;
when i follow some guidelines... on DispatchAction in Struts visit to :
Request[/DispatchAction] does not contain handler parameter named 'parameter'. This may be caused by whitespace in the label text. - Struts
Struts File Upload
Working Of DispatchAction Class Works
So... Request[/DispatchAction] does not contain handler parameter named 'parameter'. This may be caused by whitespace in the label text. I am trying
Struts
;Basically in Struts we have only Two types of Action classes.
1.BaseActions
2.BridgeActions
BaseAction consists DispatchAction,LookUpDispatchAction...Struts why in Struts ActionServlet made as a singleton what
struts
struts <p>hi here is my code in struts i want to validate my form fields but it couldn't work can you fix what mistakes i have done</p>...;gt;
<html:form
<pre>
Action tag - JSP-Servlet
Action tag Hello,
I want to help ....i hav one feedback form there is action ,
..
can i use two action at the same form because i want... to next form and i want TestResult.php as well as html page actions at the same time
Struts2 Actions
generated by a Struts
Tag. The action tag (within the struts root node of ... Action interface
All actions may implement... that here the action class doesn't extend any
other class or
interface. The method
Chain Action Result Example
Chain Action Example
Struts2.2.1 provides the feature to chain many actions...;
<action... in an application by applying
Chain Result to a action. A Chain Result is an result type
About Struts processPreprocess method - Struts
that will make me to use this method . Can I use this for client validation, so... is not valid? Can I access DB from processPreprocess method.
Hi...About Struts processPreprocess method Hi java folks,
Help me2 Actions
is usually generated by a Struts
Tag.
Struts 2 Redirect Action
In this section, you will get familiar with struts 2 Redirect action...
Struts2 Actions
Struts2 Actions
Struts Built-In Actions
Struts Built-In Actions
... actions shipped with Struts APIs. These
built-in utility actions provide different...;
to combine many similar actions into a
single action
Introduction to Action interface
Introduction To Struts Action Interface
The Action interface contains the a single method execute(). The business
logic of the action is executed within this method. This method is implemented
by the derived class. For example this...??
Thanks in advance
No action instance for path
;
</action-mappings>
</struts-config>... struts@roseindia.net
*/
/**
* Struts File Upload Action Form...No action instance for path <%@ taglib uri="http
struts
struts <p>hi here is my code can you please help me to solve...;
<p><html>
<body></p>
<form action="login.do">...*;
import org.apache.struts.action.*;
public class LoginAction extends (Data Tag) Example
tag that is used
to call actions directly from a JSP page by
specifying the action... tag is used to call actions directly from a JSP page
by specifying the action...
Action Tag (Data Tag) Example
attribute in action tag - Java Beginners
attribute in action tag I'm just a beginner to struts.
The name tag(name="bookListForm") is used to define the form used with the action class. But i`m not clear about the attribute tag(attribute 1 Tutorial and example programs
.
- STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS...;
Aggregating Actions In Struts Revisited -
In my previous article Aggregating Actions in Struts , I have given a brief idea of how
struts - Struts
struts am retrieving data from the mysql database so the form bean will be null for that action.... if i give it in struts config it is asking me to have a form bean.... how to solve this problem
Why Struts 2
core interfaces are HTTP
independent. Struts 2 Action classes...;
- Actions are simple POJOs. Any java class with execute() method can
be used... handling per action, if
desired.
Easy Spring
integration - Struts 2
Writing action classes in struts2.2.1
Writing action classes
Action Classes
AdmissionAction.java- It action... for registration. There is a execute
method which holds connection code... method stub
obDeleteModel = new SearchModel();
return obDeleteModel
The password forgot Action is invoked... password action requires user name and passwords same as you had entered
during,
i have formbean class,action class,java classes and i configured all in struts-config.xml then i dont know how to deploy and test... and do run on server. whole project i have run?or any particular d
Struts - Struts
Struts hi
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean... for later use in in any other jsp or servlet(action class) until session exist
struts - Struts
included third sumbit button on second form tag and i given corresponding action...struts hi..
i have a problem regarding the webpage
in the webpage i have 3 submit buttons are there.. in those two are similar and another one
STRUTS
STRUTS 1) Difference between Action form and DynaActionForm?
2) How the Client request was mapped to the Action file? Write the code and
Advance Struts2 Action
In struts framework Action is responsible... method which in an action class is execute()
methods. When the action is called this method executed automatically.
The action class in Struts2 framework
Redirect Action Result Example
;/head>
<body>
<s:form action="doLogin" method="POST"...Redirect Action Result Example
The Result uses the ActionMapper of the ActionMapperFactory for redirecting
the URL to the specified action. To redirect
different kinds of actions in Struts
different kinds of actions in Struts What are the different kinds of actions in Struts
Struts Tutorial
, Architecture of Struts, download and install struts,
struts actions, Struts Logic Tags... :
Struts provides the POJO based actions.
Thread safe.
Struts has support... the
information to them.
Struts Controller Component : In Controller, Action class
Action and AbstractAction
to implement action listeners that can be shared and coordinated.
Actions can... Used for toolbars.
Usage
Actions can be used directly in the add() method..., etc.
They can be shared with all controls which do the same thing.
Actions can | http://roseindia.net/tutorialhelp/comment/581 | CC-MAIN-2014-10 | en | refinedweb |
Superludist2_OO: An object-oriented wrapper for Superludist. More...
#include <Superludist2_OO.h>
Superludist2_OO: An object-oriented wrapper for Superludist.
Superludist2_OO Constructor.
Creates a Superludist2_OO instance, using an Epetra_LinearProblem, passing in an already-defined Epetra_LinearProblem object. The Epetra_LinearProblem class is the preferred method for passing in the linear problem to Superludist2_OO because this class provides scaling capabilities and self-consistency checks that are not available when using other constructors.
Note: The operator in LinearProblem must be an Epetra_RowMatrix.
Superludist2_OO Destructor.
Completely deletes a Superludist2_OO_CrsMatrix::ExtractMyRowView(), Epetra_MultiVector::ExtractView(), Epetra_CrsMatrix::GCID(), Epetra_LinearProblem::GetLHS(), Epetra_LinearProblem::GetOperator(), Epetra_LinearProblem::GetRHS(), Epetra_Object::GetTracebackMode(), GetTrans(), Epetra_DistObject::Import(), Insert, Epetra_BlockMap::LinearMap(), Epetra_BlockMap::MaxMyGID(), Epetra_BlockMap::MinMyGID(), Epetra_BlockMap::MyGlobalElements(), Epetra_Comm::MyPID(), Epetra_CrsMatrix::NumGlobalCols(), Epetra_BlockMap::NumGlobalElements(), Epetra_CrsMatrix::NumGlobalRows(), Epetra_CrsMatrix::NumMyCols(), Epetra_BlockMap::NumMyElements(), Epetra_CrsMatrix::NumMyEntries(), Epetra_CrsMatrix::NumMyNonzeros(), Epetra_CrsMatrix::NumMyRows(), Epetra_Comm::NumProc(), Epetra_MultiVector::NumVectors(), and Epetra_CrsMatrix::RowMap(). | http://trilinos.sandia.gov/packages/docs/dev/packages/amesos/doc/html/classSuperludist2__OO.html | CC-MAIN-2014-10 | en | refinedweb |
I am new to Java, I am woring on learning inheritance.
I am creating an abstract class called Thing.
I have to put this requirement in, Please could somebody help me with Syntax
Thing will have the following private class field:
• Things, an ArrayList defined with a Thing generic. This ArrayList must be maintained as Thing objects are constructed. This ArrayList must contain all unique objects for which (object instanceof Thing) is true. Each time an object for which (object instanceof Thing) is true is constructed, a reference to that object must be put in the ArrayList, if that object does not already exist in the ArrayList. The Thing equals method will be used to test if the object is not unique, i.e., already exists in the ArrayList. Your code must not useany object casts and must not use any instance of operator.
Java Code:
Code :
import java.util.*; public abstract class Thing { public String iName = new String(); private ArrayList<Thing> iThings = new ArrayList<Thing>(); public static void main(String[] args) { Thing vehicle1 = new Vehicle(); } public Thing(String name) { iName = name; } public String getName() { return iName; } public abstract void show(); public abstract boolean equals(Thing b); public void showThings() { System.out.println("Things"); show(); } }
Thank you,
urpalshu | http://www.javaprogrammingforums.com/%20collections-generics/11478-arraylist-inheritance-printingthethread.html | CC-MAIN-2014-10 | en | refinedweb |
my decision about tagging/classifying stuff is to keep tags/categories
as a document per category with all the tags inside, AND for each
tag keep all tagged-items-ids inside there too.
Thus items-to-classify are completely independent from classificator
and can be anything - only id's are used. Changes of classificator stay
in classificator.
one can split category from (sub)tag... depends on frequency/source of
updates and such.
This way it does take 2 queries to filter anything - one to get
ids-of-items, and another to fetch those items.
But intersection queries (AND/join) aren't well doable anyway.
if u need many of those over vast number of rows, consider lucene plugin
or another such indexer that supports it.
as of hierarchical classification/grouping.. i do manualy all the ANDs
but my tags are not hierarchical. This came from semantical stuff where
same tag can have diff.meaning in diff.aspect/namespace, e.g. "joe" can
be a person itself, or ownership, or place, etc.
well, not sure if this is of any help..
svil
On Mon, 20 May 2013 18:29:08 +0200
Bernd Grolig <altbauwohnung_lehel@web.de> wrote:
> Hello,
>
> I just started to set up an mobile App using TouchDB. It's the first
> time for me to work with a NoSQL Database. While setting up the
> basics so far worked very well, I stepped deeper in how to design the
> data structure of the app.
>
> The principle question for me is, what is the best design for 1:many
> relations and for grouping.
>
> I researched quite a lot in the web, but I am stil not sure, how to
> design it in the best way. Would be great to get some hints from this
> mailing list.
>
> So this is the basic data structure:
>
> Document type: Categories
>
> {
> "_id": "a124",
> "_rev": "8-089da95f148b446bd3b33a3182de709f",
> "detCat": "1st Category",
> "mainCat": "Main Category",
> "mainBereich": "Division",
> "type": "Transaction"
> }
>
> {
> "_id": "a125",
> "_rev": "3-089da95f148b446bd3b33a3182de232",
>
> "detCat": "2nd Category",
> "mainCat": "Main Category",
> "mainBereich": "Division",
> "type": "Transaction"
>
> }
>
> Document type: Transaction
>
> {
> "_id": "7568a6de86e5e7c6de0535d025069084",
> "_rev": "2-501cd4eaf5f4dc56e906ea9f7ac05865",
> "Value": 133.23,
> "Sender": "Sender Name",
> "Booking Date": "11.02.2013",
> "Detail": "Some Transaction details",
> "catID": "a124"
> }
>
> {
> "_id": "23982304201948231213",
> "_rev": "2-234123412342",
> "Value": 199.23,
> "Sender": "Sender Name",
> "Booking Date": "11.04.2013",
> "Detail": "Some Transaction details",
> "catID": "a125"
> }
>
> As long as I want to receive all transactions with its correlating
> category it is quite easy by using "include_docs=true" in the search
> string.
>
> But as soon as I want to have a reduce or grouping e.g. to "MainCat"
> or to "Division" I could not find a good solution to solve this.
>
> My question is, if there is a possibility to generate a map/reduce
> view to group to Main Cat or Division and sum all the transactions to
> this level?
>
> The only possibility I see is to put the Category names and Main
> Category Names and Division Names inside the document type of the
> transaction. But this would cause a lot of work for updates when the
> name of a category is changed.
>
> The other possibility would be to get the result without reduce and
> sum within the application logic, but this seems also not to be the
> very elegant way.
>
> I think this is a very basic design question and used many times in
> the web, e.g. Tagging. However all examples I found only wrote the
> name of the tag or in my case category in the document itself.
> I'm curious to get some hints to solve this questions.
>
> Best regards,
> Bernd | http://mail-archives.apache.org/mod_mbox/incubator-couchdb-user/201305.mbox/%3C20130521173719.65d10996@svilendobrev.com%3E | CC-MAIN-2014-10 | en | refinedweb |
SCUI_Client_ShowFavoritingView()
This method requests display of favorite games view.
Synopsis:
#include <scoreloop/scui_client.h>
SC_Error_t SCUI_Client_ShowFavoritingView(SCUI_Client_h self)
Arguments:
- self
An opaque handle for the current SCUI_Client instance. the result | https://developer.blackberry.com/native/reference/core/com.qnx.doc.scoreloop.lib_ref/topic/scui_client_showfavoritingview.html | CC-MAIN-2014-10 | en | refinedweb |
See:
Description
The Mobile Information Device Profile provides a mechanism for MIDlets to persistently store data and later retrieve it. This persistent storage mechanism is modeled after a simple record oriented database and is called the Record Management System.
The MIDP provides a mechanism for MIDlets to persistently store data and retrieve it later. This persistent storage mechanism, called the Record Management System (RMS), is modeled after a simple record-oriented database.
A record store consists of a collection of records that will remain persistent across multiple invocations of a MIDlet. The platform is responsible for making its best effort to maintain the integrity of the MIDlet's record stores throughout the normal use of the platform, including reboots, battery changes, etc.
Record stores are created in platform-dependent locations, which are not exposed record stores associated with its MIDlets MUST also be removed. MIDlets within a MIDlet suite can access one another's record stores directly. New APIs in MIDP 2.0 allow for the explicit sharing of record stores if the MIDlet creating the RecordStore chooses to give such permission.
Sharing is accomplished through the ability to name a RecordStore in another MIDlet suite and by defining the accessibilty rules related to the Authentication of the two MIDlet suites.
RecordStores are uniquely named using the unique name of the MIDlet suite plus the name of the RecordStore. MIDlet suites are identified by the MIDlet-Vendor and MIDlet-Name attributes from the application descriptor.
Access controls are defined when RecordStores to be shared are created. Access controls are enforced when RecordStores are opened. The access modes allow private use or shareable with any other MIDlet suite.
Record store names are case sensitive and may consist of any combination of up to 32 Unicode characters. Record store names MUST be unique within the scope of a given MIDlet suite. In other words, MIDlets within a MIDlet suite are not allowed to create more than one record store with the same name; however, a MIDlet in one MIDlet suite is allowed to that no
corruption occurs with multiple accesses. However, if a MIDlet
uses multiple threads to access a record store, it is the
MIDlet's responsibility to coordinate this access, or unintended
consequences may result. For example, if two threads in a MIDlet
both call
RecordStore.setRecord() concurrently on
the same record, the record store will serialize these calls
properly, and no database corruption will occur as a result.
However, one of the writes will be subsequently overwritten by
the other, which may cause problems within the
MIDlet. Similarly, if a platform performs transparent
synchronization of a record store or other access from below, it
is the platform's responsibility to enforce exclusive access to
the record store between the MIDlets and synchronization
engine.
This record store API uses long integers for time/date stamps,
in the format used by
System.currentTimeMillis()
. The record store is time stamped with the last time it was
modified. The record store also maintains a version, which is an
integer that is incremented for each operation that modifies the
contents of the record store. These are useful for
synchronization engines as well as applications.
Records are arrays of bytes. Developers can use
DataInputStream and
DataOutputStream
as well as
ByteArrayInputStream and
ByteArrayOutputStream to). MIDlets can create other indices
by using the
RecordEnumeration class.
The example uses the Record Management System to store and retrieve high scores for a game. In the example, high scores are stored in separate records, and sorted when necessary using a RecordEnumeration.
import javax.microedition.rms.*; import java.io.DataOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; /** * A class used for storing and showing game scores. */ public class RMSGameScores implements RecordFilter, RecordComparator { /* * The RecordStore used for storing the game scores. */ private RecordStore recordStore = null; /* * The player name to use when filtering. */ public static String playerNameFilter = null; /* * Part of the RecordFilter interface. */ public boolean matches(byte[] candidate) throws IllegalArgumentException { // If no filter set, nothing can match it. if (this.playerNameFilter == null) { return false; } ByteArrayInputStream bais = new ByteArrayInputStream(candidate); DataInputStream inputStream = new DataInputStream(bais); String name = null; try { int score = inputStream.readInt(); name = inputStream.readUTF(); } catch (EOFException eofe) { System.out.println(eofe); eofe.printStackTrace(); } catch (IOException eofe) { System.out.println(eofe); eofe.printStackTrace(); } return (this.playerNameFilter.equals(name)); } /* * Part of the RecordComparator interface. */ public int compare(byte[] rec1, byte[] rec2) { // Construct DataInputStreams for extracting the scores from // the records. ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1); DataInputStream inputStream1 = new DataInputStream(bais1); ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2); DataInputStream inputStream2 = new DataInputStream(bais2); int score1 = 0; int score2 = 0; try { // Extract the scores. score1 = inputStream1.readInt(); score2 = inputStream2.readInt(); } catch (EOFException eofe) { System.out.println(eofe); eofe.printStackTrace(); } catch (IOException eofe) { System.out.println(eofe); eofe.printStackTrace(); } // Sort by score if (score1 < score2) { return RecordComparator.PRECEDES; } else if (score1 > score2) { return RecordComparator.FOLLOWS; } else { return RecordComparator.EQUIVALENT; } } /** * The constructor opens the underlying record store, * creating it if necessary. */ public RMSGameScores() { // // Create a new record store for this example // try { recordStore = RecordStore.openRecordStore("scores", true); } catch (RecordStoreException rse) { System.out.println(rse); rse.printStackTrace(); } } /** * Add a new score to the storage. * * @param score the score to store. * @param playerName the name of the play achieving this score. */ public void addScore(int score, String playerName) { // // Each score is stored in a separate record, formatted with // the score, followed by the player name. // int recId; // returned by addRecord but not used ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); try { // Push the score into a byte array. outputStream.writeInt(score); // Then push the player name. outputStream.writeUTF(playerName); } catch (IOException ioe) { System.out.println(ioe); ioe.printStackTrace(); } // Extract the byte array byte[] b = baos.toByteArray(); // Add it to the record store try { recId = recordStore.addRecord(b, 0, b.length); } catch (RecordStoreException rse) { System.out.println(rse); rse.printStackTrace(); } } /** * A helper method for the printScores methods. */ private void printScoresHelper(RecordEnumeration re) { try { while(re.hasNextElement()) { int id = re.nextRecordId(); ByteArrayInputStream bais = new ByteArrayInputStream(recordStore.getRecord(id)); DataInputStream inputStream = new DataInputStream(bais); try { int score = inputStream.readInt(); String playerName = inputStream.readUTF(); System.out.println(playerName + " = " + score); } catch (EOFException eofe) { System.out.println(eofe); eofe.printStackTrace(); } } } catch (RecordStoreException rse) { System.out.println(rse); rse.printStackTrace(); } catch (IOException ioe) { System.out.println(ioe); ioe.printStackTrace(); } } /** * This method prints all of the scores sorted by game score. */ public void printScores() { try { // Enumerate the records using the comparator implemented // above to sort by game score. RecordEnumeration re = recordStore.enumerateRecords(null, this, true); printScoresHelper(re); } catch (RecordStoreException rse) { System.out.println(rse); rse.printStackTrace(); } } /** * This method prints all of the scores for a given player, * sorted by game score. */ public void printScores(String playerName) { try { // Enumerate the records using the comparator and filter // implemented above to sort by game score. RecordEnumeration re = recordStore.enumerateRecords(this, this, true); printScoresHelper(re); } catch (RecordStoreException rse) { System.out.println(rse); rse.printStackTrace(); } } public static void main(String[] args) { RMSGameScores rmsgs = new RMSGameScores(); rmsgs.addScore(100, "Alice"); rmsgs.addScore(120, "Bill"); rmsgs.addScore(80, "Candice"); rmsgs.addScore(40, "Dean"); rmsgs.addScore(200, "Ethel"); rmsgs.addScore(110, "Farnsworth"); rmsgs.addScore(220, "Farnsworth"); System.out.println("All scores"); rmsgs.printScores(); System.out.println("Farnsworth's scores"); RMSGameScores.playerNameFilter = "Farnsworth"; rmsgs.printScores("Farnsworth"); } } | http://developer.nokia.com/resources/library/Java/_zip/GUID-0D0A1092-5037-4421-B466-B958CB777414/javax/microedition/rms/package-summary.html | CC-MAIN-2014-10 | en | refinedweb |
do you declare a DLL dependency?
Hi all,
I'm trying to leverage the WebRTC library, and found that it's available via NuGet (). Visual Studio seems to allow me to add the dependency to the build solution, but not the code solution. Also, I believe the build solution gets completely overwritten whenever you rebuild from Unity.
Is there a way to declare the dependency directly in the Unity project? Or, perhaps I can manually copy the DLLs directly into the project, and somehow make the code aware of the declared namespaces, methods and interfaces?
I suspect this question is better suited for Unity forums, but since I noticed others on this forum talk about related issues, I thought I'd ask here as well.
Any pointers would be greatly appreciated.
Cheers,
Dan. | https://forums.hololens.com/discussion/2271/how-do-you-declare-a-dll-dependency | CC-MAIN-2020-29 | en | refinedweb |
Providing type checker plugin on command line results in false cyclic import error
I am playing around with the new type checker plugins using the current development branch of GHC. When I supply the plugin module to GHC through the command line I get a cyclic import error message, which I think is false. If I supply the same plugin module using a pragma I do not get an error message.
Minimal Example (Command Line)Minimal Example (Command Line)
MyPlugin.hs:
module MyPlugin ( plugin ) where import Plugins ( Plugin, defaultPlugin ) plugin :: Plugin plugin = defaultPlugin
Test.hs:
module Test where main :: IO () main = return ()
Command line call of GHC:
~/ghc/inplace/bin/ghc-stage2 \ --make -package ghc-7.11.20150209 \ -fplugin=MyPlugin \ Test.hs
Results in the following error
Module imports form a cycle: module ‘MyPlugin’ (./MyPlugin.hs) imports itself
which does not seem reasonable to me understand.
Minimal example (pragma)Minimal example (pragma)
On the other hand, if I change
Test.hs to the following
{-# OPTIONS_GHC -fplugin MyPlugin #-} module Test where main :: IO () main = return ()
and calling GHC like this
~/ghc/inplace/bin/ghc-stage2 \ --make \ -package ghc-7.11.20150209 \ -dynamic \ Test.hs
it works.
I did not change
MyPlugin.hs.
NoteNote
- Using
-fplugin=MyPluginvs.
-fplugin MyPlugindoes not make a difference.
- The command line example behaves the same independent of whether I supply the
-dynamicflag or not.
- I had to add the
-dynamicflag, because otherwise GHC will complain that:
<no location info>: cannot find normal object file ‘./MyPlugin.dyn_o’ while linking an interpreted expression
This might be a long shot, but maybe using the
-fplugin option should imply the
-dynamic flag? | https://gitlab.haskell.org/ghc/ghc/-/issues/10077 | CC-MAIN-2020-29 | en | refinedweb |
A simple React component implement swipe to delete UI-pattern
React-swipe-to-delete-component
A simple React component implement 'swipe to delete' UI-pattern.
Install
React-swipe-to-delete-component is available via npm.
npm install --save react-swipe-to-delete-component
Else you can download the latest builds directly from the "dist" folder above.
Usage
The React-swipe-to-delete-component wrap your a content component. It's become swiped. If it's swiped more certain percent than the swipe-to-delete-component will remove a component.
Example
import React from 'react'; import {render} from 'react-dom'; // Import the react-swipe-to-delete-component import SwipeToDelete from 'react-swipe-to-delete-component'; // CommonJS // var SwipeToDelete = require('react-swipe-to-delete-component').default; const data = [ {id: 1, text: 'Best part of the day ☕', date: '5.03.2016'}, {id: 2, text: 'What\'s everybody reading?', date: '3.03.2016'}, {id: 3, text: 'End of summer reading list', date: '1.03.2016'} ]; const list = data.map(item => ( <SwipeToDelete key={item.id}> <a className="list-group-item"> <h4 className="list-group-item-heading">{item.date}</h4> <p className="list-group-item-text">{item.text}</p> </a> </SwipeToDelete> )); const app = ( <div className="list-group"> {list} </div> ); render(app, document.getElementById('root'));
Props
- tag - This is tag name of a root element. By default, it's "div". Optional.
- classNameTag - This is classes of a root element. Optional.
- background - This is a decoration component under a content component. By default, showed red element with trash icons. Optional.
- deleteSwipe - This is a number. If a content component is swiped more this the number than a swipe-to-delete component will start a delete animation. By default, it's equal "0.5". Optional.
- onDelete - This is a function. If a content component is deleted then It will be called. Optional.
- onCancel - This is a function. If a content component isn't deleted then It will be called. Optional.
- onRight/onLeft - This is a function. If a content component is swiped then these functions is called. Optional.
Styles
You may set up styles in "swipe-to-delete.css" under the comment "Custom styles". The class js-content is content region, js-delete is delete region. Classes js-transition-delete-right and js-transition-delete-left are added on a content component when it's swiped more than "deleteSwipe" options. Class js-transition-cancel is added when a content component swiped less than "deleteSwipe" options. Animations are made by CSS3 transition.
GitHub
Get the latest posts delivered right to your inbox | https://reactjsexample.com/a-simple-react-component-implement-swipe-to-delete-ui-pattern/ | CC-MAIN-2020-29 | en | refinedweb |
Component: Per edge Color More...
#include <component.h>
Inherits T.
Inherited by vcg::edge::Color4b< TT >.
Component: Per edge Color
Usually most of the library expects a color stored as 4 unsigned chars (so the component you use is a
vertex::Color4b) but you can also use float for the color components.
Definition at line 216 of file edge/component.h. | http://vcglib.net/classvcg_1_1edge_1_1Color.html | CC-MAIN-2020-29 | en | refinedweb |
, see it here. here.
Transfer & Encrypt
In order to transfer and encrypt the data, let’s add a couple of
Steps that each contain a
Tasklet.
Step #1
Here is the first
Step:
@Bean public Step encTransferFirstStep(StepBuilderFactory stepBuilderFactory) { return stepBuilderFactory.get("encTransferFirstStep").tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution sc, ChunkContext cc) throws Exception { String filename = "testfile.txt"; String path = "./"; File localFile = new File(path, filename); // generate key KeyGenerator kgen; kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey aesKey = kgen.generateKey(); cc.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("inKey", aesKey); // Encrypt cipher Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); encryptCipher.init(Cipher.ENCRYPT_MODE, aesKey); cc.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("inIv", encryptCipher.getIV()); // setup encrypted output FileOutputStream fos = new FileOutputStream(localFile.getAbsoluteFile() + ".enc"); CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, encryptCipher); BufferedOutputStream bos = new BufferedOutputStream(cipherOutputStream); // ftp the file to encrypted file FTPClient client = new FTPClient(); client.connect(FTP_URL); client.login(FTPUSER, FTP_PW); client.enterLocalPassiveMode(); //client.changeWorkingDirectory("/"); //client.setFileType(); boolean retVal = client.retrieveFile(filename, bos); logger.info("ftp returned " + retVal); bos.flush(); bos.close(); cc.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("encFileName", localFile.getAbsoluteFile() + ".enc"); return RepeatStatus.FINISHED; } }).build();
For the first
Tasklet, I created it right in the
Step. In my opinion, this is a fine technique for simple or at least short tasks that we know will never be reused. This puts all the code in the same class as the configuration, so it is easy to find if you need to maintain it. However, if you will be using this type of process across multiple Spring Batch
Jobs, or may be across multiple projects, you should make it more generic and move it to its own class.
So what’s going on here?
First we have to figure out what the name of our file is. I hard-code it into this example, but it can be gotten from the parameters, the context, or even by looking it up on our FTP server. We create a
File object so we can use File’s
methods letter to get path and other information.
Encryption
Next we are going to use Java’s cryptography library to generate a key. While no security is going to be absolutely fool proof, I think this one is going to be pretty strong. We generate the key in the application instead of passing it in, because we will never try to decrypt the file outside of the program, or even outside of this
job. This gives us the additional security of having a key that no one else knows.
We then place that key in the
Job Context to use later in the application. Now, on some systems that may create a weak point in my security. Spring Batch may be writing the context back to a database somewhere. If your database might be compromised at the same time your application server is compromised, you may want to look for another way to store this. Remember, a cracker would have to have this value, the value of the initialization vector we will discuss in a moment, and the name of the file, for any of them to be useful.
Once we have the key, we create a
Cypher that we’ll use to encrypt our file. At this time, we will grab the initialization vector that we used to randomize the encryption. This will be required later to read the file.
Transferring
Now that our encryption is in place, we create a File to write the data to. We are wrapping the
BufferedOutputStream around a
CipherOutputStream provided for us by Java.
To do the FTP, we are using Apache’s FTP client so that we can set the
Output stream we want to use. We can swap out a regular
OutputStream with our new encrypted one, meaning we don’t have to download the file and then encrypt it.
Once the file is transmitted, we
flush the stream and close it. We specifically call the
flush before closing because I was having issues with the stream closing before all the data was written. This caused the encrypted file to be corrupted, but there was no way to just open the file and see that. I spent a great deal of time trying to figure out why my file was corrupted.
Finally, we let the rest of the application know our filename. We added a
.enc to the end so we can find it easily later during testing.
Step #2
Ok, let’s skip to the next
Step which will take our result file and write it back to the FTP server.
@Bean public Step encTransferLastStep(StepBuilderFactory stepBuilderFactory) { return stepBuilderFactory.get("encTransferLastStep").tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution sc, ChunkContext cc) throws Exception { SecretKey aesKey = (SecretKey) cc.getStepContext().getStepExecution().getJobExecution().getExecutionContext().get("inKey"); byte[] iv = (byte[]) cc.getStepContext().getStepExecution().getJobExecution().getExecutionContext().get("inIv"); Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); encryptCipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv)); File f = new File("outfile.txt.enc"); FileInputStream fis = new FileInputStream(f); CipherInputStream cis = new CipherInputStream(fis, encryptCipher); BufferedInputStream bis = new BufferedInputStream(cis); FTPClient client = new FTPClient(); client.connect(FTP_URL); client.login(FTPUSER, FTP_PW); client.changeWorkingDirectory("/"); client.setFileType(); client.storeFile("outfile.txt", bis); f.delete(); String encfilename = (String) cc.getStepContext().getStepExecution().getJobExecution().getExecutionContext().get("encFileName"); File inputFile = new File(encfilename); inputFile.delete(); return RepeatStatus.FINISHED; } }).build(); }
We get the key and the initialization vector (IV) back from context and create a new
Cipher for reading the encrypted result file. We are using the same key and IV we created on the input file. You could create new ones in the
Writer later on if you desire.
This time we use
CipherInputStream to read the file. Apache’s FTP client will again allow us to provide a input stream, so we hand it our new encrypted input stream. This will write the file to the secured FTP server as plain text.
Reading & Writing
Now that we have a way to transfer the files around, how to we read and write them. First, we’ll need two new classes. We’ve extended
UrlResource and
FileSystemResource to provide access to the
CipherInputStream and
CipherOutputStream and we can use these Resources in our
Reader and
Writer.
public class CyrptUrlResource extends UrlResource { private final Cipher encryptCipher; public CyrptUrlResource(URI uri, Cipher encryptCipher) throws MalformedURLException { super(uri); this.encryptCipher = encryptCipher; } @Override public InputStream getInputStream() throws IOException { return new PushbackInputStream(new CipherInputStream(super.getInputStream(), encryptCipher), (2048 * 2048)); } }
And
public class CyrptFileSystemResource extends FileSystemResource { private Cipher encryptCipher; public CyrptFileSystemResource(String path, Cipher encryptCipher) { super(path); this.encryptCipher = encryptCipher; } @Override public OutputStream getOutputStream() throws IOException { return new CipherOutputStream(super.getOutputStream(), encryptCipher); } @Override public InputStream getInputStream() throws IOException { return new CipherInputStream(super.getInputStream(), encryptCipher); } }
We created both because we found that in some situations, especially binary files, the
UrlResource works better than the
File System Resource. Try both and see which one fits your situation better. The
CyrptUrlResource contains a
PushBackInputStream. We implemented that because we were reading Excel files (a future post) and the reader we were using required that. This can be removed if not needed, or a flag added to signal whether to use it or not. I left it here in case someone else was having a similar issue.
To use them, I’m going back to the
Reader and
Writer in the Delegate post I mention earlier. For the
Reader, the change is as simple as adding the following code to the beforeStep:
final SecretKey aesKey = (SecretKey) stepExecution.getJobExecution().getExecutionContext().get("inKey"); byte[] iv = (byte[]) stepExecution.getJobExecution().getExecutionContext().get("inIv"); String encfilename = (String) stepExecution.getJobExecution().getExecutionContext().get("encFileName"); File f = new File(encfilename); Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); encryptCipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv)); CyrptUrlResource cur = new CyrptUrlResource(f.toURI(), encryptCipher); delegate.setResource(cur);
We replace the Resource on the delegate with the
CyrptUrlResource. The Resource is created using the key and IV we generated earlier in the first
Tasklet.
Our writer is much more of a rewrite.
@Configuration @StepScope public class BookListWriter implements ItemStreamWriter<List<BookList>> { private static final Logger logger = LoggerFactory.getLogger(BookListWriter.class); private StepExecution stepExecution; private DelimitedLineAggregator<BookList> dla; private BufferedOutputStream bos; @BeforeStep public void beforeStep(StepExecution stepExecution) { logger.debug("beforeStep"); this.stepExecution = stepExecution; dla = new DelimitedLineAggregator<>(); dla.setDelimiter(","); BeanWrapperFieldExtractor<BookList> fieldExtractor = new BeanWrapperFieldExtractor<>(); fieldExtractor.setNames(new String[]{"bookName", "author"}); dla.setFieldExtractor(fieldExtractor); } @Override public void close() throws ItemStreamException { try { bos.flush(); bos.close(); } catch (IOException ex) { logger.error(ex.getMessage(), ex); throw new ItemStreamException(ex); } } @Override public void open(ExecutionContext ec) throws ItemStreamException { try { SecretKey aesKey = (SecretKey) stepExecution.getJobExecution().getExecutionContext().get("inKey"); byte[] iv = (byte[]) stepExecution.getJobExecution().getExecutionContext().get("inIv"); String encfilename = "outfile.txt.enc"; File f = new File(encfilename); Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); encryptCipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv)); CyrptFileSystemResource cur = new CyrptFileSystemResource(f.getAbsolutePath(), encryptCipher); bos = new BufferedOutputStream(cur.getOutputStream()); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IOException ex) { logger.error(ex.getMessage(), ex); throw new ItemStreamException(ex); } } @Override public void update(ExecutionContext ec) throws ItemStreamException { } @Override public void write(List<? extends List<BookList>> list) throws Exception { logger.info("write"); for (List<BookList> bookList : list) { for (BookList book : bookList) { String line = dla.aggregate(book) + "\n"; bos.write(line.getBytes()); } } } }
We move the
Aggregator to the class level because we are going to use it later. Also, we capture the
StepExecution for later use. A new
BufferedOutputStream is created that will actually do the writing. We can no longer use the flat file writer because we are now dealing with a binary file.
The Open Method
So let’s jump over close and talk about the
open method. Here we once again get our key and IV from the context and use them to create our Cipher. Our Cipher is then used to create a File Resource which is in turn used to create our
BufferedOutputStream. Since we are not using a built-in
Writer as a
Delegate anymore, we could have skipped the
Resource and created our
OutputStream for
BufferedOutputStream to wrap right here, but we have it and might as well use it.
We now have a file ready to write our encrypted data. The update method no longer has anything to do, so we leave it blank and move on to the
write. As our
Processor created a list of
BookLists, and Spring Batch hands the output of the
Reader/
Processor to the
Writer as a list, we have a list of lists to loop through. We use our
aggregator, which is unchanged from the original version, to put together our output string, but don’t forget the end of line character.
Once all our data has been written out, we come back to our close method. Again, we call the
flush method before closing to ensure that all the data is written before moving on.
Final Thoughts
That is the complete change we made to provide a little more security to the data we are passing around. While no single security measure can provide a 100% guarantee of safety, the more layers you add, the more secure you become. This solution provides a easy to maintain layer.
Believe in good code. | https://keyholesoftware.com/2017/11/13/encrypting-working-files-locally-in-spring-batch/ | CC-MAIN-2020-29 | en | refinedweb |
From: David Abrahams (dave_at_[hidden])
Date: 2007-06-23 18:21:01
> Also I believe in many other places I am using type& within unnamed
> namespace. This seems to be valid usage, right?
You've left out too much detail for me to make a determination.
-- Dave Abrahams Boost Consulting The Astoria Seminar ==>
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2007/06/123810.php | CC-MAIN-2020-29 | en | refinedweb |
by Guido Schmitz
Efficient Data Transformations Using Transducers
Transforming large collections of data can be expensive, especially when you’re using higher order functions like map and filter.
This article will show the power of transducers to create efficient data transformation functions, which do not create temporary collections. Temporary collections are created when map and filter functions are chained together. This is because these functions return a new collection and will pass the result to the next function.
Imagine having records of 1,000,000 people and wanting to create a subset of “names of women above the age of 18 that live in The Netherlands”. There are different ways to solve this, but let’s start with the chaining approach.
If this approach is new to you, or you want to learn more about it, I’ve written a blog post on using higher order functions.
const ageAbove18 = (person) => person.age > 18;const isFemale = (person) => person.gender === ‘female’;const livesInTheNetherlands = (person) => person.country === ‘NL’;const pickFullName = (person) => person.fullName;
const output = bigCollectionOfData .filter(livesInTheNetherlands) .filter(isFemale) .filter(ageAbove18) .map(pickFullName);
Below is the visualisation of using the chained approach that creates temporary arrays. Imagine the expense of looping over 1,000,000 records 3 times!
Of course, the filtered collections will be reduced by some amount, but it’s still quite expensive.
A key insight, however, is that map and filter can be defined using reduce. Let’s implement the above code in terms of reduce.
const mapReducer = (mapper) => (result, input) => { return result.concat(mapper(input));};
const filterReducer (predicate) => (result, input) => { return predicate(input) ? result.concat(input) : result;};
const personRequirements = (person) => ageAbove18(person) && isFemale(person) && livesInTheNetherlands(person);
const output = bigCollectionOfData .reduce(filterReducer(personRequirements), []) .reduce(mapReducer(pickFullName), []);
We can further simplify the filterReducer by using function composition.
filterReducer(compose(ageAbove18, isFemale, livesInTheNetherlands));
When using this approach we reduce (haha!) the number of times we create a temporary array. Below is a visualization of the transformation when using the reduce approach.
Beautiful, right? But we were talking transducers. Where are our transducers?
It turns out, the filterReducer and mapReducer we created are reducing functions. We can express this as:
reducing-function :: result, input -> result
Transducers are functions that accept a reducing function and return a reducing function. This can be expressed as the following:
transducer :: (result, input -> result) -> (result, input -> result)
The most interesting part is that transducers are roughly symmetric in their type signature. They take one reducing function and return another.
Because of this we can compose any number of transducers using function composition.
Building your own Transducers
Hopefully it’s all starting to make more sense now. Let’s build our own transducer functions for map and filter.
const mapTransducer = (mapper) => (reducingFunction) => { return (result, input) => reducingFunction(result, mapper(input));}
const filterTransducer = (predicate) => (reducingFunction) => { return (result, input) => predicate(input) ? reducingFunction(result, input) : result;}
Using the transducers we’ve created above, let’s transform some numbers. We will use the compose function from RamdaJS.
RamdaJS is a library that provides practical functional methods and is specifically designed for functional programming styles.
const concatReducer = (result, input) => result.concat(input);const lowerThan6 = filterTransducer((value) => value < 6);const double = mapTransducer((value) => value * 2);
const numbers = [1, 2, 3];
// Using Ramda's compose hereconst xform = R.compose(double, lowerThan6);
const output = numbers.reduce(xform(concatReducer), []); // [2, 4]
The concatReducer is called the iterator function. This will be called on every iteration and will be responsible for transforming the output of the transducer function.
In this example, we simply concat the result. Because every transducer only accepts a reducing function, we cannot use value.concat.
When we compose multiple transducers into a single function, most of the time it’s called a xform transducer. So when you see this somewhere, you know what it means.
Composing multiple transducers
We’ve been using ordinary function composition in the previous example, and you may be wondering what the order of evaluation is. Although function composition applies functions from right to left, the transformations will actually be evaluated from left to right at execution time — which is far more intuitive to those of us who read in left-to-right languages.
It takes a little bit of thinking to see why this is true: given our transducer double which returns a reducing function, and our transducer lowerThan6 which also returns a reducing function, when you compose double and lowerThan6, the output of double will be passed to lowerThan6, which will then return the reducing function of lowerThan6. Thus, double is the result of the composition and the order of evaluation is indeed from left to right.
I’ve created a JSBin example with some console.log statements, so you can have a look at it for yourself.
Using RamdaJS to improve readability
Since transducers are a perfect example for a functional programming style, let’s look at the way Ramda can help us by using their set of methods.
const lowerThan6 = R.filter((value) => value < 6);const double = R.map((value) => value * 2);const numbers = [1, 2, 3];
const xform = R.compose(double, lowerThan6);
const output = R.into([], xform, numbers); // [2,4]
With Ramda, we can use their map and filter methods. This is because Ramda’s internal reduce method uses the Transducer Protocol under the hood.
“The goal of the Transducer Protocol is that all JavaScript transducer implementations interoperate regardless of the surface level API. It calls transducers independently from the context of their input and output sources and specifies.”
Conclusion
Transducers are a powerful and composable way to build transformations that you can reuse in many contexts. Once you’ve got a transducer, you can do an open set of things.
They’re especially useful when transforming big datasets, but you can also use the same transducer to transform a single record.
If you want to learn more about this subject, I recommend the following articles: | https://www.freecodecamp.org/news/efficient-data-transformations-using-transducers-c779043ba655/ | CC-MAIN-2020-29 | en | refinedweb |
TypeScript is a typed superset of JavaScript. It has become popular recently in applications due to the benefits it can bring. If you are new to TypeScript it is highly recommended to become familiar with it first before proceeding.
TypeScript is a typed superset of JavaScript. It has become popular recently in applications due to the benefits it can bring. If you are new to TypeScript it is highly recommended to become familiar with it first before proceeding.
TypeScript is a great language to choose if you are a JavaScript developer and interested in moving towards a statically typed language. Using TypeScript is such a logical move for developers that are comfortable with JavaScript but haven’t written in languages that are statically typed (like C, JVM’s, Go, etc).
As I began my journey to TypeScript, (I’m most comfortable with JS, but have written a little bit in Go and C), I found it to be pretty easy to pick up. My initial thought was: “It really isn’t that bad typing all the argument in my function and typing the return value; what’s the fuss all about?” It was nice and simple until we had a project where we needed to create a React/Redux app in TypeScript.
It’s super easy to find material for React + JS, but as you begin to search for React + TS and especially React + Redux + TS, the amount of online tutorials (including YouTube videos) begin to dwindle significantly. I found myself scouring Medium, Stack Overflow, etc. for anything I could find to help explain how to set up the project, how types are flowing between files (especially once Redux is involved), and how to build with Webpack. This article is a way for me to solidify my knowledge of React + Redux + TS, and to hopefully provide some guidance for anyone else who is interested in using this tech stack for the front end. TypeScript is becoming more popular, so I hope this is useful to others in the community.
Prerequisites: I assume you’re aware of how React, Redux, and Webpack work, and also most concepts in TypeScript (at least interfaces and generics).
What are we gonna build? Just to keep it simple, we’ll build the infamous to-do list application. Remember that the purpose is to understand how to set up the project and know how TypeScript integrates with React and Redux. The features that this application will support are:
The code for the project can be found here:.
For my project, I didn’t use
create-react-app --typescript to get the project started. I found that it was a valuable learning experience to get it started from scratch. I’ll go step by step through the import files and folders needed to get this project up and running. Before we start, let me show you what the final structure looks like.
TS-Redux-React-Boilerplate ├── build ├── node_modules ├── public │ ├── bundle.js │ └── index.html ├── src │ ├── App.tsx │ ├── index.tsx │ ├── actions │ │ ├── actions.ts │ │ └── index.ts │ ├── components │ │ ├── index.ts │ │ └── TodoItem.tsx │ ├── containers │ │ └── TodoContainer.tsx │ ├── reducers │ │ ├── index.ts │ │ └── todoReducers.ts │ ├── store │ │ └── store.ts │ └── types │ └── types.d.ts ├── .gitignore ├── package-lock.json ├── package.json ├── tslint.json ├── tsconfig.json ├── webpack.config.js └── README.md
First, let’s look at the
package.json file and install these dependencies using
npm i.
"dependencies": { "@types/node": "^12.0.0", "@types/react": "^16.8.15", "@types/react-dom": "^16.8.4", "@types/react-redux": "^7.0.8", "react": "^16.8.6", "react-dom": "^16.8.6", "react-redux": "^7.0.3", "redux": "^4.0.1", "ts-loader": "^5.4.5", "typesafe-actions": "^4.2.0", "typescript": "^3.4.5", "webpack": "^4.30.0", "webpack-cli": "^3.3.1" }
Let’s first look at the dependencies with the format
@types/[npm module here]. If you aren’t familiar with what these modules are, look up. Since most modules are written in JavaScript, they aren’t written with proper type definitions. Once you attempt to import a module without any type information into a project that is all typed, TypeScript will complain. To prevent this, the community of contributors at DefinitelyTyped create high-quality type definition of the most commonly used JavaScript modules so that those modules will integrate as seamlessly as possible with TS.
You are probably familiar with the next four.
ts-loader is needed because Webpack needs a plugin to parse
.ts and
.tsx files. (This is similar to
babel.)
typesafe-actions is a library I use with Redux + TypeScript. Without it, the files can get quite noisy in terms of declaring types for the Store, Reducer, and Actions. This library provides methods that infer type definition for redux code so that the files are a bit cleaner and focused.
webpack and
webpack-cli are used to bundle the
.ts and
.tsx files into one
.jsfile that can be sent to the front end.
Next, let’s look at the
tsconfig.json file. The purpose of this file is to configure how you want the ts compiler to run.
{ "compilerOptions": { "baseUrl": ".", "outDir": "build/dist", "module": "commonjs", "target": "es5", "sourceMap": true, "allowJs": true, "jsx": "react" } }
baseUrl denotes the folder.
outDir directs the compiler where it should put the compiled code.
module tells the compiler which JavaScript module types to use.
target tells the compiler which JS version to target.
sourceMap tells the compiler to create a
bundle.js.map along with
bundle.js. Because bundling will turn multiple files into one large .js file, troubleshooting code will be difficult because you wouldn’t easily know which file and at which line the code failed (since everything is just one big file). The
.map file will map the bundled file to the respective unbundled file.
tslint.json provides options on how strict or loose you want the ts linter to be. The various options you can set for the linter can be found online.
Normally when I start projects with Redux, I begin at the action creators. Let’s quickly review the features that we need to implement: Adding an item to a list and removing an item from the list. This means we’ll need two action creators, one for adding and another for removing.
import { action } from "typesafe-actions"; // use typescript enum rather than action constants export enum actionTypes { ADD = "ADD", DELETE = "DELETE" } export const todoActions = { add: (item: string) => action(actionTypes.ADD, item), delete: (idx: number) => action(actionTypes.DELETE, idx) };
In the actions.ts file, I’m using the
enum feature in TS to create the action constants. Secondly, I’m using the
action method provided from the
typesafe-actions module. The first argument you pass into the method is a string which represents that action, and the second argument is the payload. The
add method will add an item to the list of to-dos, and the
deletemethod will remove an item, based on the provided index, from the list of to-dos.
In terms of type safety, what we want in our reducers file is the proper type of the payload, given a specific action. The feature in TypeScript that provides this support is called discriminated union *and type guarding*. Consider the example below:
// this is an example of discriminated unions // this file isn't used in the project interface ActionAdd { type: "ADD", payload: string } interface ActionDelete { type: "DELETE", payload: number } type Actions = ActionAdd | ActionDelete function reducer(a: Actions) { switch(a.type) { case "ADD" : { // payload is a string } case "DELETE" : { // payload is a number } } }
Given the shape of the two action objects, we can discriminate between them based on the
type property. Using control flow analysis, like
if-else or
switch-case statements, it’s very logical that in line 16, the only type that the payload can be is a string. Since we only have two actions, the remaining payload in line 22 will be a number. If you are interested in learning more about discriminated unions and type guarding, I would recommend learning more about it here and here.
After defining our action creators, let’s create the reducer for this project.
import * as MyTypes from "MyTypes"; import { actionTypes } from "../actions/"; interface ITodoModel { count: number; list: string[]; } export const initialState: ITodoModel = { count: 2, list: ["Do the laundry", "Do the dishes"] }; export const todoReducer = (state: ITodoModel = initialState, action: MyTypes.RootAction) => { switch (action.type) { case actionTypes.ADD: { return { ...state, count: state.count + 1, list: [...state.list, action.payload] }; } case actionTypes.DELETE: { const oldList = [...state.list]; oldList.splice(action.payload, 1); const newList = oldList; return { ...state, count: state.count - 1, list: newList }; } default: return state; } };
In lines four through seven, I’m defining the model (or schema) of our
Todostore. It will keep track of how many to-do items we have, as well as the array of strings. Lines nine through 12 are the initial state when the application first starts. Within the
todoReducer function, we want type safety within the
casestatements. Based on the earlier gist, we accomplished that by discriminated unions and type guarding, done by typing the
action parameter. We have to first define an interface for every action object, and then create a union of them all and assign that to a type. This can get tedious if we have a lot of action creators — luckily,
typesafe-actions has methods to help create the proper typing of the action creators without having to actually write out all the interfaces.
declare module "MyTypes" { import { StateType, ActionType } from "typesafe-actions"; // 1 for reducer, 1 for action creators export type ReducerState = StateType<typeof import("../reducers").default>; export type RootAction = ActionType<typeof import("../actions/actions")>; }
Ignoring line four for now and focusing on line five, we use a method called
ActionType from the module, and import the actions from
actions.ts to create the discriminated union types, which are then assigned to a type called
RootAction. In line one of the todoReducers.ts, we import
MyTypes and in line 14, we type the
action parameter with
MyTypes.RootAction. This allows us to have IntelliSense and autocompletion within the reducers!
Now that we have the reducer set up, the
ReducerState type from the
types.d.ts file allows TypeScript to infer the shape of the state object in the reducer function. This will provide IntelliSense when we try to access the payload object within the Reducer. An example of what that looks like is in the picture below.
IntelliSense in the Reducer
Finally, let’s hook up the reducer to the redux store.
import { createStore } from "redux"; import rootReducer from "../reducers"; const store = createStore(rootReducer); export default store;
Let’s recap what we have accomplished up until this point. We have created and typed our action creators using the
action method from
typesafe-actions. We have created our
types.d.ts file which provide type information on our action creators and reducer state. The reducer has been created and the actions are typed by using
MyTypes.RootAction, which provide invaluable auto-completion information of the payload within the reducer’s case statements. And lastly, we created our Redux store.
Let’s change gears and begin working on creating and typing our React components. I’ll go over examples of how to properly type both function and class based components, along with instructions on how to type both the props and state (for stateful components).
import * as React from "react"; import TodoContainer from "./containers/TodoContainer"; export const App: React.FC<{}> = () => { return ( <> <h1>React Redux Typescript</h1> <TodoContainer /> </> ); };
App is a functional component that is typed by writing
const App: React.FC<{}>. (FC refers to functional component.) If you aren’t familiar with generics (which is the
<{}> ), I think of them like variables but for types. Since the shape of
props and
state can differ based on different use cases, generics are a way for us to, well, make the component generic! In this case,
App doesn’t take any props; therefore, we pass in an empty object as the generic. How do we know that the generic is specifically for props? If you use VS code, IntelliSense will let you know what type it needs.
Where it says
<P = {}> , it means type
{} has been assigned to P, where
Pstands for props. For class-based components, React will use
S to refer to state.
App is a functional component that receives no props and is not connected to the Redux store. Let’s go for something a little more complicated.
import * as React from "react"; import { connect } from "react-redux"; import { Dispatch } from "redux"; import * as MyTypes from "MyTypes"; import { actionTypes } from "../actions"; import { TodoItem } from "../components"; interface TodoContainerState { todoInput: string; } interface TodoContainerProps { count: number; todoList: string[]; addToDo: (item: string) => object; deleteToDo: (idx: number) => object; } class TodoContainer extends React.Component<TodoContainerProps, TodoContainerState> { constructor(props) { super(props); this.state = { todoInput: "" }; } handleTextChange = e => { this.setState({ todoInput: e.target.value }); }; handleButtonClick = () => { this.props.addToDo(this.state.todoInput); this.setState({ todoInput: "" }); }; handleDeleteButtonClick = (idx: number) => { console.log("deleting", idx); this.props.deleteToDo(idx); }; render() { let todoJSX: JSX.Element[] | JSX.Element; if (!this.props.todoList.length) { todoJSX = <p>No to do</p>; } else { todoJSX = this.props.todoList.map((item, idx) => { return ( <TodoItem item={item} key={idx} idx={idx} handleDelete={this.handleDeleteButtonClick} /> ); }); } return ( <div> {todoJSX} <input onChange={this.handleTextChange} placeholder={"New To Do Here"} value={this.state.todoInput} /> <button onClick={this.handleButtonClick}>Add To Do</button> </div> ); } } const MapStateToProps = (store: MyTypes.ReducerState) => { return { count: store.todo.count, todoList: store.todo.list }; }; const MapDispatchToProps = (dispatch: Dispatch<MyTypes.RootAction>) => ({ addToDo: (item: string) => dispatch({ type: actionTypes.ADD, payload: item }), deleteToDo: (idx: number) => dispatch({ type: actionTypes.DELETE, payload: idx }) }); export default connect( MapStateToProps, MapDispatchToProps )(TodoContainer);
OK,
TodoContainer.tsx is the most complicated of them all, but I’ll walk you through what’s going on in the code.
TodoContainer is a React Class Component because I need it to hold in its state the value for the input box. It is also connected to the redux store, so it’ll have
MapStateToProps and
MapDispatchToProps . First, I’ve defined
TodoContainerState . Since I’ll be holding the value of the input box in state, I’ll type the property as a string.
Next, I’ve defined
TodoContainerProps, which will be the shape of the Container’s props.
Because class-based components can have both state and props, we should expect that there should be at least two generics that we need to pass into
React.Component.
P for Props and S for State
If you mouse over
React.Component, you can see that it takes in three generics,
P,
S, and
SS. The first two generics are props and state. I’m not quite sure what
SS is and what the use case is. If anyone knows, please let me know in the comments below.
After passing in the generics into
React.Component , IntelliSense and autocompletion will work within
this.state and for
props.
Next, we want to type
MapStateToProps and
MapDispatchToProps. This is easily achievable by leveraging the
MyTypes module that we built in the redux section. For
MapStateToProps, we assign the
store type to be
MyTypes.ReducerState. An example of the IntelliSense it will provide is in the below screenshot.
IntelliSense for MapStateToProps
Lastly, we want to have type safety within
MapDispatchToProps. The benefit that is provided is a type-safe payload given an action type.
Type-safe payloads
In the screenshot above, I purposely typed
item as a boolean. Immediately, the TSServer will pick up that the boolean payload within
MapDispatchToProps is not correct because it’s expecting the payload to be a string, given that the type is
actionTypes.ADD.
TodoContainer.tsx has the most going on since it is a class based React component, with both state and props, and is also connected to the store.
Before we wrap up, let’s look at our last component:
TodoItem.tsx
This component is a functional component with props — code below.
import * as React from "react"; interface TodoItemProps { item: string; idx: number; handleDelete: (idx: number) => void; } export const TodoItem: React.FC<TodoItemProps> = props => { return ( <span> {props.item} <button onClick={() => props.handleDelete(props.idx)}>X</button> </span> ); };
The shape of the props are defined in the interface
TodoItemProps. The type information is passed into as a generic in
React.FC. Doing so will provide auto-completion for
props within the component. Awesome.
Another great feature that TypeScript provides when used with React is IntelliSense for props when rendering React Components within JSX. As an example, if you delete
idx:number from
TodoItemProps and then you navigate to
TodoContainer.tsx, an error will appear at the place where you render
<TodoItem />.
Property ‘idx’ does not exist
Because we removed
idx from the
TodoItemProps interface, TypeScript is letting us know that we have provided an additional prop that it couldn’t find,
idx, into the component.
Lastly, let’s build the project using Webpack. In the command line, type
npm run build. In the
public folder within the root directory, you should see
bundle.js alongside
index.html. Open
index.html in any browser and you should see a very simple, unstyled, to-do app.
After webpack build
I hope that I was able to demonstrate the power of TypeScript coupled with React and Redux. It may seem a bit overkill for our simple to-do list app — you just need to imagine the benefit of TS + React + Redux at scale. It will help new developers read the code quicker, provide more confidence in refactoring, and ultimately improve development speed.
If you need more reference and material, I used the following two Git repos to teach myself
Both these repos have proved invaluable for my learning, and I hope they will be the same for you.
redux reactjs typescript javascript.
In this React tutorial, you'll learn how to build a type-safe React Redux store with TypeScript. React is a component library developers commonly use to build the frontend of modern applications. Redux is a state management library that is popular in the React ecosystem
Let's write a note taking application using ReactJS with Typescript and Redux. We'll use React-Redux hooks with Typescript here. Also I show how to use Redux...
Using React with Redux and TypeScript . | https://morioh.com/p/d51255512a15 | CC-MAIN-2020-29 | en | refinedweb |
- All dashboards
- Kubernetes App Metrics (k8s 1.16)
Kubernetes App Metrics (k8s 1.16)
by rschef
Dashboard
After selecting your namespace and container you get a wealth of metrics like request rate, error rate, response times, pod count, cpu and memory usage. You can view cpu and memory usage in a variety of ways, compared to the limit, compared to the request, per pod, average per pod, etc.
Last updated: 8 months ago
Get this dashboard:
11143
Dependencies:
Grafana 5.2.1
Graph 5.0.0
Prometheus 5.0.0
Table 5.0.0 | https://grafana.com/grafana/dashboards/11143 | CC-MAIN-2020-29 | en | refinedweb |
Some test text!
Welcome to PDFTron. Java Java applications on Windows. Your free trial includes unlimited trial usage and support from solution engineers.
JDK >= 5.
Make sure that the JDK has been added to your
path environment variable.
The Troubleshooting section has more information about some of the common Java installation issues.
Extract the folder from the .zip file.
This article uses
PDFNET_BASE as the path into the
PDFNetDotNet4 folder that you extracted.
PDFNET_BASE = path/to/extraction/folder/PDFNetC(64)/
Navigate to the location of extracted contents. Find and enter the
Samples folder. Here you can find sample code for a large number of features supported by the PDFTron SDK.
Run a specific sample
JAVAfolder inside.
RunTest.batand run it. This can be done using either CLI or with a double-click. The results should appear on a
cmdwindow.
Run all samples
runall_java.batin the samples folder and double click.java, open and edit it using your favorite text editor.
Insert the following to your file:
import java.io.File; import java.io.IOException; // These are the most important packages to import // for basic document manipulation. import com.pdftron.common.PDFNetException; import com.pdftron.pdf.*; import com.pdftron.sdf.SDFDoc; import java.io.*; public class HelloWorld { // Just a simple setup for the application public static void main(String[] args) { // PDFNet must always be initialized before any PDFTron // classes and methods can be used PDFNet.initialize(); System.out.println("Hello World!"); // Most PDFTron operations are required to be wrapped in // a try-catch block for PDFNetException, or in a method/class that // throws PDFNetException try { // Creates a new PDFDoc object PDFDoc doc = new PDFDoc(); // Creating a new page and adding it // to document's sequence of pages Page page1 = doc.pageCreate(); doc.pagePushBack(page1); // Files can be saved with various options // Linearized files are the most effective // for opening and viewing quickly on various platforms doc.save(("linearized_ouput.pdf"), SDFDoc.SaveMode.LINEARIZED, null); doc.close(); } catch (PDFNetException e) { System.out.println(e); e.getStackTrace(); } PDFNet.terminate(); } }
To test that your code works, compile and run the code using a shell in the
HelloWorld folder using:
javac -cp .;../../Lib/PDFNet.jar HelloWorld.java java.exe -Djava.library.path=../../Lib -classpath .;../../Lib/PDFNet.jar HelloWorld
Once you have successfully run this, you should see an output file in the working directory of this program.
Java installation issues
More information about JDK installation, possible issues and their respective fixes. | https://www.pdftron.com/documentation/java/get-started/integration/ | CC-MAIN-2020-29 | en | refinedweb |
Thanks, worked like a charm. As usual, thank you for the prompt answer and the references;)
kav
@kav
Posts made by kav
- RE: cerebro.addbroker()?
- cere?
- RE: Switch off limit price matching rule on open
So in the file
lib/python3.6/site-packages/backtrader/brokers/, I copied
bbroker.pyto
mybbroker.pywhich is the same as the original except for the function
_try_exec_limitwhich I have replaced by:
def _try_exec_limit(self, order, popen, phigh, plow, plimit): if order.isbuy(): if 1==0: #plimit >= popen: # open smaller/equal than requested - buy cheaper pmax = min(phigh, plimit) p = self._slip_up(pmax, popen, doslip=self.p.slip_open, lim=True) self._execute(order, ago=0, price=p) elif plimit >= plow: # day low below req price ... match limit price self._execute(order, ago=0, price=plimit) else: # Sell if 1==0: #plimit <= popen: # open greater/equal than requested - sell more expensive pmin = max(plow, plimit) p = self._slip_down(plimit, popen, doslip=self.p.slip_open, lim=True) self._execute(order, ago=0, price=p) elif plimit <= phigh: # day high above req price ... match limit price self._execute(order, ago=0, price=plimit)
Now my questions is how can I tell BT to use
mybbroker.pyinstead of
bbroker.py? (I understand I can simply over-write
bbroker.pybut I'm sure there is a more elegant way to switch these things. I just don't know how)
Thanks in advance,
- RE: Switch off limit price matching rule on open
@BT: thanks for the quick answer. Just to clarify, when I wrote
Say for cases when the OHLC bars are constructed from intraday data?
I meant from say when using 1Min OHLC bars (so the bars are not daily frequencies).
When you write:
Yes. Write a broker and plug it in.
can you kindly give me the name of the function to change, so I can find it in the source and do that?
Thanks in advance,
P.S. I understand the behavior I'am trying to mute is this one:
if order.isbuy(): if plimit >= popen: # open smaller/equal than requested - buy cheaper pmax = min(phigh, plimit) p = self._slip_up(pmax, popen, doslip=self.p.slip_open, lim=True) self._execute(order, ago=0, price=p)
and
if plimit <= popen: # open greater/equal than requested - sell more expensive pmin = max(plow, plimit) p = self._slip_down(plimit, popen, doslip=self.p.slip_open, lim=True) self._execute(order, ago=0, price=p)
Could you kindly flesh out how to go about overloading the broker class so as to mute these conditions? I could not find a documentation about this,
- Switch off limit price matching rule on open
Consider the following lines in the BT doc
*Price Matching:
backtrader tries to provide most realistic execution price for Limit orders. Using the 4 price spots (Open/High/Low/Close) it can be partially inferred if the requested price can be improved. For Buy Orders Case 1: If the open price of the bar is below the limit price the order executes immediately with the open price. The order has been swept during the opening phase of the session*
Is there anyway to switch this behavior off? Say for cases when the OHLC bars are constructed from intraday data?
Basically to have the open price be treated just as the other ones (for a limit buy, if open price < smaller than limit price, execute the limit at the limit price).
Alternatively, would it be possible to have BT ignore the open price altogether? I mean is it safe to feed BT an open-less file or do I risk running into undefined behavior?
- getposition().size inside bt.observer
I was wondering if there was a way to get
getposition().size, or the same information, either in an observer or somehow out of
cerebro.run()e.g. I want to get a vector the same length as the data with at each time point the number of position held by the strategy at that point in time.
One solution is to do something like this in the Strategy:
def next(self): contract = self.datas[0] current_position = self.getposition(contract).size self.datas[0].position_size[0] = current_position
where position_size is an 0 valued column I added to the data.
which can then be recovered from as:
result = cerebro.run() result[0].datas[0].position_size.get(size = dataframe.shape[0])
where dataframe is the original data fed to cerebro.
- RE: bt.observers.Broker returning negative values.
@backtrader As usual, thanks for your answer.
I might be wrong on this, but it seems to me that backtrader (the library) is more flexible. It seems to me that a simple block like this in the backtrader.Strategy class could help toughening up the broker:
def next(self): contract = self.datas[0] current_position = self.getposition(contract).size min_nav = self.broker.getvalue() -\ ((self.datas[0].close[0] - self.datas[0].high[0])\ if current_position < 0 else\ (self.datas[0].close[0] - self.datas[0].low[0])) *\ self.datas[0].multiplier[0] * current_position margin_req = abs(current_position) * self.datas[0].MARGIN[0] if min_nav <= margin_req: if self.order: self.cancel(self.order) if current_position < 0: self.order = self.buy(exectype = backtrader.Order.Limit, data = contract, price = self.datas[0].high[0], size = abs(current_position)) else: self.order = self.sell(exectype = backtrader.Order.Limit, data = contract, price = self.datas[0].low[0], size = current_position) else: #normal trading logic
Is this foolish?
- bt.observers.Broker returning negative values.
Hi all,
bt.observers.Broker is returning negative values. Here is the relevant code:
cerebro = backtrader.Cerebro() cerebro.addobserver(backtrader.observers.Broker) # Add a strategy cerebro.addstrategy(StrategyBaseTrading) data = PandasDataStrat1(dataname = dataframe, datetime = -1, open = -1, high = -1, low = -1, close = -1, volume = -1, openinterest = None) cerebro.adddata(data) cerebro.broker\ .setcash(10000.0) cerebro.broker\ .setcommission(commission = 2.0 margin = 500.0, mult = 1000.0) return cerebro.run()
then, I find that values of:
results[0].observers[0].value.get(size = dataframe.shape[0])
are negative (at the end of the series)
My questions are:
- what does this mean? Do I read this correctly to mean that if I liquidate my positions at that point, I owe my broker money?
- is there a way to force the broker to act tougher? (liquidate the position if the value is < margin_reqs_per_contract * num_contract).
Lemme know if I can help by providing more code/details the full example (I did not want to cluter the question as I suspect my misunderstanding of the docs is the likely culprit).
- RE: keep (custom) observer value in a list.
@backtrader: Perfect. Thanks for the pointer, it indeed addresses my problem. Just to be sure, could you confirm that the backtrader-preferred way to add an observer as a new column to the original dataframe (that was fed to backtrader) is:
dataframe['observer'] = result[0].observers[2].executed_size.get(size = dataframe.shape[0])
thank you
- RE: keep (custom) observer value in a list.
@backtrader Thanks for the pointer.. But I must be doing something wrong because the output I get don't seem to match the one from the csv file.
result[0].observers[2].lines.executed_size
In [44]: len(list(result[0].observers[2].lines.executed_size)) Out[44]: 3364
(this is the correct length: that of the data).
but I must be doing something wrong because these are all nan values:
In [39]: pandas.DataFrame(list(result[0].observers[2].lines.executed_size)).dropna() Out[39]: Empty DataFrame Columns: [0] Index: []
whereas when I export the result to a csv:
cerebro.addwriter(backtrader.WriterFile, csv = True, out = outfile)
I can clearly see the
executed_sizecolumn is not all empty.
full code
class maCross(backtrader.Strategy): ''' For an official backtrader blog on this topic please take a look at: oneplot = Force all datas to plot on the same master. ''' params = ( ('sma1', 80), ('sma2', 200), ('oneplot', True), ('list_plus', []) ) def __init__(self): ''' Create an dictionary of indicators so that we can dynamically add the indicators to the strategy using a loop. This mean the strategy will work with any number of data feeds. ''' self.inds = dict()# p0 = pandas.Series(self.data.close.get(size=5)) # print(p0.head(5).transpose()) for i, d in enumerate(self.datas): self.inds[d] = dict() self.inds[d]['sma1'] = backtrader.indicators.SMA(d.close, period=self.params.sma1) self.inds[d]['sma2'] = backtrader.indicators.SMA(d.close, period=self.params.sma2) if d._name in self.params.list_plus: self.inds[d]['cross'] = backtrader.indicators.CrossOver(self.inds[d]['sma1'], self.inds[d]['sma2']) else: self.inds[d]['cross'] = backtrader.indicators.CrossOver(self.inds[d]['sma2'], self.inds[d]['sma1']) if i > 0: #Check we are not on the first loop of data feed: if self.p.oneplot == True: d.plotinfo.plotmaster = self.datas[0] def next(self): for i, d in enumerate(self.datas): dt, dn = self.datetime.date(), d._name pos = self.getposition(d).size if not pos: # no market / no orders if self.inds[d]['cross'][0] == 1: self.buy(data=d, size=1) elif self.inds[d]['cross'][0] == -1: self.sell(data=d, size=1) else: if self.inds[d]['cross'][0] == 1: self.close(data=d) self.buy(data=d, size=1) elif self.inds[d]['cross'][0] == -1: self.close(data=d) self.sell(data=d, size=1) class SimpleObserver(backtrader.observer.Observer): lines = ('executed_size', ) def next(self): for order in self._owner._orderspending: if order.data is not self.data: continue if order.status in [backtrader.Order.Completed]: self.lines.executed_size[0] = order.executed.size
then
dataframe = self.get_data(file_name) margin = 10000 # Create a cerebro entity cerebro = backtrader.Cerebro() cerebro.addobserver(SimpleObserver) # Add a strategy cerebro.addstrategy(maCross) data = PandasDataStrat1(dataname = dataframe, datetime = -1, open = -1, high = -1, low = -1, close = -1, volume = -1, openinterest = None) cerebro.adddata(data) start_cash = 100000.0 cerebro.broker\ .setcash(start_cash) cerebro.broker\ .setcommission(commission = 2.0, margin = margin, mult = 10.0) result = cerebro.run() | https://community.backtrader.com/user/kav | CC-MAIN-2020-29 | en | refinedweb |
RunLoop
RunLoop 1.1
is what RunLoop?
1.2 RunLoop and 1.3 RunLoop RunLoop thread
default principle related
case of the main thread 2.1 CFRunLoopRef
2.2 CFRunLoopModeRef
2.3 CFRunLoopTimerRef
2.4 CFRunLoopSourceRef
2.5 CFRunLoopObserverRef RunLoop 4.1 NSTimer
RunLoop principle application using
4.2 ImageView
4.3 delayed display background thread (very common) Demo permanent address in this paper: YSC-RunLoopDemo
1 RunLoop profile
1.1 what is RunLoop?
Run represents a run, Loop represents a loop. To combine is to run the cycle. Haha, I prefer to “run”. As intuitive understanding is constantly running.
RunLoop is actually an object, the object for every event handler in the operation process in the cycle (such as touch events, UI refresh events, timer events, Selector events), continuous operation so as to maintain the program; and where there is no reason when the event will enter sleep mode to save CPU resources to improve the performance of the program.
1.2 RunLoop and thread
RunLoop and the thread is closely linked, we know that the thread is used to perform one or more specific tasks, but by default, after the thread will quit, it cannot perform the task. At this point we need to use a way to allow the thread to handle the task, do not exit. So, we have RunLoop.
- A thread corresponds to a RunLoop object, each thread has a unique corresponding RunLoop object.
- We can only manipulate the RunLoop of the current thread in the current thread, but not the RunLoop of other threads.
- The RunLoop object is created at the first time the RunLoop is acquired, and the destruction is done at the end of the thread.
- The main thread of the RunLoop object system automatically helps us to create it well (as follows), while the child thread of the RunLoop object requires us to create.
1.3 by default the main thread of the RunLoop principle
When we start a iOS program, the system will call the project automatically generated main.m file. The main.m file is as follows:
Int main (int argc, char * argv[]) {@autoreleasepool {return (argc, argv, nil, NSStringFromClass ([AppDelegate class]));}}
UIApplicationMain function which helps us to open the main thread of the RunLoop, UIApplicationMain has a wireless internal code. Above the code to open the RunLoop process can be simply understood as follows:
Int main (int argc, char * argv[] BOOL) {running = YES; do {/ / perform various tasks, handle various events / /... While...} (running); return 0;}
As can be seen from the above, the program has been in the DO-WHILE loop to perform, so the UIApplicationMain function has not been returned, we will not immediately exit the program after running the program, will remain in operation.
The following figure is given by Apple’s official RunLoop model.
official RunLoop model diagram
Can be seen from the diagram, a RunLoop cycle is in the thread, RunLoop will continue in the circulation, by Input sources (input source) and Timer sources (Ding Shiyuan) two sources of waiting for the event; then the received event notification thread processing, and the rest are in no event.
2 RunLoop related classes
Below we look at the Core Foundation framework on the RunLoop of the 5 categories, only to understand the meaning of these categories, we can understand the operating mechanism of RunLoop.
- CFRunLoopRef: object representing RunLoop
- CFRunLoopModeRef:RunLoop operation mode
- CFRunLoopSourceRef: the source / event source referred to in the RunLoop model diagram
- CFRunLoopTimerRef: is the timing source referred to in the RunLoop model diagram
- CFRunLoopObserverRef: observer, able to monitor the status of RunLoop changes
The following detailed explanation of the specific meaning and relationship of the following categories.
Look at a diagram of the 5 classes (source:).
RunLoop related class diagram.Png
Then to explain the 5 class relationship (source:), this article summarizes the special good, for reference, interested friends can see, very well written.
A RunLoop object (CFRunLoopRef) contains several operating modes (CFRunLoopModeRef). And each operation mode also includes a number of input sources (CFRunLoopSourceRef), timing source (CFRunLoopTimerRef), observer (CFRunLoopObserverRef).
- Each time the RunLoop is started, only one of the operating modes (CFRunLoopModeRef) can be specified, which is called CurrentMode (CFRunLoopModeRef).
- If you need to switch the operating mode (CFRunLoopModeRef), can only exit Loop, and then re designated a running mode (CFRunLoopModeRef) into.
- This is done in order to separate the different groups of input source (CFRunLoopSourceRef), timing source (CFRunLoopTimerRef), observer (CFRunLoopObserverRef), so that they do not affect each other.
Below we explain in detail the following five categories:
2.1 CFRunLoopRef
CFRunLoopRef is the Core Foundation framework under the RunLoop object class. We can obtain the RunLoop object in the following ways:
- Core Foundation (CFRunLoopGetCurrent); / / RunLoop object CFRunLoopGetMain to obtain the current thread (); / / get the main thread of the RunLoop object
Of course, the way to get the RunLoop object class in the Foundation framework is as follows:
- Foundation [NSRunLoop currentRunLoop]; / / get the thread RunLoop [NSRunLoop mainRunLoop]; / / get the main thread of the RunLoop object
2.2 CFRunLoopModeRef
The system default defines a variety of operating modes (CFRunLoopModeRef), as follows:
- KCFRunLoopDefaultMode:App is the default mode of operation, usually the main thread is running in this mode
- UITrackingRunLoopMode: tracking user interaction events (for ScrollView tracking touch slide, to ensure that the interface is not affected by other Mode sliding)
- UIInitializationRunLoopMode: just started when the first entry of the App Mode, after the start is no longer used
- GSEventReceiveRunLoopMode: accept system internal events, usually not used
- KCFRunLoopCommonModes: pseudo mode, not a true mode of operation (used later)
The kCFRunLoopDefaultMode, UITrackingRunLoopMode and kCFRunLoopCommonModes are used in the development of our model, we use the specific method in 2.3 CFRunLoopTimerRef combined with CFRunLoopTimerRef to demonstrate.
2.3 CFRunLoopTimerRef
CFRunLoopTimerRef is a timing source (referred to in the RunLoop model diagram), understood as a trigger based on time, is basically NSTimer (ha ha, this understanding is simple).
Here we demonstrate the use of the combination of CFRunLoopModeRef and CFRunLoopTimerRef, so as to deepen understanding.
- First, we create a new iOS project, drag a Text Main.storyboard in View.
- In the ViewController.m file to add the following code, Demo call [self ShowDemo1]. – (void) viewDidLoad {[super viewDidLoad]; / / define a timer, two seconds after run agreed to call the self method of NSTimer *timer [NSTimer timerWithTimeInterval:2.0 target:self = selector:@selector (run) userInfo:nil repeats:YES]; / / the timer is added to the current RunLoop NSDefaultRunLoopMode [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];} – {(void) run NSLog (@ —run “);}
- Then run, at this time we found that if we do not do any operation on the simulator, the timer will be stable every 2 seconds to call the run method printing.
- But when we drag the Text View scroll, we find that the run method does not print, that is, NSTimer does not work. And when we let go of the mouse, NSTimer started working again.
This is because:
- When we don’t do anything, RunLoop is under NSDefaultRunLoopMode.
- And when we drag the Text View, RunLoop over NSDefaultRunLoopMode, switch to UITrackingRunLoopMode mode, this mode did not add NSTimer NSTimer, so we do not work.
- But when we release the mouse, RunLoop will end the UITrackingRunLoopMode mode, and then switch back to the NSDefaultRunLoopMode mode, so NSTimer began to work again.
You can try the above code in the [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode] statement for the [[NSRunLoop, that is; the timer is added to the current RunLoop UITrackingRunLoopMode, you will find the timer will only work in drag the Text View mode, and do the operation when the timer is not working.
Can’t we get NSTimer to work properly in these two modes?
Of course, this is the use of the pseudo model we said before (kCFRunLoopCommonModes), this is not a real mode, but a tag mode means that can run in the play Common Modes marker mode.
So what patterns are marked on the Common Modes?
NSDefaultRunLoopMode and UITrackingRunLoopMode.
So we as long as we add NSTimer to the current RunLoop kCFRunLoopCommonModes (under the framework of Foundation NSRunLoopCommonModes), we can make NSTimer two cases in operation and Text View drag pleasant work.
Specific approach is to add statements to [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Since talked about the NSTimer, here by way of the scheduledTimerWithTimeInterval method and the relationship between the RunLoop NSTimer. Add the following code:
[NSTimer scheduledTimerWithTimeInterval:2.0 selector:@selector (run) userInfo:nil target:self repeats:YES];
This code calls the scheduledTimer returned timer, NSTimer will automatically be added to the RunLoop NSDefaultRunLoopMode mode. This code is equivalent to the following two code:
NSTimer *timer = [NSTimer target:self selector:@selector (run) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode] (timerWithTimeInterval:2.0);
2.4 CFRunLoopSourceRef
CFRunLoopSourceRef is an event source (referred to in the RunLoop model diagram), CFRunLoopSourceRef has two classification methods.
- The first one is categorized according to official documents (as in the RunLoop model): Port-Based Sources (port based) Custom Sources (custom) Cocoa Perform Selector Sources
- Second according to the function call stack to classify: Source0: not based on Port Source1: Based on Port, through the kernel and other threads to communicate, receive, distribute system events
There is no difference between these two categories, but the first one is to classify the official theory, the second is in the practical application by calling the function to classify.
Let’s take a look at the function call stack and Source.
- Add a Button button to the Main.storyboard in our project and add a click action.
- Then click on the action code to add an output statement, and hit a breakpoint, as shown below:
add Button.png
- Then run the program and click the button.
- Then click the red part of the following figure in the project.
function call stack display
- You can see that as shown below is the function of the event call stack.
function call stack
So click on the event:
- First of all, the program starts, calling the 16 line of the main function, the main function calls the UIApplicationMain function of the 15 line, and then has been called up the function, the final call to the 0 line of the function, that is, click function.
- At the same time we can see that there are 11 lines of Sources0, that is, we click on the event is a Sources0 function, click the event is handled in the Sources0.
- As for Sources1, it is used to receive and distribute system events, and then distributed to the Sources0.
2.5 CFRunLoopObserverRef
CFRunLoopObserverRef is an observer, used to monitor the status of RunLoop changes
CFRunLoopObserverRef can monitor the status of the following changes:
Typedef CF_OPTIONS (CFOptionFlags, CFRunLoopActivity) {kCFRunLoopEntry (1UL = < < 0), is about to enter the Loop:1 kCFRunLoopBeforeTimers / / (1UL = < < 1), is Timer:2 kCFRunLoopBeforeSources = / / (1UL < < 2), is Source:4 kCFRunLoopBeforeWaiting = / / (1UL < < 5). About to enter dormancy: 32 / / kCFRunLoopAfterWaiting = (1UL < < 6), / / will wake up from sleep: 64 kCFRunLoopExit (1UL = < < 7), / / will exit from Loop: kCFRunLoopAllActivities = 0x0FFFFFFFU / 128} listening to all state changes;
Below we listen to the state changes in the RunLoop under the code.
- In the ViewController.m to add the following code, Demo call [self showDemo2]. – (void) viewDidLoad {[super viewDidLoad]; / / create observer CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler (CFAllocatorGetDefault), kCFRunLoopAllActivities (0, YES, (CFRunLoopObserverRef, observer, CFRunLoopActivity ^ activity) {NSLog (@ “listening to the change in RunLoop —%zd, activity);}); / / add to the current RunLoop CFRunLoopAddObserver observer ((CFRunLoopGetCurrent), observer, kCFRunLoopDefaultMode); / / observer release, finally finished adding need to release CFRelease (observer);}
- Then run, look at the print results, as shown below.
print results
You can see the status of RunLoop in the constant change, and finally became a state of 32, which is about to enter the sleep state, indicating that RunLoop will enter the sleep state.
3 RunLoop principle
Well, the five classes are explained, the following began to enlarge the recruit. So we can understand the logic of RunLoop.
Run a logic diagram below mentioned before the blogger provides (source:)
RunLoop run logic diagram
This picture is very helpful for us to understand RunLoop, so we can talk about the RunLoop logic of the official document.
When the RunLoop is opened every time, the RunLoop of the thread will automatically process the previously untreated event, and notify the relevant observer.
The specific sequence is as follows:
- Notify observer RunLoop has started
- Notify the observer about to start the timer
- Notify the observer of any upcoming non port based source
- Start any ready – to – port source
- If the source based on the port is ready and is waiting for it, start immediately and go to step 9
- Notify the watcher thread to sleep
- Place the thread in the sleep to know any of the following events: an event arrives at the port based source timer to start the RunLoop setup time has been timed RunLoop is shown to wake up
- Notify the watcher thread to be awakened
- Handle an event that is not processed. If the user defined timer starts, the timer event is processed and the RunLoop is restarted. Step 2 if the input source is started, pass the appropriate message if the RunLoop is shown to wake up and the time has not timed out, restart the RunLoop. Step 2
- Notify observer RunLoop end.
4 RunLoop combat applications
Ha ha, the principle of talk so much from knowledge, and finally to the actual application link below.
It is no use to understand the light, it is hard to apply. Here are some of the application of RunLoop.
4.1 NSTimer use
NSTimer the use of methods in the CFRunLoopTimerRef class to explain in detail, the specific reference above 2.3 CFRunLoopTimerRef.
4.2 ImageView delayed display
Sometimes, we will encounter this situation:
when the interface contains UITableView, and each UITableViewCell inside have pictures. At this time when we roll UITableView, if there is a bunch of pictures need to be displayed, then there may be the phenomenon of Caton.
How to solve this problem?
At this time, we should postpone the display of the picture, that is, ImageView delayed display pictures. There are two ways:
1 listen to the UIScrollView scroll
Because UITableView inherited from UIScrollView, so we can listen to the UIScrollView scroll, UIScrollView related delegate can be achieved.
2 use PerformSelector to set the current thread RunLoop operation mode
Using performSelector method for UIImageView call setImage: method, and use inModes to set it to RunLoop under the NSDefaultRunLoopMode operating mode. The code is as follows:
[self.imageView performSelector:@selector (setImage:) withObject:[UIImage imageNamed:@ "Tupian" afterDelay:4.0 inModes:NSDefaultRunLoopMode];
The use of Demo under the demonstration of the method.
- In the project in the Main.storyboard to add a UIImageView, and add attributes, and simply add a constraint (or can not be displayed) as shown in the following figure.
add UIImageView
- Drag a picture into the project, such as the following.
tupian.jpg
- Then we add the following code in the touchesBegan method, in Demo, please call [self touchesBegan in the showDemo3] method. – (void) touchesBegan: (NSSet< UITouch *> touches withEvent: (* *) UIEvent event) {[self.imageView performSelector:@selector (setImage:) withObject:[UIImage imageNamed:@ afterDelay:4.0 inModes:@[NSDefaultRunLoopMode]] “Tupian”];}
- Run the program, click on the screen, then drag drag UIText View, more than 4 seconds, 4 seconds after the discovery, UIImageView also did not show the pictures, when we release, display pictures, results are as follows:
UIImageView delay display effect.Gif
In this way, we will achieve the drag after the delay in the display UIImageView.
4.3 background resident thread (very commonly used)
We are in the process of developing applications, especially if the background operation frequently, often do some time-consuming operation in the thread (download files, background music playback etc.), we can make the best of this thread is always in memory.
So how to do it?
Add a strong reference to the resident memory of Zi Xiancheng, in the thread under the RunLoop to add a Sources, open RunLoop.
The specific implementation process is as follows:
- In the project’s ViewController.m add a strong reference to the thread thread properties, as follows:
add thread attributes
- In viewDidLoad to create a thread self.thread, so that the thread starts and executes the Run1 method, the code is as follows. In Demo, please call [self showDemo4] at viewDidLoad; method. – (void) viewDidLoad {[super viewDidLoad]; / / create a thread, and call the Run1 method to perform the task of self.thread = [[NSThread alloc] initWithTarget:self selector:@selector object:nil] (Run1); / / thread [self.thread start] Run1 (void);} – {/ / written here task NSLog (@ “—-run1—–“); / / add two below the code, you can open RunLoop, after self.thread became the resident threads, can be added at any time, and handed over to the RunLoop currentRunLoop] addPort:[NSPort port] forMode: NSDefaultRunLoopMode] [[NSRunLoop; [[NSRunLoop currentRunLoop] run]; / / test whether to open the RunLoop, if RunLoop is open, can not come here, because the RunLoop open cycle. NSLog (@ “RunLoop”);}
- After the operation was found to print the —-run1—–, and did not open the RunLoop is not printed.
At this time, we will open a resident thread, below we try to add other tasks, in addition to the time before the creation of the call to the Run1 method, we also click on the time to call the run2 method.
So, we call PerformSelector in touchesBegan, so as to achieve the time to click on the screen to call the run2 method. Demo address. Specific code is as follows:
- (void) touchesBegan: (NSSet< UITouch *> touches withEvent: (* *) UIEvent event) {/ / by performSelector, in the self.thread thread to call the run2 method to perform the task [self performSelector:@selector (run2) onThread:self.thread withObject: nil waitUntilDone:NO];} - {(void) run2 NSLog (@ ----run2------);}
After running the test, in addition to the previously printed —-run1—–, whenever we click on the screen, you can call —-run2——.
so that we can achieve the requirements of the resident thread.
Learn more about multi thread series:
- IOS multi threading – a thorough understanding of multi-threaded pthread, NSThread
- IOS multi threading – a thorough understanding of multi-threaded GCD
- IOS multi threading – a thorough understanding of multi-threaded NSOperation | http://w3cgeek.com/ios-multi-threading-a-thorough-understanding-of-multi-threaded-runloop.html | CC-MAIN-2017-51 | en | refinedweb |
Martijn Moeling wrote:
> Hi all,
>
>
>
> I started the development of a specific kind of CMS over 2 years ago,
> and due to sparse documentation I am still puzzled about a few things.
>
> Basically it consist of one .py and a mysqldatabase with all the data
> and templates, ALL pages are generated on the fly.
>
>
>
> First of all I am confused about PythonInterPerDirectory and
> PythonInterpPerDirectory
>
> In the way I use modpython.
>
>
>
> My apache has no configured virtual hosts since my CMS can handle this
> on its own by looking at req.host
>
> On one site which is running on my system (
> <> ) we use different subdomains, so basically
>
> the page to be build is derived from the req.host (e.g.
> xxx.yyy.mkbok.nl) where xxx and yyy are variable.
>
> This is done by DNS records like * A ip1.ip2.ip3.ip4
You don't actually state what problem here. ;)
> My next problem seems mysql and mysqldb.
>
> Since I do not know which website is requested (multiple are running on
> that server) I open a database connection, do my stuff and close the
> connection,
>
> Again the database selection comes from req.host, and here the
> domainname is used for database selection.
>
>
>
> The system runs extremely well, but once in a while the webserver
> becomes so busy that it does not respond to page request anymore.
>
>.
>
> So logging in to the UPS remotely and power down the system by virtually
> unplugging the cable is the only (and BAD) solution.
Ouch. Maybe you can run a cron job every 5 minutes to check the load and
try to catch the problem before you hit 100%? I'm not suggesting this is
a permanent solution, just do it until you can track down the cause.
Is there a chance that mysql is hitting its connection limit? (although
I'm not sure if that would cause the behaviour you describe).
>
> So what is best practice when you have to connect to mysql with mysqldb
> in a mod_python environment keeping in mind that the database connection
> has to be build every time a visitor requests a page? Think in terms of
> a "globally" available db or db.cursor connection.
I don't think the performance penalty for creating a connection to mysql
is too great - at least compared to some other databases. You might want
to google for more information.
> Since global variables are troublesome in the .py contaning the handler
> I use a class from which an instance is created every time a client
> connects and the DB connection is global to that class, ist that wrong?
This looks OK.
>
>
> What happenens if mod_python finds an error before my mysqldb connection
> is closed (not that this happenes a lot, but it does happen, sorry)
It depends on how you handle the exception. This is why you should close
the connection in a registered cleanup function, which will always run.
>
> Also I do not understand the req.register_cleanup() method, what is
> cleaned up and what not?
Whatever function you register is run during the cleanup phase (unless
mod_python segfaults - but then you've got other problems). The cleanup
phase occurs after the response has been sent and anything registered is
guaranteed to run, regardless of what happens in prior phases. Typical
usage looks like this:
def handler(req):
conn = MySQLdb.connect(db='blah', user='blah', passwd='blah')
req.register_cleanup(db_cleanup, conn)
... do your request handling ...
return apache.OK
def db_cleanup(connection):
connection.close()
Jim | http://modpython.org/pipermail/mod_python/2006-July/021629.html | CC-MAIN-2017-51 | en | refinedweb |
On Mon, Feb 11, 2008 at 7:16 AM, <Nadia.Derbey@bull.net> wrote:> Index: linux-2.6.24-mm1/ipc/msg.c> ===================================================================> --- linux-2.6.24-mm1.orig/ipc/msg.c 2008-02-07 15:02:29.000000000 +0100> +++ linux-2.6.24-mm1/ipc/msg.c 2008-02-07 15:24:19.000000000 +0100...> +out_callback:> +> + printk(KERN_INFO "msgmni has been set to %d for ipc namespace %p\n",> + ns->msg_ctlmni, ns);> +}This patch has now made its way to mainline. I can see how this printkwas really useful to you while developing this patch. But does it addmuch value in a production system? It just looks like another piece ofclutter on the console to my uncontainerized eyes.-Tony | http://lkml.org/lkml/2008/4/29/575 | CC-MAIN-2017-51 | en | refinedweb |
Sp three black garments in stock.
Spock makes it possible to map tests very closely to scenario specifications using the same given, when, then format. In Spock, we could implement the first scenario as:
class SampleSpec extends Specification{ def "Scenario 1: Refunded items should be returned to stock"() { given: "that a customer previously bought a black sweater from me" // ... code and: "I have three black sweaters in stock." // ... code when: "he returns the black sweater for a refund" // ... code then: "I should have four black sweaters in stock." // ... code } }
What would be nice would be to ensure accurate mapping of test scenario requirements to test scenario implementations. We could get a way down this path if we could output the syntax of the given, when, then from our test. Spock allows us to add this functionality through its extension framework.
So, let's say our BA is really curious and wants more confidence from the developer that they stuck to the same given, when, then format and their code is in-sync. They want to get this information easily. The developer could provide this information by first defining this annotation:
import java.lang.annotation.* import org.spockframework.runtime.extension.ExtensionAnnotation @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @ExtensionAnnotation(ReportExtension) @interface LogScenarioDescription {}
Followed by this implementation:
import org.apache.log4j.Logger import org.spockframework.runtime.AbstractRunListener import org.spockframework.runtime.extension.AbstractAnnotationDrivenExtension import org.spockframework.runtime.model.FeatureInfo import org.spockframework.runtime.model.SpecInfo class LogScenarioDescriptionExtension extends AbstractAnnotationDrivenExtension { final static Logger logger = Logger.getLogger("scenarioLog." + ReportExtension.class); @Override void visitSpecAnnotation(Report annotation, SpecInfo spec) { spec.addListener(new AbstractRunListener() { @Override void afterFeature(FeatureInfo feature) { if (System.getEnv("logScenarios")) { logger.info("***SCENARIO TEST:*** " + feature.name) for (block in feature.blocks) { logger.info(block.kind); for (text in block.texts) { logger.info(text) } } } } }) } }
This will then be applied to the test:
@LogScenarioDescription class SampleSpec extends Specification { // ... }
When the test is executed, it gives the following output:
***SCENARIO TEST:*** Scenario 1: Refunded items should be returned to stock GIVEN that a customer previously bought a black sweater from me AND I have three black sweaters in stock. WHEN he returns the black sweater for a refund THEN I should have four black sweaters in stock.
Output to a specific logfile for scenario logging by using the following log4j:
log4j.rootLogger=INFO, stdout log4j.logger.scenarioLog.extension.custom=INFO, scenarioLog log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%m%n log4j.appender.scenarioLog=org.apache.log4j.FileAppender log4j.appender.scenarioLog.File=logs/scenario.log log4j.appender.scenarioLog.layout=org.apache.log4j.PatternLayout log4j.appender.scenarioLog.layout.ConversionPattern=%m%n
And now you have a logfile that your BA and QA can read! This helps foster an Agile culture of collaboration and ATDD where it's possible to check that test scenarios were implemented with everything agreed upon.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/extending-spock-outputting-the-givenwhenthen | CC-MAIN-2017-51 | en | refinedweb |
Hello All,
I seem to be having a relatively small problem with a Maze program I'm working on. Basically, I read a txt file containing a maze into a 12 x 12 2D array, but the problem is when I try to display it, none of the white spaces that are in the maze show up. I know it has something to do with the getline() function, but I have no clue as to where to put it.
Here is what an example of a txt file used contains:
~~~~~~~~~~~~ ~ = ? *~ ~ = ^ ? ^ *~ ~ = ^ ? ^ *~ ~ ^ ^ =~ ~***^~~~^ =~ ~ =~ ~ ===???^^^~ ~ ^~ ~~ ~~ ^~ ~ ~ $~ ~~~~~~~~~~~~
Here is my code so far:
#include "Maze.h" #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; Maze::Maze() { mazeStore[12][12] = ' '; } int Maze::inputMaze() { string fileName; char ch; cout << "Enter the file name: "; cin >> fileName; ifstream inFile; inFile.open(fileName.c_str()); if (!inFile) { cout << "File could not be opened." << endl; exit(1); } else { while (!inFile.eof()) { for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { inFile >> mazeStore[i][j]; } } } inFile.close(); } } void Maze::outputMaze() { cout << "MAZE:\n"; cout << " 111\n"; cout << " 123456789012\n"; for(int a = 0; a < 12; a++) { for(int b = 0; b < 12; b++) { cout << mazeStore[a][b]; } cout << endl; } return; }
Thanks in advance for any help given! | https://www.daniweb.com/programming/software-development/threads/265697/need-help-on-reading-txt-file-into-2d-array | CC-MAIN-2017-51 | en | refinedweb |
I can't say I fully understand namespaces, but I'm going to start using std::, I guess I'll wait until my book covers it.
#2
The question - Where is it applicable to use cin.ignore() and cin.get(), rather than just cin.get()?
I've noticed that in some cases I don't need to use cin.ignore() before cin.get(). | https://cboard.cprogramming.com/cplusplus-programming/67733-magnetos-journey-becoming-cplusplus-expert-2.html | CC-MAIN-2017-51 | en | refinedweb |
Label Rotation big problemPrideU2 Aug 11, 2006 8:01 AM
I have a simple task, to rotate the label, inside a repeater. The rotation works fine since the font is already emb.
This content has been marked as final. Show 12 replies
1. Re: Label Rotation big problemFlex harUI
Aug 11, 2006 6:00 PM (in response to PrideU2)For performance and code size reasons, the Flex containers do not factor rotation into the measurement and layout code. I would recommend making a subclass of Label (let's call it RotatedLabel) and beef up its measurement and other related code to handle the fact that it will be rotated. Once RotatedLabel returns the appropriate width/height it will layout appropriately, but if you want the labels so close together that the right edge of one overlaps the left edge of another, you might just be better off writing code to place them in a subclass of Canvas by overriding updateDisplayList.
2. Re: Label Rotation big problemPrideU2 Aug 14, 2006 8:48 AM (in response to Flex harUI)Good answer indeed. I'll go for the subclass then.
Thank you so much for the good idea.
Victor
3. Re: Label Rotation big problemPrideU2 Aug 14, 2006 11:22 AM (in response to PrideU2)I managed to reposition the labels using a class extendning the HBox, and working with the updateDisplayList. The problem is that the container object has its width large becuase its calculated by the width of all labels before rotation.
Is there a way to CROP a component? so i leave out the empty space I have now?
Victor
4. Re: Label Rotation big problemFlex harUI
Aug 14, 2006 12:51 PM (in response to PrideU2)You want to avoid using HBox/VBox and most of our containers as they measure assuming rotation=0. Your subclass should just subclass Label, or alternatively, subclass UIComponent and put the Label as the only child.
5. Re: Label Rotation big problemPrideU2 Aug 14, 2006 5:42 PM (in response to Flex harUI)excellent!!. It's working like a charm right now... I cannot thank you enough for the tips you gave me.
6. Label Rotation big problemrmarp Oct 10, 2006 4:18 PM (in response to PrideU2)Any chance you could post the code for this RotatedLabel class? I was trying it myself but I'm not completely clear what I should be doing in the subclass with respect to dimensions/position.
Thanks!
7. Re: Label Rotation big problemPrideU2 Oct 17, 2006 4:04 AM (in response to rmarp)Sure, no trouble at all, here's the code. Hope it helps, if you want , you can send me an email if you have further trouble.
It's solved simpler in this stage, first a style:
<mx:Style>
.estiloRotado {
fontFamily:"Arial";
fontSize: 12px;
fontAntiAliasType:advanced;
background-alpha:0;
}
</mx:Style>
<mx:Label</mx:Label>
I placed this label inside a repeater, which then uses another class to place the repeated labels, because as you know , once you rotate the label the X and Y work strangely. Here's the class that controls positioning , extending an HBOX, which includes the repeater of the rotated labels.
package
{
import mx.containers.VBox;
import mx.core.EdgeMetrics;
import mx.core.UIComponent;
import mx.containers.HBox;
import mx.containers.Canvas;
import mx.controls.Label;
public class LabelRotada extends HBox
{
public function LabelRotada() {
super();
}
override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
var obj:Label;
var posX:int=0;
for (var i:int = 0; i < numChildren; i++)
{
obj = Label(getChildAt(i));
obj.x=posX;
posX=posX+38;
}
}
}
}
8. Label Rotation big problemFlightGuy Jan 28, 2007 9:33 PM (in response to PrideU2)Here's the reusable solution - I've overridden two methods: measure() and updateDisplayList(). I don't call super.updateDisplayList, since I don't want it to truncate the label or wrap (a result of the width being less than the text width). I don't need it to support this - just have a single line of text, though you could extend Text rather than Label, and give it just a little attention in the updateDisplayList, duplicating what's done in the mx:Text class, but using unrotatedWidth and unrotatedHeight in place of unscaledWidth and unscaledHeight.
The reason for overriding updateDisplayList is to move the textField such that, after rotation, the top left corner of the box containing the rotated text is placed at the control's x and y coords. Because the width and height are now correct, this will correctly center as well.
Tim
import mx.controls.Label;
public class RotableText extends Label
{
private var unrotatedWidth:Number;
private var unrotatedHeight:Number;
override protected function measure():void{
super.measure();
var rotationRadians:Number = -rotation * Math.PI / 180;
unrotatedHeight = measuredHeight;
unrotatedWidth = measuredWidth;
measuredHeight = unrotatedHeight * Math.cos(rotationRadians) + unrotatedWidth * Math.sin(rotationRadians);
measuredWidth = unrotatedHeight * Math.sin(rotationRadians) + unrotatedWidth * Math.cos(rotationRadians);
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
var rotationRadians:Number = -rotation * Math.PI / 180;
var sinRot:Number = Math.sin(rotationRadians);
var cosRot:Number = Math.cos(rotationRadians);
textField.y = unrotatedWidth * sinRot * cosRot;
textField.x = -unrotatedWidth * sinRot * sinRot;
textField.setActualSize(unrotatedWidth, unrotatedHeight);
}
}
9. Re: Label Rotation big problemFlightGuy Jan 29, 2007 11:00 AM (in response to PrideU2)Here's a later version that supports rotation to any angle (the former only supported -90 < r < 0 - the normal rotation for angled text). I also streamlined it a bit so it only does the trig calculations when the rotation is set.
import mx.controls.Label;
public class RotableText extends Label
{
protected var unrotatedWidth:Number;
protected var unrotatedHeight:Number;
protected var sinRot:Number = 0;
protected var cosRot:Number = 1;
override public function set rotation(value:Number):void{
super.rotation = value;
var rotationRadians:Number = rotation * Math.PI / 180;
sinRot = Math.sin(rotationRadians);
cosRot = Math.cos(rotationRadians);
}
override protected function measure():void{
super.measure();
unrotatedHeight = measuredHeight;
unrotatedWidth = measuredWidth;
measuredHeight = Math.abs(unrotatedHeight * cosRot) + Math.abs(unrotatedWidth * sinRot);
measuredWidth = Math.abs(unrotatedWidth * cosRot) + Math.abs(unrotatedHeight * sinRot);
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
if (sinRot >= 0){
if (cosRot >= 0){
textField.x = unrotatedHeight * sinRot * cosRot;
textField.y = -unrotatedHeight * sinRot * sinRot;
} else {
textField.x = unrotatedWidth * (sinRot * sinRot - 1);
textField.y = -unrotatedHeight + unrotatedWidth * sinRot * cosRot;
}
} else {
if (cosRot >=0){
textField.x = -unrotatedWidth * sinRot * sinRot;
textField.y = -unrotatedWidth * sinRot * cosRot;
} else {
textField.x = - unrotatedWidth - unrotatedHeight * sinRot * cosRot;
textField.y = unrotatedHeight * (sinRot * sinRot - 1);
}
}
textField.setActualSize(unrotatedWidth, unrotatedHeight);
}
}
10. Re: Label Rotation big problemPrideU2 Jan 29, 2007 11:10 AM (in response to PrideU2)great, thanks for the update!
11. Re: Label Rotation big problemGil1 Oct 2, 2007 11:19 AM (in response to PrideU2)Hi,
I would like to know how to use this class.
I have tried adding a RotableText element directly in the MXML section like:
<local:RotableText
It does not produce a compilation error, but when I run it the screen appears blank.
Then, I tried with AS like:
var text1:RotableText = new RotableText;
text1.rotation =90;
text1.x =100;
text1.y =100;
text1.text = "Hello world";
But it produces a compilation error saying "Access to an undefined property text1"
Gilbert
12. Re: Label Rotation big problemJabbyPandaUA Oct 3, 2007 3:12 AM (in response to PrideU2)You must embed fonts in order to view the text while rotating it. | https://forums.adobe.com/thread/3275 | CC-MAIN-2017-51 | en | refinedweb |
Module: AWS
- Defined in:
- lib/core.js
Overview
The main AWS namespace
Defined Under Namespace
Modules: EventListeners Classes: ACM, APIGateway, AlexaForBusiness, AppStream, AppSync, ApplicationAutoScaling, Athena, AutoScaling, Batch, Budgets, CUR, Cloud9, CloudDirectory, CloudFormation, CloudFront, CloudFront, CloudHSM, CloudHSMV2, CloudSearch, CloudSearchDomain, CloudSearch, CloudTrail, CloudWatch, CloudWatchEvents, CloudWatchLogs, CodeBuild, CodeCommit, CodeDeploy, CodePipeline, CodeStar, CognitoIdentity, CognitoIdentityCredentials, CognitoIdentityServiceProvider, CognitoSync, Comprehend, Config, ConfigService, CostExplorer, CredentialProviderChain, Credentials, DAX, DMS, DataPipeline, DeviceFarm, DirectConnect, DirectoryService, Discovery, DynamoDB, DynamoDBStreams, DynamoDB, EC2, EC2MetadataCredentials, ECR, ECS, EFS, ELB, ELBv2, EMR, ES, ElastiCache, ElasticBeanstalk, ElasticTranscoder, Endpoint, EnvironmentCredentials, FileSystemCredentials, Firehose, GameLift, Glacier, Glue, Greengrass, GuardDuty, Health, HttpClient, HttpRequest, HttpResponse, IAM, ImportExport, Inspector, IoTJobsDataPlane, Iot, IotData, KMS, Kinesis, KinesisAnalytics, KinesisVideo, KinesisVideoArchivedMedia, KinesisVideoMedia, Lambda, Lambda, LexModelBuildingService, LexRuntime, Lightsail, MQ, MTurk, MachineLearning, MarketplaceCommerceAnalytics, MarketplaceEntitlementService, MarketplaceMetering, MediaConvert, MediaLive, MediaPackage, MediaStore, MediaStoreData, MetadataService, MigrationHub, Mobile, MobileAnalytics, OpsWorks, OpsWorksCM, Organizations, Pinpoint, Polly, Pricing, RDS, RDS, RDS, RDS, RDS, Redshift, Rekognition, RemoteCredentials, Request, ResourceGroups, ResourceGroupsTaggingAPI, Response, Route53, Route53Domains, S3, SAMLCredentials, SES, SMS, SNS, SQS, SSM, STS, SWF, SageMaker, SageMakerRuntime, ServerlessApplicationRepository, Service, ServiceCatalog, ServiceDiscovery, SharedIniFileCredentials, Shield, SimpleDB, Snowball, StepFunctions, StorageGateway, Support, TemporaryCredentials, Translate, WAF, WAFRegional, WebIdentityCredentials, WorkDocs, WorkSpaces, XRay
Constant Summary
- SimpleWorkflow =
AWS.SWF
- VERSION =
'2.167.0'
- config ⇒ Object static readwrite
Reset configuration.
Property Summary collapse
- ECSCredentials ⇒ Object static readwrite
Represents credentials received from relative URI specified in the ECS container.
- events ⇒ AWS.SequentialExecutor static readonly
A collection of global event listeners that are attached to every sent request.
Property Details
config ⇒ Object (static, readwrite)
Reset configuration
ECSCredentials ⇒ Object (static, readwrite)
This feature is not supported in the browser environment of the SDK.
Represents credentials received from relative URI specified in the ECS container.
This class will request refreshable credentials from the relative URI specified by the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or the AWS_CONTAINER_CREDENTIALS_FULL_URI environment variable. If valid credentials are returned in the response, these will be used with zero configuration.
This credentials class will by default timeout after 1 second of inactivity and retry 3 times. If your requests to the relative URI are timing out, you can increase the value by configuring them directly:
AWS.config.credentials = new AWS.ECSCredentials({ httpOptions: { timeout: 5000 }, // 5 second timeout maxRetries: 10, // retry 10 times retryDelayOptions: { base: 200 } // see AWS.Config for information }); | http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS.html | CC-MAIN-2017-51 | en | refinedweb |
QNetworkManager : resend qnetworkrequest before end make it crash
Hey,
I'm working on an embedded buying application. When the customer add a product to his cart, i send a QNetworkRequest with a webservice as URL to update the backoffice. But if the customer double click the add-to-cart button, i think that the request is resend before the end of the first and make the application exit with error : "QEventLoop::exec: instance 0x423190 has already called exec()".
Here is my doRequest function :
const QString& Request::doRequest(const QString& request, RequestType type, const QByteArray& data) {(); delete _reply; return (result); } delete _reply; return (""); }
Does anyone encounter the same problem ? Is there a work around?
One possible solution is to launch one thread for each request
- SGaist Lifetime Qt Champion
Hi and welcome to devnet,
That's because you are calling exec on
_eventLooptwice. You should rather use a local QEventLoop or not allow the query to start if already in progress. | https://forum.qt.io/topic/64927/qnetworkmanager-resend-qnetworkrequest-before-end-make-it-crash | CC-MAIN-2017-51 | en | refinedweb |
We are familiar with the Fibonacci series and algorithm to find the n th Fibonacci number using recursion. which may be as follows.
def fibonacci(n):factorial if n<2 : return n else: return fibonacci(n-1) + fibonacci(n-2)
Which seems to be a simple solution. But in actual practice using recursion is a tedious task for the computer. The complexity of calculation increases incredibly with an increase in single number. with this algorithm to compute fibonacci(30), it will take few seconds to calculate the result( result is 832040 ). Further increase in number may not produce any result due to stack overflow. Recursion uses stacks to remember function calls and every computer has a stack size limit.If stack cannot hold these recursive function calls it will not produce any result or sometimes take long time to print result.So Even though recursion makes the solution is simple, it is always advisable to stay out from it.
But using python dictionary we can reduce the complexity of recursive function call by remembering the results of each function call and thus reusing the value straight away with out function call. It will dramatically reduce the recursive function call complexity. we can even compute fibonacci(220) ( I have done it in less than 1sec) easily. Here is the program.
def fib(n): if n<2 : return n elif not n in fib_dict : fib_dict[n]= fib(n-1) + fib(n-2) return fib_dict[n] #dictionary which store Fibonacci values fib_dict = {} result = fib(220) print result # result :4244200115309993198876969489421897548446236915 | https://jineshpaloor.wordpress.com/2011/07/09/optimized-program-to-find-the-n-th-fibonacci-number-using-python/ | CC-MAIN-2017-51 | en | refinedweb |
Curate makes it easy to quickly expose database queries to an express-api. It also features a client component that makes it easy to consume those API methods.
It works especially well with modella and chino.
app.js
var app = express(),
curate = require('curate');
curate.app = app; curate.namespace = 'api/v1'
user-model/server.js
var curate = require('curate'), db = require('mong')('localhost/db'); var User = module.exports = function(attrs) { this.username = attrs.username; this.password = attrs.password; this.email = attrs.email; } User.allUsers = function(cb) { db.get('users').find({}, cb); } curate('users/all', User.allUsers);
You can now visit and get JSON of the users
returned by the
User.allUsers query.
Curate also provides easy consumption of the generated API.
user-model/client.js
var curate = require('curate'); var User = module.exports = function() { } User.allUsers = curate('users/all', User);
This maps the client-side User.allUsers to hit
/api/v1/users/all and use the
resulting JSON in a callback. The resulting function has the same fingerprint as
the server-side function. It expects a
cb(err, results) for its argument.
The second argument passes the JSON returned into a constructor. ie. Instead of passing just JSON in, it will pass the JSON to the constructor to make full-fledged objects.
Sometimes you don't want the raw-db exposed to the client. For this, you can
specify the filter method in the
app.js
For example:
var app = express(), curate = require('curate'); curate.app = app; curate.filterMethod = 'filter';
Now, if an instance has a method named
filter it will call it and only pass
the results of that method into the exposed API. | https://www.npmjs.com/package/curate | CC-MAIN-2017-51 | en | refinedweb |
Graham Dumpleton wrote:
>
> Yes, except that there are really two issues here. The first as you
> highlight is that all scripts run as the same user.
>
> The bigger immediate problem is the potential cross pollution of Python
> modules and the visibility of another users Python modules within the
> executing process. This will occur where requests for each user are
> handled within the context of one Python interpreter instance, which is
> the default if both users requests are handled within the context of the
> same virtual host.
>
> With a bit of work, one could specify in the main Apache configuration
> file that each user has a distinct interpreter using PythonInterpreter
> directive, but there is no way of stopping the user changing it to
> something else in .htaccess file, bar preventing the use of .htaccess
> file altogether.
>
> The consequence of this is that I could use PythonInterpreter to name
> some other users interpreter and create special handlers that allowed
> me to then browse all his loaded modules looking for senstive data
> such as login details, or cached data out of a database etc.
>
> What is really required in mod_python is a way for an administrator to
> set PythonInterpreter in the main Apache configuration differently for
> differently parts of the URL namespace and then set some other option
> to say that it cannot be overridden in a .htaccess file at all.
>
> This way the administrator has better control and can ensure some
> seperation. I'm not sure though whether there is a means by which it
> could be added to mod_python such that this could be done. Would need
> some digging into the Apache internals.
>
> This wouldn't solve the problem completely though, as the fact that
> all users code runs as the same actual user, means that you could just
> read the source code in direct as text and steal it that way. This means
> someone is doing it deliberately, but at present with how mod_python
> works, the cross pollution of in memory modules can lead to unexpected
> behaviour without even trying. Hopefully mod_python 3.3 will solve this
> with the module importing system being reimplemented.
>
> So yes, your concerns are quite valid and no there aren't any simple
> answers. :-(
>
> Graham
>
That is why I was attempting to get the mod_python behind a reverse
proxy to work. At least that way, the apache instance is running as the
user that owns the python modules. There are also implications there,
but those are more easily solved. In the future, I will try and go with
a complete virtual server approach, but my machine's resources will not
allow that now.
Anyhow, thanks for all the great insight.
-Roberto
--
Roberto C. Sanchez | http://modpython.org/pipermail/mod_python/2005-December/019792.html | CC-MAIN-2017-51 | en | refinedweb |
Generics in the .NET Framework.
This topic provides an overview of generics in the .NET Framework and a summary of generic types or methods. It contains the following sections:.
The following terms are used to discuss generics in the .NET Framework: in Generics.
Constraints are limits placed on generic type parameters. For example, you might limit a type parameter to types that implement the System.Collections.Generic.IComparer.<T>, FindLast<T>, and FindAll.
For more information, see "Nested Types" in MakeGenericType.
The .NET Framework provides a number of generic collection classes in the following namespaces:
The System.Collections.Generic namespace catalogs most of the generic collection types provided by the .NET Framework, such as the List<T> and Dictionary<TKey, TValue> generic classes.
The System.Collections.ObjectModel namespace catalogs . | https://msdn.microsoft.com/en-us/library/vstudio/ms172192 | CC-MAIN-2015-14 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.