text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringclasses 91
values | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
|---|---|---|---|---|---|
How.
First, make sure you buy an Arduino Duemilanove. Yes, there are newer devices out there. No, you do not want them. They are all supposed to use the same code, but this code is sensitive to the timing on the Duemilanove. Use another board and you'll be fighting issues all the way. After over a year of this, I just switched and I'm glad I did.
Second, the Twitter world moves much faster than it did. 30 tweets of the original terms go by in less than a second. Since everything is computed in tweets per minute, this obviously won't do. Everything registers off the scale.
You'll have to substitute this code in TwitterParser.cpp to compensate.
#ifdef DEBUG
m_printer->println("assuming tweet was from yesterday");
#endif // #ifdef DEBUG
}
long seconds = time1 - time2;
return seconds / 60;
}
with
#ifdef DEBUG
m_printer->println("assuming tweet was from yesterday");
#endif // #ifdef DEBUG
}
long seconds = time1 - time2;
return seconds;
}
I also had to modify my LED.cpp file to make sure colors showed up properly. In particular, I had to adjust the array values in the beginning to accurately show colors with my LED -- apparently my red isn't as bright as the blue and green and so full value on all three skews the colors. I added the following text to the WorldMood.cpe to make it easy to test light colors -- right after the device starts up, it triggers the light to the values specified. Value range goes from 0 to 255.
//a way to quickly test colors and connections
analogWrite(redPin, 255);
analogWrite(greenPin, 35);
analogWrite(bluePin, 0);
It goes immediately after this line:
LED led(Serial, redPin, greenPin, bluePin, fadeDelay);
I am still adjusting my search criteria and making minor adjustments, but this solves most of the "out of the box" issues I've seen people experience..
Twitter has changed its API and now the query returns errors.
Is there a way i can still make it ?
would be a great help if you can sugest a way to do this ?
Unfortunately, no. I've not been able to get it to interface with the new API.
Is there anyone out there who has an idea of making code for aduinos?!
By the way, I'm using an arduino uno. Thankyou. Please reply.
excellent idea, i think the search terms could be 'work in progress' but other than that a really cool idea.
I second you, too.
So can this still be done ?
If yes , do i need to buy the same hardware?
Since all the heavy work runs on the server, the mood could be updated much faster than the Arduino, and it would save battery life.
I'd write the server software myself, except I suck at interfacing with Twitter... :P
Can you actually make it passively receive the data in a periodical manner? or wait for a device or app to send a 'mood' to it whenever this device receives a twitt? I know it is always possible, but what could be the implementation please? do you have any idea or example?
As I would like to make one that ideally be waiting and be triggered so to consume the minimum power
Long story short: I started working on this using the 1.01 Arduino IDE, an Arduino Uno and an LED "ball" which I found referenced here:
I liked the look of that ball, and thought to myself "what can I do with it that is cool". I bought one, and then decided to see where I could take this instructable.
Like many of you, I ran into all sorts of errors when trying to load up the sketch and libraries to make it work.
After hacking away at it for about 8 hours over the last week, I've gotten it compiling and running on the new version of Arduino, with an Uno and not the Duemilanove. Once I get things a bit cleaner, and I document what changes I actually made,
I will post the full code somewhere and add it to this comment thread.
The quick overview:
1) Wired up my LED. I am using the LED array that came inside the ball. I also wired up a Sparkfun RGB LED Breakout to see if it would work across both. (). It does. I had to make the code change referenced in the comments and on this blog to make the colors match best with the Sparkfun LED kit. ()
2) In each of the libraries that were included, I had to update the code to replace: #include "WProgram.h" with #include
3) The timing and error handling are still pretty screwed up, and not where they should be. I am going to work on that next. The code will execute, and throw some errors, but in true arduino fashion, if you let it run, it will power through things and get to the next step.
4) Pay attention to the comments in "step 6", download the code: I HAD to do this. If you have a newer board then you may need to change this struct SPI_UART_cfg SPI_Uart_config = {0x50,0x00,0x03,0x10}; to this: struct SPI_UART_cfg SPI_Uart_config = {0x60,0x00,0x03,0x10};
5) Once I did those things, I got it to compile and pushed to the Arduino.
It would go out and attempt to make a request to twitter, but I'd get a 404 from twitter. This caused me to scratch my head for a day, contemplate rewriting the entire WIFLY library and then it hit me...
The http request had something wrong with it. In the worldmood sketch, you must look at the lines where you define the search request and make a small change, appending HTTP 1.0 to the end of each.
It WILL NOT WORK UNLESS YOU DO THIS.
These lines:
prog_char string_1[] PROGMEM = "GET /search.json?q=\"happiest\"+OR+\"so+happy\"+OR+\"so+excited\"+OR+\"i'm+happy\"+OR+\"woot\"+OR+\"w00t\"&rpp=30&result_type=recent";
Should become:
prog_char string_1[] PROGMEM = "GET /search.json?q=\"happiest\"+OR+\"so+happy\"+OR+\"so+excited\"+OR+\"i'm+happy\"+OR+\"woot\"+OR+\"w00t\"&rpp=30&result_type=recent HTTP/1.0";
I think that is about it, but I need to go back and look at everything to ensure that there weren't other items necessary.
The one item I haven't addressed yet is that when left as-is, the twitter search for "envy" still fails. I can't understand why, but I haven't taken much of a look at it yet.
To get past this, I changed the search string from the original to this:
prog_char string_4[] PROGMEM = "GET /search.json?q=\"i+wish+i\"+&rpp=60&result_type=recent HTTP/1.0";
I basically got rid of the search and just put in "I wish I" for the time being.
So, there you have it. If anyone wants to continue to improve, the army of "modern" Arduino hackers can start from this modified code that indeed works. (yay!)
Enjoy, and please share comments as you make progress.
Dave
#include "WProgram.h"
with
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
(source:)
I compiled this code and getting me lot of errors..
plz help me!!!
How long are you experiencing the 9V battery last?
Thanks for this, it's going to get me working with acrylic, something I haven't done yet.
If I figure out how to make it work again, I'll post the code here. If not..... I guess I'll hope someone else figures it out.
I was still excited to see the concept on the international stage.
Or perhaps with an ethernet shield? I'm really interested!
It only updates once/day, but might be interesting to monitor over time.
will the script be different?
|
http://www.instructables.com/id/Twitter-Mood-Light-The-Worlds-Mood-in-a-Box/C5NO2DFG962KO2Z
|
CC-MAIN-2014-49
|
refinedweb
| 1,308
| 73.27
|
PloneFlashUpload 1.1 (Beta release) (Jan 20, 2008)
This is not a final release. Experimental releases should only be used for testing and development. Do not use these on production sites, and make sure you have proper backups before installing.
Plone 3.0 compatibility release. No functionality changes.
For additional information about this project, please visit the project page .
Available downloads
For all platforms (0 kB)
Release Notes
Plone Flash Upload
Plone Flash Upload is a Plone add-on product which adds an upload tab to folders which takes the user to an upload form. This upload form uses a flash applet to provide the ability to upload multiple files simultaneously.
Requirements
The 1.1 version only works on plone 3.0. Also you'll apparently need zope 2.10.5 as otherwise lib/python packaged can't be in the Products namespace.
- Zope 2.10.5+
- Plone 3.0.x
Installation
Option one: use buildout and specify 'Products.PloneFlashUpload' as an egg dependency. (Or depend on it in your own product's setup.py).
Option two: simply extract downloaded archive into the $INSTANCE_HOME/lib/python registered.
Reinout van Rees has updated the product for plone 3.0 and turned it into an egg for Zest software.
Change log
Release 1.1 beta2
- I stupidly forgot to do an svn up so that the z3c.widget.flashupload didn't get included... [Reinout van Rees]
Release 1.1 beta1
- Switched from being a Product to a lib/python library. [Reinout van Rees]
- Switched to genericsetup for the definition of our actions. [Reinout van Rees]
- First rough update to get it working on plone 3.0 [Reinout van Rees]
|
http://plone.org/products/ploneflashupload/releases/1.1
|
crawl-002
|
refinedweb
| 277
| 70.5
|
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo
On Mon, 2002-08-19 at 17:45, Matt Feifarek wrote:
> | Well, most of the time we just put persistent values in module-level
> | globals (remembering to do proper locking via threading.Lock, and often
> | using dictionaries to organize the data).
>
> Can you elaborate on that threading.lock bit a little? We use a similar
> technique, and don't mess with threading.
It's not always necessary to use locks, but everything in Webware has to
be threadsafe -- servlets are run in their own threads, and those
threads can simultaneously access the same function or method. More
specifically, you have to be careful with writing to global resources
(module-level variables, class variables, etc). Threading bugs will
often only arise under heavy usage, and are a pain to debug, so it's
worth being careful.
For an example, I use a factory pattern that create an object based on
an ID, but if the object by that ID already exists then that object is
recycled. Actually, instead of giving pseudocode, I'll just list that
factory, which uses locks. It would work without locks, but it could
not ensure that there would never be two objects from the same ID.
(Actually, instead of ID, it uses a tuple of arguments to the
constructor, but in practice I only use a single integer ID)
from threading import Lock
class ParamFactory:
def __init__(self, klass):
self._lock = Lock()
self._cache = {}
self._klass = klass
def __call__(self, *args):
self._lock.acquire()
if not self._cache.has_key(args):
value = self._klass(*args)
self._cache[args] = value
self._lock.release()
return value
else:
self._lock.release()
return self._cache[args]
Only in a very specific, and fairly unlikely situation would this lock
be necessary. Say you do something like:
# setup...
class _User:
def __init__(self, userID):
...
# User is my faux-class, actually a factory
User = ParamFactory(_User)
# thread 1 does:
u = User(userID)
# thread 2 does the same thing:
u2 = User(userID)
If both threads are executing this instruction at once, and thread 1
gets to the "if not self._cache.has_key(args)", but hasn't finished
"self._cache[args] = value" before thread 2 gets to that same if
statement, then two instances of the object will be created. As you
might expect, this might only happen one time in a million. Or it may
only occur under some specific and (at least initially) unusual
circumstance. But other kinds of global-writes can cause these race
conditions quite often.
Ian
View entire thread
|
http://sourceforge.net/p/webware/mailman/message/12378340/
|
CC-MAIN-2015-22
|
refinedweb
| 438
| 58.08
|
Build a chat app with Vue.js and Laravel
Familiarity with JavaScript and PHP would be beneficial, but isn’t compulsory to complete this tutorial as I will also show you how to setup Laravel from scratch.
What you will build
In this tutorial you will do the following:
- Create a Pusher account.
- Set Laravel broadcasting to use Pusher Channels.
- Connect a Vue.js client to Channels with Laravel Echo.
- A simple form to send messages.
- Display received messages in a list.
The code of the completed demo is available on GitHub.
1. Getting started
Before we dive into the tutorial there are a few steps you need to take to get set up.
Pusher account
If you don’t already have one you should go ahead and register for a Pusher account. The Channels sandbox plan is completely free and will be more than ample to complete this sample project.
How to create a Channels app
Once you have signed up for a Pusher account you need to create a Channels app by clicking “Get Started” under Channels:
Follow the steps in the dialog box to name your app and choose a preferred cluster location from the list. The tech stack settings are optional, they are just for the getting started page.
From the App Keys page note down the
app_id,
key,
secret and
cluster as you will need these to connect to your Channels app.
Set up a Laravel environment
For this tutorial, you will need PHP 8, Composer 2 and Node.js 16. For MacOS I recommend installing them with Homebrew. For Windows see instructions for PHP, Composer and Node.
2. Creating the project
We’re going to use Composer’s create-project command to download and install the latest starter Laravel project into a “laravel-chat” folder. Our pusher- library supports a minimum Laravel version of 8.29.
composer create-project laravel/laravel laravel-chat
You can take a look at this now:
cd laravel-chat php artisan serve
Go to in your web browser and you should see a Laravel starter welcome page.
3. Set up Pusher
Switch the broadcast driver to Pusher
We need to tell Laravel to use Pusher Channels for realtime updates. Register the Broadcast application service by opening
config/app.php and uncommenting this line:
// App\Providers\BroadcastServiceProvider::class,
In your project root’s
.env file, change the broadcast driver from its default “log” value to “pusher.
// .env BROADCAST_DRIVER=pusher
If you scroll further down this file, you can see some of the Pusher environment variables are already there. Laravel already integrates some of the Pusher configuration, so you just need to fill in keys you got when you created your Channels app.
PUSHER_APP_ID=123456 PUSHER_APP_KEY=192b754680b23ce923d6 PUSHER_APP_SECRET=a64521345r457641sb65pw PUSHER_APP_CLUSTER=mt1
Install the Channels SDK
Though Laravel already has some Pusher integration, we still need to install the Pusher PHP SDK:
composer require pusher/pusher-php-server
Install front-end dependencies
We will need Laravel Echo, which is the javascript library for listening to broadcast events, and pusher-js for connecting your client to Pusher. Install them by navigating into the project directory and running this npm command (which is javascript package manager installed as part of Node):
npm install --save laravel-echo pusher-js
Now you can enable your Pusher credentials in your Echo client. Uncomment these statements at the bottom of
resources/js/bootstrap.js.
\\ import Echo from 'laravel-echo'; \\ window.Pusher = require('pusher-js'); \\ window.Echo = new Echo({ \\ broadcaster: 'pusher', \\ key: process.env.MIX_PUSHER_APP_KEY, \\ cluster: process.env.MIX_PUSHER_APP_CLUSTER, \\ forceTLS: true \\ });
And thats it. The public key and cluster is already taken from your .env file that we previously updated.
4. Add the login system
Add the login pages
Let’s add the login pages. In the terminal, install the laravel/ui package:
composer require laravel/ui
Then the following command will enable the Vue javascript framework and add a login page to your project:
php artisan ui vue --auth
Finally install the dependencies and compile it with the below command:
npm install && npm run dev
Take a look at your new login page by starting your webserver:
php artisan serve
Then go to in your web browser. On the Laravel welcome screen, you will see a new login and register button on the top right.
Create the database
Before we can register a user, we will need to connect to a database for Laravel to use. Create an empty sqlite file with
touch database/db.sqlite
and in your
.env, replace this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=
with this:
DB_CONNECTION=sqlite DB_DATABASE=<Full path to db.sqlite file>
Make sure you replace
<Full path to db.sqlite file> with the actual path to the file, for example
/Users/user/laravel-chat/database/db.sqlite.
Right now
db.sqlite is just an empty file. We will first need to insert Laravel’s default
users table (and a few other user account related tables) with the following command:
php artisan migrate
In your terminal, run
php artisan serve, navigate to then click on the register link and fill in the form to create a login. You should now be logged in with your newly created user. We’re going to use this user to authenticate for some of the message receiving later on.
5. The message model
Create the model
Create a
Message model along with the migration file by running the command:
php artisan make:model Message --migration
Add the
$fillable attribute into the Message class in your newly created
Message.php in
app/Models:
class Message extends Model { use HasFactory; //insert the line below protected $fillable = ['message']; }
Add
user_id and
message columns to your messages schema by editing your newly created
<creation_date_>create_messages_table.php in database/migrations so it looks like this:
//database/migrations/<creation_date_>create_messages_table.php Schema::create('messages', function (Blueprint $table) { $table->id(); $table->timestamps(); //insert the lines below $table->integer('user_id')->unsigned(); $table->text('message'); });
Now run the migrations script to add the messages table to our database:
php artisan migrate
User To Message Relationship
We will need to setup a one-to-many relationship between users and their many messages. In
app/Models/User.php add the
messages() function to the User class:
class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; protected $fillable = ['name','email','password',]; protected $hidden = ['password','remember_token',]; protected $casts = ['email_verified_at' => 'datetime',]; //Add the below function public function messages() { return $this->hasMany(Message::class); } }
Then we define the inverse direction in the
Message class in
app/Models/Message.php:
class Message extends Model { use HasFactory; protected $fillable = ['message']; //Add the below function public function user() { return $this->belongsTo(User::class); } }
We’re going to to use these functions to retrieve the messages for a user and vice versa.
7. Defining routes
Thats the database setup part done, we can move onto the server api. We will define some routes for our server. Routes are an important part of a Laravel application, so I recommend looking at their documentation here to get a feel for what is going on. Once you’ve done that, add these routes to
routes/web.php:
Route::get('/chat', [App\Http\Controllers\ChatsController::class, 'index']); Route::get('/messages', [App\Http\Controllers\ChatsController::class, 'fetchMessages']); Route::post('/messages', [App\Http\Controllers\ChatsController::class, 'sendMessage']);
Laravel has already put in a dashboard /home route for you. I’m going to leave this intact to keep this tutorial as simple as possible.
8. ChatsController
We’re going to create a ChatsController to handle the requests for the routes we just added. Take a brief look at the documentation here to understand this concept. Then run this command:
php artisan make:controller ChatsController
This will add a ChatsController.php file into app/Http/Controllers/. We’re going to add some functions to it, so first import our Message model at the top along with the existing
use Illuminate\Http\Request;:
use App\Models\Message;
We’re also going to add some authorisation in this controller, so import that as well:
use Illuminate\Support\Facades\Auth;
In the ChatsController class, add these functions:
class ChatsController extends Controller { //Add the below functions public function __construct() { $this->middleware('auth'); } public function index() { return view('chat'); } public function fetchMessages() { return Message::with('user')->get(); } public function sendMessage(Request $request) { $user = Auth::user(); $message = $user->messages()->create([ 'message' => $request->input('message') ]); return ['status' => 'Message Sent!']; } }
$this->middleware('auth') in
__contruct() will only allow authorised users to access ChatsController’s methods. The
index() function will return a chat view which we will create later.
fetchMessages() returns a json of all messages with the user that sent that message. Lastly, the
sendMessage() function will use the
create() method to save the message into the database.
If you’re not familiar with database Object Relational Mappers and how our message gets saved into the messages table, read Laravel’s documentation to enhance your understanding.
We haven’t added the code to actually send the message yet. We will do that shortly.
9. Creating the Chat App view
We’re going to put the chat messages inside a Bootstrap 4 card to make it look nice. Create a new
resources/views/chat.blade.php file and paste this into it:
<!-- resources/views/chat.blade.php --> @extends('layouts.app') @section('content') <div class="container"> <div class="card"> <div class="card-header">Chats</div> <div class="card-body"> <chat-messages :</chat-messages> </div> <div class="card-footer"> <chat-form v-on:</chat-form> </div> </div> </div> @endsection
Notice we have two custom tags:
chat-messages and
chat-form, these are Vue components which we’ll create soon. The
chat-messages component will display our chat messages and the
chat-form will provide an input field and a button to send the messages. Notice
v-on:messagesent="addMessage" :user="{{ Auth::user() }}": later on this will receive a messagesent event from the
chat-form component and pass the user property to the
chat-form.
Create a new
ChatMessages.vue file within
resources/js/components and paste the code below into it:
// resources/js/components/ChatMessages.vue <template> <ul class="chat"> <li class="left clearfix" v- <div class="clearfix"> <div class="header"> <strong> {{/js/components and paste the code below into it. I’ve added comments to explain what each part does.
//resources/js/components/ChatForm.vue <template> //Display an input field and a send button. <div class="input-group"> //Input field. <input id="btn-input" type="text" name="message" class="form-control input-sm" placeholder="Type your message here..." v- //Button <span class="input-group-btn"> //Call sendMessage() this button is clicked. <button class="btn btn-primary btn-sm" id="btn-chat" @ Send </button> </span> </div> </template> <script> export default { //Takes the "user" props from <chat-form> … :</chat-form> in the parent chat.blade.php. props: ["user"], data() { return { newMessage: "", }; }, methods: { sendMessage() { //Emit a "messagesent" event including the user who sent the message along with the message content this.$emit("messagesent", { user: this.user, //newMessage is bound to the earlier "btn-input" input field message: this.newMessage, }); //Clear the input this.newMessage = ""; }, }, }; </script>
If you take a look at
resources/views/chat.blade.php, you will notice in the
<chat-form> tag there is a
v-on:messagesent="addMessage". This means that when a
messagsent event gets emitted from the above code, it will be handled by the
addMessage() method in the
resources/js/app.js root Vue instance. We have another tutorial on emitting in Vue here. That tutorial uses
v-on: but they are equivalent.
@instead of
Next, we need to register our component in the root Vue instance. Open
resources/js/app.js and add the following two components after the example-component Vue component that is already there:
//resources/js/app.js Vue.component('example-component', require('./components/ExampleComponent.vue').default); //Add these two components. Vue.component('chat-messages', require('./components/ChatMessages.vue').default); Vue.component('chat-form', require('./components/ChatForm.vue').default);
At the bottom of this file, there exists already a default root Vue instance
app. Add to it the following:
//app and el already exists. const app = new Vue({ el: '#app', //Store chat messages for display in this array. data: { messages: [] }, //Upon initialisation, run fetchMessages(). created() { this.fetchMessages(); }, methods: { fetchMessages() { //GET request to the messages route in our Laravel server to fetch all the messages axios.get('/messages').then(response => { //Save the response in the messages array to display on the chat view this.messages = response.data; }); }, //Receives the message that was emitted from the ChatForm Vue component addMessage(message) { //Pushes it to the messages array this.messages.push(message); //POST request to the messages route with the message data in order for our Laravel server to broadcast it. axios.post('/messages', message).then(response => { console.log(response.data); }); } } });
As you can see in the above Vue code, we are using the Axios javascript library to retrieve and send data to our Laravel backend server.
Finally, we should also create a link so the user can click to navigate to the chat view. In resources/views/home.blade.php, add this just under the
{{ __('You are logged in!') }} line:
<a href="{{ url('/chat') }}">Chat</a>
Before we go onto the next section, let’s take a look at what your application is capable of so far. Run the terminal commands
npm run dev and
php artisan serve, navigate to and login with the user you created back in section 4. Click on the “Chat” link you added just now on the home page to load the Vue chat app.
Now let’s try sending a message to another user.
Register a second user. Open another private window and log in is your second user. Send a message from your first user. Notice how the chat window doesn’t update on the second user’s chat app. However if you refresh the page, the message is now present. This is because the recipient chat window retrieved the message from the database instead of receiving live updates from Pusher Channels. We will do this next.
10. Broadcasting Message Sent Event
To add the realtime interactions to our chat app, we need to broadcast some kind of events based on some activities. In our case, we’ll fire a
MessageSent when a user sends a message. First, we need to create an event called
MessageSent:
php artisan make:event MessageSent
This will create a new
MessageSent event class within the
app/Events directory. Open it and import our user and message models:
//app/Events/MessageSent.php namespace App\Events; //Add the following two models use App\Models\User; use App\Models\Message; ... ...
Add the implements
ShouldBroadcast interface to the
MessageSent class:
class MessageSent implements ShouldBroadcast { ... }
Inside the class, add these two public properties:
public $user; public $message;
There is already an empty
__construct() function, modify it to the following:
public function __construct(User $user, Message $message) { $this->user = $user; $this->message = $message; }
Set the channel to broadcast onto the chat private channel:
public function broadcastOn() { return new PrivateChannel('chat'); }
Since we created a private channel by returning a
PrivateChannel('chat') instance, only authenticated users will be able to listen to it. So, we need a way to authorise that the currently authenticated user can actually listen on the channel. This can be done by adding the following channel in the
routes/channels.php file:
Broadcast::channel('chat', function ($user) { return Auth::check(); });
Finally, we need to go back to
ChatsController and add in the statements to actually send a message onto Channels (we didn’t before). In
app/Http/Controllers/ChatsController.php import the
MessageSent event we just made:
use App\Events\MessageSent;
Just before the return statement at the bottom of the
sendMessage() function, add the important
broadcast() call to broadcast to Pusher.
broadcast(new MessageSent($user, $message))->toOthers();
We’ve now finished the Laravel server side part! Run
php artisan serve and load the chat app. Open your debug console in your Pusher dashboard and send a message from the chat app. You will see this log:
If Pusher isn’t getting the request from you, you may able to find an error message in storage/logs/laravel.log. Failing that, compare your code with my repository.
For our next and final part, we’re going to get Laravel Echo to listen for new messages.
11. Laravel Echo
We will use Laravel Echo to subscribe to the private chat channel and
listen() for the
MessageSent event. Add this in
resources/js/app.js inside
created(){…} after
this.fetchMessages():
window.Echo.private('chat') .listen('MessageSent', (e) => { this.messages.push({ message: e.message.message, user: e.user }); });
Upon receiving a
MessageSent event, the above code will push the data onto the
messages array, which will update the message chat history on the web page.
Compile it for the last time and then run it:
npm run dev php artisan serve
Open two private web browser windows, log in as two users, and send a message from one of them. You will see the other window immediately update. What happened was the chat app which had sent the message had requested Pusher Channels to broadcast the message to other clients, which in this case was the chat app in the other window.
If the other chat app isn’t immediately updating, use the web browser Javascript console to see if there are any errors. If you’re getting 404 errors (ignore the sourcemap warnings), use the
php artisan route:list command to display all routes which should help you spot any missing ones.
If you want to add a typing indicator, take a look at another one of our tutorials here.
Conclusion
You saw how Laravel already has some built in integration for Pusher Channels. With a little bit of extra configuration, you’re good to start sending out messages from Laravel, and receiving them in realtime with Echo, using Pusher in between.
October 13, 2021
by Benjamin Tang
|
https://pusher.com/tutorials/how-to-build-a-chat-app-with-vue-js-and-laravel/
|
CC-MAIN-2022-21
|
refinedweb
| 3,007
| 54.63
|
On Mon, Jan 16, 2012 at 12:49 PM, Colin Walters <walters@verbum.org> wrote:> On Sun, 2012-01-15 at 16:37 -0800, Andy Lutomirski wrote:>> To make the no_new_privs discussion more concrete, here is an updated>> series that is actually useful. It adds PR_SET_NO_NEW_PRIVS>> I think it'd be clearer to call it PR_SET_NOSUID - basically it should> match the semantics for MS_NOSUID mounts, as if on every exec()> thereafter the target binary was on a nosuid filesystem.The MS_NOSUID semantics are somewhat ridiculous for selinux, and I'drather not make them match for no_new_privs. AppArmor completelyignores MS_NOSUID, so I think the rename would just cause moreconfusion.>> You might then change this flag to only take effect on a later exec(),> which would solve your race condition for the hypothetical PAM module.That would just make it more complicated. The race is already solvedin the current patch, anyway.>>> with the>> same semantics as before (plus John Johansen's AppArmor fix and with>> improved bisectability). It then allows some unshare flags>> What's the rationale behind the unshare subset? Did you actually> analyze any setuid binaries found on Debian/Fedora etc. and determined> that e.g. CLONE_NEWNET was problematic for some reason?CLONE_NEWNET seems more likely to consume significant kernel resourcesthan the others. I didn't have a great reason, though. Unsharing thefilesystem namespace is possibly dangerous because it could prevent anunmount in the original namespace from taking effect everywhere.>> I actually want CLONE_NEWNET for my build tool, so I can be sure the> arbitrary code I'm executing as part of the build at least isn't> downloading more new code.>>Fair enough. I may add this in v3. seccomp is an even bettersolution, though :)--Andy--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
|
https://lkml.org/lkml/2012/1/16/413
|
CC-MAIN-2016-07
|
refinedweb
| 315
| 56.66
|
Patent application title: METHOD AND ARRANGEMENT FOR RE-LOADING A CLASS
Inventors:
Evgueni Kabanov (Tartu, EE)
IPC8 Class: AG06F954FI
USPC Class:
719320
Class name: Electrical computers and digital processing systems: interprogram communication or interprocess communication (ipc) high level application control
Publication date: 2008-11-13
Patent application number: 20080282266
Abstract:
The method is for deploying an input class in a computer readable memory.
A state class is created that has at least one field and at least one
proxy method and a behavior class version that includes at least one
method on the basis of the input class. At least one method call of the
state class is redirected to the behavior class version. Also, an
arrangement and a computer-software are disclosed.
Claims:
1. A computer executable method for deploying an input class during
runtime in a computer readable memory, comprising:creating on a basis of
the input class a state class comprising at least one field and at least
one proxy method and a behavior class version comprising at least one
method, andredirecting at least one method call of the state class to the
behavior class version.
2. A method according to claim 1, wherein the input class is a Java® class.
3. A method according to claim 1, wherein a behavior class is determined by a redirecting service.
4. A method according to claim 1, wherein the behavior class version, to which the method call is redirected, is determined during runtime.
5. A method according to claim 1, wherein the creation of state class and behavior class is performed during runtime.
6. A method according to claim 3, wherein the redirecting service invokes at least one method using reflection.
7. A method according to claim 1, a name of a behavior class comprises the version information.
8. A method according to claim 3, a method of a behavior class comprises a call to a method of a class of the redirecting service.
9. A method according to claim 3, the method of the state class comprises a call to a method of a class of the redirecting service.
10. An arrangement for deploying an input class in a computer readable memory during runtime, comprising:means for creating from the input class a state class comprising at least one field and at least one proxy method,means for creating a behavior class version comprising at least one method, andmeans for redirecting at least one method call to the behavior class version.
11. A software method for deploying an input class in a computer readable memory during runtime, comprising:providing a computer executable program code for creating from an original class a state class comprising at least one field and at least one proxy method,creating a behavior class version comprising at least one method, andredirecting at least one state class method call to the behavior class version.
Description:
PRIOR APPLICATION
[0001]This is a US national phase application that claims priority from Finnish Application No. 20070366, filed 9 May, 2007.
TECHNICAL FIELD OF INVENTION
[0002]The invention relates to a method and arrangement for loading classes in a computer system.
BACKGROUND AND SUMMARY OF THE INVENTION
[0003]Development and testing of an application program in environments such as Java® often require constant switching between code writing and running. The re-starting of application e.g. for testing after making changes to the source code is often a quite time and resource consuming task.
[0004]The runtime environments, e.g. Java®, where the application code may be run, are often large and complex. Since the first release of Java® language Java developers could not benefit from rapid development as Java Virtual Machine (JVM) did not support a way to reload classes after they have been loaded at least once by some class loader. Starting the environment and application program for testing may thus require a relatively long time, e.g. even several minutes, because classes of the needed runtime environment along with classes of the application need to be re-loaded even if only one of the application's classes was changed.
[0005]A standard JVM supports reloading class loaders (a standard, modifiable component of a Java environment) along with all their classes. However, in such a case all the current class instances were lost, unless explicitly preserved via e.g. serialization. This was used to support application redeployment, but could not be used for supporting any generic fine-grained reloading.
[0006]Another approach called HotSwap for reloading classes while debugging is known in the prior art. It only allows changing the method bodies, not allowing updates to method signatures, classes and fields. Because of its limitations, this approach does not satisfy most programmers and is rarely used.
[0007]A scientific publication by Mikhail Dmitriev (a dissertation submitted for the Degree of Doctor of Philosophy, Department of Computing Science, University of Glasgow, March 2001) with title "Safe Class and Data Evolution in Large and Long-Lived Java® Applications" provides an overview about some prior art solutions for reloading classes. The publication discusses solutions for the following interrelated areas: consistent and scalable evolution of persistent data and code, optimal build management, and runtime changes to applications.
[0008]U.S. Patent application US20020087958 teaches a method and apparatus of transforming a class. The method involves creating modified class such that each access to class field is replaced by invocation of access function for fetching. In the disclosed method, the class is split and converted into a modified class and/or a helper class.
[0009]After the transformation, a safe class sharing among several processes is achieved whereby the startup times and the memory usage for the processes are reduced. The inter-process communication (IPC) becomes faster.
[0010]U.S. Patent application US20040168163 teaches a system and method for shortening class loading process in Java program. The method and system has a class loader performing linking and initialization processes to generate run time data which is stored in accessible state in memory.
[0011]U.S. Pat. No. 6,901,591 discloses frameworks for invoking methods in virtual machines. The disclosure provides an internal class representation data structure for use by virtual machine at runtime. The data structure comprises method and a reference cell corresponding to the method.
[0012]U.S. Pat. No. 6,092,079 discloses an apparatus and method for updating an object without affecting the unique identity of the object. In the disclosed method, a second object is created which is an instance of a first class. The data from the first object is copied into the second object. The method table pointer of the first object is then changed to the method table of the second class. The data section of the first object is then reallocated according to the data requirements of the second class. The data in the second object is then converted to data in the first object. The resultant first object has both methods and data updated to the second class without passivating the object.
[0013]U.S. Pat. No. 5,974,428 teaches a method and apparatus for class version naming and mapping. In an embodiment of the disclosed invention, a class versioning and mapping system allows a user to request a desired class without knowing which class version is the most recent or correct version for the desired class. The class versioning and mapping system uses a version mapping mechanism to cross reference the requested class, select the most recent or best version of the requested class, and then return an object to the user that belongs to the selected class.
[0014]The prior art fails to teach a method and arrangement that allows efficiently re-loading a changed class into a runtime environment without re-loading a number of other, unchanged classes at the same time. A solution for efficiently re-loading classes whose body, interface and/or attributes have changed, is therefore desired.
[0015]The object of the present invention is to provide a method and system for efficiently re-loading changed classes in a computer arrangement comprising a run-time environment such as Java® Virtual Machine.
[0016]The invention discloses a method, arrangement and computer program to re-load a changed class in a run-time environment.
[0017]Class reloading method and arrangement of the present invention is based on a combined effect of a plurality of functional components. One such functional component comprises a method to split the original class into a state class that will hold the state (i.e. attributes and their values) and a behavior class that will hold static program code derived from the code of the original class. The split may be performed during runtime e.g. by generating the state and behavior classes from the original class and deploying at least one of the generated classes in the runtime environment.
[0018]A further possible component comprises functionality to simulate the signature of the original class in the state class by proxying every method call in the state class through a runtime environment to a method of the last version of the respective behavior class. "Proxying" in this context means e.g. generating a proxy method e.g. in the state class that forwards the method call to another class.
[0019]A yet further possible component comprises functionality to redirect method calls made from the versioned code class through runtime system using reflection to ensure that last version of a behavior class is called. By using reflection, the use of default virtual machine invocation logic may be avoided. Reflection is functionality provided e.g. by a Java runtime environment (JRE).
[0020]In the present invention, actual class reloading into the runtime environment may occur e.g. when the file containing the original class is updated and a new versioned behavior class is created (generated) on the basis of the modified original class. The runtime system of the present invention makes sure that all subsequent method calls will be redirected to the latest version of the behavior class.
[0021]An aspect of the invention is a computer executable method for deploying an input class during runtime in a computer readable memory. The method is characterized in that the method comprises steps of (a) creating on the basis of the input class a state class comprising at least one field and at least one proxy method and a behavior class version comprising at least one method and (b) redirecting at least one method call of the state class to the behavior class version.
[0022]The correct version of the behavior class may be determined e.g. by a redirecting service. The version of the behavior class, to which the method call should be redirected, may further be determined during runtime.
[0023]The creation of the state class and/or the behavior class may be performed during runtime.
[0024]The redirecting service may invoke at least one method using reflection.
[0025]The behavior class may comprise version information.
[0026]A method of said behavior class may comprise a call to a method of a class of the redirecting service.
[0027]The method of the state class may comprise a call to a method of a class of said redirecting service.
[0028]Creating a class in this context means e.g. generating the class and deploying it in the computer readable memory for use of e.g. a runtime environment, e.g. a Java® runtime environment.
[0029]The computer readable memory may contain a runtime environment that may be an object oriented runtime environment, e.g. a Java® runtime environment.
[0030]The class may be a class of any suitable object oriented development and/or runtime environment e.g. a Java® class.
[0031]Another aspect of the invention is an arrangement for deploying an input class in a computer readable memory during runtime. The arrangement is characterized in that it comprises means for (i) creating (generating) from the input class a state class comprising at least one field and at least one proxy method and (ii) means for creating (generating) from the input class a behavior class version comprising at least one method and (iii) means for redirecting at least one state class method call to the behavior class version.
[0032]The correct version of the behavior class to be used may be determined e.g. by the redirecting means.
[0033]Yet another aspect of the invention is software for deploying an input class in a computer readable memory during runtime, said software comprising computer executable program code for (i) creating (generating) from the input class a state class comprising at least one field and at least one proxy method, (ii) creating from the input class a behavior class version comprising at least one method and (iii) redirecting at least one state class method call to the behavior class version.
[0034]The correct version of the behavior class to be used may be determined e.g. by the redirecting program code of the software.
[0035]Some embodiments of the invention are described herein, and further applications and adaptations of the invention will be apparent to those of ordinary skill in the art.
BRIEF DESCRIPTION OF DRAWINGS
[0036]In the following, some embodiments of the invention are described in greater detail with reference to the accompanying drawings in which
[0037]FIG. 1 shows an exemplary method of transforming a class,
[0038]FIG. 2 depicts an exemplary class implementing a redirecting service,
[0039]FIG. 3 shows an example about redirecting a method call to a versioned class through the state class proxy method,
[0040]FIG. 4 shows another example about redirecting a method call to a versioned class directly, and
[0041]FIG. 5 shows yet another example about redirecting method calls between different classes according to an embodiment of the invention.
DETAILED DESCRIPTION OF THE DRAWINGS
[0042]In the following detailed description, words that have a special meaning in Java® development and/or runtime environments and application programming language are written in courier font. Such words are e.g. the reserved words (e.g. static or public) of the Java programming language. Also example code snippets are written using courier font.
[0043]To make a class re-loadable efficiently in a runtime environment according to an embodiment of the invention, the original (input) class written e.g. by an application programmer or generated by an application development environment needs to be transformed into a plurality of classes as shown in FIG. 1. The input class 100 that comprises both fields (also referred to as attributes or member variables) 101 and methods 102 is provided as an input to a transformation component 103 that produces two classes, a state class 104 and a behavior class 107, from the input class 100. In one embodiment, the class transformation process comprises one or more of e.g. following operations to transform the input class into a state class: [0044]Modifiers of state class 104 are the same as class modifiers of input class 100. If the method was "synchronized" (as used in Java® environment) it is omitted. [0045]Superclass of state class 104 (i.e. the class from which the state class inherited) is the same as superclass of the input class 100. [0046]State class 104 implements a RuntimeVersioned marker interface (using standard interface programming means of Java® environment) in addition to input class 100 implemented interfaces to express that there is a versioned behavior class corresponding to the state class 104. [0047]Fields specified in the input class 100 (both static and non-static) are left as is 105 in the state class 104. One or multiple additional "synthetic" fields may be added to the state class 104. [0048]Methods specified in the input class 100 (both static and non-static) are replaced in the state class 104 with proxy methods 106 that redirect the call to the runtime redirector component. The names and signatures of the proxy methods stay as is. [0049]Constructors (methods that create an instance of a class) are transformed as described later in this disclosure. [0050]Static initializers are copied as is.
[0051]The class transformation process also creates (generates) a re-loadable versioned behavior class 107 from the input class 100. This transformation process executed by the transformer component 103 may comprise any number of operations (or all of them) from the following set of operations: [0052]Behavior class 107 is declared "public" and "abstract" using Java® programming means. [0053]The super class of the behavior class 107 is made the same as super class of input class 100. Suitably, the behavior class 107 does not implement any Java® "interface"s. [0054]All fields (both static and non-static as specified in Java environment) of the input class are omitted from the behavior class 107. [0055]Every static method 108 of the behavior class 107 is set to be public. The body of the method is copied applying e.g. the method transformation described later in this disclosure. [0056]Some or all virtual methods 102 are modified to be Java® public static" methods 108 and take the state class 104 as the first parameter. The body of the method is copied applying method transformation described later in this disclosure. [0057]Some or all "constructors" (as known to a Java application developer) are transformed as described later in this disclosure. [0058]"Static initializers" (as known to a Java application developer) are left out.
[0059]In some embodiments, the only connection between the generated classes 104 and 107 is the extra parameter of type class 104 taken by the (ex-virtual) methods in class 107. They do not refer to each other in any other way. The scheme described in FIG. 1 preserves the "extends" relation (object inheritance in Java® environment) between original classes in proxies.
[0060]As part of the transformation process, each method body in the versioned behavior class must be transformed to make calls through the runtime redirector component. This means for example that the INVOKE* and GET*/PUT* instructions of the Java Virtual Machine must be transformed to calls into the runtime redirector component.
[0061]In some embodiments, all method parameters are wrapped into an object array. This involves boxing all basic types into appropriate object wrappers.
[0062]The following table shows an example of how to convert JVM instructions into runtime redirector method calls. In the example, it is assumed that the "parameters" on stack is the wrapped object array of method call parameters.
TABLE-US-00001 JVM Instruction Runtime redirector method INVOKESTATIC C.m:d invokeStatic(parameters, "C", "m", Stack: parameters "d") INVOKEVIRTUAL C.m:d invokeVirtual(target, parameters, Stack: target, "C", "m", "d") parameters INVOKESPECIAL C.m:d if m is private: invokeVirtual Stack: target, (target, parameters, "C", "m", "d") parameters otherwise: invokeSuper(target, Surrounding class: S parameters, "S", "C", "m", "d") INVOKEINTERFACE C.m:d invokeVirtual(target, parameters, Stack: target, "C", "m", "d") parameters GETFIELD C.f:d getFieldValue(target, "C", "f", "d") Stack: target GETSTATIC C.f:d getFieldValue(null, "C", "f", "d") Stack: PUTFIELD C.f:d setFieldValue(target, value, "C", Stack: target, value "f", "d") PUTSTATIC C.f:d setFieldValue(null, value, "C", "f", Stack: value "d")
[0063]After the conversion process the state and behavior classes that have been generated from the input class are now ready for use in an application program that may be already running in a runtime environment. FIG. 2 shows a runtime redirector component of an embodiment of the present invention that has been implemented so that it comprises at least a Redirector class 201 that is associable with a ClassLoader class 200. The Redirector class 201 comprises one or multiple fields 202, e.g. an array of references to versioned classes it manages. The Redirector class 201 also comprises methods 203 needed to perform the redirecting services.
[0064]In one embodiment, the methods 203 comprise for example the following:
TABLE-US-00002 Object getFieldValue(Object obj, String classname, String fieldname, String descriptor) void setFieldValue(Object obj, Object value, String classname, String fieldname, String descriptor) Object invokeVirtual(Object target, Object[ ] parameters, String classname, String methodname, String descriptor) Object invokeStatic(Object target, Object[ ] parameters, String classname, String methodname, String descriptor) Object invokeSuper(Object target, Object[ ] parameters, String fromClassname, String toClassname, String methodname, String descriptor)
[0065]The signatures (list of parameters) of the runtime methods shown above correspond to the JVM INVOKE* and GET*/PUT* instruction parameters. The class name and descriptor parameters are given in JVM internal form (descriptor contains the types of all parameters and return value in case of method). The functionality and use of the JVM instructions and their parameters are well known to a person skilled in the art.
[0066]The purpose of the runtime redirector component is to find the correct version of a behavior class for each method call and redirect the method call to that version of the class. Unlike the default JVM method application, the runtime redirector will first try to find the method in the versioned classes. Thus, if methods have been added, removed or changed to a class during runtime of the application, the changes will be taken into consideration.
[0067]In some embodiments, the calls from methods of a versioned behavior class will be redirected to calls to methods of versioned behavior class directly, without a need to call proxy methods of the corresponding state class. The proxy method of a state class thus serves typically only as a gateway for the non-versioned classes not managed by the runtime redirector component, which can call its methods directly and still benefit from the class reloading.
[0068]Field access methods are needed to access private fields and also handle freshly added fields.
[0069]In some embodiments, the runtime redirector component uses "reflection" (as known to a person skilled in the art of Java® application development) to call the correct method in the end and it requires security bypass to call private methods. In a Java® environment, the reflection API represents, or reflects, the classes, interfaces, and objects in the current Java Virtual Machine. With the reflection API one can for example: [0070]Determine the class of an object. [0071]Get information about a class's modifiers, fields, methods, constructors, and superclasses. [0072]Find out what constants and method declarations belong to an interface. [0073]Create an instance of a class whose name is not known until runtime. [0074]Get and set the value of an object's field, even if the field name is unknown to your program until runtime. [0075]Invoke a method on an object, even if the method is not known until runtime. [0076]Create a new array, whose size and component type are not known until runtime, and then modify the array's components.
[0077]In an embodiment of the invention, the default Reflection API implementation of a standard Java® runtime environment may need to be at least partially overridden to allow redirecting calls to the runtime redirector. Such embodiment makes it possible e.g. to make reflective calls to methods that did not exist originally. Additionally the changes to methods, fields and constructors need to be shown to appear in the API. In one embodiment, this means that the following methods of java.lang.Class class available in a Java® environment must be altered: [0078]getDeclaredMethod( ) and getDeclaredMethods( ) result must reflect added/removed/changed methods of behavior classes accordingly. [0079]getMethod( ) and getMethods( ) result must reflect added/removed/changed public methods of behavior classes in the current and all super classes accordingly. [0080]getDeclaredConstructor( ) and getDeclaredConstructors( ) result must reflect added/removed/changed constructor methods of behavior classes accordingly. [0081]getConstructor( ) and getConstructors( ) result must reflect added/removed/changed constructor methods accordingly. [0082]getDeclaredField( ) and getDeclaredFields( ) result must reflect added/removed/changed static and non-static fields accordingly. [0083]getField( ) and getFields( ) result must reflect added/removed/changed static and non-static public fields in the current and all super classes accordingly. [0084]getInterfaces( ) result should reflect added/removed/changed implemented "interface"s.
[0085]The changes in java.lang.Class class can be done using instrumentation techniques known to a person skilled in the art, causing it to consult e.g. runtime redirector's versioned class directory before returning results.
[0086]FIG. 3 shows a method invocation diagram about redirecting a method call from a state class (104 in FIG. 1) to a correct version of a behavior class (107 in FIG. 1). A method in an object 301 calls method1( ) 305 of class ClassA 302. The class 302 is a state class that has only a proxy of the called method. The proxy method contains a invokeVirtual( ) method call 306 to the Redirector class 303. The Redirector resolves the most recent version of the behavior class 304 and calls the method1( ) 307 of the behavior class. The state class 302 is added as a parameter to the method call 307. Should the method1( ) return a value, it may be returned back to Redirector, further to the state object 302 and finally to the calling client 301.
[0087]FIG. 4 depicts a method invocation diagram about calling a method of a versioned class from another versioned class. The calling class 401 doesn't need to call the state class. Instead, it calls 404 the Redirector 402 that further calls 405 the correct (e.g. latest) version 403 of the behavior class.
[0088]FIG. 5 depicts an overall view about an arrangement of classes according to an embodiment of the present invention. The arrangement comprises a set 500 of unversioned classes 502, 503 and a set 501 of versioned classes 508, 509. One ("ClassA") of the shown unversioned classes 502 is a class that is not associated with the runtime redirector component 505 at all. Another one ("ClassC") of the unversioned classes is a state class 503 that has a corresponding versioned behavior class 508 ("ClassC4") among the set of versioned classes 501. There's also a versioned behavior class 509 ("ClassB1") among the versioned classes that doesn't have a corresponding state class shown in the picture (although such class would exist in a real running system). The runtime redirector 505 is associated with at least one ClassLoader component 506 who loads the versioned 500 and unversioned 501 classes into the computer's memory when needed. ClassLoader should in this context be understood as a ClassLoader of a Java® environment. The ClassLoader 506 has thus an association 513, 514 with the versioned and unversioned classes. When an unversioned class 502 calls a method of a versioned class 508, it must send the method call 504 (e.g. method1( )) to the state class 503 related to the behavior class 508. The state class forwards 507 the method call to the runtime redirector component 505. At this phase, the method call is invokeVirtual ("ClassC", "method1"). (For clarity, some details may be omitted in the examples. Those details are apparent to a person skilled in the art.) The first parameter of this method call identifies the name of the class and the second parameter identifies the name of the method of the class. The redirector runtime determines the correct recipient "ClassC4" 508 for the method call and forwards 511 the call to the class. At this phase, the method call is again method1( ). If a versioned behavior class 508 calls 510 a method of another versioned class 509, the call is sent from the calling class 508 to the redirector runtime 505 as a invokeVirtual ("ClassB", "method2") call 510. In this example, the name of the class is "ClassB" and the method of the class to be called is "method2( )". The runtime redirector resolves the correct version of the versioned behavior class "ClassB1" 509 and sends the method2( ) call 512 to the class.
[0089]In the following, an example with programming code is provided to further illustrate some embodiments of the present invention. For convenience, Java code notation is used in this example although the same principles may be applicable in other object-oriented programming and runtime environments.
[0090]An original (input) class of this example is defined as follows:
TABLE-US-00003 public class C extends X { int y = 5; int method1(int x) { return x + y; } void method2(String s) { System.out.println(s); } }
[0091]The class of the example has name C, it extends (inherits from) class X, it has one field (y) and two methods (method1 and method2).
[0092]In an embodiment of the present invention, the original input class is transformed into two classes, a state class and a behavior class.
[0093]The state class can now be generated from the input class to be as follows.
TABLE-US-00004 public class C extends X { int y = 5; int method1(int x) { Object[ ] o = new Object[l]; o[0] = x; return RedirectorRuntime.invokeVirtual(this, o, "C", "method1", "(I)I"); } void method2(String s) { Object[ ] o = new Object[1]; o[0] = s; return RedirectorRuntime.invokeVirtual( this, o, "C", "method2", "(Ljava/lang/String;)V"); } }
[0094]The behavior class can now be generated from the input class to be as follows:
TABLE-US-00005 public abstract class C0 { public static int method1(C c, int x) { int tmp1 = RedirectorRuntime.getFieldValue(c, "C", "y", "I"); return x + tmp1; } public static void method2(C c, String s) { PrintStream tmp1 = RedirectorRuntime.getFieldValue( null, "java/lang/System", "out", "Ljava/io/PrintStream;"); Object[ ] o = new Object[1]; o[0] = s; RedirectorRuntime.invokeVirtual( tmp1, o, "java/io/PrintStream;", "println", "(Ljava/lang/String;)V"); } }
[0095]This example case is left without any special handling or optimization for simplicity.
[0096]Now the original class C may be updated e.g. by an application developer or a code generation program of an application development environment, e.g. as shown in the following code example:
TABLE-US-00006 public class C { int y = 5; int z( ) { return 10; } int method1(int x) { return x + y + z( ); } ... }
[0097]The original class has now one new method ("z( )") and the "method1( )" of the class has been altered. These changes should now be implemented in the runtime environment without re-starting the environment or re-loading a number of unchanged classes. To achieve this goal, a new version of the behavior class is generated after the update of the original class. The new version of the behavior class is then loaded into the runtime system's memory, the runtime redirector service is notified about the new version of the behavior class and all further calls to the methods of the modified class are to be redirected to the new version of the behavior class.
TABLE-US-00007 public class C1 { public static int z(C c) { return 10; } public static int method1(C c, int x) { int tmp1 = RedirectorRuntime.getFieldValue(c, "C", "y", "I"); int tmp2 = RedirectorRuntime.invokeVirtual(c, null, "C", "z", "(V)I"); return x + tmp1 + tmp2; } ... }
[0098]Because the state class was not updated, it is not necessary to reload it into the memory. Thus, the state of the existing instances is preserved even though the implementation of the class has been altered.
[0099]In some embodiments, fields may be added to the original class. To handle these added fields, a synthetic field, e.g. of name _RUNTIME_FIELDS_and of type Map, is added to every generated state class. This will allow holding the values for added fields in the _RUNTIME_FIELDS_values with concatenated field name and type descriptors serving as keys. This will also handle the case when the field type changes, but name doesn't as the key will change. The getFieldValue( )/setFieldValue( ) methods of the runtime redirector (201 in FIG. 2) need to be implemented so that they search for field values in the _RUNTIME_FIELDS_map first. An example state class may then look e.g. like the following:
TABLE-US-00008 public class C extends X { private Map _RUNTIME_FIELDS-- = new HashMap( ); int y = 5; //Rest of the class... }
[0100]Java® environment allows implementation of "synchronized" methods. In one embodiment of the invention, such methods are replaced by non-synchronized methods that have a "synchronized" block over the proxy instance in the versioned class method. Since proxy methods, i.e. methods of the state class that just forward the method call to the runtime redirector, do not access any global values they are safe to be unsynchronized. Assuming that method1( ) of a class C was declared synchronized the resulting behavior class will in one embodiment look like this (state class will stay the same):
TABLE-US-00009 public abstract class C0 { public static int method1(C c, int x) { synchronized (c) { int tmp1 = RedirectorRuntime.getFieldValue(c, "C", "y", "I"); return x + tmp1; } } //Rest of the class... }
[0101]To access methods of unversioned superclasses, accessor methods are generated in some embodiments with prefix _RUNTIME_SUPER_for all unversioned super methods that are overridden in the proxy. The runtime redirector's invokeSuper method should call the topmost such method if a super call to unversioned class is to be made. An example about a state class may then look e.g. like the following:
TABLE-US-00010 public class C extends X { int y = 5; int method1(int x) { Object[ ] o = new Object[1]; o[0] = x; return RedirectorRuntime.invokeVirtual(this, o, "C", "method1", "(I)I"); } int _RUNTIME_SUPER_method1(int x) { return super.method1(x); } //Rest of the class... }
[0102]In the above example, it is assumed that class X is unversioned and also has a method int method1(int).
[0103]In some embodiments, it is also possible to generate a _RUNTIME_SUPER_method for each directly or indirectly inherited method in the topmost unversioned class only. This will increase this class size, but can make invokeSuper method work simpler.
[0104]Because of limitations imposed by Java runtime environment, constructors need to be treated differently from other virtual methods, although semantically constructors are just a virtual method of a particular name and type. In some embodiments, the transformer (103 in FIG. 1) generates a _RUNTIME_INIT_static method with same type except for the state class added as first argument instead of each constructor in the original class. In addition, the transformer generates a constructor with a slightly different signature for each constructor in the original class superclass. A RuntimeVersioned marker interface ("interface" should here be interpreted as an interface of a Java® programming language) is added as the last type. The purpose of this constructor is to be called when a super constructor call (i.e. call of a constructor method of a Java® superclass) is required (constructors being subject to the same limitations as usual methods). These constructors will just call the super ones. In one embodiment, a state class and its constructor may look e.g. like the following:
TABLE-US-00011 public class C extends X { int y = 5; public C( ) { Object[ ] o = new Object[1]; o[0] = c; //Not valid in Java, but possible in bytecode Return RedirectorRuntime.invokeStatic( null, o, "C", "_RUNTIME_INIT_", "(C)C"); } public C(RuntimeVersioned o) { super( ); } //Rest of the class... }
[0105]In the above example, original class C must necessarily have a default constructor with no arguments that just calls super( ).
[0106]The behavior class in this embodiment may look e.g. like the following:
TABLE-US-00012 public abstract class C0 { public static C _RUNTIME_INIT_(C c) { //Not valid in Java, but possible in bytecode c.<init>((RuntimeVersioned) null); } //Rest of the class... }
[0107]There is little needed to handle calls to interfaces in the class conversion and runtime redirector process. The behavior classes are not generated for interfaces and the state classes correspond almost one-to-one with the original. Since all versioned calls are done using reflection, the INVOKE_INTERFACE primitive may always be treated same as a usual virtual call. The use of reflection allows weak type checking in method calls instead of strong types in e.g. a Java® environment. Or in other words, use of reflection allows dynamic method calls instead of static calls.
[0108]When calling a public static method in an embodiment of the invention, it is known during class loading whether the loaded class is managed by the runtime redirector (201 in FIG. 2) or not. Thus the calls to the unmanaged classes are left as is, and only calls to managed versioned classes are redirected using the runtime redirector. Same solution applies also to the public static fields.
[0109]When calling a static method with any visibility from inside the same class, the versioned class method can be called directly in an embodiment of the invention.
[0110]When calling a private virtual method from inside the same class, the versioned class method can be called directly in an embodiment of the invention.
[0111]When calling a public virtual method, two alternatives are possible according to an embodiment. If the class is not managed and its virtual method is final or the class is final, the virtual method can be called directly. However, if the class is not versioned, code may be generated to test whether the instance of class implements the RuntimeVersioned marker interface (for details, see description of FIG. 1). In such a case, the call needs to be redirected through the runtime redirector. Otherwise the call may be made directly.
[0112]There are some issues related to inheritance (class hierarchy) that are useful to be addressed. In one embodiment an issue regarding overriding of an unmanaged class C (i.e. class whose method calls are not managed by the runtime redirector) method m by a managed subclass C' method m is solved. If the call is made through the runtime redirector it will resolve the method m correctly to class C'. However if the call comes from an unmanaged class, runtime redirector may not be involved, and the wrong method C.m would be called.
[0113]This issue can be solved for example by making calls to managed classes go through the runtime redirector, including ones made to the methods implemented by superclasses (i.e. classes from which other classes are inherited). This is done by generating a proxy method (with same modifiers and signature) for each of the overridden methods, thus making sure the runtime redirector is involved in resolving the method to call.
[0114]The above embodiment is an extension of the proxy method generation taught in another embodiment. The extension makes the proxy method generation more intrusive, since the inherited methods will now show up in Class.getDeclaredMethods( ) reflection calls. This might cause some problems with code that does not expect that (e.g. Java bean handling code). However this problem can be solved by overriding reflection as taught in this disclosure and then ignoring the extra generated methods.
[0115]The embodiments taught herein may be further optimized for runtime use. The runtime redirector provides methods similar to the JVM instructions. However JVM instructions use the constant pool to reuse string constants, referring to them by integer indexes. The same approach can be applied in the runtime redirector, redefining the runtime methods to accept integer indexes instead of class names and method names (including type descriptor). The runtime redirector could have for example the following interface after constant pool introduction:
TABLE-US-00013 Object getFieldValue(Object obj, long classname, long fieldnameWithDescriptor) void setFieldValue(Object obj, Object value, long classname, long fieldnameWithDescriptor) Object invokeVirtual(Object target, Object[ ] parameters, long classname, long methodnameWithDescriptor) Object invokeStatic( Object[ ] parameters, long classname, long methodnameWithDescriptor) Object invokeSuper(Object target, Object[ ] parameters, long fromClassname, long toClassname, long methodnamewithDescriptor)
[0116]The main advantage of building a constant pool is that then the same indexes can be used to create a dictionary of classes and methods using array structures. Such structures are efficient to access compared to hash tables and similar structures. This may increase runtime performance of the crucial runtime redirector methods.
[0117]However the above approach means that a dictionary of all classes needs to be made accessible to the runtime redirector. This may result as a noticeable memory overhead. Considering that Java® ClassLoader hierarchy allows several versions of same class in unrelated ClassLoaders, a choice needs to be made between having a full dictionary per ClassLoader or having a complex system of dependencies between constant pools.
[0118]The embodiments of the invention allow altering classes in a flexible manner and deploying the altered classes in an already running runtime environment in a quick and resource efficient manner. Thus, the various embodiments of the invention disclosed herein allow e.g. significant performance improvements e.g. in application development environments where both application programming and testing work may be performed.
[0119]To a person skilled in the art, the foregoing exemplary embodiments illustrate the model presented in this application whereby it is possible to design different methods and arrangements, which in obvious ways to the expert, utilize the inventive idea presented in this application.
[0120]While the present invention has been described in accordance with preferred compositions and embodiments, it is to be understood that certain substitutions and alterations may be made thereto without departing from the spirit and scope of the following claims.
Patent applications by Evgueni Kabanov, Tartu EE
Patent applications in class HIGH LEVEL APPLICATION CONTROL
Patent applications in all subclasses HIGH LEVEL APPLICATION CONTROL
User Contributions:
Comment about this patent or add new information about this topic:
|
http://www.faqs.org/patents/app/20080282266
|
CC-MAIN-2015-27
|
refinedweb
| 6,878
| 51.99
|
i'm happy with django built in user/auth , i just want to add some fields to it and change table name (mostly the last one , i can use another table for custom fields )
so i searched around and apparently we can use subclass as suggested on Rename Django's auth_user table?
So i have to start a new app and use it's model to as a subclass for
AbstractUser
customuser
from django.db import models
from django.contrib.auth.models import AbstractUser
class customuser(AbstractUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
db_table = 'customuser'
To use a custom user model, you need to set the
AUTH_USER_MODEL setting in your settings module.
Note that you don't need to set
swappable = 'AUTH_USER_MODEL'. This is an undocumented and private attribute, and is probably better left untouched.
|
https://codedump.io/share/SaImB7CB7Fom/1/changing-default-authuser-table-name
|
CC-MAIN-2016-50
|
refinedweb
| 133
| 50.67
|
Learn the differences between $http in Angular 1.x and Http in Angular 2. Find out how to use the RxJS Observables that Http returns.
TL;DR: Making HTTP requests in Angular 2 apps looks somewhat different than what we're used to from Angular 1.x, a key difference being that Angular 2's Http returns observables. In this tutorial, we cover how to use Http to make requests and how to handle the responses. We'll also see how we can do basic authentication for an Angular 2 app. Check out the repo for the tutorial to see the code.
This is Part 3 in our Angular 2 series. Be sure to check out Part 1 on Pipes and Part 2 on Models.
It's fair to say that most of Angular 2 looks and feels completely different than Angular 1.x, and the Http API is no exception. The $http service that Angular 1.x provides works very nicely for most use cases, and is fairly intuitive to use. Angular 2's Http requires that we learn some new concepts, including how to work with observables.
In this tutorial, we'll look at some of the key differences in the way that Angular 1.x and 2 implement HTTP requests, and we'll also see how to make requests and handle responses. Incidentally, the sample we use to test out Http will also let us see the basics of adding authentication to an Angular 2 app.
It's important to note that the Http implementation for Angular 2 is still a work in progress, and a lot of things are still in flux or aren't complete yet.
Differences between Angular 1.x $http and Angular 2 Http
Angular 2's Http implementation again provides a fairly straightforward way of handling requests, but there are some key differences. For starters, HTTP calls in Angular 2 by default return observables through RxJS, whereas $http in Angular 1.x returns promises. Using observable streams gives us the benefit of greater flexibility when it comes to handling the responses coming from HTTP requests. For example, we have the potential of tapping into useful RxJS operators like
retry so that a failed HTTP request is automatically re-sent, which is useful for cases where users have poor or intermittent network communication. We'll see later in the article how we can implement RxJS operators in our Http observables.
In Angular 2, Http is accessed as an injectable class from
angular2/http and, just like other classes, we
import it when we want to use it in our components. Angular 2 also comes with a set of injectable providers for Http, which are imported via
HTTP_PROVIDERS. With these we get providers such as
RequestOptions and
ResponseOptions, which allow us to modify requests and responses by extending the base class for each. In Angular 1.x, we would do this by providing a
transformRequest or
transformResponse function to our
$http options.
In Angular 1.x we can transform requests globally in the application's
config.
.config(function($httpProvider) { $httpProvider.defaults.transformRequest = function(data) { return JSON.stringify({name: "Ryan"}); } });
Whereas in Angular 2, we would extend the
BaseRequestOptions.
class MyOptions extends BaseRequestOptions { body: string = JSON.stringify({name: "Ryan"}); } bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {useClass:MyOptions})]);
Http in Action
Let's take a look at how we can perform some basic requests with Http. We'll see how to work with
GET requests by using our trusty NodeJS Chuck Norris quote backend, which will require us to retrieve and store a JWT, and thereby implement basic authentication.
Getting Started
As we have in our other Angular 2 articles, we'll use Pawel Kozlowski's ng2-play repo for this tutorial. To get started, clone the repo and run
npm install, then
gulp play.
We also need to get our random quote server running. With the Angular 2 seed project installed, let's clone and install the quote server in the root of our project.
We also need to set up our
app component by importing what we need and providing a template.
// app.ts import {Component, View} from 'angular2/angular2'; import {Http, Headers} from 'angular2/http'; import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2'; @Component({ selector: 'app' }) @View({ directives: [ CORE_DIRECTIVES, FORM_DIRECTIVES ], template: ` <header> <h1 class="title">Angular 2 HTTP</h1> </header> <section> <h2>Login</h2> <form # <div ng- <label for="username">Username</label> <input type="text" id="username" ng-Password</label> <input type="password" id="password" ng-Get Random Quote!</button> <section> <section> <h2>Secret Quote</h2> <hr> <h3>{{secretQuote}}</h3> <button (click)="getSecretQuote()">Get Secret Quote!</button> <section> ` }) export class App { constructor(public http: Http) { } } bootstrap(App, [HTTP_BINDINGS])
As you can see, we've imported some familiar pieces like
Component and
View, but we are also pulling in
Http and
Headers. We'll see it later on, but we can modify the headers we send in our requests with the
Headers class.
We're making use of a form for the user to eventually provide their credentials. The form calls an
authenticate method on submit.
In the
App class, we're passing
Http to the constructor so that we can use it in our class methods.
Simple GET Request
Let's start with a simple
GET request to the
api/random-quote route which doesn't require authentication.
getRandomQuote() { this.http.get('') .map(res => res.text()) .subscribe( data => this.randomQuote = data, err => this.logError(err), () => console.log('Random Quote Complete') ); } logError(err) { console.error('There was an error: ' + err); }
The
getRandomQuote method starts off looking pretty familiar--we do an
http.get request by passing in a URL as an argument. Remembering
$http from Angular 1.x, this is where we would tap into the promise that gets returned by using
.then, but as you can see here, we're doing something pretty different.
As was mentioned earlier, HTTP calls in Angular 2 return observables, so we need to use RxJS methods to operate on them. The first thing we do is map the values that are returned as text, since our call to the
api/random-quote endpoint returns text. If we were expecting a JSON response, we would call
res.json() instead. After this, we need to subscribe to it so that we can observe values that are returned.
"HTTP calls in Angular 2 return observables, so we need to use RxJS methods to operate on them."
TWEET THIS
An observable subscription takes three functions to handle what happens as the stream is observed. The first function is the next case, or what happens when the HTTP call is successful. If the call is successful, we're saying that the data returned should be put on a property
randomQuote so it can be displayed in the view. The second function is the error case, and in our example we are logging any error messages to the console by calling our
logError method. Finally, the third function defines what happens once the call is complete, and here we are simply logging out the things are finished.
Let's test that out to make sure it works.
POST Request with Modified Content Type
Our
authenticate method will need to make a
POST request to the back end and specify the content type so that we can send our credentials. For this, we'll use
Headers.
// app.ts ... class CredentialsModel { username: string; password: string; } ... authenticate(data) { var username = data.credentials.username; var password = data.credentials.password; var creds = "username=" + username + "&password=" + password; var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); this.http.post('', creds, { headers: headers }) .map(res => res.json()) .subscribe( data => this.saveJwt(data.id_token), err => this.logError(err), () => console.log('Authentication Complete') ); } saveJwt(jwt) { if(jwt) { localStorage.setItem('id_token', jwt) } } ...
The
authenticate method accepts
data that is passed down from the view when the form is submitted. We're grabbing the username and password from it and making a
creds string in the form that the server expects.
We need to say that the content type should be
application/x-www-form-urlencoded and this can be done by appending a header onto our
headers instance. Then we simply pass this as a header in the options object when we make the
POST request. From here, the returned observable is handled in the same way that we saw in the
GET request, but this time the response is JSON, so we use
res.json(). We also call the
saveJwt method and pass it the token that is received to save it in local storage.
GET Request with Authorization Header
Now that we know how to modify headers, sending the JWT as an
Authorization header is simple.
// app.ts ... getSecretQuote() { var jwt = localStorage.getItem('id_token'); var authHeader = new Headers(); if(jwt) { authHeader.append('Authorization', 'Bearer ' + jwt); } this.http.get('', { headers: authHeader }) .map(res => res.text()) .subscribe( data => this.secretQuote = data, err => this.logError(err), () => console.log('Secret Quote Complete') ); } ...
We can check this in the browser to make sure our call to the protected endpoint works.
What Can We Do with Observables?
You might be wondering why Http doesn't just return promises like it used to, so we can stick to our familiar methods for resolving HTTP calls. The fact of the matter is that we can do much more with observables than promises. With observables, we have a whole bunch of operators to pull from, which let us customize our streams in nearly any way we want.
If you haven't worked with observables before, you can get an idea of how they work in our recent post on Authenticable Observables.
It should be noted that the Angular team is still deciding on the best way of implementing the RxJS operators with Http, which means these operators aren't all available for use just yet.
We can get a taste for how they work by plugging in some simple operators. For example, in our
GET call to
api/random-quote, we can attach a filter.
// app.ts ... getRandomQuote() { var count = 0; this.http.get('') .map(res => res.text()) .filter(x => x.length > 100) .subscribe( data => this.randomQuote = data, err => this.logError(err), () => console.log('Random Quote Complete') ); } ...
Now only quotes with a length greater than 100 characters will come through. If we click the "Get Random Quote" button a few times, we see it at work.
We can also delay our subscription if we want. Here we wait two seconds before printing the quote to the screen.
// app.ts ... .map(res => res.text()) .delay(2000) .subscribe( data => this.randomQuote = data, err => this.logError(err), () => console.log('Random Quote Complete') ); ...
While that might not be the most useful, what we will really benefit from once Http is solidified are operators like
retry. If we were expecting network connectivity issues, we could define a number of times to retry the request.
// app.ts ... .retry(3) .map(res => res.text()) .subscribe( data => this.randomQuote = data, err => this.logError(err), () => console.log('Random Quote Complete') ); ...
Another benefit of observables is that they can be cancelled. This can be useful for situations where HTTP requests are going on for a long time, perhaps to an unresponsive server somewhere. This is something that isn't easily done with promises, and something that the Fetch API has yet to implement.
Aside: Using Angular.
Wrapping Up
HTTP requests in Angular 2 definitely look different than they did in Angular 1.x, but with the change comes a big boost in capability. Having requests return observables is great because we will be able to use RxJS's operators to get the returned streams behave the way we like. We'll be able to use operators like
retry to automatically start a request again if there are network issues.
In this tutorial we saw how Http can be used to make
GET and
POST requests, but we can also use other HTTP verbs like
PUT,
DELETE, and
PATCH. We also saw how we can customize the headers we send with the
Headers class.
As with Angular 2 in general, Http is always going through changes. The Angular team keeps a very good backlog of Http issues and feature implementations, which is a good place to keep updated on how Http progresses.
|
https://auth0.com/blog/angular-2-series-part-3-using-http/
|
CC-MAIN-2017-04
|
refinedweb
| 2,052
| 65.62
|
I did it <:-P finally!!
Thank u so much for the help I can now submit it and go to bed!!! :)
The result of the election is:
Candidate Votes % of Total Votes
I did it <:-P finally!!
Thank u so much for the help I can now submit it and go to bed!!! :)
The result of the election is:
Candidate Votes % of Total Votes
im sorry but I don't know how to do what you are saying to do.
I don't understand how to do that how to save the index into the array where the max value was found?
I'm really no expert I find if I am given an example then I learn from my mistakes you may...
the names are the candidate variable.
but need to output the name of the candidate with the max votes which I have but can only print out the max votes not the candidates name that had the max...
just ran it again and I dont have the winners name just the votes how do I do that?
do I need to set up another array for the winner?
and DecimalFormat class means nothing to me lecturer just...
got it working thanks for the help!
Just one thing how to I format the percentage to 2 decimal places?
import java.util.Scanner;
class Election2
{
public static void main(String args[])...
no i don't understand what you mean if you could just give me an example of what you are talking about then I would know.
If you mean that I cant work with the percentage until the loop has...
I'm looking for help with this I don't know what I am doing wrong I know that having
double percentage = (double) votes[i] / (double) sum * 100;
in the for loop isnt doing what I want it to do...
vote is the candidates vote and sum is the total votes i changed it so its simpler
import java.util.Scanner;
class Election2
{
public static void main(String args[]) throws Exception
{
...
I don't know any formula other than what i said the candidates vote / the total votes and * by 100 I haven't been given a formula.
im really confused if i move it out like so
for(int i = 0; i < candidate.length; i++)
{
System.out.println("Please enter the total votes for " + candidate[i]);
votes[i] =...
I guess what I am stuck on is actually how do I assign the votes for each candidate to the percentage variable at the end not every time a vote is inputed by the user so this is as far as can go...
Im only starting arrays and im stuck on the percentage of the total votes. I have all the rest of it compiling Im just getting an error when I try with the percentage bit. I havent finished the last...
had same problem other day shoulda known silly me!! thank you so much i feel like crying with relief!!! ^:)^
Ive to write a software program that allows a user to order groceries?
Ive to ask for the users details names, address etc.
I have to ask the user to input their grocery item and then the...
|
http://www.javaprogrammingforums.com/search.php?s=25ec63055da58c1b3b2bf6d34dbc400c&searchid=1223077
|
CC-MAIN-2017-30
|
refinedweb
| 539
| 80.92
|
This portion of the Kotlin Koans showed off a really boss feature of the language: Data Classes. These are special classes whose primary purpose is to hold data.
Here is a Java class that we start with that’s taken directly from the tutorial.
public class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
It’s not a special class. This is a class with a primary constructor, getters/setters and two private variables. It’s also one of my biggest complaints about the Java language. I can do the same thing in Python like this.
class Person: def __init__(self, name=None, age=None): self.name = name self.age = age
Four lines of code in Python. In all fairness to Java, would could just declare name and age to be public variables, but doing so is not only frowned upon, but many Java libraries look for getter/setter method to access a property of a Java bean. Basically speaking, even though we could allow for public access of a Java property, it’s not really practical at this point.
There is a Java library called Lombok that does a lot to solve this problem.
@Data public class Person { private String name; private String age; }
Lombok has been the solution I have used for most of my projects. It’s not perfect however. For example, I can’t use the @Data annotation to make a read only class. That forces me to use a mix of Lombok annotations or define a stereotype annotation. It’s not a huge problem, but it’s still something to think about.
Kotlin data classes take this to a whole other level. Here is the same class in Kotlin.
data class Person(val name: String, val age: Int)
That’s it! One line of code!!! With this single line of code, we get our two properties, it’s getter methods, hashcode, equals, toString() and a constructor. The class is immutable because the variables are declared with the val keyword. We can make the class mutable by using var instead of val. Finally, we aren’t losing our ability to work with existing Java libaries.
I really don’t see how it can get any better than this. I have used data classes countless times when working with ORM libraries such as hibernate. I’d say 95% of these classes are classes that just hold data and map to a table in the database. Although any IDE can generate constructors, getters/setters, equals, and hashcode, and toString, let’s face it, it’s even better to have this built directly into the language itself.
You can click here to see Part 6
|
https://stonesoupprogramming.com/tag/data-classes/
|
CC-MAIN-2020-29
|
refinedweb
| 469
| 74.79
|
Advanced Namespace Tools blog
12 January 2018
Guide to configuring Plan 9 upas to work with gmail
It has been a few years since I was using Plan 9 for my email. I took a break from Plan 9 during 2014 and during that time fell back into the habit of using the web-gmail interface. I decided it was time to fix this, which meant figuring out, for the 3rd time or so, how to get 9front talking with gmail's servers. It only took a couple hours of feverish manpage and guide reading and debugging to get the config worked out. This particular configuration process is not the most graceful aspect of Plan 9, but the mail environment is very nice once it is set up. In general, configuring systems to work with non-plan 9 protocols is always going to be more of a hassle than staying entirely within the ecosystem, so I'm not saying I see a better way to do all this. I understand that the whole system was originally designed and intended for running your own mail server, not retrieving things from gmail, so the awkardness seems related to that.
Receiving and reading email - the easy part
Just being able to receive and read messages is easy. Step one - log into your gmail via the web interface, go to the account options, and tell it to allow less-secure login methods. Now, in your plan9 system, enter a command like this:
upas/fs -f /imaps/imap.gmail.com/myname@mydomain.com
This will spit out an error that looks like:
upas/fs: opening /imaps/imap.gmail.com/myname@mydomain.com: \ imap.gmail.com/imaps:cert for imap.gmail.com not recognized: \ sha256=x9n2C90RHrd4e97E/i21h9Ios0mKZJ9w3WDg9OE9Ud9
Now you can make that hash be recognized. Note the x509 prefix in the echo statement:
echo 'x509 sha256=x9n2C90RHrd4e97E/i21h9Ios0mKZJ9w3WDg9OE9Ud9' >>/sys/lib/tls/mail
Now rerun the same upas/fs command as above, and factotum will prompt you for your password. Enter it, and upas will spend some time (which varies depending on the size of your mailbox) setting things up. Now you can start the mail program to read messages with the command
The tricky part: configuration for sending mail
Given how nice and easy that was, one might hope sending mail would be equally simple. Not quite. The configuration for sending is considerably more involved. A first step:
echo 'key proto=pass server=smtp.gmail.com service=smtp user=myname@mydomain.com !password=yourpassword' >/mnt/factotum/ctl
With that done, we have two files to configure in /mail/lib. The first is /mail/lib/rewrite. There is a template to use located at /mail/lib/rewrite.gateway. The easiest thing to do is just append the template to the blank-except-for-comments original.
cat /mail/lib/rewrite.gateway >> /mail/lib/rewrite
Editing the rewrite file is pretty simple. The only section that usually needs to be changed is shown below, and the change is obvious.
# append the local domain to addresses without a domain local!"(.+)" alias \1@mydomain.com local!(.*) alias \1@mydomain.com
With that done, we are ready to configure /mail/lib/remotemail. The configuration shown below may not be perfectly well-constructed, but works in practice.
#!/bin/rc shift sender=myname@mydomain.com shift addr=smtp.gmail.com shift fd=`{/bin/upas/aliasmail -f $sender} switch($fd){ case *.* ; case * fd=mydomain.com } echo exec /bin/upas/smtp -u myname@mydomain.com -a -h $fd $addr $sender $* >>/sys/log/remotemail exec /bin/upas/smtp -u myname@mydomain.com -a -h $fd $addr $sender $*
Note the addition of the -a flag to the pre-existing upas/smtp command. The echo statement is purely optional extra logging. We are almost done! You can try sending some mail with
mail someone@somedomain
Note that the mail program makes use of rio's "hold" mode, so you need to enter your message, then press escape, then hit ctrl-d to EOF the data you are sending. Sending this first message will fail because we need to add another bit of tls related info.
cat /sys/log/smtp
Will show an error that looks like
Jan 11 20:40:43 cert for gmail-smtp-msa.l.google.com not recognized: sha256=gE9IwK9spTR9613V92I5+sVI9R0U9PLKyaZjr8OiNH9
Again, you need to add this in the right place, which in this case is /sys/lib/tls/smtp.
echo 'x509 sha256=gE9IwK9spTR9613V92I5+sVI9R0U9PLKyaZjr8OiNH9' >>/sys/lib/tls/smtp
If all of this is done correctly, you should now be able to send mail successfully using the mail command.
Namespaces for your faces
Assuming you got all this done correctly and you can send and receive mail, you probably want to use Plan9's famous "faces" program to help out. It shows new mails as they arrive, and if you right click on the face icon, it will open them for you in a new window. However, you have to have a plumber running underneath your current rio, and faces needs to be in a namespace with access to upas/fs. You want to see a namespace stack like this within the rio you are working within:
mount '#s/plumb.user.15857' /mnt/plumb mount '#|/data1' /mail/fs mount '#s/rio.user.15869' /mnt/wsys 6
In other words, plumber first, then upas/fs, then start rio, then start faces within the rio. The conventional way to do this is having the plumber and upas started on your terminal from /usr/name/lib/profile.
Troubleshooting: check the logs
If something is misconfigured, you can often find out the problem from the logfiles. /sys/log/mail, /sys/log/runq, /sys/log/smtp, /sys/log/smtp.fail may all be relevant. I also added another log via the echo statement shown in remotemail, /sys/log/remotemail. Here is a summary of what needs to be done - check above for full details.
Reading mail
change your gmail settings to allow less-secure devices
add x509 crypto hash to /sys/lib/tls/mail after upas/fs -f to gmail imap
run upas/fs -f to gmail imap and answer factotum prompt for password
run mail program to read mail
Sending mail
Add key to factotum manually
Configure /mail/lib/rewrite based on /mail/lib/rewrite.gateway
Configure /mail/lib/remotemail script with appropriate variables
Add x509 crypto hash to /sys/lib/tls/smtp
run mail tosomeone@somewhere to send mail
Using multiple accounts
(The following information was provided by qwx)
I need to monitor multiple mailboxes, and be able to select from which one I should send. In order to select a different account from which to send from, you need to:
- set $upasname
- make /mail/lib/remotemail select the smtp user and server you need to send from.
My hacky solution so far is to just add a switch-case statement to remotemail, like:
; cat /mail/lib/remotemail #!/bin/rc shift sender=$1 shift addr=$1 shift if(~ gmail.com `{echo $sender | sed 's/^[^@]+@//'}){ fd=gmail.com addr=tcp!smtp.gmail.com!ssmtp user=(-tu $sender) } if not{ fd=other.server.net addr=other.server.net # WHY user=() } exec /bin/upas/smtp -dah $fd $user $addr $sender $*
Then, I can do:
; upasname=seymour@gmail.com mail -s 'whatever' butts@gmail.com
and this sends a mail from seymour@gmail.com to butts@gmail.com as expected. The user allegedly needs to be set as 'seymour@gmail.com', not just 'seymour'. The other thing is connecting to an SMTPS port: to do this, you can add -t to the upas/smtp command line, and specify !ssmtp in the address.
|
http://doc.9gridchan.org/blog/180112.upas.gmail
|
CC-MAIN-2021-21
|
refinedweb
| 1,269
| 64.1
|
I searched the site, but I didn't see anything quite matching what I was looking for. I created a stand-alone application that uses a web service I created. To run the client I use:
C:/scriptsdirecotry> "run-client.bat" param1 param2 param3 param4
How would I go about coding this in Python or F#. It seems like it should be pretty simple, but I haven't seen anything online that quite matches what I'm looking for.
Python is similar.
import os os.system("run-client.bat param1 param2")
If you need asynchronous behavior or redirected standard streams.
from subprocess import * p = Popen(['run-client.bat', param1, param2], stdout=PIPE, stderr=PIPE) output, errors = p.communicate() p.wait() # wait for process to terminate
In F#, you could use the
Process class from the
System.Diagnostics namespace. The simplest way to run the command should be this:
open System.Diagnostics Process.Start("run-client.bat", "param1 param2")
However, if you need to provide more parameters, you may need to create
ProcessStartInfo object first (it allows you to specify more options).
|
https://pythonpedia.com/en/knowledge-base/2916758/running-a-batch-file-with-parameters-in-python-or-fsharp
|
CC-MAIN-2020-16
|
refinedweb
| 181
| 59.19
|
I've developed & exposed jboss web service, is there a way to check which SOAP & WSDL version it supports?
you can either check the wsdl you started with, if wsdl first, or check the wsdl via your browser at
what you're looking for is the namespace used for either SOAP or WSDL or SOAP Envelope
if it starts with = SOAP 1.1 = SOAP 1.2/20
Would this xmlns:soap="" mean I'm using SOAP 1.1 ? Since we are using JB5, i thought it would support latest SOAP version 2.
It's 1.1
FYI, SOAP 1.2 isn't commonly used. At all
You can force a 1.2 binding by altering your wsdl and regenerating the code (wsdl first) or by adding some jaxws annotation to the implementing class ( i have no idea which ones)
|
https://community.jboss.org/message/724121?tstart=0
|
CC-MAIN-2014-15
|
refinedweb
| 139
| 82.65
|
What is package
Package in is a structure which organizes various class files in Java into different folders according to their functionality or categories by user, for example, all the java.io classes will be in java.io package whereas all the java.net classes such as Socket or SeverSocket will be inside java.net package.
Why we require Package in Java?
Package is required in java to differentiate between various types of classes such as java.net,java.io which allows us to access those classes more easily. Same as we keep a sad song, rock music in different sub-folders of folder music.
Creating a New Package
1) Go to your JAVA IDE such as Eclipse, Netbeans
2) Select new java package
3) Give a name to your package
4) Now drag and drop all the classes of similar functionality you want to put in your new created package
Packages Directory Structure
There are multiple things which occur when a class is placed in a package :
- The package name becomes a part of the name of the class
- The package name must match the directory structure where the corresponding bytecode belongs.
Importing a Package in a Class
Below is an example of a JAVA program to import package in a class
package packexample;
import packexample.dao.AccDao;
Public class PackExample {
public static void main (String[] args)
{
AccDAO obj = new AccDAO();
}
}
Using a class in a Package
package packxample.dao;
public class ACcDAO {
|
https://www.stechies.com/packages-java/
|
CC-MAIN-2021-17
|
refinedweb
| 244
| 51.78
|
19 February 2009 20:45 [Source: ICIS news]
BRUSSELS (ICIS news)--EU industry commissioner Gunter Verheugen warned on Thursday of structural change in European industry, driven by the current deep financial and economic crisis.
“The scope and depth of this crisis is unprecedented,” he said at the launch of the final report of the EU’s High Level Group on competitiveness of the chemicals industry.
“We are in a kind of freefall and have not yet hit the bottom,” he added.
EU analysis shows that the real economy has been hit hard by the crisis in the financial markets, Verheugen said.
“We must be aware that the industrial landscape in ?xml:namespace>
The first major effects of the crisis on European industry were expected this spring, the commissioner warned.
Delegates at the Industry Commission meeting, which was held to launch the High Level Group (HLG) of chemicals competitiveness final report, expected industry restructuring and job losses to mount in
“Structural change cannot be prohibited or prevented but can be managed,” Verheugen said as he warned against member states enacting anti-competitive policy to support some industries and jobs.
“Policy makers cannot make management decisions,” he said. “We must not allow market participants and members of the EU to jeopardise the functioning of the internal market.”
The European Commission must play a watchdog role in the circumstances, he said. “In our crisis response, we should not allow that short term needs jeopardise longer-term objectives, “he added.
Policy makers cannot prevent structural change, the industry commissioner suggested. “You don’t help the company or the sector involved,” he added.
Describing the HLG on chemicals process as a unique opportunity to discuss the views of the chemicals industry and sector stakeholders with the Commission, BASF CEO Jurgen Hambrecht said the industry was strongly committed to
The industry has restructured, he said. “We can take care of our own destiny.”.
|
http://www.icis.com/Articles/2009/02/19/9194195/eu+industry+commissioner+warns+of+structural+chem+changes.html
|
CC-MAIN-2013-20
|
refinedweb
| 317
| 50.46
|
Py5Image.get()
Contents
Py5Image.get()#
Reads the color of any pixel or grabs a section of an image.
Examples#
def setup(): mountains = py5.load_image("rockies.jpg") py5.background(mountains) py5.no_stroke() c = mountains.get(60, 90) py5.fill(c) py5.rect(25, 25, 50, 50)
def setup(): mountains = py5.load_image("rockies.jpg") py5.background(mountains) new_mountains = mountains.get(50, 0, 50, 100) py5.image(new_mountains, 0, 0)
Description#
Reads the color of any pixel or grabs a section of an image. If no parameters are specified, the entire image is returned. Use the
x and
y parameters to get the value of one pixel. Get a section of the image by specifying additional
w and
h parameters. When getting an image, the
x and
y parameters define the coordinates for the upper-left corner of the returned image, regardless of the current image_mode().
If the pixel requested is outside of the image, black is returned. The numbers returned are scaled according to the current color ranges, but only
RGB values are returned by this function. For example, even though you may have drawn a shape with
color_mode(HSB), the numbers returned will be in
RGB format.
Getting the color of a single pixel with
get(x, y) is easy, but not as fast as grabbing the data directly from Py5Image.pixels[]. The equivalent statement to
get(x, y) using Py5Image.pixels[] is
pixels[y*width+x]. See the reference for Py5Image.pixels[] for more information.
Underlying Processing method: PImage 16:36:02pm UTC
|
https://py5.ixora.io/reference/py5image_get.html
|
CC-MAIN-2022-40
|
refinedweb
| 253
| 52.97
|
On Tue, May 22, 2012 at 12:31 PM, Eric V. Smith eric@trueblade.com wrote:
On 05/22/2012 11:39 AM, Nick Coghlan wrote:.
This discussion has gotten me thinking: should we expose a pkgutil.declare_namespace() API to allow such an __init__.py to turn itself back into a namespace? (Per our previous discussion on transitioning existing namespace packages.) It wouldn't need to do all the other stuff that the setuptools version does, it would just be a way to transition away from setuptools.
What it would do is: 1. Recursively invoke itself for parent packages 2. Create the module object if it doesn't already exist 3. Set the module __path__ to a _NamespacePath instance.
def declare_namespace(package_name): parent, dot, tail = package_name.rpartition('.') attr = '__path__' if dot: declare_namespace(parent) else: parent, attr = 'sys', 'path' with importlockcontext: module = sys.modules.get(package_name) if module is None: module = XXX new module here module.__path__ = _NamespacePath(...stuff involving 'parent' and 'attr')
It may be that this should complain under certain circumstances, or use the '__path__ = something' idiom, but the above approach would be (basically) API compatible with the standard usage of declare_namespace.
Obviously, this'll only be useful for people who are porting code going forward, but even if a different API is chosen, there still ought to be a way for people to do it. Namespace packages are one of a handful of features that are still basically setuptools-only at this point (i.e. not yet provided by packaging/distutils2), but if it's the only setuptools-only feature a project is using, they'd be able to drop their dependency as of 3.3.
(Next up, I guess we'll need an entry-points PEP, but that'll be another discussion. ;-) )
|
https://mail.python.org/archives/list/python-dev@python.org/message/JBSQ226KQ2M5464JLMUXVJG7MLERQZ2O/
|
CC-MAIN-2022-27
|
refinedweb
| 295
| 57.27
|
in reply to How can I improve the efficiency of this very intensive code?
It may be that sorted arrays are the way to go, as mentioned elsewhere. But it might make sense to go from the data you have now to an inverted list of best matches, so as to sort each list only once:
and now the strong match test becomes:and now the strong match test becomes:my $inv = {}; for my $index (keys %$rc) { my $subhash = $rc->{$index}; my @sorted = sort { $subhash->{$a} <=> $subhash->{$b} } keys %$sub +hash; if ($subhash->{$sorted[0]} < $subhash->{$sorted[1]}) { # this is the best match push @{ $inv->{$sorted[0]} }, $index; } }
return (@{ $inv{$id2} } == 1) ? 1 : 0;
I'm not sure that I fully understand the problem, so the code might need some tweaking ...
Hugo
In Section Seekers of Perl Wisdom
|
https://www.perlmonks.org/?node_id=481573;displaytype=print;replies=1
|
CC-MAIN-2020-29
|
refinedweb
| 138
| 63.02
|
NAME
libroar - RoarAudio sound library roarvs - RoarAudio very simple API
SYNOPSIS
#include <roaraudio.h> roar_vs_t * vss;
DESCRIPTION
The VS (for Very Simple) API is a high level abstraction layer used to allow use of RoarAudio from very simple programs. The API was designed to help people to easly upgrade existing artsc and pulse-simple code to RoarAudio. While the API is equivalently simple it is much more powerful than one one by aRtsc or PulseAudio. The VS API also has a mode to play back (and record) files easly. As this uses VIO/DSTR it can handle streams as well.
TUTORIALS
Tutorials can be found in roartut(7).
IMPORTANT FUNCTIONS
There are several important functions. This is a small list of the most important ones. Error handlingf roar_vs_strerr(3) Opening roar_vs_new(3), roar_vs_new_simple(3), roar_vs_new_playback(3), roar_vs_new_from_file(3) Closing roar_vs_close(3) Reading and writing roar_vs_read(3), roar_vs_write(3) Non-Blocking and Asyncron IO roar_vs_blocking(3), roar_vio_select(3) Volume and Flags roar_vs_pause(3), roar_vs_mute(3), roar_vs_volume_mono(3), roar_vs_volume_stereo(3), roar_vs_volume_get(3) Meta data roar_vs_meta(3), roar_vs_role(3) File mode roar_vs_file(3), roar_vs_file_simple(3), roar_vs_iterate(3), roar_vs_run(3) Buffered mode roar_vs_buffer(3), roar_vs_iterate(3), roar_vs_run(3)
BUGS
A lot...
SEE ALSO
roar-config(1), roartypes(1), roartut(7), RoarAudio(7).
|
http://manpages.ubuntu.com/manpages/oneiric/man7/roarvs.7.html
|
CC-MAIN-2014-41
|
refinedweb
| 208
| 55.44
|
Cross Compling Code
I have never used the OpenWRT tool chain. It took me a bit to get the cross compile setup to a point where I think its working on an ubuntu system.
I followed the steps from
I setup a new package that's currently just a hello world example but will become an I2C to SPI library to use an SC18IS602 I2C to SPI converter ()
When I build my new test package:
$ make package/i2c_spi_bridge/compile
make[1] package/i2c_spi_bridge/compile
make[2] -C package/libs/toolchain compile
make[2] -C package/i2c_spi_bridge compile
so building appears fine but I can't tell where the compiled code is located, where did it go?
I then compiled directly calling a gcc from the staging_dir/toolchain directory, not sure if this is the correct one but the code did compile. Is this the correct gcc to use?
../../../staging_dir/toolchain-mips_34kc_gcc-4.8-linaro_uClibc-0.9.33.2/bin/mips-openwrt-linux-uclibc-gcc i2c_spi_bridge.c -o test
I haven't tested this yet because the onion is on a different wireless network then I'm on, but is hooked up to this machine using the usb port. Is there a way for me to send a file to the onion using the usb port?
@will-burke Congratulations on getting Cross Compile going with the OpenWrt tool chain - it takes quite an effort to figure it out and get it working
A few pointers that may assist with the issues you raise in your message:
The built *.ipk packages will be found in your openwrt directory somewhere under the directory /bin/ar71xx/packages/
The best way to install an .ipk that you have built is to copy it to somewhere on your Omega and then run the command:
opkg install <path-to-ipk-file>
If you just want to compile standard C/C++ code without building .ipk, the toolchain compiler is the best way to go.
I use a separate copy of the toolchain from :
and details of its setup and usage can be found at:
I have been using this for building my new-gpio C++ code and associated programs, information on which can be found at:
Finally, connecting to you Omega via the USB port can be done using COM port access as is covered in
Hope that some of this may be helpful to you
Thanks for the tips. I have compiled and successfully tested on the Omega using the separate copy of the toolchain as you describe.
I'm on to my next issue. I'm trying to use the I2C library:
I copied over the libonioni2c.so from the onion and am trying to link to the .so. However when I call the i2c_ functions they are still undefined references.
Command:
Output:
/tmp/cc4spNYj.o: In function
SC18IS602::WriteBytes(unsigned char*, unsigned char)': SC18IS602.cpp:(.text+0x2c): undefined reference toi2c_writeBuffer'
/tmp/cc4spNYj.o: In function
SC18IS602::ReadBytes(unsigned char*, unsigned char)': SC18IS602.cpp:(.text+0x80): undefined reference toi2c_read'
/tmp/cc4spNYj.o: In function
SC18IS602::ReadByte()': SC18IS602.cpp:(.text+0x198): undefined reference toi2c_readByte'
/tmp/cc4spNYj.o: In function
SC18IS602::WriteRegister(unsigned char, unsigned char)': SC18IS602.cpp:(.text+0x1f4): undefined reference toi2c_write'
collect2: error: ld returned 1 exit status
@will-burke Glad to hear you have got something going on cross compilation.
Don't know why you are having linking to libonioni2c.so
I have not tried directly linking to .so files copied from the Omega.
I normally compile such libraries myself from the sources and link to them.
Having said that, i can see nothing immediately wrong in the information you posted.
I tried copying libonioni2c.so from my Omega to my Kubuntu system so I could try running nm, objdump and readelf on it (these are not currently available on the Omega).
While I don't know if there is any issues with running the Kubuntu versions of these programs against an Omega .so, they all indicated that there was no dynamic link entries for the functions you reference.
@will-burke Update to my previous message:
I have found where to get nm, objdump and readelf for the Omega. Run opkg install binutils and they will be available on the Omega.
Using these against /usr/lib/libonioni2c.so gives the same information as the Kubuntu versions. I.E. can find no reference to the required functions.
So, sorry still no ideas
- will burke last edited by will burke
That is most likely the issue. I'm trying to use the i2c library. What I really need is spi but I'm io limited so I can't just Bit Bang spi on the gpio. I need to use the i2c to spi bridge. I just assumed I was linking to the correct .so with those functions, it appears that I'm not.
Thanks for the help. That was the issue. I had to include the src files from src/lib/onion-i2c.c and src/lib/onion-debug.c. The section on using the library was not completely clear and I assumed the header was just for reference the functions in the library.
Header File
To add the Onion I2C Library to your C/C++ program, include the header file in your C code:
#include <onion-i2c.h>
Library for Linker
In your project's makefile, you will need to add the following static libraries to the linker command:
-loniondebug -lonioni2c
The static libraries are stored in /usr/lib on the Omega.
@will-burke Glad you have got something going
I confess I missed something in your original post. Where you use you are trying to both compile and link in one go.
Basically OK but not commonly used for anything but the simplest of programs. Also, as I believe you have found, you need to #include headers (.h files) in your source for anything for which you are not providing the code directly.
More common way of building is to:
- Compile each .cpp file to a .o (object file) using something like:
mips-openwrt-linux-uclibc-g++ -c -O2 -fPIC xxx.cpp -o xxx.o
- Then link all the .o files and any used libraries using something like:
mips-openwrt-linux-uclibc-g++ -o <prog-name> <list-of-obj-files> -L<lib-dir> -l<libname1> -l<libname2>
What I find a bit surprising/confusing is that throughout it refers to static libraries. Yet files like libonioni2c.so are dynamic libraries (and the examples in the reference use them as such). Access to the dynamic libraries are needed during linking to resolve the access to the functions, but (unlike static linked libraries) are NOT included in the linked code - rather, a reference is included in the linked code to the library name which is used to actually load the needed code at RUN time.
I now have my code compiling and running. I successfully configure the I2C to SPI Bridge.
As a first test I'm sending/receiving 0x55 and 0xAA bytes on the SPI bus. I looped MOSI to MISO so that I receive the data sent. This is working, however after successfully running and transmitting all bytes of data the program aborts. Could this abort be caused by the static vs dynamic linking that you are talking about?
@will-burke Well done on getting something running
Given that you say you are successfully sending and receiving data via you I2C to SPI bridge, your problem almost certainly is not due to any linking issues. It is more likely to be a bug somewhere in your code.
In the absence of any remote interactive debugger system (that I know of) for debugging code running on the Omega, my best suggestion is that you liberally sprinkle meaningful diagnostic printf statements through out you code to track at what point it fails.
While I don't have access to an I2C to SPI bridge device, I could cast an eye over your code if you sent me a copy of the source code and any Makefile (or commands you use to build it) to see if I can spot anything you might be doing wrong.
The
@will-burke I'll take a look at the code you sent and will get back to you if I spot anything.
- Kit Bishop last edited by Kit Bishop
@will-burke Have had a play with the code you sent.
It all looks good and (as far as I can tell without having an I2c to SPI bridge myself) works as intented.
Except for getting the Aborted at the end.
I'm not sure why this would be so, but it seems to be due to creating i2cspi in i2c_spi_bridge.c on the stack rather than the heap. I made changes to i2c_spi_bridge.c to allocate i2cspi on the heap (this is the changed file: i2c_spi_bridge.c ). The changes consist of:
- Changing the line:
SC18IS602 i2cspi=SC18IS602(SC18IS602_ADDRESS_000);
to
SC18IS602 * i2cspi=new SC18IS602(SC18IS602_ADDRESS_000);
- Replacing all instances of i2cspi. to i2cspi->
- Ensuring that delete i2cspi; is called before exit.
Now all seems to be running OK.
I have also taken the liberty of making some small changes to the following files which I also attach:
- onion-debug.c - the path is not needed in the #include since it is taken care of by the -I used in build_test1
- build_test1 - have removed the -L and -l stuff from the link step. You are not actually linking to these libraries since you build the .o files and include them already in the link step.
Hope this all helps.
|
https://community.onion.io/topic/574/cross-compling-code/10?lang=en-GB
|
CC-MAIN-2020-45
|
refinedweb
| 1,596
| 72.46
|
This is part of a series I started in March 2008 - you may want to go back and look at older parts if you're new to this series.
It's been a few months, and apart from my side step into parser land I haven't had much time to keep posting this series, in part because of work, and part because of repeated illness that after being poked and prodded and x-rayed and being subjected to ultrasound (no, I'm not pregnant, nor is anything about to rupture) and being tapped for what feels like several litres of blood turns out to likely 'only' be infectious mononucleosis. Luckily I've avoided the sometimes lengthy bouts of fatigue, but 4 rounds with several days of fevers and fatigue in just a few months hasn't been entertaining, and if I'm unlucky I might keep getting them occasionally for a few more months. Fun.
Anyway, enough moaning. Last time, I implemented support for arrays, and mentioned local variables as one of the remaining targets:
Lets first figure out how to do it, by resorting to our trusted old method of seeing what gcc does to this:
int foo() { unsigned int i; i = 42; }
This is the abbreviated result of gcc -s:
foo: pushl %ebp movl %esp,%ebp subl $16, %esp movl $42, -4(%ebp) leave ret
Figuring out what's going on shouldn't be too hard:
There's not all that much to it.
Our first step is to introduce a new type of scope. Previously I added the Scope class to keep track of named parameters to a function. Now we have another form: A set of variables tied to a local scope. Why not tie it directly to the function, and just add it to the Scope class? Consider Ruby blocks or the lambda's we've already introduced: Many languages have constructs that introduce new scopes inside a function that may only encompass part of that function. Adding a new class gives us flexibility to introduce new scopes wherever we want:
class LocalVarScope def initialize locals, next_scope @next = next_scope @locals = locals end def get_arg a a = a.to_sym return [:lvar,@locals[a]] if @locals.include?(a) return @next.get_arg(a) if @next return [:addr,a] # Shouldn't get here normally end end
This LocalVarScope class follows the same interface as the Scope class for the #get_arg method which is the only thing we really cares about. It returns a new type :lvar to indicate a local variable, which needs to be given different treatment during code generation. If it can't find a local variable, it tries passing the #get_arg request on to the next scope. The last line is a fallback - at that point we could either make it an error, or do as we've done in the past and just assume it refers to a global variable defined elsewhere. It would only get that far if the LocalVarScope occurs outside a function, which is a major WTF, so perhaps I should make it a variable. That's one for later.
Our next step is to handle :lvar. The following is added to #compile_eval_arg immediately before the return:
@e.load_local_var(aparam) if atype == :lvar
This calls a new function in the emitter to load a local variable into %eax. So lets add the new functions to the emitter:
def local_var(aparam) # FIXME: The +2 instead of +1 is ecause %ecx is pushed onto the stack in "main". It's really only needed there. "-#{PTR_SIZE*(aparam+2)}(%ebp)" end def load_local_var(aparam) movl(local_var(aparam),:eax) end def save_to_local_var(arg,aparam) movl(arg,local_var(aparam)) end def with_local(args) # FIXME: The "+1" is a hack because main contains a pushl %ecx with_stack(args+1) { yield } end
#local_var is a helper to return the correct offset off (%ebp). The FIXME relates to the fact that we save %ecx in the main function, and for now I won't treat the main function differently, which means wasting 4 bytes for every strack fame instead. [Yeah, I know - it'll get fixed]
#with_local is a helper equivalent to #with_stack. It's introduced for two reasons: a) it's possible we'll want to implement them differently on different architectures, and more importantly for now, b) it hides the "hack" mentioned above squarely in the Emitter.
#load_local_var and #save_to_local var does the obvious things - they load and store the local variable from/to a register where we can manipulate the value more easily. Which brings us to a problem...
So far we've done nothing to handle register allocation. We've just assumed "default" registers for various expressions, and it's worked. But it's worked because almost all we've done has been function calls which involve saving stuff to the stack and popping it back off.
However, that's a very inefficient solution, and eventually it needs to be fixed. There are two approaches to solving this:
1) Allocate registers "properly"; and there's a hell of a lot of literature on doing that well - you want to avoid unnecessary memory accesses by keeping the most frequently used variables in memory, but you also need to be careful as it can cause a real mess when it comes to thread synchronization etc.
2) Keep pushing things on the stack, and then rely on a "smart" peephole analyzer to "fix" things by removing stack manipulation and doing the register allocation properly at that stage. Essentially you're not getting away from #1 - to get a high performance compiler, sooner or later you need to worry about proper register allocation.
Unsurprisingly, I've opted for later. Functionality first. So to make sure things continues to work for now we make some small changes to use the stack. Here's a diff of #compile_assign:
def compile_assign scope, left, right source = compile_eval_arg(scope, right) + @e.pushl(source) atype, aparam = get_arg(scope,left) if atype == :indirect + @e.popl(:eax) @e.emit(:movl,source,"(%#{aparam})") + elsif atype == :lvar + @e.popl(:eax) + @e.save_to_local_var(source,aparam) elsif atype == :arg + @e.popl(:eax) @e.save_to_arg(source,aparam) else raise "Expected an argument on left hand side of assignment" end return [:subexpr] end
In addition to the call to the previously defined #save_to_local_var to handle the case where a local variable is the left argument to an assign, we've littered the function with a pushl (push to the stack) and popl (pop something off the stack) to avoid clobbering intermediate results.
"let" is a name with long traditions - having been used in LISP, numerous BASIC's and a variety of modern functional languages. We use "let" as a construct to list a bunch of local variables, and make the expressions contained in a "let" define the scope. Example:
(let (a b c) expr1 expr2 .. expr-n)
This allows us to introduce new scopes wherever we like. Later, when I put a more advanced parser on top, we may end up hiding this functionality and have the parser or an intermediate stage introduce let's where it fits to introduce new scopes.
First we augment #compile_exp:
return compile_let(scope,*exp[1..-1]) if (exp[0] == :let)Simple enough, so let's move on to #compile_let:
def compile_let(scope,varlist,*args) vars = {} varlist.each_with_index {|v,i| vars[v]=i} ls = LocalVarScope.new(vars,scope) @e.with_local(vars.size) { compile_do(ls,*args) } end
As you can see it quite straightforwardly uses the new LocalVarScope class, and it then compiles the expressions enclosed in the let expression.As you can see it quite straightforwardly uses the new LocalVarScope class, and it then compiles the expressions enclosed in the let expression.
prog = [:let, [:i], [:assign, :i, [:array, 2]], [:printf, "i=%p\n",:i], [:assign, [:index, :i, 0], 2], [:assign, [:index, :i, 1], 42], [:printf, "i[0]=%ld, i[1]=%ld\n",[:index,:i,0],[:index,:i,1]] ]
As usual the full source code is available for download here.
|
https://hokstad.com/writing-a-compiler-in-ruby-bottom-up-step-13
|
CC-MAIN-2021-21
|
refinedweb
| 1,330
| 57.71
|
So I am checking event viewer and on one user's computer I keep getting this warning. A provider, InvProv, has been registered in the Windows Management Instrumentation namespace Root\cimv2 to use the LocalSystem account. This account is privileged and the provider may cause a security violation if it does not correctly impersonate user requests. Should I be worried about this? When I google this I only get other forums with users requesting more information about this.
2 Replies
· · ·
Mar 26, 2015 at 22:24 UTC
Are you noticing any problems with that computer? If not, this is a pretty mundane event and shouldn't cause any issues.
1
· · ·
Apr 25, 2018 at 14:22 UTC
Just saw this on a computer as well. User recently clicked a link through email and are Virus control blocked multiple exe files from installing.
0
|
https://community.spiceworks.com/topic/862452-wmi-providers
|
CC-MAIN-2018-22
|
refinedweb
| 143
| 64.41
|
Code the Streaming Lite Custom Java Adapter
09/27/2018
Details
The full source code for the Custom Java Adapter is available in the ‘Appendix’ section of this tutorial.
Add the following import statements required to create our custom Java Adapter, below our package
custom_java_adapter line:;
We will need to use our
SDK object throughout the code, and so we will add it inside of our
JavaAdapter class:
private static final SDK s_sdk = SDK.getInstance();
We will now add a method inside our
JavaAdapter class, before the
main() method and after our
SDK object. It will be called
exec(), and is used to output the value printed by whatever command is given in input. This function is useful because various scripts can be executed to poll external hardware sensors on our
Raspberry Pi (or other remote device).; }
We are ready to code the
main() function, and the first thing to do is declare adapter variables.
The adapter variables can be split into two groups. The first group is used to connect to our Streaming Lite project, and control the quantity and rate of rows sent. The second group is the schema of the stream we are writing to, with one variable for each column.
Declare and define all variables in the first group. They are:
hostname,
port,
stream,
username,
repeat, and
interval. These variables can be named whatever you wish; they are either passed into the various
SDKcalls, or used for loop logic.
Our implementation is shown here. You will need to change these values to suit your program:
String val_host = "SAPraspberrypi2-B3"; int val_port = 9230; String val_stream = "isFreezerTemperatureReading"; String val_username =""; String val_password =""; int val_repeat = -1; int val_interval = 1;
When this Java Adapter executes, it will connect with the project running on port
9230, and write to the stream
"isFreezerTemperatureReading". There are no credentials, and the program will continuously send one row every second.
Declare and define column variables in the second group. Recall that the schema of the stream we are writing to is:
This means we will be using four variables. Every custom Java Adapter will have a different group of variables for this section. Once again, naming does not matter. In this document they will be:
String val_sensorId ="RaspberryPi"; String val_Temperature_Command = "echo 90"; Date val_readingDate = null; //generated right before row is sent long val_id = 0; //generated in streaming lite
String val_sensorIdis the name of our sensor.
String val_temperatureholds the command to run in order to obtain the value for our Temperature column.
Date val_readingDateis a timestamp. A value will be assigned to it later in the code, directly before it is used.
long val_idis our primary key, but will be auto-generated inside the streaming project. Although we still declare it, the value of
val_idis arbitrary and will be overwritten once inside the streaming project. The reason we need it in our custom Java Adapter is because the entire row must be constructed before it is sent into Streaming Lite.
We will now start using
SDK calls to connect with the project we want to write to. However, in order to do that, we must be aware of the errors our code might throw. Therefore, we will add a
try/catch block in our
main().
Add this block directly after our adapter variables:
try{ } catch (LoginException | EntityNotFoundException | ServerErrorException | IOException e){ e.printStackTrace(); }
For the question below, select the correct answer, and click Validate.
Generally, all
SDK calls (inside the
main()) can be grouped into two sections. The first section prepares for writing to our project, and creates/connects the required
project/
credentials/
streams/
writer objects. The second section writes a single row into our project, and runs inside a loop. We will take a look at the first section now. All of this will be included inside of our try block.
Start the
SDK:
s_sdk.start();
Create the Credentials object, even if our username and password are both blank:
Credentials creds = new Credentials.Builder(Credentials.Type.USER_PASSWORD).setUser(val_username).setPassword(val_password).create();
Create and connect to the Project object. When we connect, we will wait for a max of 1000 milliseconds.
Project project = s_sdk.getProject(val_host, val_port, creds); project.connect(1000);
Create and connect to the Publisher object.
Publisher publisher = project.createPublisher(); publisher.connect();
Create the Stream object
Stream stream = project.getStream(val_stream);
Create the
MessageWriter object. The
MessageWriter object builds a single row to be sent into the specific project and stream it was created for
MessageWriter message = publisher.getMessageWriterCached(stream);
Create the
RelativeRowWriter object. The
RelativeRowWriter object formats a row of data for the stream that the
MessageWritter writes to.
RelativeRowWriter row = message.getRelativeRowWriter();
After setting up all required objects, we will now be able to construct and send our row. This will be done inside a loop, governed by our
val_repeat and
val_interval variables. This loop runs inside our try block, and is what controls the quantity and frequency of data the custom Java Adapter sends. It will contain the second section of
SDK calls.
We will be using a
do/while loop. Copy this directly after our
SDK preparation calls (we are still inside the
try block):
do { if ( val_repeat != -1) val_repeat-- ; //SDK row writing calls go here // wait for interval.. if ((val_repeat == -1 || val_repeat > 0) && val_interval > 0){ try { Thread.sleep(val_interval*1000); } catch (InterruptedException e) { e.printStackTrace(); break; } } } while ((val_repeat == -1 || val_repeat > 0) && val_interval > 0);
There are two if statements inside the loop. The first if statement checks for our infinity condition. If the value of
val_repeat is
-1, no decrement occurs and the loop runs forever.
The second if statement pauses execution using the
Thread.sleep() function for a
val_interval*1000 number of milliseconds. This controls the frequency of loop execution. If an exception is thrown, the loop will exit.
The second section of
SDK calls used to construct and send a row will be written in between these 2 if statements.
In this section we will start a row, and set its fields according to the schema of the stream we are sending it into. This is the part of the code that must be customized for each project that the custom Java Adapter is used with.
Starting the row
Start a new row definition. It is the first call when starting a new row:
row.startRow();
Set the row operation as insert:
row.setOperation(Operation.INSERT);
Other possible
enumvalues are:
- NOOP
- UPDATE
- DELETE
- UPSERT
- SAFEDELETE
Setting Fields
The
RelativeRowWriterclass provides a series of functions which set one field of your row at a time. Every function will set a field with a specific data type, and these functions cannot search by field name. Therefore, calling one will set the next available matching field of that data type, without regard for field names.
A full list of the functions for each data type can be found by viewing the
RelativeRowWriterclass. Under the Package Explorer window, go to Referenced Libraries, and then expand:
streaming_client.jar > com.sybase.esp.sdk.data > RelativeRowWriter.class
- Column 1: Following the schema of the stream we are writing to, we will now set the first field called
SensorId. This field is a type String, and the value we wish to write is in our variable
val_sensorId. To set the field, we will use
row.setString()
row.setString(val_sensorId);
- Column 2: The second column we are setting is called
Temperature, and will contain our temperature sensor data. This is where the function
exec()will be called, to run the command in our string variable
val_Temperature_Command. We will declare a new String variable to hold the return value of our
exec()function, and parse it into a double before setting the field using
row.setDouble()
String temperature_s = exec(val_Temperature_Command); row.setDouble(Double.parseDouble(temperature_s));
- Column 3: The third column is called
ReadingDate, and is a timestamp of when the temperature value was read. We will provide our
val_readingDatewith the current time value, and pass it into
row.setMSDate()
val_readingDate = new Date(); row.setMSDate(val_readingDate);
- Column 4: The forth column is called
Id, will be automatically generated in our Streaming Lite project. Therefore, we will be arbitrarily sending it a value of
0, from our
val_idvariable. To set this last column, we will use
row.setLong()
row.setLong(val_id);
Ending the Row
We end the row by calling
row.endRow():
row.endRow();
Writing the Completed Row to Streaming Lite
We now publish the row which
RelativeRowWriterhas packaged inside our
MessageWriterobject
publisher.publish(message, true);
When we commit the publisher, the row gets sent into Streaming Lite:
publisher.commit();
We can add this line after sending the row successfully:
System.out.print("Message published successfully\n");
Now that we have completed coding everything inside the loop, as well as the
try/catch block, we will need to stop the
SDK, no matter how the program exits.
The last line of our
main() method is a stop call to the SDK. This is placed directly after the catch block, and before the closing bracket for our
main() method:
s_sdk.stop();
Click the Done button below once you have completed this tutorial.
Below is the source code for our Java Adapter, customized to write into Freezer Monitoring Lite. You will need to change the hostname variable
(val_host) to match your remote device.
JavaAdapter.java
package custom_java_adapter;; public class JavaAdapter { private static final SDK s_sdk = SDK.getInstance(); /* * Executes a command and return result as string. * In this example the command should only generate one number. */ private static String exec(String cmd) throws IOException { Process p = Runtime.getRuntime().exec(cmd); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); String s = stdInput.readLine(); return s; } public static void main(String[] args) { String val_host = "SAPraspberrypi2-B3"; int val_port = 9230; String val_stream = "isFreezerTemperatureReading"; String val_username = ""; String val_password = ""; int val_repeat = -1; int val_interval = 1; String val_sensorId = "RaspberryPi"; String val_Temperature_Command = "echo 90"; Date val_readingDate = null; //generated right before row is sent long val_id = 0; //generated in streaming lite try { //start SDK s_sdk.start(); //create Credentials object Credentials creds = new Credentials.Builder(Credentials.Type.USER_PASSWORD).setUser(val_username).setPassword(val_password).create(); //create and connect Project object Project project = s_sdk.getProject(val_host, val_port, creds);; project.connect(1000); //create and connect Publisher object Publisher publisher = project.createPublisher(); publisher.connect(); //create Stream object Stream stream = project.getStream(val_stream); //create MessageWriter object MessageWriter message = publisher.getMessageWriterCached(stream); //create RelativeRowWriter object RelativeRowWriter row = message.getRelativeRowWriter(); do { if (val_repeat != -1) val_repeat--; //starts a new row definition. First call when starting row row.startRow(); //set row operation row.setOperation(Operation.INSERT); //column 1 a string (SensorID) row.setString(val_sensorId); //column 2 a float (Temperature) String temperature_s = exec(val_Temperature_Command); row.setDouble(Double.parseDouble(temperature_s)); //column 3 a msdate (ReadingDate) val_readingDate = new Date(); row.setMSDate(val_readingDate); //column 4 a long (Id) //end row row.endRow(); //publish and commit data publisher.publish(message, true); publisher.commit(); System.out.print("Message published successfully\n"); // wait for interval.. if ((val_repeat == -1 || val_repeat > 0) && val_interval > 0) { try { Thread.sleep(val_interval * 1000); } catch (InterruptedException e) { e.printStackTrace(); break; } } } while ((val_repeat == -1 || val_repeat > 0) && val_interval > 0); } catch (LoginException | EntityNotFoundException | ServerErrorException | IOException e) { e.printStackTrace(); } //stops SDK s_sdk.stop(); } }
|
https://developers.sap.com/canada-fr/tutorials/hsa-lite-custom-java-adapter-part3.html
|
CC-MAIN-2018-43
|
refinedweb
| 1,842
| 58.08
|
I was reading Rupert Miller’s book Beyond ANOVA when I ran across this line:
I never use the Kolmogorov-Smirnov test (or one of its cousins) or the χ² test as a preliminary test of normality. … I have a feeling they are more likely to detect irregularities in the middle of the distribution than in the tails.
Rupert wrote these words in 1986 when it would have been difficult to test is hunch. Now it’s easy, and so I wrote up a little simulation to test whether his feeling was justified. I’m sure this has been done before, but it’s easy (now—it would not have been in 1986) and so I wanted to do it myself.
I’ll compare the Kolmogorov-Smirnov test, a popular test for goodness-of-fit, with the Shapiro-Wilks test that Miller preferred. I’ll run each test 10,000 times on non-normal data and count how often each test produces a p-value less than 0.05.
To produce departures from normality in the tails, I’ll look at samples from a Student t distribution. This distribution has one parameter, the number of degrees of freedom. The fewer degrees of freedom, the thicker the tails and so the further from normality in the tails.
Then I’ll look at a mixture of a normal and uniform distribution. This will have thin tails like a normal distribution, but will be flatter in the middle.
If Miller was right, we should expect the Shapiro-Wilks to be more sensitive for fat-tailed t distributions, and the K-S test to be more sensitive for mixtures.
First we import some library functions we’ll need and define our two random sample generators.
from numpy import where from scipy.stats import * def mixture(p, size=100): u = uniform.rvs(size=size) v = uniform.rvs(size=size) n = norm.rvs(size=size) x = where(u < p, v, n) return x def fat_tail(df, size=100): return t.rvs(df, size=size)
Next is the heart of the code. It takes in a sample generator and compares the two tests, Kolmogorov-Smirnov and Shapiro-Wilks, on 10,000 samples of 100 points each. It returns what proportion of the time each test detected the anomaly at the 0.05 level.
def test(generator, parameter): ks_count = 0 sw_count = 0 N = 10_000 for _ in range(N): x = generator(parameter, 100) stat, p = kstest(x, "norm") if p < 0.05: ks_count += 1 stat, p = shapiro(x) if p < 0.05: sw_count += 1 return (ks_count/N, sw_count/N)
Finally, we call the test runner with a variety of distributions.
for df in [100, 10, 5, 2]: print(test(fat_tail, df)) for p in [0.05, 0.10, 0.15, 0.2]: print(test(mixture,p))
Note that the t distribution with 100 degrees of freedom is essentially normal, at least as far as a sample of 100 points can tell, and so we should expect both tests to report a lack of fit around 5% of the time since we’re using 0.05 as our cutoff.
Here’s what we get for the fat-tailed samples.
(0.0483, 0.0554) (0.0565, 0.2277) (0.1207, 0.8799) (0.8718, 1.0000)
So with 100 degrees of freedom, we do indeed reject the null hypothesis of normality about 5% of the time. As the degrees of freedom decrease, and the fatness of the tails increases, both tests reject the null hypothesis of normality more often. However, in each chase the Shapiro-Wilks test picks up on the non-normality more often than the K-S test, about four times as often with 10 degrees of freedom and about seven times as often with 5 degrees of freedom. So Miller was right about the tails.
Now for the middle. Here’s what we get for mixture distributions.
(0.0731, 0.0677) (0.1258, 0.1051) (0.2471, 0.1876) (0.4067, 0.3041)
We would expect both goodness of fit tests to increase their rejection rates as the mixture probability goes up, i.e. as we sample from the uniform distribution more often. And thatis what we see. But the K-S test outperforms the S-W test each time. Both test have rejection rates that increase with the mixture probability, but the rejection rates increase faster for the K-S test. Miller wins again.
3 thoughts on “Testing Rupert Miller’s suspicion”
I thought that this was well known and the solution was to use Kuiper’s variant of the KS test. At least this seems to be what _Numerical Recipes_ (3rd edition, section 14.3.4) is saying.
“Power comparisons of the Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests” by Razali agrees with you ;-)
Thanks, Amos. I’m not familiar with Kuiper’s variant. Miller thought that variations on KS had the same problem, but I don’t know whether he knew of Kuiper’s version.
I was going to repeat my simulations with the test you recommend, but apparently there’s no implementation of it in SciPy, and I don’t want to put more time into this by searching for implementations or writing one myself.
|
https://www.johndcook.com/blog/2019/09/18/kstest-shapiro/
|
CC-MAIN-2019-51
|
refinedweb
| 874
| 72.05
|
IRC log of i18nits on 2008-01-23
Timestamps are in UTC.
13:38:36 [RRSAgent]
RRSAgent has joined #i18nits
13:38:36 [RRSAgent]
logging to
13:38:42 [Zakim]
Zakim has joined #i18nits
13:38:55 [fsasaki]
meeting: i18n ITS WG
13:38:59 [fsasaki]
chair: Yves
13:39:03 [fsasaki]
scribe: Felix
13:39:08 [fsasaki]
scribeNick: fsasaki
13:39:20 [fsasaki]
regrets: Christian, Jirka
13:39:40 [fsasaki]
agenda:
13:53:46 [YvesS]
YvesS has joined #i18nits
13:57:01 [YvesS]
Hi Felix
13:57:15 [fsasaki]
Hi Yves
14:00:22 [Zakim]
I18N_TS()9:00AM has now started
14:00:29 [Zakim]
+Yves_Savourel
14:00:58 [Zakim]
+Felix
14:03:31 [fsasaki]
topic: action items
14:03:45 [fsasaki]
ACTION-3 to be done soon
14:04:01 [YvesS]
14:04:21 [fsasaki]
ACTION-11 and ACTION-59
14:04:38 [Zakim]
+??P10
14:04:47 [bbogacki]
bbogacki has joined #i18nits
14:04:49 [fsasaki]
Yves: external file is nice
14:05:23 [r12a]
r12a has joined #i18nits
14:05:27 [r12a]
zakim, dial richard please
14:05:27 [Zakim]
ok, r12a; the call is being made
14:05:29 [Zakim]
+Richard
14:06:54 [fsasaki]
close ACTION-59
14:06:54 [trackbot-ng]
ACTION-59 Send another mail to Leigh Klotz about XForms example closed
14:07:13 [fsasaki]
action: Felix to create local and global ITS markup for the XForms example file
14:07:13 [trackbot-ng]
Created ACTION-63 - Create local and global ITS markup for the XForms example file [on Felix Sasaki - due 2008-01-30].
14:07:23 [fsasaki]
close ACTION-11
14:07:23 [trackbot-ng]
ACTION-11 Send his ITS rules files to XForms WG closed
14:08:06 [fsasaki]
ACTION-33 and ACTION-45
14:08:31 [fsasaki]
14:11:03 [fsasaki]
Richard: fine by me
14:11:15 [fsasaki]
Felix: I'll implement the changes
14:11:48 [fsasaki]
ACTION-54 talk about it later
14:12:37 [fsasaki]
ACTION-55 ongoing
14:13:25 [fsasaki]
ACTION-56 ongoing (see mail to member list)
14:13:54 [fsasaki]
close ACTION-58 (done by Yves)
14:14:01 [fsasaki]
close ACTION-58
14:14:01 [trackbot-ng]
ACTION-58 Remove revision log before publication of BP document as WG Note closed
14:14:47 [fsasaki]
close ACTION-60
14:15:17 [fsasaki]
close ACTION-60
14:15:17 [trackbot-ng]
ACTION-60 Remove edit marks closed
14:15:27 [fsasaki]
close ACTION-61 ongoing
14:15:37 [fsasaki]
ACTION-62 pending
14:15:47 [fsasaki]
topic: Review of other drafts
14:16:00 [fsasaki]
14:19:15 [fsasaki]
Felix summarizes the mail
14:19:24 [fsasaki]
Yves: good idea
14:20:24 [fsasaki]
Felix: will send a mail with a concrete text proposal, keep ACTION-54 OPEN
14:20:38 [fsasaki]
Yves: no other formats to review
14:20:48 [fsasaki]
topic: Best Practices Working Draft
14:20:57 [YvesS]
14:21:24 [fsasaki]
Yves: going through ed. notes
14:21:42 [fsasaki]
"[Ed. note: maybe we should point to the BP "Handling attribute values and element content in different languages"]"
14:21:58 [fsasaki]
Yves: everybody fine with that
14:23:11 [fsasaki]
Richard: I'm going to enter the reference, where the reference is
14:23:13 [fsasaki]
+1
14:23:28 [fsasaki]
"[Ed. note: I'm inclined to think we should spell out what's happening here a little more.]"
14:24:29 [fsasaki]
"This document shows how a set of ITS rules can be easily included along with customized information, like an informal description, the namespace of the vocabulary which applies the ITS rules, or an identifier and version information for the rules."
14:25:33 [fsasaki]
Richard: "easily included 'in' ..."
14:26:34 [fsasaki]
"can be easily combined with customized information"?
14:28:06 [fsasaki]
"easily included in a customized information file which contains ..."
14:30:31 [r12a]
This example shows that you can create your own format and put its rules in it and an ITS processor can process that as an external ITS rules file, if you wish.
14:31:07 [r12a]
your own format with additional custom information
14:31:22 [fsasaki]
+1
14:31:41 [fsasaki]
Richard: doing the change
14:31:50 [fsasaki]
"[Ed. note: compose or modify ? ]"
14:34:52 [r12a]
combine and provide additional rules for
14:35:02 [r12a]
Richard to change
14:36:20 [Zakim]
-??P10
14:36:55 [Zakim]
+??P10
14:38:08 [r12a]
The text below takes XML Spec 2.10 as an example and shows how you would integrate ITS into it.
14:38:26 [r12a]
Richard to edit
14:39:17 [fsasaki]
action: Felix to go to Norm if he could create a new version of XMLSpec with ITS markup in it, and the BP document contains an example
14:39:17 [trackbot-ng]
Created ACTION-64 - Go to Norm if he could create a new version of XMLSpec with ITS markup in it, and the BP document contains an example [on Felix Sasaki - due 2008-01-30].
14:39:45 [fsasaki]
"[Ed. note: is being or has been ? ]"
14:40:39 [fsasaki]
14:44:27 [fsasaki]
Felix: will create 003 version of xmlspec-i18n-dtd , with ITS markup in it
14:44:52 [fsasaki]
and create documentation under /International/xmlspec
14:45:56 [fsasaki]
"xml i18n BP" will point only to documentation
, not to the xmlspec-i18n.dtd schema with ITS
14:46:28 [fsasaki]
use the most up to date file in
, but put it into
14:47:15 [fsasaki]
work on that
14:47:47 [r12a]
when working on the updates to the documentation, add links to the actual dtd/mod etc files themselves
14:47:56 [r12a]
to the documentation
14:48:48 [r12a]
Richard to change the link to the documentation
14:49:59 [fsasaki]
topic:
14:51:23 [r12a]
Richard check language in BP 24
14:52:18 [fsasaki]
topic: publication plans
14:53:02 [fsasaki]
Richard: would like to take more time to look into the document
14:53:07 [fsasaki]
Yves: take one more week?
14:55:24 [fsasaki]
agreement
14:56:06 [fsasaki]
We could vote via mail as well, without another meeting
14:58:05 [fsasaki]
topic: AOB
15:01:16 [Zakim]
-Felix
15:01:18 [Zakim]
-Yves_Savourel
15:01:23 [Zakim]
-??P10
15:01:38 [fsasaki]
present: Bartosz, Felix, Richard, Yves
15:01:42 [RRSAgent]
I have made the request to generate
fsasaki
15:02:03 [Zakim]
-Richard
15:02:05 [Zakim]
I18N_TS()9:00AM has ended
15:02:07 [Zakim]
Attendees were Yves_Savourel, Felix, Richard
15:12:12 [RRSAgent]
I see 2 open action items saved in
:
15:12:12 [RRSAgent]
ACTION: Felix to create local and global ITS markup for the XForms example file [1]
15:12:12 [RRSAgent]
recorded in
15:12:12 [RRSAgent]
ACTION: Felix to go to Norm if he could create a new version of XMLSpec with ITS markup in it, and the BP document contains an example [2]
15:12:12 [RRSAgent]
recorded in
15:12:17 [Zakim]
Zakim has left #i18nits
|
http://www.w3.org/2008/01/23-i18nits-irc
|
crawl-002
|
refinedweb
| 1,190
| 51.04
|
Details
- Improvement
- Status: Open
- Minor
- Resolution: Unresolved
- 2.2.0
- None
-
- None
Description
When reading or writing CSV files with Spark, double quotes are escaped with a backslash by default. However, the appropriate behaviour as set out by RFC 4180 (and adhered to by many software packages) is to escape using a second double quote.
This piece of Python code demonstrates the issue
import csv with open('testfile.csv', 'w') as f: cw = csv.writer(f) cw.writerow(['a 2.5" drive', 'another column']) cw.writerow(['a "quoted" string', '"quoted"']) cw.writerow([1,2]) with open('testfile.csv') as f: print(f.read()) # "a 2.5"" drive",another column # "a ""quoted"" string","""quoted""" # 1,2 spark.read.csv('testfile.csv').collect() # [Row(_c0='"a 2.5"" drive"', _c1='another column'), # Row(_c0='"a ""quoted"" string"', _c1='"""quoted"""'), # Row(_c0='1', _c1='2')] # explicitly stating the escape character fixed the issue spark.read.option('escape', '"').csv('testfile.csv').collect() # [Row(_c0='a 2.5" drive', _c1='another column'), # Row(_c0='a "quoted" string', _c1='"quoted"'), # Row(_c0='1', _c1='2')]
The same applies to writes, where reading the file written by Spark may result in garbage.
df = spark.read.option('escape', '"').csv('testfile.csv') # reading the file correctly df.write.format("csv").save('testout.csv') with open('testout.csv/part-....csv') as f: cr = csv.reader(f) print(next(cr)) print(next(cr)) # ['a 2.5\\ drive"', 'another column'] # ['a \\quoted\\" string"', '\\quoted\\""']
The culprit is in CSVOptions.scala, where the default escape character is overridden.
While it's possible to work with CSV files in a "compatible" manner, it would be useful if Spark had sensible defaults that conform to the above-mentioned RFC (as well as W3C recommendations). I realise this would be a breaking change and thus if accepted, it would probably need to result in a warning first, before moving to a new default.
Attachments
Issue Links
- is duplicated by
SPARK-25251 Make spark-csv's `quote` and `escape` options conform to RFC 4180
-
- Resolved
SPARK-25086 Incorrect Default Value For "escape" For CSV Files
-
- Resolved
|
https://issues.apache.org/jira/browse/SPARK-22236
|
CC-MAIN-2022-21
|
refinedweb
| 349
| 60.21
|
Drafts/Canonical names
Places have names, they have been registered at OSM database as well at Wikipedia, Wikidata, DBpedia. Some place names are stable: was unchanged by years or decadades. Why OSM tools have no direct access to polygons of places names like administrative areas?
We have boundary relations and Wikidata-IDs for all countries and cities: why OSM not offer something as{country_name}/{city_name} (returning the polygons) as service?
There are a lot of technical rationale showing why we should not set OSM database with stable names or stable IDs... Even in the scope of Nominatim... But no serious discussion about how to solve the problem for the most frequently used names.
Contents
Web Semantic of places
Wikidata, DBpedia, and SchemaOrg defined what is a "place" in the context of the Semantic Web:
And Wikidata, Wikipedia, DBpedia and others (eg. CIA Fact Book) was registered thousands of place instances: a lot of them are stable. The association of an stable and frequently used label (eg. formal RDF label) with a stable place instance is the "place name". Example: all countries, cities and hierarchically intermediate administrative areas (tipically states), have stable place names, ISO codes and well-known labels in its local (stable) community.
All ontologies have consensual country and city definitions: db:country, sc:country, wd:country, db:city, sc:city, wd:city.
Specific example: Brazil, state of Paraíba in Brazil, city of João Pessoa in Paraíba,
- Brazil is ISO 3166-2 code
BR, the OSM relation 59470 (polygons), and the Wikidata-ID Q155 (used also as DBpedia entry).
- Paraíba is ISO 3166-2:BR code
BR-PB, the OSM relation 301464, and the Wikidata-ID Q38088 (DBpedia).
- João Pessoa is into
BR-PB, the OSM relation 301405, and the Wikidata-ID Q167436 (DBpedia).
The hierarchy is generated at Wikidata by the P131, "located in the administrative territorial entity" (that have also the semantic of within in the spatial relation context), creating a chain of place instances that have countries as roots... As ASCII simplified string for place name (eg. as hierarchical RDF label) we can use
br for Brazil,
br:pb for Paraíba, and
br:pb:joao.pessoa for João Pessoa.
In fact, these strings are jurisdictions in the URN LEX convention, and they can be canonical place names for offcial administrative areas at OSM.
Web names of places
There are many reliable free gazetteer services to confirm names, as Geonames and StatoIDs, that are good to "check fact" or enhance terminological consistency, but no one returns reliable polygons, no one is a name resolver.
PS: today, as proprietary-database and service, the best reference is google's place-id.
The OSM canonical name of the place
Examples of complementary datasets to use as reference in rule decisions:
- for canonical country names,
- for canonical state names at BR (re. ISO 3166-2:BR and local names)
- ...
So, when there are no "official name" we can adopt stable "official extensions" — git datasets maintained by stable communities as Open Knowledge or gazetters — to resolve ambiguities or lacks of official names. Example:
BR-GB is a non-valid ISO 3166-2:BR code, but is a fact checked by the community, the
BR-GB is valid place name for objects (eg. publication-place of historical documents and law) dated between 1960 and 1975. as showed by br-state-codes.csv dataset.
The urn:place proposal
There are a kind of "window of opportunity" for OSM, to subscribe yourself as a name resolver organization, with the new 2017's IEFT standard RFC 8141, with the new "Uniform Resource Names" (URNs) assign process.
- "An organization that will assign URNs within a formal URN namespace SHOULD meet the following criteria:"
- Organizational stability and the ability to maintain the URN namespace for a long time;
- Competency in URN assignment.
- Commitment to not reassigning existing URNs and to allowing old URNs to continue to be valid
|
https://wiki.openstreetmap.org/wiki/Drafts/Canonical_names
|
CC-MAIN-2018-43
|
refinedweb
| 650
| 52.09
|
Hi guys,
I'm having trouble getting a namespace to work from within a class definition. I'm not entirely sure this is possible, but the ultimate goal is to create an object and pass it one of the enumerated values in its constructor. I've tried doing an it as below, but the compiler does not like that route.
If I take out the namespace statement, then, in the main driver, I can create an object by calling pqueue test(pqueue::FIFO) (or any of the other three values)... Is there a way to do this with namespaces, so I can simply call pqueue test(FIFO)?
Thanks!!
-Max
class definintion - printQueue.h
Class implementation - printQueue.cppClass implementation - printQueue.cppCode:#include <iostream> using namespace std; class pqueue { public: namespace p { enum pTypes {FIFO, JOBSIZE, PRIORITY}; //used for naming which type of printer } pqueue(pTypes type); private: pTypes printer_type; //which type of printer this is job *front; //front of the queue job *back; //end of the queue };
Program driver -- test.cppProgram driver -- test.cppCode:#include <iostream> #include "printQueue.h" using namespace std; pqueue::pqueue(pTypes type) { printer_type = type; front = NULL; back = NULL; }
Code:#include <iostream> #include "printQueue.h" using namespace std; using namespace p; int main() { pqueue test(FIFO); }
|
https://cboard.cprogramming.com/cplusplus-programming/120887-namespace-within-class.html
|
CC-MAIN-2017-17
|
refinedweb
| 208
| 65.22
|
An ether being in cyberspace calling itself - Expeditus Bolanos - uttered:
|
| Date: Wed, 19 Apr 95 13:46:48 -0500
| Subject: a mail error question
|
| What does these errors mean? Should I consider these as BOUCE's and kick
| the users out. I get lots of these errors and it appears that such errors
| are dragging my mail (filling up the mail queue).
|
| >421 trac.army.mil (ddn)... Deferred: Connection refused by TRAC.ARMY.MIL
| >421 cts.com (ddn)... Deferred: Connection timed out during user open with
| >donews.cts.com
Deferred says that it will be held in the sendmail queue and tried again
later. The 421 means that sendmail either couldn't connect to the
destination host, or that the destination host found out it needed to
shut down in the middle of the transaction (e.g. system reboot). I
wouldn't kick the users out unless it became a regular problem with the
same users. If it was a problem I'd try to find out why the connection
couldn't be completed.
| Also, does anyone know where I can find documentation on what the error
| codes means such as 500, 421, 554, etc.
RFC821 contains these error codes. You can get a copy of the rfc from:
or send email:
To: mailserv@ds.internic.net
Body:
send rfc821.txt
| Any suggestions or comments will be much appreciated.
| Thank you in advance.
You're welcome.
-Paul
--
#include <stddisclamer>
__________________________________________________________________________
[ Paul-Joseph de Werk, B.S. \ RX Net, Inc. -- 800/447-9638 x162 ]
[ Systems Analyst II \ MIS Dept. ]
[ \ vrx: paul@av2.vrx.vhi.com ]
[ \ inet: paul%av2.vrx.vhi.com@vhipub.vhi.com ]
[_______________________________\__________________________________________]
|
http://www.greatcircle.com/lists/majordomo-users/mhonarc/majordomo-users.199504/msg00179.html
|
CC-MAIN-2016-44
|
refinedweb
| 275
| 76.22
|
2012/10/20 Wilfried van Asten <sniperrifle2004 at gmail.com>: > Perhaps. Alas, checking for EOF does not work. I mentioned this in passing in my prior email; the code was somewhat involved and I have deleted it. Here is a simple example of something that does not work as expected: In the first terminal: :; mkfifo fifo :; ghci -- :m + GHC.IO.Handle.FD System.IO -- do { h <- openFileBlocking "fifo" ReadMode ; hGetContents h } In the second terminal, *after* doing everything in the first terminal: :; cat > fifo < type some characters here > ^D Notice that the characters appear in the first terminal, as the output of hGetContents. Sending ^D to end cat does not register any effect in GHCi; hGetContents dutifully waits and you can in fact run cat on the FIFO again to send more characters to the same instances of hGetContents. This would seem to be due to non-blocking IO, deep in the IO manager. > -). I would prefer to leave them be, since they're passed in from the caller, who nominally owns them. If you mean that I should close them in `start', well, that would make it hard to debug this stuff; and if I simply tie them to the parent's file descriptors, it will make it hard to deal with more than a few CoBashes at one time while testing. Using cat to read the FIFOs and allowing Haskell to read from cat does work, actually. Shell really is such a nice language for tying together processes. -- Jason Dusek pgp // solidsnack // C1EBC57DC55144F35460C8DF1FD4C6C1FED18A2B {-# LANGUAGE OverloadedStrings , ScopedTypeVariables , ParallelListComp , TupleSections #-} module CoBash where import Control.Applicative import Control.Concurrent import Control.Concurrent.MVar import Control.Exception import Control.Monad import Data.Bits import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as Bytes import Data.Maybe import Data.Monoid import qualified GHC.IO.Handle.FD import System.IO import System.IO.Error import System.Process import System.Posix.ByteString import System.IO.Temp import qualified Text.ShellEscape as Esc start :: IO (Handle, Handle, Handle, ProcessHandle) start = runInteractiveProcess "bash" [] Nothing (Just []) query :: (Handle, Handle, Handle, ProcessHandle) -> ByteString -> IO (ByteString, ByteString) query (i, _, _, _) query = withFIFOs query' where query' ofo efo = do Bytes.hPut i cmd hFlush i [ob, eb] <- backgroundReadFIFOs [ofo, efo] return (ob, eb) where cmd = Bytes.unlines ["{", query, "} 1>" <> ofo <> " 2>" <> efo] shutdown :: (Handle, Handle, Handle, ProcessHandle) -> IO () shutdown (i, _, _, p) = () <$ hClose i <* waitForProcess p openFIFO path = GHC.IO.Handle.FD.openFileBlocking (Bytes.unpack path) ReadMode -- | Run an IO action with two FIFOs in scope, which will removed after it -- completes. withFIFOs :: (RawFilePath -> RawFilePath -> IO a) -> IO a withFIFOs m = withSystemTempDirectory "cobash." m' where m' = (uncurry m =<<) . mk . Bytes.pack mk d = (o, e) <$ (createNamedPipe o mode >> createNamedPipe e mode) where (o, e) = (d <> "/o", d <> "/e") mode = ownerReadMode .|. ownerWriteMode .|. namedPipeMode drainFIFO :: ByteString -> IO ByteString drainFIFO path = do (i, o, e, p) <- bash ["-c", "exec cat <"<>(Bytes.unpack path)] hClose i hClose e Bytes.hGetContents o <* waitForProcess p backgroundReadFIFOs theFIFOs = do cells <- sequence (newEmptyMVar <$ theFIFOs) sequence_ [ forkIO (drainFIFO p >>= putMVar c) | p <- theFIFOs | c <- cells ] sequence (takeMVar <$> cells) bash args = runInteractiveProcess "bash" args Nothing (Just [])
|
http://www.haskell.org/pipermail/haskell-cafe/2012-October/104033.html
|
CC-MAIN-2014-41
|
refinedweb
| 521
| 58.79
|
Dear esteemed PerlMonks
Continuing my odyssey, I need to develop an application for traversing/roaming in databases, letting the user inspect/view tables and joins in an efficient and friendly way. (On Windowz only).
Quite a while ago I decided to do it in Perl (over friendly attempts of colleagues and friends to have me use ASP .Net and C#). I had to choose a GUI development environment. Initially I've chosen Win32::GUI. It was pretty neat, but eventually I had to drop it, since:a. it doesn't support Unicode/UTF-8, and b. it doesn't seem to be supported any longer. So after considering various pieces of advice, I decided to use wxPerl.
But, I am getting more and more frustrated. Here is a concrete question, and then some more general ones:1. It seems to me that the widget I should be using for the main purpose I listed above (namely, a user-friendly way of browsing database tables and joins) is wxListCtrl (and mainly the virtual list control). (Gurus: I'd love to get you opinion on this).For a neat look, I need to be able: a. to set size and font of the list control column headings; b. to set size and font of the item lines.
The wxPerl documentation is scant. I couldn't find an example for doing that. I did find a wxPython example: at: (attached to Robert Tomlin's post, Oct 15, 2006 4:55 (8th from top)):
# taken from:
+ItemTextColor-SetItemFont-td2348263.html (main.py)
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), siz
+e=(350, 400))
# Now create the Panel to put the other controls on.
panel = wx.Panel(self)
btnBold = wx.Button(panel, -1, "Bold")
btnRed = wx.Button(panel, -1, "Red")
self.Bind(wx.EVT_BUTTON, self.OnBold, btnBold)
self.Bind(wx.EVT_BUTTON, self.OnRed, btnRed)
# create a list control
self.listControl = wx.ListCtrl(panel, style=wx.LC_REPORT, size
+=(200,100))
self.listControl.InsertColumn(0, "Col1")
self.listControl.InsertColumn(1, "Col2")
self.listControl.InsertStringItem(0, "Data 1")
self.listControl.SetStringItem(0,1, "Data 2")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.listControl, 0, wx.ALL, 10)
sizer.Add(btnBold, 0, wx.ALL, 10)
sizer.Add(btnRed, 0, wx.ALL, 10)
panel.SetSizer(sizer)
panel.Layout()
def OnBold(self, evt):
f = self.listControl.GetItemFont(0)
f.SetWeight(wx.BOLD)
self.listControl.SetItemFont(0, f)
def OnRed(self, evt):
self.listControl.SetItemTextColour(0, wx.RED)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, "Demonstrate listctrl")
self.SetTopWindow(frame)
frame.Show(True)
return True
app = MyApp(redirect=True)
app.MainLoop()
[download]
Porting this example into wxPerl:
# taken from:
+ItemTextColor-SetItemFont-td2348263.html (main.py)
# ported 23 3 2013 v 0-1
use strict;
use warnings;
use Wx;
use 5.014;
use autodie;
use Carp;
use Carp qw {cluck};
use Carp::Always;
use Win32::Console;
package MyFrame;
use Wx ':everything';
use Wx ':listctrl';
use Wx::Event 'EVT_BUTTON';
use parent -norequire, 'Wx::Frame';
sub new { #1 MyFrame::
my ($class, $parent, $title) = @_;
my $self = $class->SUPER::new(
$parent, -1, # parent window; ID -1 means any
$title, # title
[150, 150 ], # position
[ 350, 400 ], # size
);
# wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size
+=(350, 400)) (Python)
my $panel = Wx::Panel->new($self);
my $btnBold = Wx::Button->new($panel, -1, 'Bold', wxDefaultPos
+ition, wxDefaultSize);
my $btnRed = Wx::Button->new($panel, -1, 'Red', wxDefaultPosit
+ion, wxDefaultSize);
EVT_BUTTON ($self, $btnBold, sub { $self->{listControl}->MyFr
+ame::OnBold });
# self.Bind(wx.EVT_BUTTON, self.OnBold, btnBold) (Python)
EVT_BUTTON ($self, $btnRed, sub { $self->{listControl}->MyFram
+e::OnRed });
# self.Bind(wx.EVT_BUTTON, self.OnRed, btnRed) (Python)
# create a list control
$self->{listControl} = Wx::ListCtrl->new($panel, -1, wxDefault
+Position, [300,100], wxLC_REPORT);
$self->{listControl}->InsertColumn(0, 'Col1', wxLIST_FORMAT_LE
+FT, 150);
$self->{listControl}->InsertColumn(1, 'Col2', wxLIST_FORMAT_LE
+FT, 150);
$self->{listControl}->InsertStringItem( 0, 'dummy' );
$self->{listControl}->SetItemText( 0, 'Data 1');
$self->{listControl}->SetItem( 0, 1, 'Data 3');
$self->{listControl}->InsertStringItem( 1, 'dummy' );
$self->{listControl}->SetItemText(1, 'Data 2');
$self->{listControl}->SetItem( 0, 1, 'Data 3');
my $sizer = Wx::BoxSizer->new(wxVERTICAL);
$sizer->Add($self->{listControl}, 0, wxALL, 10);
$sizer->Add($btnBold, 0, wxALL, 10);
$sizer->Add($btnRed, 0, wxALL, 10);
$panel->SetSizer($sizer);
$panel->Layout();
return $self;
} #1 end sub new MyFrame::
sub OnBold { # def OnBold(self, evt)
+: (Python)
my $this = shift;
my $f = $this->GetItemFont(0);
my $f = Wx::Font->new(12, -1, wxNORMAL, wxBOLD, 0, 'arial'
+);
$f->SetWeight(wxBOLD);
$this->Wx::ListCtrl->SetItemFont(0, $f);
} #1 end sub OnBold
sub OnRed { # def OnRed(self, evt):
+ (Python)
my $this = shift;
$this->SetItemTextColour(0, wxRED);
} #1 end sub OnRed
# end class MyFrame::
# class MyApp(Wx::App): (Python)
# def OnInit(self): (Python)
my $frame = MyFrame->new(undef, 'Demonstrate listctrl');
# Wx::SetTopWindow($frame);
$frame->Show(1);
# return True (Python)
my $app = Wx::SimpleApp->new;
$app->MainLoop;
1;
[download]
you note that the "Red" button works ok (makes the items red), but the "Bold" button fails, with the error message: (the program is called: "Set item font post.pl"):
Error while autoloading 'Wx::ListCtrl' at F:/Win7programs/Dwimperl/per
+l/site/lib/Wx.pm line 48
Wx::AUTOLOAD('Wx::ListCtrl=HASH(0x26f6454)') called at Set ite
+m font post.pl line 60
MyFrame::OnBold('Wx::ListCtrl=HASH(0x26f6454)') called at Set
+item font post.pl line 31
MyFrame::__ANON__('MyFrame=HASH(0x2712734)', 'Wx::CommandEvent
+=SCALAR(0x2b9f3bc)') called at Set item font post.pl line 76
eval {...} called at F:/Win7programs/Dwimperl/perl/site/lib/Wx
+.pm line 48
[download]
So here are my case-specific questions, and some more general questions:
1. Is GetItemFont/SetItemFont implemented for Wx::ListCtrl in wxPerl? If not, how come it's not implemented; if yes, what am I doing wrong?2. Are all methods (see here:) of the wxListCtrl widget implemented in wxPerl? wxPerl documentation led me to think so?3. Should I stick with wxPerl and Wx::ListCtrl for this project, or should I choose some other tools?4. This "ObjectListView" wxPython widget looks neat:. Is there something like it in Perl? Should I try to port it into wxPerl?5. I had chosen using Perl (and investing time and energy in it) since I was impressed with the power and expressiveness of the language, and its internal logic; you can feel it was designed by a linguist. But, considering the dearth of support and examples (for displaying database tables in a neat GUI), should I abandon Perl and do the project in Python?
Esteemed gurus - your help and advice will be appreciated
Many TIA - Helen
Try to replace
$this->Wx::ListCtrl->SetItemFont(0, $f);
[download]
in sub OnBold, line 60 with
$this->{listControl}->SetItemFont(0, $f);
[download]
or
$this->SetItemFont(0, $f);
[download]
Untested, as I do not have wx but these two look more logical than yours..
Then, you can rely on CGI or friends to render the data... which you can obtain as required using DBD, DBI or other db modules. The catch is, you still have to get the user input. So -- along side your Perl-controlled browser -- why not use a wxPerl window whose capabilities handle the minimal requirements for input only, thus simplifying the UI at the requestor end?
wxListCtrl (and mainly the virtual list control). (Gurus: I'd love to get you opinion on this).
Try
2. Are all methods ...
No, but enough are, see Re^4: wxPerl: is wxListCtrl Get/SetItemFont implemented? ( Wx::ListCtrl::GetItemFont, Wx::ListCtrl::SetItemFont ), see Wx::DemoModules::wxListCtrl, Wx::DemoModules::wxListCtrl::Report
although adding the missing ones is practically trivial, just look inside Wx-0.9917/XS/ListCtrl.xs
I know what you're thinking, holy batguano batman, that just stinks ... :)
I don't know, someone smarter than me (a hermit) might just send in a bug report and/or a patch -- Wx-0.9917 released 11 Feb 2013
3. Should I stick with wxPerl and Wx::ListCtrl for this project, or should I choose some other tools?
You know, given that you've got practically no experience with any existing toolkits, picking a different toolkit, a third or fourth one, isn't going to help you finish your project any quicker -- there will always be bumps you'll run into, whatever you pick, but they're surmountable
5. But, considering the dearth of support and examples (for displaying database tables in a neat GUI), should I abandon Perl and do the project in Python?
Yes, sure, go ahead, if perl isn't working for you, if perl isn't making your life easier, stop using perl,
On the plus side, you've got all these wxPython examples you've been trying to translate, if you do your project in python, you don't have to translate any examples.
|
http://www.perlmonks.org/index.pl?node_id=1025321
|
CC-MAIN-2015-22
|
refinedweb
| 1,462
| 57.37
|
Modules have been around in javascript for a while now. The two competing standards for module declaration have been the AMD and Commonjs specification. With the new ES6 specs, module definition and consumption is now part of the language itself. This article will be the first installment of our Learning ES6 series. In this article, I am going to take some very simple examples to demonstrate the usage of ES6 modules.
- Part 1: Getting started with ES6 modules – THIS ARTICLE
- Part 2: Getting started with ES6 iterators and iterables
- Part 3: ES6 iterators and iterables – creating custom iterators
- Part 4: Getting started with ES6 generator functions
- Part 5: Generators and Yield in ES6
Quite similar to Commonjs, ES6 lets you export and import objects, albeit it does so in slightly different ways.
Example 1:
Using a single
export at the end of your module file. This form of usage is called a named export because while exporting you are defining the name of the objects being exported.
foobar.js
function foo() { return 'foo'; } function bar() { return 'bar'; } export { foo, bar };
Notice how we use the new javascript object shorthand notation on the last line when exporting objects.
You can use the exported object from another file as follows.
main.js
import {foo, bar} from 'foobar'; foo(); bar(); import * as lib from 'foobar'; lib.foo(); lib.bar();
Example 2
In another format for using named exports, you can also export objects/function as and when you create them. I find this syntax a bit more convenient than the one we saw above.
foobar.js
export function foo() { return 'foo'; } export function bar() { return 'bar'; }
Example 3
ES6 also has something called as a
default export. A file can have zero or 1 default export. Fortunately, you can use zero or many named exports in a file containing default exports. For example
foobar.js
export default function foo() { return 'default foo'; }; export function bar() { return 'bar'; };
And here’s how you would consume it
main.js
// These will only get you foo import mylib from 'foobar'; import {default as mylib} from 'foobar'; // This will get you both foo and bar import mylib, {bar} from 'foobar';
Notice how in the above code, you were able to use the name ‘mylib’ instead of ‘foo’. Thats because foo was the default export in your module so you didn’t have to pluck it out of the exported object the way you had to do it if you only had named exported objects.
And that pretty much covers the ways in which you can use the new ES6 modules.
|
https://javascript.tutorialhorizon.com/2015/06/23/es6-modules-examples/
|
CC-MAIN-2018-34
|
refinedweb
| 433
| 59.53
|
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
TIME TO END EXTREME INEQUALITY
ENDORSEMENTS
KOFI ANNAN NAWAL EL SAADAWI
Chair of the Africa Progress Panel, former Secretary- Egyptian writer and activist
General of the United Nations and Nobel Laureate
Oxfam’s report reveals a new challenge to the capitalist
The widening gap between rich and poor is at a tipping patriarchal world and its so-called free market. We need
point. It can either take deeper root, jeopardizing to fight together, globally and locally, to build a new world
our efforts to reduce poverty, or we can make based on real equality between people regardless of
concrete changes now to reverse it. This valuable gender, class, religion, race, nationality or identity.
report by Oxfam is an exploration of the problems
caused by extreme inequality and the policy options
governments can take to build a fairer world, with equal ANDREW HALDANE
opportunities for us all. This report is a call to action Chief Economist, Bank of England
for a common good. We must answer that call.
When Oxfam told us in January 2014 that the world’s 85
richest people have the same wealth as the poorest half
of humanity, they touched a moral nerve among many. Now
PROFESSOR JOSEPH STIGLITZ this comprehensive report goes beyond the statistics to
Columbia University, winner of the Nobel Prize
explore the fundamental relationship between inequality
for Economics
and enduring poverty. It also presents some solutions.
The extreme inequalities in incomes and assets we see In highlighting the problem of inequality Oxfam not only
in much of the world today harm our economies, our speaks to the interests of the poorest people but in our
societies, and undermines our politics. While we should collective interest: there is rising evidence that extreme
all worry about this it is of course the poorest who suffer inequality harms, durably and significantly, the stability of
most, experiencing not just vastly unequal outcomes in the financial system and growth in the economy. It retards
their lives, but vastly unequal opportunities too. Oxfam’s development of the human, social and physical capital
report is a timely reminder that any real effort to end necessary for raising living standards and improving
poverty has to confront the public policy choices that well‑being. That penny is starting to drop among policy
create and sustain inequality. makers and politicians. There is an imperative – moral,
economic and social – to develop public policy measures
to tackle growing inequality. Oxfam’s report is a valuable
stepping stone towards that objective.
JEFFREY SACHS ROSA PAVANELLI
Director of the Earth Institute at Columbia University Secretary General, Public Services International
Oxfam has done it again: a powerful call to action against The answers Oxfam provides are simple, smart and entirely
the rising trend of inequality across the world. And the achievable. All that stands between them and real change
report comes just in time, as the world’s governments is a lack of political will. Our job is to make the cry heard.
are about to adopt Sustainable Development Goals (SDGs) To give action to the urgency. To ceaselessly expose the
in 2015. Sustainable development means economic injustice and demand its resolution. The time to act is now.
prosperity that is inclusive and environmentally
sustainable. Yet too much of today’s growth is neither
inclusive nor sustainable. The rich get richer while the KATE PICKETT AND
poor and the planet pay the price. Oxfam spells out how
we can and must change course: fairer taxation, ending
RICHARD WILKINSON
Co-authors of The Spirit Level: Why Equality
tax and secrecy havens, equal access of the rich and
is Better for Everyone
poor to vital services including health and education; and
breaking the vicious spiral of wealth and power by which This report is the first step in changing the policies
the rich manipulate our politics to enrich themselves even which have enriched the few at the expense of the
further. Oxfam charts a clear course forward. We should all many. It is essential reading for all governments, for policy
rally to the cause of inclusive, sustainable growth at the makers and everyone who has had enough of sacrificing
core of next year’s SDGs. public wellbeing to the one percent.
JAY NAIDOO HA-JOON CHANG
Chair of the Board of Directors and Chair of Economist at the University of Cambridge
the Partnership Council, Global Alliance for
Even It Up is the best summary yet of why tackling
Improved Nutrition
inequality is crucial to global development. The gulf
All those who care about our common future should between haves and have-nots is both wrong in itself,
read this report. Rising inequality has become the and a source of needless human and economic waste.
greatest threat to world peace, and indeed to the survival I urge you to read it, and join the global campaign for
of the human species. The increasing concentration a fairer world.
of wealth in the hands of very few has deepened
both ecological and economic crises, which in turn
has led to an escalation of violence in every corner
of our burning planet.
EVEN IT UP
TIME TO END
EXTREME INEQUALITY
ACKNOWLEDGEMENTS
CONTENTS
FOREWORD FROM GRAÇA MACHEL 3
FOREWORD FROM WINNIE BYANYIMA 4
EXECUTIVE SUMMARY 6
INTRODUCTION 24
EXTREME INEQUALITY
1 A STORY THAT NEEDS A NEW ENDING 27
1.1 The reality of today’s haves and have-nots 28
1.2 Extreme inequality hurts us all 35
1.3 What has caused the inequality explosion? 54
HAT CAN BE DONE
W
2 TO END EXTREME INEQUALITY 68
2.1 A tale of two futures 70
2.2 Working our way to a more equal world 72
2.3 Taxing and investing to level the playing field 81
2.4 H
ealth and education: Strong weapons in the
fight against inequality 89
2.5 Freedom from fear 101
2.6 Achieving economic equality for women 104
2.7 People power: Taking on the one percent 108
T IME TO ACT
3 AND END EXTREME INEQUALITY 112
NOTES 121
SECTION 1 2 3 FOREWORD
FOREWORD
The last decades have seen incredible human progress
across Africa and the world. But this progress is under
threat from the scourge of rapidly rising inequality..
3
SECTION 1 2.
4
SECTION 1 2 3
5
SECTION 1 2 3 EXECUTIVE SUMMARY
A cleaner passing an image of a luxury apartment
displayed on the ground floor of a residential
complex in Chaoyang district, China (2013).
Photo: Panos/Mark Henley
EXECUTIVE
SUMMARY
6
SECTION 1 2 3 EXECUTIVE SUMMARY
education at Stellenbosch University and have well-paid jobs.4 will be out of her reach. If Nthabiseng has children there
is a very high chance they will also grow up equally poor.5..
Oxfam’s decades of experience in the world’s poorest communities have taught
us that poverty and inequality are not inevitable or accidental, but the result
of deliberate policy choices. Inequality can be reversed. The world needs
*’ to refer to extreme economic (wealth
and income) inequality. When referring to the various dimensions of inequality we make
these distinctions.
7
SECTION 1 2 3 EXECUTIVE SUMMARY There’s been class
most to people, as the poorest struggle to get by while their neighbours warfare going on for the
prosper, and this is rising rapidly in the majority of countries. Seven out of last 20 years and
10 people live in countries where the gap between rich and poor is greater my class has won.
than it was 30 years ago.9 In countries around the world, a wealthy minority
WARREN BUFFET
are taking an ever-increasing share of their nation’s income.10
THE FOURTH WEALTHIEST
PERSON IN THE WORLD11.
Since the financial crisis, the ranks of the world’s billionaires has more than
doubled, swelling to 1,645 people.15 And extreme wealth is not just a rich-
country story. The world’s richest man is Mexico’s Carlos Slim, who knocked
8
SECTION 1 2 3 EXECUTIVE SUMMARY
Bill Gates off the top spot in July 2014. Extreme disparities in
fight against poverty. New research from Oxfam has shown that in Kenya, income are slowing the
Indonesia and India, millions more people could be lifted out of poverty if pace of poverty reduction
income inequality were reduced.19 If India stops inequality from rising, it could and hampering the
end extreme poverty for 90 million people by 2019. If it goes further and reduces development of broad-based
inequality by 36 percent, it could virtually eliminate extreme poverty.20 The economic growth.
Brookings Institution has also developed scenarios that demonstrate how
KOFI ANNAN
inequality is preventing poverty eradication at the global level. In a scenario
AFRICA PROGRESS
where inequality is reduced, 463 million more people are lifted out of poverty
PANEL, 201222
compared with a scenario where inequality increases.21
Income distribution within.23
Leaders around the world are debating new global goals to end extreme poverty
by 2030. ‘growth’ case against tackling economic inequality clearly
no longer holds water.
9
SECTION 1 2 3 EXECUTIVE SUMMARY
Extreme inequality also diminishes the poverty-reducing impact of growth.27
In many countries, economic growth already amounts to a ‘winner takes all’
windfall for the wealthiest in society. For example,.28 Research by Oxfam29 and the World
Bank30 suggests that inequality is the missing link explaining how the same
rate of growth can lead to different rates of poverty reduction.
Economic inequality compounds inequalities between
women and men “
The power of growth to
reduce poverty… tends to
One of the most pervasive – and oldest – forms of inequality is that between decline both with the initial
men and women. There is a very strong link between gender inequality and level of inequality, and with
economic inequality. increases in inequality during
the growth process.
Men are over-represented at the top of the income ladder and hold more
F. FERREIRA AND
positions of power as ministers and business leaders. Only 23 chief executives
M. RAVALLION3134 demonstrate
how poverty interacts with economic and other inequalities to create ‘traps
of disadvantage’ that push the poorest and most marginalized people to the
bottom – and keep them there.
10
SECTION 1 2 3 EXECUTIVE SUMMARY.
Condemned to stay poor for generations that today.’
If Americans want to live
John Makina, Country Director for Oxfam in Malawi
the American dream, they
should go to Denmark.
RICHARD WILKINSON
Many feel that some economic inequality is acceptable as long as those who CO-AUTHOR OF THE SPIRIT LEVEL36
“.
11
SECTION 1 2 3 EXECUTIVE SUMMARY
Inequality threatens society
“
For the third year running, the World Economic Forum’s Global Risks survey has
found ‘severe income disparity’ to be one of the top global risks for the coming
decade.40 A growing body of evidence has also demonstrated that economic No society can sustain this
inequality is associated with a range of health and social problems, including kind of rising inequality.
mental illness and violent crime.41 This is true across rich and poor countries In fact, there is no example in
alike, and has negative consequences for the richest as well as the poorest human history where wealth
people.42 Inequality hurts everyone. accumulated like this and the
pitchforks didn’t eventually
Homicide rates are almost four times higher in countries with extreme economic come out.
inequality than in more equal nations.44 Latin America – the most unequal
NICK HANAUER
and insecure region in the world45 – starkly illustrates this trend.46 It has 41 of
US BILLIONAIRE AND
the world’s 50 most dangerous cities,47 and saw a million murders take place
ENTREPRENEUR43
between 2000 and 2010.48.49.
To be wealthy and
The equality instinct
honoured in an
Evidence shows that, when tested, people instinctively feel that there unjust society
is something wrong with high levels of inequality. is a disgrace.
MAHATMA GANDHI.
What has caused the inequality explosion?
Many believe that inequality is somehow inevitable, or is a necessary
consequence of globalization and technological progress. But the experiences
of different countries throughout history have shown that, in fact, deliberate
political and economic choices can lead to greater inequality. There are two
12
SECTION 1 2 3 EXECUTIVE SUMMARY
“
One of the flaws of market
fundamentalism is that it paid
and a dignified life to hundreds of millions of people across Europe, North no attention to distribution
America and East Asia. However, as economist Thomas Piketty demonstrated of incomes or the notion of
in Capital in the Twenty-First Century, without government intervention, the a good or fair society.
market economy tends to concentrate wealth in the hands of a small minority,
JOSEPH STIGLITZ53
causing inequality to rise.52 Just as any revolution eats
the recent global economic crisis, it remains the dominant ideological world its children, unchecked
view and continues to drive inequality. It has been central to the conditions market fundamentalism can
imposed on indebted European countries, forcing them to deregulate, privatize devour the social capital
and cut their welfare provision for the poorest, while reducing taxes on the essential for the long-term
rich. There will be no cure for inequality while countries are forced to swallow dynamism of capitalism itself.
this medicine.
MARK CARNEY
GOVERNOR OF THE
Capture of power and politics by elites has fuelled inequality BANK OF ENGLAND57
“
13
SECTION 1 2 3 EXECUTIVE SUMMARY
“
We can have democracy
in this country, or we can have
rights of the many. In Pakistan, the average net-worth of parliamentarians great wealth concentrated in
is $900,000, yet few of them pay any taxes.59 This undermines investment in the hands of a few, but we
sectors, such as education, healthcare and small-scale agriculture, which can can’t have both.
play a vital role in reducing inequality and poverty.
LOUIS D. BRANDEIS
FORMER SUPREME
The massive lobbying power of rich corporations to bend the rules in their
COURT JUSTICE, USA
favour has increased the concentration of power and money in the hands
“
of the few. Financial institutions spend more than €120m per year on armies
of lobbyists to influence EU policies in their interests.60 “
Without deliberate policy
interventions, high levels of
EXTREME INEQUALITY? inequality tend to be self-
perpetuating. They lead to
The continued rise of economic inequality around the world today is not the development of political
inevitable – it is the result of deliberate policy choices. Governments can and economic institutions
start to reduce inequality by rejecting market fundamentalism, opposing the that work to maintain the
special interests of powerful elites, changing the rules and systems that have political, economic and social
led to today’s inequality explosion, and taking action to level the playing field privileges of the elite.
by implementing policies that redistribute money and power.
UN RESEARCH INSTITUTE
FOR SOCIAL DEVELOPMENT62
“
Working our way to a more equal world
14
SECTION 1 2 3 EXECUTIVE SUMMARY.65
In 2014, the UK top 100 executives took home 131 times as much as their
average employee,66 yet only 15 of these companies have committed to pay
their employees a living wage.67 In South Africa, a platinum miner would need
to work for 93 years just to earn the average CEO’s annual bonus.68 Meanwhile,
the International Trade Union Confederation estimates that 40 percent of
workers are trapped in the informal sector, where there are no minimum
wages and workers’ rights are ignored.69
Oxfam research found evidence of poverty wages and insecure jobs in middle-
income Vietnam, Kenya and India, and below the extreme poverty line in Malawi,
despite being within national laws.70.71
Unions give workers a better chance of earning a fair wage. Collective
bargaining by unions typically raises members’ wages by 20 percent and
drives up market wages for everyone.72.73 Countries such as Ecuador74 and China75 have also deliberately
increased wages.
Forward-looking companies and cooperatives are also taking action to limit
executive pay. For instance, Brazil’s SEMCO SA employs more than 3,000
workers across a range of industries, and adheres to a wage ratio of 10 to 1.76
Germany’s Corporate Governance Commission proposed capping executive pay
for all German publicly traded companies, admitting that public outrage against
excessive executive pay had influenced its proposal.
15
SECTION 1 2 3 EXECUTIVE SUMMARY
Taxing and investing to level the playing field.77
The low road: The great tax failure
Tax systems in developing countries, where public spending and redistribution
“
is particularly crucial, unfortunately tend to be the most regressive78 and the
furthest from meeting their revenue-raising potential. Oxfam estimates that if
There are no politicians who
low- and middle-income countries – excluding China – closed half of their tax
speak for us. This is not just
revenue gap they would gain almost $1tn.79 But due to the disproportionate
about bus fares any more.
influence of rich corporations and individuals, and an intentional lack of global
We pay high taxes and we are
coordination and transparency in tax matters, tax systems are failing to tackle
a rich country, but we can’t
poverty and inequality.
see this in our schools,
hospitals and roads.
The race to the bottom on corporate tax collection is a large part of the
problem. Multilateral agencies and finance institutions have encouraged JAMAIME SCHMITT
developing countries to offer tax incentives – tax holidays, tax exemptions and BRAZILIAN PROTESTOR80
“
free trade zones – to attract foreign direct investment. Such incentives have
soared, undermining the tax base in some of the poorest countries. In 2008/09,
for instance, the Rwandan government authorized tax exemptions that,
if collected, could have doubled health and education spending.8182 and Starbucks,83
have been exposed for dodging billions in taxes, leading to unprecedented
public pressure for reform.
16
SECTION 1 2 3 EXECUTIVE SUMMARY
The richest individuals are also able to take advantage of the same tax
loopholes and secrecy. In 2013, Oxfam estimated that the world was losing
$156bn in tax revenue as a result of wealthy individuals hiding their assets
in offshore tax havens.84 ‘either the biggest building
or the biggest tax scam on record’.85.86.87
“
International consensus is also shifting. Despite the limitations of the ongoing
Base Erosion and Profit Shifting process,88 the fact that the G8, G20 and OECD
How people are taxed,
took up this agenda in 2013 demonstrates a clear consensus that the tax
who is taxed and what is
system is in need of radical reform. The IMF is reconsidering how MNCs are
taxed tell more about a
taxed, and, in a recent report, has recognized the need to shift the tax base
society than anything else.
towards developing countries.89 It is also considering ‘worldwide unitary
taxation’ as an alternative to ensure that companies pay tax where economic CHARLES ADAMS91
“
activity takes place.90 OECD, G20, US and EU processes are making progress
on transparency and global automatic exchange of tax information between
countries, which will help lift the veil of secrecy that facilitates tax dodging.
Ten EU countries have also agreed to work together to put a Financial
Transaction Tax in place, which could raise up to €37bn per year.92 Wealth
taxes are under discussion in some countries, and the debate about a global
wealth tax has been given new life through Thomas Piketty’s recommendations
in Capital in the Twenty-First Century, which gained widespread public
and political attention..93
Nevertheless, the vested interests opposing reform are very powerful. There
is a real risk that the gaps in global tax governance will not be closed, leaving
the richest companies and individuals free to continue exploiting loopholes
to avoid paying their fair share.
17
SECTION 1 2 3 EXECUTIVE SUMMARY
Health and education: Strong weapons in the fight
against inequality
I went for a cataract
income and wealth distribution.
operation. They told me it
costs 7,000 Egyptian pounds.
Between 2000 and 2007, the ‘virtual income’ provided by public services
All I had was seven so
reduced income inequality by an average of 20 percent across OECD countries.94
I decided to go blind.
In five Latin American countries (Argentina, Bolivia, Brazil, Mexico and Uruguay),
virtual income from healthcare and education alone have reduced inequality A 60-YEAR-OLD WOMAN
by between 10 and 20 percent.95 Education has played a key role in reducing IN A REMOTE VILLAGE IN EGYPT
“
inequality in Brazil,96 and has helped maintain low levels of income inequality
in the Republic of Korea (from here on in referred to as South Korea).97
The low road: Fees, privatization and medicines for the few
The domination of special interests and bad policy choices – especially user
fees for healthcare and education, and the privatization of public services –
can increase inequality. Unfortunately, too many countries are suffering as
a result of these ‘low.98 In Ghana, the
poorest families will use 40 percent of their household income sending just one
of their children to an Omega low-fee school.99.100.101
18
SECTION 1 2 3 EXECUTIVE SUMMARY
Despite the evidence that it increases inequality, rich-country governments
and donor agencies, such as the UK, the USA and the World Bank, are pushing
for greater private sector involvement in service delivery.103
Private services benefit the richest rather than those most in need, thus
increasing economic inequality.
“
International rules also undermine domestic policy. Intellectual property
clauses in current international trade and investment agreements are driving
We used to see just four or
up the cost of medicines so that only the richest can afford treatment. The
five women each month for
180 million people infected with Hepatitis C are suffering the consequences,
deliveries and we now see
as neither patients nor governments in developing countries can afford the
more than twenty. It used to
$1,000 per day bill for medicine that these rules result in.104
be very expensive to come to
the clinic but now women can
The high road: Reclaiming the public interest deliver here safely for free
and they do not have to wait
There are, however, good examples from around the world of how expanding
for their husbands to give
public services are helping to reduce inequality.
them the money.
The growing momentum around UHC has the potential to improve access to MIDWIFE, SURKHET, NEPAL
“
healthcare and drive down inequality. World Bank president Jim Yong Kim has
been unequivocal that UHC is critical to fighting inequality, saying it is ‘central
to reaching the [World Bank] global goals to end extreme poverty by 2030 and
boost shared prosperity’.105.106
There have also been victories over moves by major pharmaceutical companies
to block access to affordable medicines. Leukaemia patients can now take
generic versions of cancer treatment Glivec®/Gleevec® for only $175 per month
– nearly 15 times less than the $2,600 charged by Novartis – thanks to the
Indian Supreme Court’s rejection of an application to patent the drug.107.108
19
SECTION 1 2 3 EXECUTIVE SUMMARY
indigenous and black communities, which has helped to reduce inequality
of access since the mid-1990s.109 As a result, the average number of years
spent in school by the poorest 20 percent of children has doubled from four
years to eight years.110.111 The USA is seeking to target aid to district
councils in poor areas of Ghana and to support farmers to hold policy
makers accountable..112.113 Even in the poorest countries,
the evidence suggests that basic levels of social protection are affordable.114
The wrong economic choices can hit women hardest, and failure to consider
women and girls in policy making can lead governments to inadvertently
reinforce gender inequality.
In China, for instance, successful efforts to create new jobs for women were
undermined by cutbacks in state and employer support for child care and
elderly care, which increased the burden of women’s unpaid work.115 According
to research conducted on the impact of austerity in Europe,116 mothers of
young children were less likely to be employed after the financial crisis,
20
SECTION 1 2 3 EXECUTIVE SUMMARY
and more likely to attribute their lack of employment to cuts to care services.117
A recent study in Ghana also found that indirect taxes on kerosene, which is
used for cooking in low-income households, are paid mostly by women.118
Good policies can promote women’s economic equality
“
Many of the policies that reduce economic inequality, such as free public
services or a minimum wage, also reduce gender inequality. In South Africa,
a new child-support grant for the primary caregivers of young children from People are not tolerating
poor households is better than previous measures at reaching poor, black, the way a small number of
and rural women because the government gave careful consideration to the economic groups benefit from
policy’s impact on women and men.119 In Quebec, increased state subsidies the system. Having a market
for child care have helped an estimated 70,000 more mothers to get into work, economy is really different
with the resulting increased tax revenue more than covering the cost of the from having a market
programme.120 Governments must implement economic policies aimed at society. What we are asking
closing the gap between women and men, as well as between rich and poor. for, via education reform,
is that the state takes on
a different role.
People power: Taking on the one percent
CAMILA VALLEJO
To successfully combat runaway economic inequality, governments must
VICE-PRESIDENT OF THE
be forced to listen to the people, not the plutocrats. As history has shown,
STUDENT FEDERATION OF THE
this requires mass public mobilization. The good news is that despite the
UNIVERSITY OF CHILE121.127
History shows that the stranglehold of elites can be broken by the actions
of ordinary people and the widespread demand for progressive policies.
21
SECTION 1 2 3 EXECUTIVE SUMMARY
TIME TO ACT TO END EXTREME INEQUALITY.
Specific commitments must include: increasing minimum wages towards living
wages; moving towards a highest-to-median pay ratio of 20:1; transparency
on pay ratios; protection of worker’s rights to unionise and strike.
4) Share the tax burden fairly to level the playing field; national wealth taxes and exploration of
a global wealth tax.
5) Close international tax loopholes and fill holes in tax governance
Today’s economic system is set up to facilitate tax dodging by multinationals
and wealthy individuals. Until the rules are changed and there is a fairer global
22
SECTION 1 2 3 EXECUTIVE SUMMARY
governance of tax matters, tax dodging will continue to drain public budgets
and undermine the ability of governments to tackle inequality. black list and sanctions; making companies
pay based on their real economic activity.
6) Achieve universal free public services by 2020
Health and education can help to close the gap between the haves and have
nots, but under spending, privatisation and user fees as well as international
rules are standing in the way of this progress and must be tackled. everyone has access to appropriate and affordable medicines
Relying on intellectual property as the only stimulus for R&D gives big
pharmaceutical companies a monopoly on making and pricing of medicines.
This increases the gap between rich and poor and puts lives on the line.
The rules must change.
Specific commitments must include: a new global R&D treaty; increased
investment in medicines, including in affordable generics; excluding
intellectual property rules from trade agreements.
8) Implement a universal social protection floor
Social protection reduces inequality and ensures that there is a safety net for
the poorest and most vulnerable people. Such safety nets must be universal
and permanent.
Specific commitments must include: universal child and elderly care services;
basic income security through universal child benefits, unemployment benefits
and pensions.
9) Target development finance at reducing inequality and poverty,
and strengthening the compact between citizens and their government
Development finance can help reduce inequality when it is targeted to support
government spending on public goods, and can also improve the accountability
of governments to their citizens.
Specific commitments must include: increased investment from donors
in free public services and domestic resources mobilisation; assessing
the effectiveness of programmes in terms of how they support citizens
to challenge inequality and promote democratic participation.
23
Salena and Sahera walk through Shanti Busti with
bottles of water on their way to the wasteland that
they use as a toilet, India (2008).
Photo: Tom Pietrasik/Oxfam
INTRODUCTION
SECTION 1 2 3 INTRODUCTION Extreme disparities in
education at Stellenbosch University and have well-paid jobs. income are slowing the
pace of poverty reduction
As a result, Nthabiseng and Pieter’s life chances are vastly different.
and hampering the
Nthabiseng is almost one and a half times as likely to die in the first year
development of broad-based
of her life as Pieter.128 He is likely to live more than 15 years longer than
economic growth.
Nthabiseng.129
KOFI ANNAN134
Pieter will complete on average 12 years of schooling and will most
“
probably go to university, whereas Nthabiseng will be lucky if she
gets one year.130 Such basics as clean toilets, clean water or decent
healthcare131 will be out of her reach. If Nthabiseng has children there
is a very high chance they will also grow up equally poor.132. There’s been class
Oxfam has updated the facts on life chances in South Africa.133 warfare going on for the
last 20 years and
my class has won.
WARREN BUFFET
Economic inequality** – the skewed distribution of income and wealth – has
THE FOURTH WEALTHIEST
reached extreme levels and continues to rise. Seven out of 10 people on the
PERSON IN THE WORLD135
planet now live in a country where economic inequality is worse today than
“
it was 30 years ago.136 South Africa, for example, is now significantly more
unequal than it was at the end of Apartheid 20 years ago.137 This inequality
undermines global efforts to reduce poverty and hurts us all. This report is
focused on the pernicious effects of inequality, and the possible solutions to it.
Even It Up: Time to End Extreme Inequality starts by showing that the gap
between rich and poor is already very wide and is growing in the majority of
countries. It then demonstrates why extreme economic inequality is bad for all
of us. In more unequal societies, rich and poor alike have shorter lives, and live
with a greater threat of violence and insecurity. Inequality hinders economic
growth and stifles social mobility. It creates conditions in which crime and
corruption thrive. It underlies many of the world’s violent conflicts and is
a barrier in the fight against climate change.
Critically, this report will demonstrate that unless we close the gap between
the haves and the have-nots, we will not win the battle against extreme
**‘ to refer to extreme economic (wealth
and income) inequality. When referring to the various dimensions of inequality we make
these distinctions.
25
SECTION 1 2 3 INTRODUCTION
poverty, and the injustice of millions of families living in extreme poverty
alongside great wealth and prosperity will continue. Today, the rich can buy
longer, safer lives and better education, and can secure jobs for their children,
while those without money and influence are much more likely to be denied
even their basic rights. When disasters strike or food prices spike, those who
lack wealth and power suffer the most, and find it most difficult to recover.
The report then looks at what is driving this rapid increase in extreme economic
inequality, focusing on two major causes: market fundamentalism and the
capture of power and politics by economic elites. Many, including billionaire
George Soros and Nobel-laureate Joseph Stiglitz, believe that market
fundamentalism is to blame for the rapid concentration of wealth over the last
four decades. When politics and policy making are influenced by elites and
corporations, they serve their economic interests instead of those of society
as a whole. This is as true in the USA as it is in Pakistan and Mexico, and has led
to government policies and actions that benefit the few at the expense of the
many, further widening the inequality gap.
Oxfam’s decades of experience working with the world’s poorest communities
have taught us that poverty, inequality and these traps of disadvantage are not
accidental, but the result of deliberate policy choices made by governments
and international organizations. The world needs concerted action to build
a fairer economic and political system that values the many. The rules and
systems that have led to today’s inequality explosion must change. Urgent
action is needed to level the playing field by implementing policies that
redistribute money and power from the few to the many.
The second half of the report explores some of the deliberate policy choices
that will be crucial to reducing inequality. Governments and companies can
take steps to ensure decent working conditions, the right for workers to
organize, the right to a living wage, and to curb skyrocketing executive pay.
Companies must become more transparent, and policies must be enacted to
ensure that both they and rich individuals pay their fair share of taxes. Ensuring
universal access to healthcare, education and social protection will mitigate
the extremes of today’s skewed income distribution and will guarantee that
the most vulnerable are not left behind.
While there has been progress, real change will only come about if we break
the stranglehold that special interests now have over governments and
institutions, and if citizens demand their governments pursue policies that
are about redistribution and fairness.
Extreme economic inequality, the focus of this report, has exploded in the last
30 years, making it one of the biggest economic, social and political challenges
of our time. Age-old inequalities, such as gender, caste, race and religion, are
injustices in themselves, and are also worsened by the growing gap between
the haves and the have-nots.
As Oxfam launches the Even it Up campaign worldwide, we join a groundswell of
voices, such as billionaires like Warren Buffet, faith leaders like Pope Francis,
the heads of institutions, like Christine Lagarde of the IMF, as well as the World
Bank, trade unions, social movements, women’s organizations, academics and
millions of ordinary people, to demand that leaders tackle extreme inequality
before it is too late.
26
A view across Santa Marta favela and central Rio de Janeiro (2006).
Photo: John Spaull
1
EXTREME
INEQUALITY
A story that needs a new ending
SECTION 1 2 3 EXTREME INEQUALITY
Leonard Kufekeeta, 39, selling
brushes in Johannesburg (2014).
Photo: Zed Nelson
1.1
THE REALITY OF TODAY’S
HAVES AND HAVE-NOTS
Trends in income and wealth tell a clear story: the gap
between the rich and poor is wider now than ever before
and is still growing, with power increasingly in the
hands of an elite few.
28
SECTION 1 2 3 EXTREME INEQUALITY
MEASURING INEQUALITY: GINI, PALMA AND THE WORLD
TOP INCOMES DATABASE
Accurately and regularly measuring inequality is politically difficult
and often neglected, especially in developing countries. A reliance on
household surveys and tax records systematically under-reports the
incomes and wealth of the richest in society, as they often have the
resources to avoid tax and are rarely captured by surveys. The reliance
on household surveys also means that gender inequalities are not
adequately measured.
Inequality of income, wealth and other assets, such as land, have been
historically measured by the Gini coefficient, named after the Italian
statistician Corrado Gini. This is a measure of inequality where a rating
of 0 represents total equality, with everyone taking an equal share,
and a rating of 1 (or sometimes 100) would mean that one person has
everything. Throughout this paper we rely heavily on comparisons using
Gini coefficients, as this tends to be most prevalent in the research
and evidence available on economic inequality.
However, one critique of the Gini is that it is overly sensitive to the
middle 50 percent.138 The Palma ratio, named after the Chilean economist
Gabriel Palma, seeks to overcome this by measuring the ratio of the
income share between the top 10 percent and the bottom 40 percent.
This measure is gaining traction, for instance it has been proposed
by Joseph Stiglitz as the basis for a target in a post-2015 global goal
to reduce income inequality. The Palma ratio is crucial for gauging
increases in income and wealth concentration at the very top, making
it a useful tool for future research.
Tax records have also recently been used very successfully to get
a more accurate record of top incomes. The World Top Incomes
Database, co-founded by Thomas Piketty, covers 26 countries, with
information on the share of pre-tax income going to the richest one
percent since the 1980s.
There is no doubt that governments and institutions like the World Bank
must greatly increase and improve the measurement of inequality as
a fundamental foundation to tackle extreme inequality.
IN THE HANDS OF THE FEW: INCOME AND WEALTH
Global inequality – the inequality between countries – rose rapidly between
1980 and 2002,139 but has fallen slightly since due to growth in emerging
countries, particularly China.
The bottom billion have increased their share of world income by 0.2 percent
since 1990, to just short of one percent, but to increase their share to 10
percent at the same rate would take more than eight centuries.140 We have
reproduced UNICEF’s analysis in Figure 1 – dubbed the ‘Champagne Glass’ –
showing how much global income is concentrated at the very top, while the
vast majority of people take a comparatively meagre share of global income
that forms the ‘stem’ of the glass.141
29
SECTION 1 2 3 EXTREME INEQUALITY
FIGURE 1: Global income distribution by percentile of population ($)
Q5
Each horizontal band
Q4 represents an equal fifth
of the world’s population
Population (in quintiles)
Q3
Q2 Persons below
$2/day
(40 percent)
Persons below
Q1 $1.25/day
(22 percent)
Income ($)
But it is national inequality that matters most to people’s lives, and this is rising
rapidly almost everywhere. Seven out of ten people on the planet now live in
countries where economic inequality is worse than it was 30 years ago.142
Today, the rich are earning more, both in absolute terms and relative to the
rest of the population. According to the World Top Incomes Database, in all but
one of the 29 countries measured (Colombia), the share of income going to
the richest one percent increased, while in Colombia it held steady at around
20 percent.143
India, China and Nigeria are three of the world’s fastest growing, and most
populous, developing economies. Figure 2 demonstrates how their national
income is shared between the richest 10 percent and poorest 40 percent.
They show that the benefits of growth have increasingly accrued to the richest
members of society, pushing income inequality ever higher. In just these three
countries, more than 1.1 billion people – 16 percent of the world – are getting
an increasingly smaller share.144
30
SECTION 1 2 3 EXTREME INEQUALITY
FIGURE 2: Increasing inequality in three middle-income countries145
Income share held by wealthiest 10%
Income share held by poorest 40%
China
40
35
Share of national income (%)
30
25
20
15
10
5
0
1980 1985 1990 1995 2000 2005 2010
India
40
35
Share of national income (%)
30
25
20
15
10
5
0
1980 1985 1990 1995 2000 2005 2010
Nigeria
40
35
Share of national income (%)
30
25
20
15
10
5
0
1980 1985 1990 1995 2000 2005 2010
31
SECTION 1 2 3 EXTREME INEQUALITY
THE BILLIONAIRE BOOM
Inequality of wealth is even more extreme than the inequality of income.
The number of dollar millionaires – known as High Net Worth Individuals –
rose from 10 million in 2009 to 13.7 million in 2013.146 Since the financial crisis,
the ranks of the world’s billionaires has more than doubled, swelling to 1,645
people.147 The billionaire boom is not just a rich country story: the number of
“
India’s billionaires increased from just two in the 1990s,148 to 65 in early 2014.149
And today there are 16 billionaires in sub-Saharan Africa,150 alongside the
358 million people living in extreme poverty.151 No society can sustain
this kind of rising inequality.
Oxfam’s research in early 2014 found that the 85 richest individuals in the world In fact, there is no example in
have as much wealth as the poorest half of the global population.152 This figure human history where wealth
was based on the wealth of the 85 billionaires at the time of the annual Forbes accumulated like this and the
report in March 2013. In the period of a year from March 2013 to March 2014 pitchforks didn’t eventually
their wealth rose again by a further 14 percent, or $244bn.153 This equates to come out. You show me a
a $668m-a-day increase. highly unequal society, and
I will show you a police state.
Once accumulated, the wealth of the world’s billionaires takes on a momentum Or an uprising. There are
of its own, growing much faster than the broader economy in many cases. If Bill no counterexamples.
Gates were to cash in all his wealth and spend $1m every single day, it would
NICK HANAUER154
take him 218 years to spend all of his money.155 But in reality, the interest on
”
his wealth, even in a modest savings account (with interest at 1.95 percent)
would make him $4.2m each day. The average return on wealth for billionaires
is approximately 5.3 percent,156 and between March 2013 and March 2014,
Bill Gates’ wealth increased by 13 percent – from $67bn to $76bn.157 This is
an increase of $24m a day, or $1m every hour.
The richest ten people in the world would face a similarly absurd challenge
in spending their wealth, as the following calculations show.
there are 16 billionaires
in sub-saharan africa living alongside
the 358 million people living
in extreme poverty
32
SECTION 1 2 3 EXTREME INEQUALITY
TABLE 1: The number of years it would take for the richest 10 people to spend
their wealth, and earnings on modest and average interest158
Earnings per Earnings per
Years to spend all day at ordinary day at average
Name Wealth ($bn)
money, at $1m/day rate of 1.95% billionaire rate of
Interest ($m) return (5.3%) ($m)
Carlos Slim Helu
80 220 4.3 11.6
and family (Mexico)
Bill Gates (USA) 79 218 4.2 11.5
Amancio Ortega
63 172 3.3 9.1
(Spain)
Warren Buffett
62 169 3.3 8.9
(USA)
Larry Ellison (USA) 50 137 2.7 7.2
Charles Koch (USA) 41 112 2.2 5.9
David Koch (USA) 41 112 2.2 5.9
Liliane Bettencourt
37 102 2.0 5.4
and family (France)
Christy Walton
37 101 2.0 5.3
and family (USA)
Sheldon Adelson
36 100 1.9 5.3
(USA)
The decision of Bill Gates and Warren Buffet to give away their fortunes is
an example to the rest of the world’s billionaires. In fact, many billionaires
and millionaires have been vocal in their agreement that extreme wealth
is a problem that threatens us all. In the USA, a group called the Patriotic
Millionaires is actively lobbying congress to remove tax breaks for the wealthy,
writing: ‘for the fiscal health of our nation and the well-being of our fellow
citizens, we ask that you increase taxes on incomes over $1,000,000’.159
The aggregate wealth of today’s billionaires has increased by 124 percent
in the last four years and is now approximately $5.4tn. This is twice the size
of France’s GDP in 2012.160
33
SECTION 1 2 3 EXTREME INEQUALITY
Oxfam has calculated that a tax of just 1.5 percent on the wealth of the world’s
billionaires, if implemented directly after the financial crisis, could have saved
23 million lives across the world’s poorest 49 countries, by providing them with
money to invest in healthcare.161 The number of billionaires and their combined
wealth has increased so rapidly that in 2014 a tax of 1.5 percent could fill the
annual gaps in funding needed to get every child into school and to deliver
health services in those poorest countries.162
LAND: THE OLDEST FORM OF WEALTH INEQUALITY
In the history of rich nations, wealth was originally made up of land, and
in developing countries this remains the case. Farmland is particularly
vital to poor people’s livelihoods in developing countries.163 But too many
people in rural populations struggle to make a living from small plots.
Many more lack secure tenure rights, especially women, meaning they
can be driven off their land, leaving them without a source of income.
In a forthcoming Oxfam study with women’s organizations across three
continents, women’s lack of access to land was identified as one of the
top threats to community resilience.164
Most countries in Latin America score a Gini coefficient on land
inequality of over 0.8; in Asia, many score higher than 0.5. In Angola and
Zambia, small farms comprise 80 percent of all farms, but make up only
around two percent of agricultural land.165 Large-scale redistribution of
land in East Asian countries like South Korea, Japan and China played
a key role in their reducing inequality and making growth more pro-poor.
In some countries, such as Brunei, Saudi Arabia, Kuwait and Swaziland,
heads of state are the biggest landowners. In Russia, the sugar company
Prodimex owns 20 percent of all private land.166
Inequality of land ownership is not isolated to the developing world
although in rich countries, where alternative employment exists,
landlessness is less of a social problem. According to recent research
in the EU, large farms167 comprise just three percent of the total number
of farms, but control 50 percent of all farmland.168
34
SECTION 1 2 3 EXTREME INEQUALITY
A woman walks past two heavily armed
policemen on guard outside a department
store in Manhattan (2008).
1.2 Photo: Panos/Martin Roemers
EXTREME INEQUALITY
HURTS US ALL
The rapid rise of economic inequality is a significant barrier
to eliminating poverty and to sharing prosperity where
it does exist so that the poorest benefit from it. Extreme
inequality both undermines economic growth and the ability
of growth to reduce poverty. It damages our ability to live
within the planet’s resources and succeed in the fight
against climate change. It makes the struggle for equality
between the sexes far harder.
35
SECTION 1 2 3 EXTREME INEQUALITY
If a person is born poor in a very unequal country, their children are far
more likely to be poor as well. More unequal societies suffer more from
a range of social ills, including crime and violence, that hurt both rich and
poor. Fundamentally, inequality goes against strongly held moral beliefs
and a widely shared understanding of fairness, with people’s preferred
distribution of wealth and income being far more equal than it actually is.
EXTREME INEQUALITY IS A BARRIER
TO POVERTY REDUCTION
Over the last two decades the world has seen huge progress in the fight to
end extreme poverty; millions more people now have access to healthcare
and education, and approximately 150 million fewer men and women are going
hungry.169 Yet inequality threatens to undermine, and in some cases reverse,
this progress. The fruits of economic growth in recent years have often failed to
benefit the poorest, with the biggest beneficiaries being those at the top of the
income ladder.
New research by Oxfam has projected potential poverty levels in a number of
middle-income countries over the next five years, considering the implications
when inequality remains the same, reduces or increases at a constant rate.170
In all cases, the results present compelling evidence that inequality stands in
the way of poverty reduction.
Three examples:
• In Kenya, if inequality remains at the same level for the next five years,
three million more people could be living in extreme poverty than if
they reduced their Gini coefficient by just five points, the equivalent of
a 12 percent reduction.
• If Indonesia reduced its Gini coefficient by just 10 points, the equivalent
of a 28 percent reduction, they could reduce the number of people living
in extreme poverty to 1.7 million. If inequality remains at recent levels
though, there will be 13 million more Indonesian people below the extreme
poverty line in five years’ time.
• India has, in recent years, become more unequal. If India were to stop its
rising inequality, and instead hold inequality levels static, by 2019 they
could lift 90 million people out of extreme poverty. Reducing inequality by
10 points, the equivalent of a 36 percent reduction, could almost eliminate
extreme poverty altogether, by lifting up a further 83 million people.
36
SECTION 1 2 3 EXTREME INEQUALITY
FIGURE 3: Poverty projections to 2019 for different inequality scenarios in
three countries (millions in poverty)
Decline in people
Kenya living in poverty
12
Population living in poverty in 2019 (millions)
Population living in poverty in 2011
10 700,000 1.3
million
4.2 6.8
8 million million
6
4
2
0
1 point Gini No Gini 5 points Gini 10 points Gini
increase (0.43) change (0.42) decrease (0.37) decrease (0.32)
Indonesia
35 Population living in poverty in 2011
Population living in poverty in 2019 (millions)
30
16 18.1 26.6 31.2
25 million million million million
20
15
10
5
0
1 point Gini No Gini 5 points Gini 10 points Gini
increase (0.35) change (0.34) decrease (0.29) decrease (0.24)
India
200
Population living in poverty in 2011
Population living in poverty in 2019 (millions)
180
160
140 76.8 90.1 144.6 173.2
million million million million
120
100
80
60
40
20
0
1 point Gini No Gini 5 points Gini 10 points Gini
increase (0.35) change (0.34) decrease (0.29) decrease (0.24)
37
SECTION 1 2 3 EXTREME INEQUALITY
The Brookings Institution has developed scenarios that demonstrate the same
problem at a global level; that inequality is holding back poverty eradication.
They found that 463 million more people worldwide were lifted out of poverty
in a scenario where inequality was reduced, compared to a scenario where
inequality was increased.171
The challenge of eradicating extreme poverty is greatest in Africa, with
forecasts projecting its share of the world’s extreme poor rising to 80 percent
or above by 2030. If African countries continue on their current growth
trajectory with no change in levels of income inequality, then the continent’s
poverty rate won’t fall below three percent – the World Bank’s definition
of ending poverty – until 2075.172
R EDUCING INEQUALITY:
CASE STUDY A CRUCIAL INGREDIENT FOR TACKLING
POVERTY IN SOUTH AFRICA
A boy jumping over a drainage canal.
Masiphumelele township,
near Cape Town (2014).
Photo: Zed Nelson
In 2010, South Africa had a Gini coefficient of 0.66, making it one of the
most unequal societies in the world. The two richest people in South
Africa have the same wealth as the bottom half of the population.173
South Africa is significantly more unequal than it was at the end
of Apartheid.
Between 1995 and 2006, the proportion of the population living in
extreme poverty fell slightly to 17 percent. However, increases in
population over the same period meant that the total number of South
Africans living in extreme poverty fell by just 102,000. Although real
growth in GDP per capita was just under two percent, further progress
on reducing poverty was hampered by South Africa’s extremely high,
and growing, level of inequality.174
Oxfam projections show that even on the very conservative assumption
that inequality remains static, just 300,000 fewer South Africans will be
living in absolute poverty by 2019, leaving almost eight million people
living below the poverty line. Conversely, if the Gini continues to increase
even by one point, this will lead to 300,000 more people living in poverty
in five years.175
38
SECTION 1 2 3 EXTREME INEQUALITY
There is also strong evidence that the national distribution of income has
a significant impact on other poverty outcomes. Measured on the scale of
average income, both Bangladesh and Nigeria are low-income countries.
Bangladesh is the poorer of the two,176 but the distribution of income is far
more equal than in Nigeria. The difference in development outcomes speak
for themselves:
• Child mortality rates in Nigeria are nearly three times higher than those
in Bangladesh.177
• While Bangladesh has achieved universal primary education and eliminated
gender gaps in school attendance up to lower-secondary school levels,
over one-third of Nigeria’s primary school-age children are out of school.178
In many countries progress on development outcomes has been much
quicker for the wealthier sections of society, and averages have obscured the
widening gap between the rich and poor. In Uganda, for instance, under-five
mortality among the top 20 percent has halved, but for the bottom 20 percent
it has only fallen by a fifth over the same period. In other countries, such as
Niger, progress has been more even, showing that different paths to progress
are possible.179
FIGURE 4: Under-five mortality rate (per 1000 live births) in Uganda (2000‑2011)180
180
159.5
Under-5 mortality rate (per 1000 live births)
160 147.8
140
124
120
100
80 71.1
60
40
20
0
2000 2011
Richest 20% Poorest 20%
EXTREME INEQUALITY UNDERMINES GROWTH
For decades the majority of development economists and policy makers
maintained that inequality had little or no impact on a country’s growth
prospects. This was based on the understanding that inequality inevitably
accompanies the early stages of economic growth, but that it would be
short-lived, as growth would gradually ‘trickle down’ through the layers of
society, from the richest to the poorest.181 A mass of more recent evidence has
overwhelmingly refuted this assumption and shown that extremes of inequality
are, in fact, bad for growth.182
39
SECTION 1 2 3 EXTREME INEQUALITY
A multi-decade cross-country analysis by IMF economists, for instance,
strongly suggests that not only does inequality hinder growth’s poverty
reducing function it also diminishes the robustness of growth itself.183 The IMF
has documented how greater equality can extend periods of domestic growth184
and that inequality was a contributing factor to the 2008 financial crisis.185
Growth is still possible in countries with high levels of inequality, but inequality
reduces the chances of such growth spells being robust and long lasting.
Moreover, detailed analysis of developed and developing countries from the
mid-1990s onwards shows that a high level of inequality constitutes a barrier
to future economic growth186 because it obstructs productive investment, limits
the productive and consumptive capacity of the economy, and undermines
the institutions necessary for fair societies.187
If national governments care about strong and sustained growth, then they
should prioritize reducing inequality. This is especially true for developing
countries, where inequality is on average higher than in rich countries. The
Asian Development Bank (ADB) has gone so far as to suggest that growth
and equality can ‘be seen as part of a virtuous circle.’188
INEQUALITY HINDERS THE POVERTY-REDUCING
POTENTIAL OF GROWTH
If inequality is reduced, poverty reduction happens faster and growth is more
robust. Conversely, if inequality becomes worse poverty reduction slows and
growth becomes more fragile.189
It is the distribution of economic growth that matters for poverty reduction
rather than the pursuit of growth for its own sake. For example, in Zambia, GDP
per capita growth averaged three percent every year between 2004 and 2010,
pushing Zambia into the World Bank’s lower-middle income category. Despite
“
this growth, the number of people living below the $1.25 poverty line grew from
65 percent in 2003 to 74 percent in 2010.190 Nigeria had a similar experience
The power of growth to
between 2003 and 2009; poverty increased more than anticipated, and the
reduce poverty… tends to
richest 10 percent experienced a six percent increase in the share of national
decline both with the initial
consumption while everyone else’s share fell.191
level of inequality, and with
increases in inequality during
Research by Oxfam suggests that inequality is the missing link that
the growth process.
explains how the same rate of growth can lead to different rates of poverty
reduction.193 The World Bank has similarly found that in countries with very F. FERREIRA AND
low income inequality, such as several in Eastern Europe, every one percent M. RAVALLION192
“
of economic growth reduced poverty by four percent.194 In countries with
high inequality, such as Angola or Namibia, growth had essentially no impact
on poverty.195 Even in medium-income countries, the level of inequality can
have a huge impact on the poverty reducing impact of growth.196 The World
Bank’s researchers concluded that ‘the power of growth to reduce poverty
depends on inequality,’ both its initial level and its evolution.197
40
SECTION 1 2 3 EXTREME INEQUALITY
EXTREMES OF WEALTH AND INEQUALITY ARE
ENVIRONMENTALLY DESTRUCTIVE
The world is approaching a number of ‘planetary boundaries’, where
humanity is using the maximum possible amount of natural resources,
such as carbon or safe drinking water. The closer we get to reaching
these limits, the more the hugely unequal distribution of natural
resources matters.198
Often it is the poorest that are hit first and hardest by environmental
destruction and the impacts of climate change.199 Yet it is the
wealthiest who most impact on our planet’s fragile and finite resources.
Narinder Kakar, Permanent Observer to the UN from the International
Union for Conservation of Nature, has declared that environmental
decline can be attributed to less than 30 percent of the world’s
population.200 The richest seven percent of world’s population (equal
to half a billion people) are responsible for 50 percent of global CO2
emissions; whereas the poorest 50 percent emit only seven percent
of worldwide emissions.201
Key to this are the consumption patterns of the richest. The majority
of emissions from wealthier households in rich countries are indirect,
such as through the consumption of food, consumer goods and
services, much of which is produced beyond their nations’ shoreline.202
It is the ‘population with the highest consumption levels [that] is likely
to account for more than 80 percent of all human-induced greenhouse
gas emissions’.203
Such inequalities in emissions have a parallel in the disproportionate
use of the world’s resources. Just 12 percent of the world’s people
use 85 percent of the world’s water.204
41
SECTION 1 2 3 EXTREME INEQUALITY
Female construction workers work to
build offices for IT companies in a new
ECONOMIC INEQUALITY COMPOUNDS technology park, Bangalore, India (2004).
GENDER INEQUALITY Photo: Panos/Fernando Moleres
One of the most pervasive – and oldest – forms of inequality is that between
men and women, and there is a very strong link between gender and economic
inequality. Gender discrimination is an important factor in terms of access
to, and control over, income and wealth. While the reasons behind inequality
between women and men are about more than money, there is no doubt that
<
the overlap between economic inequality and gender inequality is significant.
Men are overwhelmingly represented at the top of the income ladder, and
Only 23
Fortune 500 chief
women are overwhelmingly represented at the bottom. Of the 2,500 people that
executives are women
attended the World Economic Forum in 2014, just 15 percent were women.205
Only 23 chief executives of Fortune 500 companies are women. Of the top
30 richest people in the world, only three are women. The richest in society are
>
very often disproportionately represented in other positions of power; be they
presidents, members of parliament, judges or senior civil servants. Women are
largely absent from these corridors of power.
At the same time, around the world, the lowest paid workers and those in the
most precarious jobs are almost always women. The global wage gap between
men and women remains stubbornly high: on average women are paid 10 to 30
percent less than men for comparable work, across all regions and sectors.206
The gap is closing, but at the current rate of decline it will take 75 years
to make the principle of equal pay for equal work a reality.207
42
SECTION 1 2 3 EXTREME INEQUALITY
2089
EQUAL PAY FOR
EQUAL WORK
AT THE CURRENT RATE, IT WILL TAKE 75 YEARS
FOR WOMEN TO EARN THE SAME AS MEN
FOR DOING THE SAME WORK
The wage gap is higher in more economically unequal societies. Women are
significantly more likely to be employed in the informal sector, with far less
job security than men. Some 600 million women, 53 percent of the world’s
working women, work in jobs that are insecure and typically not protected
by labour laws.208
In Bangladesh, women account for almost 85 percent of workers in the garment
industry. These jobs, while often better for women than subsistence farming, <
3
have minimal job security or even physical safety. The majority of those killed by
the collapse of the Rana Plaza garment factory in April 2013 were women.
In Brazil, 42 percent of women are in insecure and precarious jobs, compared to
Just
26 percent of men.209 Country-level studies have also demonstrated that the of the 30 richest
gender distribution of wealth, including land and access to credit, is far more people are women
unequal than income.210
>
The majority of unpaid care work is also shouldered by women and is one of
the main contributors to women’s concentration in low-paid, precarious and
unprotected employment. In many countries, women effectively subsidize the
economy with an average of 2–5 hours more unpaid work than men per day.211
Even when women are employed, their burden of work at home rarely shrinks.
In Brazil, women’s share of household income generation rose from 38 percent
in 1995 to 45 percent in 2009, but their share of household care responsibility
43
SECTION 1 2 3 EXTREME INEQUALITY
fell only by two percent in the second half of that period – from 92 percent in
2003 to 90 percent in 2009.212 The same trend is true for many other countries.
The concentration of income and wealth in the hands of men gives them more
decision-making power at the national level, where women usually have little
voice or representation. National laws often take a piecemeal and incoherent
approach to addressing gender inequality; for instance, implementing policies
that increase job opportunities for women, but without policies to prevent low
wages, or to promote adequate working conditions and high-quality childcare.
Discriminatory laws and practices around asset ownership and inheritance
rights prevent women from escaping the bottom of the economic ladder. This
creates a vicious cycle, as women living in poverty are more likely to lack the
legal entitlements, time and political power that they need to increase their
income. Gender discriminatory legislation and the requirements of lending
“
institutions are additional barriers which exclude women from access to credit.
In its World Development Report 2012, the World Bank noted that women In India, the average daily
are more vulnerable to income shocks, such as unemployment or increased wage of a male worker
poverty, precisely because they have less economic power. Women tend is about two and a
to have fewer assets than men, less access to economic opportunities half times that of his
to deal with sudden changes, and less support through compensation female counterpart.213
“
from government.214
The recent rapid rise in economic inequality in the majority of countries
therefore represents a serious barrier in the drive to achieve equality
between women and men.
ECONOMIC INEQUALITY DRIVES INEQUALITIES
“
IN HEALTH, EDUCATION AND LIFE CHANCES
The stark reality is that economic status dictates life chances; poorer people Things are changing in
have shorter lives. This is a problem in rich countries and poor countries alike. South Africa for the worst.
In the UK, for instance, men born in the richest part of the country can expect The public schools are
to live nine years longer than men from the most deprived areas.215 The rapidly no good. Those in the
growing gap between rich and poor in the majority of countries is worrying not government, they are very
just on its own terms, but because of the way it interacts with other rich, the rest of us are poor.
inequalities and discrimination to hold some people back more than others.
LEONARD KUFEKETA, 39
“
Economic inequality adds new dimensions to old disparities, such as gender,
geography and indigenous rights. In every country, average rates of child
survival, education and access to safe water are significantly higher for men
than women. Women in poor households are far less likely to have prenatal
and antenatal care when they are pregnant and give birth than their wealthier
neighbours. Their children are more likely to be malnourished and many will not
live past the age of five. If they do, they are far less likely to complete primary
education. If they can find employment as adults, they will likely have much
lower incomes than those from higher income groups. This cycle of poverty
and inequality is then transmitted across generations.
Using the latest national Demographic and Health Surveys, Oxfam has
calculated how poverty interacts with economic and other inequalities
44
SECTION 1 2 3 EXTREME INEQUALITY
in Ethiopia to create ‘traps of disadvantage’, pushing the poorest and most
marginalized to the bottom.
Over 50 percent of Ethiopian women have never been to school, compared to
just over a third of men. However, as Figure 5 shows, when we consider gender
and economic inequality together, a much greater wedge is driven between the
haves and the have-nots. Nearly 70 percent of the poorest women don’t attend
school, compared to just 14 percent of the richest men.216
FIGURE 5: Gender and economic inequalities: Percentage of Ethiopians who
have not attended school
TOTAL PERCENTAGE OF POPULATION
NOT ATTENDING SCHOOL
45.2%
WOMEN MEN
52.1% 38.3%
LEAST LEAST
WEALTHY WEALTHIEST WEALTHY WEALTHIEST
WOMEN WOMEN MEN MEN
69.2% 26.6% 54.1% 14%
Those living in rural areas are also consistently worse off. As Figure 6 shows,
the richest and poorest Ethiopians living in urban areas have a greater chance
of going to school than those of comparable incomes living in rural areas.
Taking gender into account, a girl born into one of the richest urban families
is still only half as likely to go to school as a boy born to a similar family.
45
SECTION 1 2 3 EXTREME INEQUALITY
FIGURE 6: Multiple Inequalities: Percentage of Ethiopians who have not
attended school
TOTAL PERCENTAGE OF POPULATION
NOT ATTENDING SCHOOL
45.2%
POOREST 20% RICHEST 20%
62.1% 20.7%
POOREST 20% POOREST 20% RICHEST 20% RICHEST 20%
RURAL URBAN RURAL URBAN
62.4% 45.7% 26.7% 19.2%
POOREST POOREST POOREST POOREST RICHEST RICHEST RICHEST RICHEST
RURAL RURAL URBAN URBAN RURAL RURAL URBAN URBAN
WOMEN MEN WOMEN MEN WOMEN MEN WOMEN MEN
69.6% 54.6% 48.7% 42.8% 32.6% 20.9% 25.1% 12.2%
46
SECTION 1 2 3 EXTREME INEQUALITY
Caste, race, location, religion, ethnicity, as well as a range of other identities
that are ascribed to people from birth, play a significant role in creating
divisions between haves and have-nots. In Mexico, maternal mortality rates
for indigenous women are six times the national average and are as high as
many countries in Africa.217 In Australia, Aboriginal and Torres Strait Islander
Peoples remain the country’s most significantly disadvantaged group,
disproportionately affected by poverty, unemployment, chronic illness,
disability, lower life expectancy and higher levels of incarceration.
Around the world, these different inequalities come together to define people’s
opportunities, income, wealth and asset ownership, and even their life spans.
CONDEMNED TO STAY POOR FOR GENERATIONS
“
Beyond the impact that rising economic inequality has on poverty reduction
and growth, it is becoming increasingly clear that the growing divide between
rich and poor is setting in motion a number of negative social consequences That’s why they call it
that affect us all. the American Dream,
because you have to be
It would be hard to find anyone to disagree with the idea that everyone asleep to believe it.
should be given an equal chance to succeed in life, and that a child born into
GEORGE CARLIN
poverty should not have to face the same economic destiny as their parents.
COMEDIAN
There should be equality of opportunity so that people can move up the
“
socioeconomic ladder; in other words, there should be the possibility of social
mobility. This is an idea that is deeply entrenched in popular narratives and
reinforced through dozens of Hollywood films, whose rags to riches stories
continue to feed the myth of the American Dream in the USA and around
the world.
However, in both rich and poor countries, high inequality has led to diminished
social mobility.218 In these countries the children of the rich will largely replace
their parents in the economic hierarchy, as will the children of those living
in poverty. today that.’
John Makina, Country Director for Oxfam in Malawi
47
SECTION 1 2 3 EXTREME INEQUALITY
In countries with higher levels of inequality it is easier for parents to pass on
their advantages to their children; advantages that less wealthy parents
“
cannot afford.219 The clearest example of this is expenditure on education.
Wealthier parents often pay for their children to attend costly private schools
If Americans want to live
that then facilitate their entry into elite universities, which in turn help them
the American dream, they
secure higher paid jobs. This is reinforced by other advantages, such as the
should go to Denmark.
resources and social networks that richer parents share with their children,
which further facilitate employment and education opportunities. In this way, RICHARD WILKINSON
the richest capture opportunities, which then become closed off from those CO-AUTHOR OF THE SPIRIT LEVEL221
“
who do not have the means to pay.220
Figure 7 demonstrates the negative relationship between rising inequality and
diminishing social mobility across 21 countries. In Denmark, a country with
a low Gini coefficient, only 15 percent of a young adult’s income is determined
by their parent’s income. In Peru, which has one of the highest Gini coefficients
in the world, this rises to two-thirds. In the USA, nearly half of all children born
to low-income parents will become low-income adults.222
FIGURE 7: The Great Gatsby Curve: The extent to which parents’ earnings
determine the income of their children223
0.8
0.7
Peru
Intergenerational earnings elasticity
0.6
Brazil
0.5 Chile
Argentina
Pakistan Spain USA
Switzerland Singapore
0.4 France New Zealand
Japan
0.3 Germany
Australia
Sweden Canada
0.2 Italy
Norway Finland
Denmark
0.1
China United Kingdom
0
20 25 30 35 40 45 50 55 60 65
Gini coefficient
In Pakistan, social mobility is a distant dream. A boy born to a father224 from the
poorest 20 percent of the population has a 6.5 percent chance of moving up to
the wealthiest 20 percent of the population.225
In many countries, social mobility for women and marginalized ethnic groups is
a virtual impossibility due to entrenched discriminatory practices, such as the
caste system in India, which are compounded by economic inequality.226
Policies designed to reduce inequality can provide opportunities to poor
children that were denied to their parents. Education, for example, is widely
considered to be the main engine of social mobility,227 as those with more
48
SECTION 1 2 3 EXTREME INEQUALITY
education often secure higher paid jobs. Countries that spend more on high-
quality public education give poorer students the means to compete more
fairly in the job market, while simultaneously reducing the incentive for richer
parents to privately educate their children.
EXTREME INEQUALITY HURTS US ALL
AND THREATENS SOCIETY
A growing body of evidence indicates that inequality negatively affects social
well-being and social cohesion. In their book, The Spirit Level: Why More Equal
Societies Almost Always Do Better, Kate Pickett and Richard Wilkinson
“
Inequality is the root
of social evil.
demonstrate that countries with higher levels of income inequality experience
POPE FRANCIS
higher rates of a range of health and social problems compared to more equal
“
countries.228 Inequality is linked to shorter, unhealthier and unhappier lives, and
higher rates of obesity, teenage pregnancy, crime (particularly violent crime),
mental illness, imprisonment and addiction.229
Inequality is so toxic, Wilkinson and Pickett explain, because of ‘social status
differentiation’: the higher the levels of inequality, the greater the power and
importance of social hierarchy, class and status, and the greater people’s
urge to compare themselves to the rest of society. Perceiving large disparities
between themselves and others, people experience feelings of subordination
and inferiority. Such emotions spark anxiety, distrust and social segregation,
which set in motion a number of social ills. Although the impacts tend to be felt
most severely lower down the social ladder, the better-off suffer too.230
Crucially, inequality, not the overall wealth of a country, appears to be the most
influential factor. Highly unequal rich countries are just as prone to these ills as
highly unequal poor countries.231 Such ills are from two to 10 times as common
in unequal countries than in more egalitarian ones.232 As Figure 8 demonstrates,
the USA pays a high price for having such high income inequality.
FIGURE 8: Health and social problems are worse in more unequal countries233
Worse
USA
Index of health and social problems
Portugal
United Kingdom
Greece
Ireland New Zealand
France Australia
Austria
Canada Italy
Denmark Germany
Spain
Finland Belgium
Netherlands Switzerland
Norway
Sweden
Better Japan
Low High
Income inequality (Gini)
49
SECTION 1 2 3 EXTREME INEQUALITY
The social divisions reinforced by higher levels of economic inequality become
self-perpetuating, as the rich increasingly share fewer interests with those
who are less well-off.234 When those at the top buy their education and health
services individually and privately, they have less of a stake in the public
provision of these services to the wider population. This in turn threatens
the sustainability of these services, as people have fewer incentives to
make tax contributions if they are not making use of the services provided;
further damaging the social contract.235
When the wealthy physically separate themselves from the less well-off,
fear and distrust tend to grow, something consistently demonstrated in
global opinion surveys. The World Values Survey asks random samples of
the population in numerous countries whether or not they agree with the
statement: ‘Most people can be trusted’.236 The differences between countries
are large, with a clear correlation between lack of trust and high levels
of economic inequality.
INEQUALITY FUELS VIOLENCE
ONDURAS:
H
CASE STUDY UNEQUAL AND DANGEROUS
The Colonia Flor del Campo neighbourhood
in Tegucigalpa, Honduras (2014).
Photo: Oxfam
Honduras is widely considered to be the most dangerous country in the
world, with a homicide rate of 79 per 100,000237 (compared to less than
1 per 100,000 in Spain).238 Insecurity has been increasing since the
political coup in 2009,239 as has inequality.240 Extremely high rates of
violence against women and girls have been recorded, including
many killings.
Regina, 26, lives in a high-security residential gated community in the
Honduran capital, Tegucigalpa, which is home to 150 people.
‘My parents are always fearing for my sister and my security. It’s okay
to go out in a car at night, but it would be a problem if we had to take
public transport. I wouldn’t walk around at night. [...] You always have to
be on the lookout. To protect yourself you have to live in gated houses
with private security and if you can’t afford that then you’ve got to just
be on the lookout.’
50
SECTION 1 2 3 EXTREME INEQUALITY
(CASE STUDY CONTINUED)
Carmen, 34, lives in another neighbourhood in Tegucigalpa, which has no
running water, no street lights, and no tarmac roads to permit access to
cars. A number of her friends and family have been murdered; two were
“
killed inside her house.
‘I feel completely unprotected by the state, mostly because the state
The persistence of inequality
is not concerned with us [residents of her neighbourhood]. Quite the
could trigger social and
opposite, they stigmatize us by labelling our neighbourhoods as “hot-
political tensions, and lead
neighbourhoods”, meaning that they know the difficult situation we live
to conflict as is currently
in here and choose to do nothing about it. I’ve tried to denounce acts
happening in parts of Asia.
of violence against women that occur in my community, but every time
I have been stopped by gangs who have told me that I have to ask their ASIAN DEVELOPMENT BANK241
“
permission before reporting an abuse.’
Quotes taken from Oxfam interviews (2014).
Evidence has clearly linked greater inequality to higher rates of violence –
including domestic violence – and crime, particularly homicides and assaults.242
Compared to more equal countries, those with extreme economic inequality
experience nearly four times the number of homicides.243 While all in society are
affected, violence and crime have a disproportionate impact on those living in
poverty, who receive little protection from the police or legal systems, often live
in vulnerable housing, and cannot afford to pay for private security.
“
Countries in Latin America starkly illustrate this trend.244 Despite the social
and economic advances of the last two decades, Latin America remains the
No society can surely
most unequal and the most insecure region in the world,245 with 41 of the
be flourishing and happy, of
world’s 50 most dangerous cities, and one woman murdered every 18 hours.246
which the far greater part of
A staggering one million people were murdered in Latin America between
the members are poor and
2000 an 2010.247
miserable. It is but equity,
besides, that they who feed,
Greater inequality has frequently been linked to the onset and risk of violent
clothe and lodge the whole
conflict.249 Many of the most unequal countries in the world are affected by
body of the people, should
conflict or fragility. Alongside a host of political factors, Syria’s hidden fragility
have such a share of the
before 2011 was, in part, driven by rising inequality, as falling government
produce of their own labour
subsidies and a fall in public sector employment affected some groups
as to be themselves tolerably
more than others.250 Inequality does not crudely ‘cause conflict’ more than
well fed, clothed and lodged.
any other single factor, but it has become increasingly clear that inequality
is part of the combustible mix of factors making conflict or substantial ADAM SMITH248
“
violence more likely.251
LIVING IN FEAR
In cities around the world people live in fear of walking alone; they are afraid
to stop their cars at traffic lights and can no longer enjoy family outings to
parks or beaches; all due to the fear that they may be attacked.252 These are
important infringements of basic human freedoms and have a large impact
51
SECTION 1 2 3 EXTREME INEQUALITY
on the quality of life of individuals and communities, especially for women
and marginalized groups.
Violence, and equally the fear of violence, often leads to people cutting
themselves off from the rest of society, something that is most starkly
illustrated by people living in gated communities. As Joan Clos, the Director
of UN-Habitat puts it: ‘The gated community represents the segregation of
the population. Those who are gated are choosing to gate, to differentiate,
to protect themselves from the rest of the city.’253
INEQUALITY PUTS THE LIVES OF THE POOREST AT RISK
IN CRISES AND DISASTERS
“
Risk is not shared equally across society; the most vulnerable and
marginalized are more affected by crises, pushing them further into
poverty. Those who are hit hardest in times of crisis are always the Our approach has been
poorest, because they spend a much higher proportion of their income to look to reduce inequalities.
on food and do not have access to welfare or social protection schemes, That is at the centre of
insurance, or savings to help them withstand an emergency. our policies on Disaster
Risk Reduction, because
Extreme inequality of wealth and power also drives national and
inequality just increases
international policies that shelter the rich from risk, passing this on
vulnerability.
to the poor and powerless. Countries with higher levels of economic
inequality have more vulnerable populations.254 MARÍA CECILIA RODRIGUÉZ
MINISTER OF SECURITY,
Inequality between countries explains why 81 percent of disaster deaths
ARGENTINA256
are in low-income and lower-middle income countries, even though they
“
account for only 33 percent of disasters.255
THE EQUALITY INSTINCT
Across the world, religion, literature, folklore and philosophy show remarkable
confluence in their concern that the gap between rich and poor is inherently
unfair and morally wrong. That this concern with distribution is so prevalent
across different cultures and societies suggests a fundamental preference
for fairness and equitable societies.
One of the most influential modern political philosophers, John Rawls, asks us
to imagine that we are under a ‘veil of ignorance’ and know nothing about the
various advantages, social or natural, that we are born into. What principles of
“
To be wealthy and
honoured in an
a good society would we then agree on? One of the most convincing principles unjust society
that emerges from this thought experiment, states that, ‘Social and economic is a disgrace.
inequalities are to be arranged so that they [societies] are both (a) to the
MAHATMA GANDHI
greatest expected benefit of the least advantaged and (b) attached to offices
“
and positions open to all under conditions of fair equality of opportunity.’257
Our preference for fairness and equality are further demonstrated by surveys
from around the world, which consistently show a desire for more equitable
societies.258 An Oxfam survey across six countries (Spain, Brazil, India, South
Africa, the UK and the USA) found that a majority of people believe that
the distance between the wealthiest in society and the rest is too great.
In Brazil, 80 percent agreed with that statement.
52
SECTION 1 2 3 EXTREME INEQUALITY
Similarly, a majority of people agreed with the statement, ‘Reducing inequality
will result in a strong society/economy’.
In research that compared people’s views of what an ideal distribution
of wealth would be, the overwhelming majority selected a preference for
a more egalitarian society. In the USA, when respondents were asked to chose
their preference between two distributions, they overwhelmingly selected
the one that reflected distribution in Sweden over the USA (92 percent
to eight percent).259
Today’s disparities of income and wealth are in opposition to people’s
visions and desires for a fair and just society.
53
SECTION 1 2 3 EXTREME INEQUALITY
Luxury yachts moored in Puerto Adriano, Spain (2013).
Photo: Panos/Samuel Aranda
1.3
WHAT HAS CAUSED THE
INEQUALITY EXPLOSION?
It is clear that economic inequality is extreme and rising,
and that this has huge implications in many areas of life.
But what has caused today’s levels of inequality?
Many believe that inequality is an unfortunate but necessary by-product of
globalization and technological progress. However, the different paths taken
by individual nations belie this view. Brazil has reduced inequality despite being
part of a globalized world, while, over the same period, India has seen a rapid
increase. Rising economic inequality is not the unavoidable impact of
supposedly elemental economic forces – it is the product of deliberate
economic and political policies.
54
SECTION 1 2 3 EXTREME INEQUALITY
This chapter looks at two economic and political drivers of inequality, which
go a long way towards explaining the extremes we see today. The first is the
rise of an extreme variant of capitalism, known as ‘market fundamentalism’.
The second is the capture of power and influence by economic elites, including
companies, which in turn drives further inequality, as political policies and
public debate are shaped to suit the richest in society instead of benefiting
the majority. Together these two drivers form a dangerous mix that greatly
increases economic inequality.
MARKET FUNDAMENTALISM: A RECIPE
FOR TODAY’S INEQUALITY
‘Just as. Market fundamentalism – in the form of light-touch regulation,
the belief that bubbles cannot be identified and that markets always clear
– contributed directly to the financial crisis and the associated erosion
of social capital.’
Mark Carney, Governor of the Bank of England260
With regulation, capitalism can be a very successful force for equality and
prosperity. Over the last three hundred years, governments have used the
market economy to help bring a dignified life to hundreds of millions of people,
first in Europe and North America, then in Japan, South Korea and other
East Asian countries.
However, left to its own devices, capitalism can be the cause of high levels of
economic inequality. As Thomas Piketty demonstrated in his recent influential
book, Capital in the Twenty-First Century, the market economy tends to
“
concentrate wealth in the hands of a small minority, causing inequality to rise.
But governments can act to correct this flaw, by placing boundaries on markets
through regulation and taxation.261 One of the flaws of market
fundamentalism is that it paid
In wealthy societies, for much of the 20th century, effective mobilization no attention to distribution
by working people convinced elites to act on this evident truth, conceding of incomes or the notion of
the need for taxation, regulation and government social spending to keep a good or fair society.
inequality within acceptable bounds.
JOSEPH STIGLITZ262
“
In recent decades however, economic thinking has been dominated by, what
George Soros was the first to call, a ‘market fundamentalist’ approach, which
insists on the opposite: that sustained economic growth comes from leaving
markets to their own devices. A belief in this approach has significantly driven
the rapid rise in income and wealth inequality since 1980.
When good markets go bad: Liberalization and deregulation
Market fundamentalism increases inequality in two ways: it changes existing
markets to make them more unregulated, driving wealth concentration; and
it extends market mechanisms to ever more areas of human activity, meaning
that disparities of wealth are reflected in increasing areas of human life.
55
SECTION 1 2 3 EXTREME INEQUALITY
The same economic medicine worldwide
In countries around the world, during the 1980s and 1990s, increases in
government debt led creditors (principally the IMF and the World Bank) to
impose a cold shower of deregulation, privatization, and financial and trade
liberalization, alongside rapid reductions in public spending, an end to price
stabilization and other public support measures to the rural sector. Generous
tax cuts were provided for corporations and the wealthy, and a ‘race to the
bottom’ to weaken labour rights began, while regulations to protect employees,
such as maternity leave and the right to organize, as well as anti-competition
laws to stop monopolies and financial rules to protected consumers,
were abolished.
In East Asia, the shift to liberalization started in the early 1990s and was
accelerated following the 1997 financial crisis that paved the way for IMF-
imposed public sector reforms, known as ‘structural adjustment programmes’.
These programmes were implemented in many countries, such as Thailand,
South Korea and Indonesia, which subsequently experienced an increase in
levels of economic inequality. In Indonesia, the number of people living on less
than $2 a day rose from 100 million in 1996 to 135 million in 1999;263 since 1999
inequality has risen by almost a quarter.264
Across Africa, rapid market liberalization, under structural adjustment
programmes, increased poverty, hunger and inequality in many
countries. Between 1996 and 2001, the number of Zambians living below the
poverty line rose from 69 to 86 percent; in Malawi, this number increased from
60 to 65 percent over the same period.265 In Tanzania, inequality rose by 28
percent.266 By 2013, across the continent an extra 50 million people were under-
nourished compared to 1990–92.267
In the countries of the former Eastern bloc, market fundamentalism after
the fall of communism in 1989–91 led to economic reforms which focused
on liberalization and deregulation, and resulted in a significant increase in
poverty and inequality. In Russia, the Gini coefficient almost doubled in the
20 years from 1991, and the incomes of the richest 10 percent of the population
are now over 17 times that of the poorest 10 percent, an increase from four
times in the 1980s. Meanwhile the wealthiest one percent of Russians – who
greatly benefitted from the opaque process of privatization during the 1990s –
now hold 71 percent of the national wealth.268
Increases in poverty and inequality were lower in the countries of East Central
Europe, such as Hungary and the Czech Republic, where the governments
played a key role in regulating the market and responded to soaring levels
of poverty.269
56
SECTION 1 2 3 EXTREME INEQUALITY
CASE STUDY I NEQUALITY IN RUSSIA
Vasily outside the derelict Vyshnevolotsky textile
factory in Vyshny Volochek, where he and his wife
once worked (2007).
Photo: Geoff Sayer/Oxfam
Vasily and his wife once both worked at the Vyshnevolotsky textile
factory in the Russian town of Vyshny Volochek, but in 2002 it was shut
down and the building now lies derelict. Vasily’s family lives within sight
of the factory, which provided employment for thousands of workers
from the surrounding community, until it failed to survive privatization.
‘About 3,000 people lost their jobs. My wife worked there, on the third
floor. It was a miserable time. Everyone here lost their jobs. We were
victims of these changes. We thought someone would care about our
situation, but no one did, no-one helped us. In Moscow, they were
getting rich, but the government didn’t care what was happening
here. Everyone had to look to set up their own business. There were
no jobs to find.
‘At the time the factory closed, my wife was eighth on the list for an
apartment. She had waited for years. All that was swept away. There
was not even a payment. In fact, they were given something, 100 Rubles
each. It was an insult.’
In Latin America, historically a region where extreme wealth has sat alongside
extreme poverty, inequality worsened considerably in the 1980s, when debt
relief was made contingent on the adoption of wide-ranging structural
adjustment programmes. These slashed public spending to what became the
world’s lowest levels, at around 20 percent of GDP,270 while also decimating
labour rights, real wages and public services.
By 2000, inequality in Latin America had reached an all-time high, with most
countries registering an increase in income inequality over the previous two
decades.271 In every country in the region except Uruguay, the income share
of the richest 10 percent increased while the share of the poorest 40 percent
either decreased or stagnated. This had a considerable impact on living
standards, causing a significant increase in the number of men and women
living in poverty.272 It is estimated that half of the increase in poverty during this
period was due to redistribution in favour of the richest.273
57
SECTION 1 2 3 EXTREME INEQUALITY
Although Latin America remains the most unequal region in the world, over
the past decade inequality in most countries has begun to decrease.274 This is
the result of a concerted shift in government policy away from those policies
favoured by the economic model of structural adjustment (discussed in the
Busting the Inequality Myths box which follows).
Women are hit hardest by market fundamentalism
Structural adjustment programmes and market-oriented reforms have been
strongly associated with a deterioration of women’s relative position in
the labour market, due to their concentration in a few sectors of economic
activity, their limited mobility and their roles in the unpaid care economy.275
A combination of gender discrimination and the limited regulation favoured by
market fundamentalism have meant that the potential for women – especially
poor women – to share in the fruits of growth and prosperity and to prosper
economically have been severely limited. Women remain concentrated in
precarious work, earn less than men and shoulder the majority of unpaid
care work.
Liberalization of the agricultural sector, including the removal of subsidized
inputs, like credit and fertilizer, has impacted on all poor farmers, but in many
poor countries, the majority of farming is done by poor women. Many of the
labour regulations that market fundamentalism has reduced or removed, like
paid maternity and holiday entitlements, are disproportionately beneficial
to women. Removing these regulations hits women hardest.
Women, along with children, also benefit most from public services such
as healthcare and education. In education, when fees are imposed, girls
are often the first to be held back from school. When health services are cut,
women have had to bear the burden of providing healthcare services to their
family members that were previously provided by public clinics and hospitals.
Equally, women are often the majority of teachers, nurses and other public
servants and, as a result, any cuts to state provision of these roles means
more unemployment for women than for men.
A tenacious worldview
Despite, in fact, being an extreme version of capitalism, market
fundamentalism today permeates the architecture of the world’s social,
political and economic institutions. For many the global financial crisis and
the recession that followed highlighted the failures of excessive market
fundamentalism. However, the push towards liberalization, deregulation and
greater involvement of the markets has in many places been strengthened.
Nowhere is this clearer than in Europe, where the Troika committee – the
European Commission, the European Central Bank and the IMF – attached
sweeping market fundamentalist reforms as pre-conditions for the financial
rescue of struggling states. This has included, for example, proposing workers
in Greece be forced to work six days a week.276
The tenacity of this worldview is arguably the result of two things, which
are in turn linked once more to inequality: the predominant ideology and
the self‑interest of elites.
58
SECTION 1 2 3 EXTREME INEQUALITY
Ideologically, dominant elites in almost every sphere are much more likely
to support the market fundamentalist worldview than ordinary people.
Economists, in particular, are much more likely to strongly hold this view, and
this brand of economics has dominated public thought over the last 30 years.
Market fundamentalism, by leading to the concentration of wealth by elites,
is also in their self-interest. Elites, therefore, use their considerable power
and influence to capture public debate and politics to continue to push for
this market fundamentalist approach, as the next section shows.
CAPTURE OF POWER AND POLITICS BY ELITES
HAS FUELLED INEQUALITY
The second major driver of rapidly rising economic inequality is the excessive
influence over politics, policy, institutions and the public debate, which elites
are able to employ to ensure outcomes that reflect their narrow interests rather
than the interests of society at large. This has all too often led to governments
failing their citizens, whether over financial regulation in the USA or tax rates
in Pakistan.
Elites are those at the top of social, economic or political hierarchies – based
on wealth, political influence, gender, ethnicity, caste, geography, class, and
other social identities. They may be the richest members of society, but they
can also be individuals or groups with political influence, or corporate actors.
Economic elites often use their wealth and power to influence government
policies, political decisions and public debate in ways that lead to an even
greater concentration of wealth. Money buys political clout, which the richest
and most powerful use to further entrench their influence and advantages.
Other non-economic elites, such as politicians or senior civil servants,
use access to power and influence to enrich themselves and protect their
interests. In many countries it is not uncommon for politicians to leave
government having amassed great personal wealth. Political elites sometimes
use the state to enrich themselves in order to keep in power and make huge
fortunes while they govern. They use the national budget as if it was their own
to make individual profit. Non-economic elites also often collude with other
elites to the enrichment of both.
For instance, today’s lopsided tax policies, lax regulatory regimes and
unrepresentative institutions in countries around the world are a result of
this elite capture of politics.277 Elites in rich and poor countries alike use their
heightened political influence to benefit from government decisions, including
tax exemptions, sweetheart contracts, land concessions and subsidies, while
pressuring administrations to block policies that may strengthen the hand of
workers or smallholder food producers, or that increase taxation to make it
more progressive. In many countries, access to justice is often for sale, legally
or illegally, with access to the best lawyers or the ability to cover court costs
only available to a privileged few.
In Pakistan, the average net worth of a parliamentarian is $900,000, yet
few of them pay taxes. Instead, elites in parliament exploit their positions
to strengthen tax loopholes.278 The dearth of tax revenue limits government
59
SECTION 1 2 3 EXTREME INEQUALITY
investment in sectors like education and healthcare that could help to reduce
inequality, and keeps the country dependent on international aid. This prevents
the growth of a diverse and strong economy, while perpetuating economic
and political inequalities.279
Many of today’s richest people made their fortunes thanks to the
exclusive government concessions and privatization that came with
market fundamentalism. Privatization in Russia and Ukraine, after the fall
of communism, made billionaires of the political elite overnight. Mexico’s
Carlos Slim – who rivals Bill Gates as the richest person in the world – made
his many billions by securing exclusive rights to the country’s telecom
sector when it was privatized in the 1990s.280 Since his monopoly hinders any
significant competition, Slim is able to charge his fellow Mexicans inflated
prices, with the costs of telecommunications in the country being among the
most expensive in the OECD.281 He has subsequently used his wealth to fend
off many legal challenges to his monopoly.
Despite being a country ravaged by poverty, the number of billionaires in India
has soared from two in the mid-1990s to more than 60 today.282 A significant
number of India’s billionaires made their fortunes in sectors highly dependent
on exclusive government contracts and licenses, such as real estate,
construction, mining, telecommunications and media. A 2012 study estimated
that at least half of India’s billionaire wealth came from such ‘rent-thick’
sectors of the economy.283 The net worth of India’s billionaires would be enough
to eliminate absolute poverty in the country twice over,284 yet the government
continues to underfund social spending for the most vulnerable. For instance,
in 2011, public health expenditure per capita in India was just four percent of
the OECD country average in per capita terms.285 As a consequence, inequality
in India has worsened.
Corporate interests have also captured policy-making processes to their
own advantage. Recent analysis of the influence of corporate interests on
nearly 2,000 specific policy debates in the USA over 20 years concluded that
‘economic elites and organized groups representing business interests have
substantial independent impacts on US government policy, while mass-based
interest groups and average citizens have little or no independent influence’.286
Financial institutions spend more than €120m per year influencing the
European Union.287
60
SECTION 1 2 3 EXTREME INEQUALITY
T HE POLITICS OF LAND
CASE STUDY DISTRIBUTION IN PARAGUAY
Ceferina Guerrero at her home in Repatriación,
Caaguazú (2013).
Photo: Amadeo Velazquez/Oxfam
Paraguay has a long history of inequality, perpetuated by decades of
cronyism and corruption.288 Large-scale landowners control 80 percent
of agricultural land.289 Every year, 9,000 rural families are evicted from
their land to make room for soy production; many are forced to move
to city slums having lost their means of making a living.290
In 2008, after years of political instability, Fernando Lugo was elected
president as a champion for the poor, promising to redistribute land more
fairly. But, in June 2012, after 11 farm workers and six police officers
were killed during an operation to evict squatters from public land being
claimed as private property by a powerful land-owner (and opponent
of Lugo), he was ousted in a coup and replaced by one of the country’s
richest men, tobacco magnate Horacio Cartes.
Today, Paraguay is the quintessential example of skewed economic
development and political capture by elites, leading to incredible levels
of inequality. In 2010 it had one of the fastest growing economies in the
world, thanks to a massive rise in global demand for soy for biofuels
and cattle feed in wealthier nations,291 but one in three people still
lives below the poverty line and inequality is increasing.292
Ceferina is a 63 year-old grandmother, living in the Caaguazú district in
central Paraguay. She has a relatively small plot of five hectares, which
she has been refusing to sell to a big soy company.
‘I have no alternative but to stay here, even though business gets harder
every day. In this area there are now towns where nothing is left but
soybean crops. Everyone has left, they are ghost towns. It is a lie that
these big plantations create job opportunities. They buy modern farm
machinery that does everything, so they only need one person to drive a
tractor to farm 100 hectares. Who is that providing jobs for? Many people
have moved to city suburbs and they are living in misery, on the streets.
These people are famers, like us, who sold their land and left, hoping to
find a better life in the city. Selling our land is no solution. We need land,
we need fair prices and we need more and better resources.’
61
SECTION 1 2 3 EXTREME INEQUALITY
Elite capture is also capture by men
The capture of political processes by elites can also be seen as the capture
of these processes by men. It contributes to policies and practices that are
harmful to women or that fail to help level the playing field between men
and women. As a result, women are also largely excluded from economic
policy making.
Despite significant progress since 2000, as of January 2014, only nine women
were serving as a head of state and only 15 as the head of a government; only
17 percent of government ministers worldwide were women, with the majority
of those overseeing social sectors, such as education and the family (rather
than finance or economics).293 Women held only 22 percent of parliamentary
seats globally.294
Women’s leadership is critical to ensuring that economic and social policies
promote gender equality. The concentration of income and wealth in the hands
of wealthy elites, the majority of whom are men, gives men more decision-
making power at national level, and contributes to national laws failing to
help level the playing field for women. Around the world there is a legacy of
discriminatory laws and practices that compound gender discrimination; for
instance on inheritance rights, lending practices, access to credit and asset
ownership for women.
CORRUPTION HITS THE POOREST HARDEST
When elites capture state resources to enrich themselves it is at the
expense of the poorest. Large-scale corruption defrauds governments
of billions in revenue and billions more through the inefficiencies of
‘crony contracting’.
At the same time, poor people are hit hardest by petty corruption, which
acts as a de facto privatization of public services that should be free.
One study found that in rural Pakistan the extremely poor had to pay
bribes to officials 20 percent of the time, whereas for the non-poor this
figure was just 4.3 percent.295
Elites shape dominant ideas and public debate
Around the world elites have long used their money, power and influence
to shape the beliefs and perceptions that hold sway in societies, and have
wielded this power to oppose measures that would reduce inequality.
Elites use this influence to promote ideas and norms that support the economic
and political interests of the privileged; such as through the promotion of ideas
like ‘the majority of rich people have secured their wealth through hard work’, or
‘strong labour rights and taxation of bankers’ bonuses will irreparably harm the
economy’. Language is cleverly deployed in Orwellian ways, with inheritance
tax rebranded as the ‘death tax’, and the rich becoming ‘wealth creators’.296 As
a result, across much of the world there is a considerable misperception of the
scope and scale of inequality and its causes. In the majority of countries, the
media is also controlled by a very small, male, economic elite.
62
SECTION 1 2 3 EXTREME INEQUALITY
One study of academic economists in the USA found extensive and largely
undisclosed links to the financial sector among them, and a very strong
correlation between these ties and intellectual positions that actively
absolved the financial sector of responsibility for the financial crisis.297 These
economists have often appeared in the mainstream media as independent
‘experts’. Meanwhile, the share of the world’s population enjoying a free press
remains stuck at around 14 percent. Only one in seven people lives in a country
where political news coverage is robust, independent and where intrusion by
the state into media is limited.298
Elites also use their considerable power to actively stop the spread of ideas
which go against their interests. Recent examples of this include governments,
driven by elites, clamping down on the use of social media. The Turkish
government attempted to prevent access to Twitter following mass protests,
and Russia has implemented a law that equates popular bloggers with
media outlets, thus requiring them to abide by media laws which restrict
their output.299
THE PEOPLE ARE LEFT BEHIND
The capture of politics by elites undermines democracy by denying an equal
voice to those outside of these groups. This undermines the ability of the
majority to exercise their rights, and prevents poor and marginalized groups
from escaping from poverty and vulnerability.300 Economic inequality produces
increased political inequality, and the people are being left behind.
Since 2011, the divide between elites and the rest of society has sparked mass
protests throughout the world – from the USA to the Middle East, and from
emerging economies (including Russia, Brazil, Turkey and Thailand) to Europe
(even Sweden). The majority of the hundreds of thousands who took to the
streets were middle-class citizens who saw that their governments were not
responding to their demands or acting in their interests.301
Unfortunately, in many places, rather than putting citizens’ rights back at the
heart of policy-making and curbing the influence of the few, many governments
responded with legal and extra-legal restrictions on the rights of ordinary
citizens to hold governments and institutions to account. Governments in
countries as diverse as Russia, Nicaragua, Iran and Zimbabwe, have launched
concerted campaigns of harassment against civil society organizations, in an
effort to clamp down on citizens who seek to voice their outrage at the capture
of political and economic power by the few.302
63
SECTION 1 2 3 EXTREME INEQUALITY
BUSTING THE
INEQUALITY MYTHS
Those who say that extreme inequality is not a problem,
or that it is the natural order of things, often base their
arguments on a number of myths.
MYTH 1
Extreme inequality is as old as humanity, has always been with us,
and always will be.
The significant variations in levels of inequality over time and between different
countries demonstrates that levels of inequality are dependent on a number
of external factors, such as government policies, rather than simply being
the natural order of things.
The 20th century provides numerous examples of how inequality can be
significantly reduced and how it can radically increase within the span of
just one generation. In 1925, income inequality in Sweden was comparable
with contemporary Turkey. But, thanks to the creation of the Swedish welfare
state, which, among other things, included provisions for universal free
access to healthcare and universal public pensions, by 1958 inequality in
Sweden had reduced by almost half and continued to decrease for the next
20 years.303 The experience of Russia mirrors that of Sweden. At the end of the
1980s, levels of inequality in Russia were comparable with its Scandinavian
neighbours. However, since the beginning of the transition to a market
economy in 1991, inequality has almost doubled.304
In more recent years, countries in Latin America have significantly reduced
inequality. Between 2002 and 2011, income inequality dropped in 14 of the 17
countries where there is comparable data.305 During this period, approximately
50 million people moved into the emerging middle class, meaning that, for
the first time ever, more people in the region belong to the middle class
than are living in poverty.306 This is the result of years of pressure from
people’s movements that have campaigned for more progressive social
and economic policies. The governments that the people have elected
have chosen progressive policies, including increased spending on public
health and education, a widening of pension entitlements, social protection,
progressive taxation and increases in employment opportunities and the
minimum wage. Latin America’s experience shows that policy interventions
can have a significant impact on income inequality.
There is also a strong body of evidence which shows that extreme inequality
has been rising in every other region of the world over the past three decades,
which is why the negative consequences must be taken seriously, now more
than ever.307
64
SECTION 1 2 3 EXTREME INEQUALITY
MYTH 2
Rich people are wealthier because they deserve it and work harder
than others.
This myth assumes that everyone starts from a level playing field and that
anyone can become wealthy if they work hard enough. The reality is that,
in many countries, a person’s future wealth and income is largely determined
by the income of their parents. A third of the world’s richest individuals
amassed their wealth not through hard work, but through inheritance.308
This myth is also flawed in its assumption that the highest financial reward is
given for the hardest amount of work. Some of the lowest paid jobs are those
that require people to work the hardest, while some of the highest paid jobs
are those that require people to work the least. Many of the richest collect large
profits from the rent they generate on stocks, real estate and other assets.
When this is taken into account, it becomes clear that those who are paid less
work just as hard (or even harder) as those at the top of the wage ladder.309
Women spend more time on unpaid domestic and caring responsibilities
than their highly paid counterparts, and are more likely than men to have
multiple jobs.310
MYTH 3
Inequality is necessary to reward those who do well.
Incentivizing innovation and entrepreneurship through financial reward will
always lead to some levels of inequality, and this can be a good thing. However,
extreme inequality and extremes of potential reward are not necessary to
provide this incentive. It would be absurd to believe that a company CEO who
earns 200 times more than the average worker in the company is 200 times
more productive or creates 200 times more value for society. The success of
alternative business models such as cooperatives, which have greater income
equality at their core, also disproves this myth.
65
SECTION 1 2 3 EXTREME INEQUALITY
MYTH 4
The politics of inequality is little more than the politics of envy.
High levels of inequality have negative consequences for everyone in society:
the haves as well as the have-nots. As demonstrated in this report, societies
with higher levels of economic inequality have overall higher crime rates, lower
life expectancy, higher levels of infant mortality, worse health and lower levels
of trust.311 Extreme inequality also concentrates power in the hands of a few,
posing a threat to democracy,312 and hinders economic growth and poverty
reduction. It is not envy, but a preoccupation with the well-being of the whole
of society that drives those who campaign against inequality.
MYTH 5
There is a trade-off between growth and reducing inequality,
especially through redistribution.
It has long been a central tenet of economics that there is an unavoidable
trade-off between strong growth and enacting measures to reduce inequality,
especially through taxing and redistributing from the rich to the poor. However,
recently there have been a growing number of studies showing that the
opposite appears to be the case. In fact, high and growing inequality is actually
bad for growth – meaning lower growth rates and less sustained growth.
A recent high-profile, multi-decade, cross-country analysis by IMF economists
showed that lower inequality is associated with faster and more durable
growth, and that redistribution does not have a negative impact on growth,
except in extreme cases.313 By mitigating inequality, redistribution is actually
good for growth.
MYTH 6
Rising inequality is the inevitable and unfortunate impact of
technological progress and globalization, so there is little that
can be done about it.
This myth is based on the idea that a combination of globalization and
technological progress inevitably leads to increased inequality. However, it is
based on a set of assumptions that do not tell the whole story. Namely that
globalization and new technologies reward the highly educated and drive up
wages for the most skilled who are in demand in a global market; that this
same technological progress means many low-skilled jobs are now done by
66
SECTION 1 2 3 EXTREME INEQUALITY
machines; and that technology and an increasingly globalized market have also
enabled companies to shift a lot of low-skilled work to developing countries,
further eroding the wages of lower-skilled workers in developed countries.
The myth is that all of this drives a relentless and unavoidable increase
in inequality.
However, if this myth were true there would be little difference in the
development of job markets in individual countries. In fact, while Germany has,
to a large extent, resisted the mass export of jobs and the explosion in wealth
and high salaries at the top, countries like the USA and UK have seen high-
levels of erosion among mid-level jobs and huge concentrations of wealth.
Similarly, Brazil has managed to benefit from globalization while reducing
economic inequality, whereas other countries, such as India, have seen
big increases in inequality.
So, while technological change, education and globalization are important
factors in the inequality story, the main explanation lies elsewhere, in
deliberate policy choices, such as reducing the minimum wage, lowering
taxation for the wealthy and suppressing unions. These are, in turn, based
on economic policy and political ideology, not on inevitable and supposedly
elemental economic forces.
MYTH 7
Extreme economic inequality is not the problem, extreme poverty is
the problem. There is no need to focus on inequality and the growth
in wealth for a few at the top, as long as poverty is being reduced for
those at the bottom.
This is a widely held view, that the focus of development should be confined to
lifting up those at the bottom, and that any focus on the growing wealth at the
top is a distraction.
Extreme economic inequality not only slows the pace of poverty reduction,
it can reverse it.314 It is not possible to end poverty without focusing first on
extreme economic inequality and the redistribution of wealth from those at the
top to those at the bottom. On a planet with increasingly scarce resources, it is
also not sustainable to have so much wealth in the hands of so few.315 For the
good of the whole world we must focus our efforts on the scourge of extreme
economic inequality.
67
Amir Nasser, 12, Jamam refugee camp, Upper Nile, South Sudan (2012).
Photo: John Ferguson
2
WHAT CAN
BE DONE
To end extreme inequality
SECTION 1 2 3 WHAT CAN BE DONE
THE HIGH ROAD OR THE LOW ROAD
Inequality is not inevitable, but the result of policy choices. In this section, we
explore some of the deliberate policy choices that have been and are currently
being taken by governments that have affected inequality.
“
The choice which governments face, to move towards or away from inequality,
is illustrated first by two fictional articles, each of which describes a potential
Without deliberate
future for Ghana as the Economist magazine may describe it in 2040.
policy interventions, high
levels of inequality tend
The report then focuses on four key areas where strong policy action can help
to be self-perpetuating.
to tackle inequality: work and wages, taxation, public services, and economic
They lead to the
policies that can specifically tackle gender inequality.
development of political
and economic institutions
The section finishes by looking at the kind of progressive political change that
that work to maintain
is necessary to ensure that governments break the stranglehold of special
the political, economic and
interests, and act in favour of the majority of citizens and of society as a whole.
social privileges of the elite.
Action can be taken to reverse the trends that are fuelling today’s yawning UNRISD316
gap between rich and poor, the powerless and the powerful. The world needs
“
concerted action to build a fairer economic and political system that values
the many over the few. The rules and systems that have led to today’s extreme
economic inequality must change, with action taken to level the playing field
by implementing policies that redistribute both wealth and power.
69
SECTION 1 2 3 WHAT CAN BE DONE
2.1
A TALE OF TWO FUTURES
The Economist 1 April 2040
The government followed this with the introduction of
progressive direct taxation – taxing the richest to pave the
GHANA: way for the end of the oil period and to rebuild the ‘social
contract’ between government and governed.
MELTDOWN TO MIRACLE
The APC used this new income for a classic exercise in
nation-building, helped by the return of many highly skilled
T
Ghanaians who flocked home from the capitals of Europe
he world’s top egalitarians arrived in Accra this
and North America. By 2017, the country had achieved
week for the inaugural meeting of the Progressive
universal health coverage and primary and secondary
20 (P20) countries. Ghana, which has been instrumental
education. It invested in an army of nurses, doctors and
in establishing the new group, is keen to show off its
generic medicines that today make the Ghanaian National
impressive credentials on redistribution and development.
Health Service the envy of the world. They moved swiftly
Many of the visitors will linger for a few days of tourism,
on to upgrade the quality of education, pioneering some of
not least because of Ghana’s largely crime-free streets.
Africa’s most successful vocational and technical training,
and building some of the continent’s best universities.
Leaders convening today will look back to the 2015 ‘oil
curse crisis’, when a power grab for the nation’s newly
Oil money paid for roads and hydroelectric dams, allowing
discovered hydrocarbon reserves threatened to tear the
Ghana to avoid risky ‘public–private partnerships’, which
country apart. They will start by commemorating those
decades on are still draining national budgets across the
who died or were injured in the 2015 riots that triggered
rest of Africa.
the country’s New Deal.
Ghana is particularly proud of its pioneering ‘Fair Living
Hundreds died in that conflict, spurring politicians and
Wage’ policy, which tied the minimum wage to average
ethnic leaders, marshalled by the legendary Daavi Akosua
wages, and then ratcheted up the pressure on inequality
Mbawini (dubbed by many as ‘Ghana’s Gandhi’), to draw
by moving the minimum from an initial 10 percent of the
back from the brink. The 2016 elections that followed
average to an eventual 50 percent. The Fair Living Wage
saw the cross-party Alliance of Progressive Citizens (APC)
has since become one of the membership criteria for
take power, backed by a multi-ethnic coalition of Ghana’s
the P20. Other positive steps delivered huge benefits
vibrant people’s organizations. The APC promptly embarked
for women, not least Ghana’s Equal Pay Act.
on what has become a textbook case in development.
The APC also made ‘getting the politics right’ an explicit
Advised by Norway and Bolivia, the new government
priority. Temporary affirmative action campaigns rebooted
negotiated a sizeable increase in oil and gas royalties,
Ghana’s political system, filling parliament and the civil
and introduced an open, competitive tender process for
service with the best and brightest among women and
exploration and drilling. But it did not stop there. Learning
ethnic minority groups. Citizens and their organizations
from the experiences of other oil booms, Ghana put 40
were involved from the beginning (for example in the
percent of oil revenues into a heritage fund, so that future
recent ‘Be a Responsible Citizen, Pay your Tax’ campaign
generations could share in the benefits of the windfall
that rejuvenated Ghana’s tax base).
(production is already falling from its 2030 peak). Proceeds
from the government’s famous victory over Swiss tax
Now a retired elder stateswoman, Daavi Akosua Mbawini
havens at the International Court of Justice also swelled
says her country has gone from ‘meltdown to miracle in
the fund’s coffers.
one generation’. For once, the political rhetoric is justified.
70
SECTION 1 2 3 WHAT CAN BE DONE
BURKINA FASO
BENIN
The Economist 1 April 2040
GHANA: GHANA
OPEN FOR BUSINESS?
CÔTE D'IVOIRE
GHANA TOGO
R epresentatives from the world’s biggest multinationals
are headed to Ghana this week for the country’s annual
trade fair, ‘Ghana: Open for Business’. Ghana’s business
Lake
Volta
class can take credit for creating favourable conditions
for foreign investment to flourish in the country, which
has enjoyed solid growth rates in recent years. Foreign
companies that invest in the country are offered tax-free
status and access to the world’s cheapest labour force.
With no minimum wage in Ghana, most workers earn Accra
on average $0.50 per hour.
Trade fair attendees will land at the new state-of-the-
art jet port on the Elysium-style island in the middle of The governing elite were swift to spot an opportunity and
Lake Volta that is home to the ten families who own 99 in no time had sold off the country’s newly discovered
percent of the country’s wealth. Crocodile-infested waters resources to the highest foreign bidder, personally
surrounding the island should preclude any protests by collecting a royalty dividend for their efforts. As trade
the millions living in destitution on the mainland. It is hard unions and social movements mobilized to call for a fairer
to credit that Ghana was once seen as the great hope distribution of the natural resource bounty, the political
of West Africa, a country that combined a dynamic and elite moved just as swiftly to criminalize public protest
sustainable economy with an impressively stable and and collective organizing. Hundreds died in the riots
democratic political system. All that fell apart under the that followed, leading the government to suspend the
influence of the ‘curse of wealth’, in the shape of oil and constitution and install an ‘interim’ presidency.
gas finds in the early years of the 21st century.
Ghanaians still lament the assassination of Daavi Akosua
Mbawini (dubbed ‘Ghana’s Gandhi’) as she was building
a cross-party movement, the now mostly forgotten
‘Alliance of Progressive Citizens’.
Those who can afford it
buy their drinking water from For those on the mainland, electricity comes on for a few
hours a day at best. People are afraid to leave their homes,
tankers; the rest have no even in daylight hours, for fear of assault. Health and
option but to use polluted education are a privatized, disintegrated, fee-charging
mess, to which poor Ghanaians have little access. Those
rivers and wells. Little wonder who can afford it buy their drinking water from tankers;
that cholera outbreaks are a the rest have no option but to use polluted rivers and
wells. Little wonder that cholera outbreaks are a regular
regular occurrence and infant occurrence and infant mortality is among the highest
mortality is among the in the region. Farmers in many areas have reverted to
subsistence agriculture, as tapping into more lucrative
highest in the region. markets is now impossible.
Small wonder then that foreign investors arriving into Volta
will not set foot on the mainland, and their presence will
go unnoticed by the vast majority of Ghanaians.
71
SECTION 1 2 3 WHAT CAN BE DONE
Businessmen pass an official union demonstration against
low wages and lack of benefits for cleaners in the City.
London, UK (2007). Photo: Panos/Mark Henley
2.2
WORKING OUR WAY TO
A MORE EQUAL WORLD
Income from work determines most people’s economic
status.317 The reality for many of the world’s poorest people
is that no matter how hard they work they cannot escape
poverty, while those who are already rich continue to see
their wealth grow at an ever-increasing rate, exacerbating
market inequalities.
72
SECTION 1 2 3 WHAT CAN BE DONE
In South Africa, a platinum miner would need to work for 93 years just to earn
their average CEO’s annual bonus.318 In 2014, the UK top 100 executives took <
home 131 times as much as their average employee;319 only 15 of these
It would take a
companies have committed to pay their employees a living wage.320
South African miner
Today’s combination of indecently low wages for the majority and scandalously
high rewards for top executives and shareholders is a recipe for accelerating
economic inequality.
93 years
to earn their average CEO’s
annual bonus
Labour’s declining share of income
>
FIGURE 9: Share of labour income in GDP for world and country groups321
70
65
60
Percentage
55
50
45
40
90
92
94
96
98
00
02
04
06
08
10
12
19
20
19
19
19
20
20
20
20
19
20
20
World G20 High Income
G20 Middle and Lower-middle Income Groups not in G20
Since 1990, income from labour has made up a declining share of GDP across all
countries, low-, middle- and high-income alike, while more has gone to capital,
fuelling growing material inequalities between the haves and the have-nots.
According to the International Labour Organization (ILO), policies that
redistribute income in favour of labour, such as increases in the minimum
wage, would bring significant improvements in aggregate demand and growth,
while also reducing poverty and inequality.322
73
SECTION 1 2 3 WHAT CAN BE DONE
THE LOW ROAD: WORKING TO STAND STILL
ALAWI TEA PLUCKERS:
M
CASE STUDY IN WORK AND IN EXTREME POVERTY
Tea picking in Mulanje, Southern Malawi (2009).
Photo: Abbie Trayler-Smith
Mount Mulanje is home to Malawi’s 128 year-old tea industry, which
employs more than 50,000 workers in the rainy season. Maria, 32,
has plucked tea on the green, seemingly endless hills for over seven
years. She and her fellow tea pluckers are the face of in-work
extreme poverty.
Maria is fortunate that she lives in housing provided by a plantation
and has recently been put on a long-term contract; but almost three-
quarters of workers have neither of these things.323 The difficulties
workers face are exacerbated by the fact that most have no land
of their own and cannot supplement their income or food intake
through farming.
The work is hard and Maria must pick a minimum of 44 kilograms of
tea every day to earn her daily cash wage. This wage still sits below
the $1.25 a day World Bank Extreme Poverty Line at household level,324
and she struggles to feed her two children with it, both of whom are
malnourished. According to a recent living wage estimation, Maria would
need to earn around twice her existing wage just to meet her basic
needs and those of her family.325
But things are starting to change. In January 2014, the Malawian
government raised the minimum wage by approximately 24 percent.
A coalition, led by Ethical Tea Partnership and Oxfam, is seeking new
ways to make decent work sustainable in the longer term.326
Government regulation and the right of workers to collectively bargain with
employers can help to tackle inequality and increase wages for ordinary
workers. However, in recent decades, in the context of weakened labour laws,
the repression of unions, and the ability of industries to relocate to where
74
SECTION 1 2 3 WHAT CAN BE DONE
wages are low and workers are passive, companies have been free to choose
poverty wages and poor labour conditions for their workers.
According to the International Trade Union Confederation, more than 50 percent
of workers are in vulnerable or precarious work, with 40 percent trapped in an
informal sector where there are no minimum wages and no rights.327 In today’s
global economy many sectors are organized into global value chains, including
industrial manufacturing, such as clothing and electronics, and agricultural
trade in commodities like sugar and coffee. Within these, multinational
companies (MNCs) control complex networks of suppliers around the world.
They reap enormous profits by employing workers in developing countries,
few of whom ever see the rewards of their work.
The prevalence of ‘low road’ jobs in profitable supply chains has been
confirmed by three recent Oxfam studies of wages and working conditions.
The studies found that poverty wages and insecure jobs were prevalent
in Vietnam and Kenya, both middle-income countries, and wages were
below the poverty line in India and below the extreme poverty line in Malawi,
despite being within national laws.328
A separate set of three studies of wages in food supply chains in South Africa,
Malawi and the Dominican Republic, commissioned by six ISEAL members, found
that minimum wages in the relevant sectors were between 37 to 73 percent of
an estimated living wage – not nearly enough for food, clothing, housing and
some discretionary spending.329
FIGURE 10: Minimum wages as a percentage of estimated living
wages (monthly)330
100
Minimum wages as a percentage of
estimated living wages (monthly)
80
72.9
60
40.2 36.5
40
20
0
South Africa Dominican Republic Malawi Tea
Grape Sector Banana Sector Sector
Some argue that low worker wages are a result of consumer demand for low
prices. But numerous studies have shown that even significant wage increases
for workers of apparel products, for example, would barely alter retail prices.331
Oxfam’s own study found that doubling the wages of workers in the Kenyan
flower industry would add just five pence to a £4 ($6.50) bouquet in UK shops.
75
SECTION 1 2 3 WHAT CAN BE DONE
The median income of a UK supermarket CEO – in whose shops Kenyan flowers
are sold – more than quadrupled from £1m to over £4.2m between 1999 and
2010.332 If executive reward can be factored into business models, why not
a living wage for the workers on whom their reward depends?
Women are on a lower road than men for work and wages. In Honduras, for
example, women predominate in sectors where labour law is unenforced and
there is no social security. They earn less than men, despite working longer
hours. The average woman’s wage covers only a quarter of the cost of a basic
food basket in rural areas. Their economic dependence on their partners,
coupled with the discrimination they face in wider society, can also lock them
into abusive relationships in the home, as well as harassment in the workplace.
OVERTY WAGES IN THE RICHEST
P
CASE STUDY COUNTRY IN THE WORLD
Detroit, Michigan (2008).
Photo: Panos/Christian Burkert
Low wages and insecure work is not a story confined to developing
countries. Three of the six most common occupations in the USA –
cashiers, food preparers and waiters/waitresses – pay poverty wages.
The average age of these workers is 35 and many support families.
Forty-three percent have some college education, and many hold
a four-year degree.333
In a recent survey, half of those questioned told Oxfam that they had had
to borrow money to survive, while only a quarter receive sick leave, paid
holidays, health insurance or a pension. They live in one of the richest
countries in the world, but carry a burden similar to that of workers in the
poorest of countries.
76
SECTION 1 2 3 WHAT CAN BE DONE
(CASE STUDY CONTINUED)
Dwayne works in a fast food restaurant in Chicago. His wages have
to provide for two daughters, as well as his siblings, his mother and his
grandmother. ‘I’m the sole provider of the household and can’t manage
with an $8.25/hour wage ... given how hard we are worked, fast food
workers deserve to show something for it.’334
The rise in inequality in the USA has happened in parallel with the
decline in the real value of the minimum wage and the decline in union
membership.335 The incomes of the bottom 90 percent of workers
have barely risen, while the average income of the top one percent
has soared.336
The erosion of bargaining power
Unions represent an important counterweight to top executives and
shareholders whose imperative is largely to maximize profit. Their negotiating
power helps ensure prosperity is shared; collective bargaining by unions
typically raises members’ wages by 20 percent and drives up market wages for
everyone.337 Trade unions also play a crucial role in protecting public services.
In South Korea, for instance, public sector health unions held a strike and
protest rallies in June 2014 after the government announced deregulation
and privatization of health services.
Many developing countries lack a history of strong unions, and in many
places workers are facing a crackdown on their right to organize, which has
contributed to falling union membership. In Bangladesh’s garment industry,
where 80 percent of workers are women, union membership stands at one
in 12.338 According to an analysis of the Rana Plaza disaster, Bangladesh
factory owners have ‘outsize influence in the country’s politics, hindering
the establishment and enforcement of labour law’.339
In South Korea, public sector workers face deregistration of unions, unlawful
arrests and anti-strike action. In 2014, Yeom Ho-seok, a Korean employee of
a company making repairs to Samsung phones and founder of the Samsung
Service Union, committed suicide following a period of financial hardship. After
founding the Samsung Service Union, Yeom’s work was reported to have been
reduced by his employer; his take home wage fell to just $400 a month.340
The right to organize has been enshrined in ILO conventions, but since 2012
the official group representing employers (the Employers Group) has contended
that this does not include the right to strike. In 2014 this conflict was referred
to the ILO’s governing body. Striking is the last resort of workers to bargain
with their employees for a fair deal, and revoking it would be a huge blow
to workers’ rights.
77
SECTION 1 2 3 WHAT CAN BE DONE
THE HIGH ROAD: ANOTHER WAY IS POSSIBLE
Turning the tide on poverty wages
Some countries are bucking the trend in the race to the bottom on wages,
decent work and labour rights.
Brazil’s minimum wage rose by nearly 50 percent in real terms between 1995
and 2011, in parallel with a decline in poverty and inequality (Figure 11).
FIGURE 11: Inequality levels in Brazil during the period in which the minimum
wage rose by 50 percent341
0.62
Income inequality (as Gini coefficient)
0.6
0.58
0.56
0.54
0.52
0.5
0.48
95
96
97
98
99
00
01
02
03
04
05
06
07
08
09
10
11
19
19
19
19
20
19
20
20
20
20
20
20
20
20
20
20
20
Income inequality (as Gini coefficient)
Since taking office in 2007, the Ecuadorean government, led by Rafael Correa,
has pursued a policy of increasing the national minimum wage faster than
the cost of living.342 Ecuador joined the World Banana Forum to improve
conditions in this key export industry.343 Profitable companies were already
required by law to share a proportion of profits with their employees, but new
regulations also required them to demonstrate that they pay a living wage;
that is a wage ‘covering at least the basic needs of the worker and their family
and corresponds to the cost of the basic family basket of goods divided by
the (average number) of wage earners per household.’344 A decade ago, many
workers earned less than half this amount.
In China, where the government has followed a deliberate strategy of raising
wages since the 2008 recession, spending by workers is forecast to double
over the next four years to £3.5tn, increasing demand for imported and locally
made goods alike.345
78
SECTION 1 2 3 WHAT CAN BE DONE
Some MNCs have taken voluntary steps towards improving the lot of their
workers. Unilever, International Procurement and Logistics (IPL) and the Ethical
“
Tea Partnership have acknowledged the labour issues identified by Oxfam in
recent joint studies and are implementing plans to address them.346 H&M has
It is clear that good jobs
published a ‘road map to a living wage’, starting with three factories in
help families and societies
Bangladesh and Cambodia, which produce 100 percent for the company.347
to progress more quickly.
In the UK, 800 companies have been accredited as living wage employers,
Our experience at Tesco is
including Nestlé, KPMG and HSBC.348 In another hopeful sign, Bangladesh’s
that this also makes sense
Accord on Fire and Building Safety now has more than 180 corporate members,
from a business perspective;
and has brought brands, industry, government and trade unions around the
the best supplier partners
same table for meaningful dialogue on worker organizing in factories,
for the long-term are
as well as on getting to grips with safety standards.
those that invest in their
people: they tend to be
the most productive, most
‘ H IGHER ROAD’ EMPLOYERS THAT reliable and make the best
CASE STUDY POINT THE WAY quality products.
GILES BOLTON
In the Dominican Republic, the US company Knights Apparel established
GROUP DIRECTOR, RESPONSIBLE
a living wage factory to supply ethical clothing to the student market.350
SOURCING, TESCO PLC,
Maritza Vargas, president of the Altagracia Project Union, describes the
AUGUST 2014349
impact that having a living wage had on her life:
‘I can now access nutritious food and I never have to worry that I can’t
feed my family. I have been able to send my daughter to university and
keep my son in high school – this was always my dream … We now
“
find we are treated with respect in the workplace – this is completely
different to our experience in the other factory.’
There have been benefits for local shops and trades people too, as
a result of workers’ increased spending power. This change came about
due to pressure from consumers and, while an encouraging example,
it is unfortunately not typical of the companies which work in the
Dominican Republic.351
Kenya’s cut flower sector was the target of civil society campaigns in the
2000s. Since then the workers who process these high-value, delicate
products have seen real improvements in some areas. Their wages are
still far from being a living wage,352 but the most skilled workers, 75
percent of whom are women, report improvements in health and safety,
a reduction in sexual harassment and more secure contracts compared
with 10 years ago. A majority of workers surveyed for the report agreed
that ‘it is easier to progress from temporary to permanent employment
than when I started work.’353
Factors aiding this include the implementation of codes, such as the
Ethical Trading Initiative Base Code, product certification (Kenya Flower
Council, Fairtrade), more professional human resource management,
the establishment of gender committees and improved legislation.354
In neighbouring Uganda, conditions in the industry have improved
even more (though from a lower base), helped by greater worker
organization.355
79
SECTION 1 2 3 WHAT CAN BE DONE
Despite the knee-jerk claims of some employers, increases in the minimum
wage have had little or no negative macro-level effect on the employment of
minimum-wage workers.356 Goldman Sachs economists found that increases
in the minimum wage are unlikely to result in significant job losses because of
the resulting increase in consumer demand.357 Wage increases offer benefits
to business as well; for instance, they often lead to lower worker turnover,
which can constitute a significant cost.358
Ending excessive pay at the top
If a key cause of the widening wealth gap is labour’s declining share of
national income, an obvious solution is a more equitable sharing of wealth
within companies.
The idea of restricting income at the top is not a new one. Plato recommended
that the incomes of the wealthiest Athenians should be limited to five times
those of its poorest residents. And since the 2008 financial crisis, MNCs
have faced increasing public pressure to forgo executive bonuses and
cap top incomes.
Some forward-looking companies, cooperatives and governance bodies
are taking action. Brazil’s SEMCO SA, for instance, employs more than 3,000
workers across a range of industries and adheres to a wage ratio of 10 to 1.359
Germany’s Corporate Governance Commission proposed capping executive pay
for all German publicly traded companies, admitting that public outrage against
excessive executive pay ‘has not been without influence’. Two US states –
California and Rhode Island – have suggested linking state corporate tax rates
to the CEO-worker pay ratio – the higher the pay gap, the higher the tax rate.360
Shared interest: Giving workers a stake
A growing body of evidence shows that companies owned at least in part
by employees tend to survive longer and perform better. In the UK, they
consistently outperform the FTSE All-Share index.361 When employees are
given a say in governance, as well as share ownership, the benefits appear
to be even greater.362
Employee-owned firms have been found to have higher levels of productivity;
they demonstrate greater economic resilience during turbulent times,
are more innovative, enhance employee wellbeing, have lower rates of
absenteeism, create jobs at a faster rate, improve employee retention, and
also demonstrate high levels of communication and employee engagement.363
And ‘unlike changes in tax policy (which can be reversed), employee ownership
is long-term and sustainable.’364 It is a powerful and practical idea for a more
inclusive capitalism.
Productive work will only be part of the solution to out-of-control inequality
if decent jobs pay living wages and workers’ rights are upheld and enforced
by governments. Voluntary action by employers alone is not enough.
80
SECTION 1 2 3 WHAT CAN BE DONE
Hamida Cyimana, 6 years old, does sums on a
blackboard, Kigali, Rwanda (2012).
Photo: Simon Rawles/Oxfam
2.3
TAXING AND INVESTING TO
LEVEL THE PLAYING FIELD
The tax system is one of the most important tools
a government has at its disposal to address inequality.
81
SECTION 1 2 3 WHAT CAN BE DONE
Data from 40 countries shows the potential of well-designed redistributive
taxation and corresponding investment by governments to reduce income
inequality driven by market conditions.365 Finland and Austria, for instance,
have halved income inequality thanks to progressive and effective taxation
accompanied by wise social spending.
FIGURE 12: Gini coefficient (income) before and after taxes and transfers
in OECD and Latin American and the Caribbean (LAC) countries (2010)366
Percentage variation Before taxes and transfers After taxes and transfers
Peru
Bolivia
Mexico
South Korea
LAC average
Brazil
Argentina
Uruguay
Switzerland
USA
Israel
Canada
New Zealand
Australia
The Netherlands
Spain
Japan
Estonia
Poland
Portugal
UK
Italy
OECD average
Greece
France
Iceland
Sweden
Luxemburg
Norway
Slovakia
Germany
Denmark
Ireland
Czech Republic
Austria
Belgium
Slovenia
Finland
-60 -40 -20 0 0 20 40 60
Reduction in inequality (%) Gini coefficient before and after taxes and transfers
Badly designed tax systems, on the other hand, exacerbate inequality. When
the most prosperous enjoy low rates and exemptions and can take advantage
of tax loopholes, and when the ri chest can hide their money in overseas tax
havens, huge holes are left in national budgets that must be filled by the rest
of us, redistributing wealth upwards.
82
SECTION 1 2 3 WHAT CAN BE DONE
International tax experts, and standard-setters like the OECD and IMF,
acknowledge the damage caused by exemptions, loopholes and tax
havens,367 but their commitment to solutions does not match the scale
of the problem. Powerful corporations and national and global elites have
connived to make international and national tax systems increasingly unfair,
thus worsening inequality.
THE LOW ROAD: THE GREAT TAX FAILURE
“
All countries, whether rich or poor, are united in their need for tax revenue to
fund the services, infrastructure and ‘public goods’ that benefit all of society.
There are no politicians who
But tax systems in developing economies – where public spending and
speak for us. This is not just
redistribution are particularly crucial to lift people out of poverty – tend to be
about bus fares any more.
the most regressive, often penalizing the poor.368 The poorest 20 percent of
We pay high taxes and we are
Nicaraguans pay 31 percent of their income in tax, while the richest 20 percent
a rich country, but we can’t
contribute less than 13 percent.369 Indirect taxes like the Value Added Tax (VAT),
see this in our schools,
that fall disproportionately on the poor make up, on average, 43 percent of
hospitals and roads.
total tax revenues in the Middle East and North Africa, and up to 67 percent
in sub‑Saharan Africa.370 JAMAIME SCHMITT
BRAZILIAN PROTESTOR371
CASE STUDY
T HE UNEQUAL TAX BURDEN IN THE
DOMINICAN REPUBLIC “
Bernarda Paniagua Santana in front of
her business in Villa Eloisa de las Cañitas,
Dominican Republic (2014).
Photo: Pablo Tosco/Oxfam
Bernarda Paniagua sells cheeses and other products in Villa Eloisa
de las Cañitas, one of the poorest and most under-served areas of
the Dominican Republic. Victor Rojas is the manager of a prestigious
company; he lives in one of the wealthiest areas of the country. Bernarda
pays a higher proportion of her income in indirect taxes than Victor. In fact,
the majority of the country’s tax revenue comes from consumption taxes,
rather than income tax. Consumption taxes affect the poorest most as
they spend a higher percentage of their income on consumption.
Children in Victor’s neighbourhood lack for nothing: they receive the best
education on offer and have a doctor visiting the house at the first sign of
a fever.
In contrast, Bernarda’s oldest daughter, Karynely finished high school four
years ago and now helps Bernarda sell cheeses. She is unable to continue
studying or find a good job because she lacks the necessary IT skills,
as there weren’t any computers at her school.
83
SECTION 1 2 3 WHAT CAN BE DONE
Developing countries also have the lowest tax-to-GDP ratios, meaning they
are farthest from meeting their revenue-raising potential. While advanced
economies collected on average 34 percent of GDP in taxes in 2011, in
developing countries this was far lower – just 15 to 20 percent of GDP.372 Oxfam
estimates that if low- and middle-income countries – excluding China – closed
half of their tax revenue gap they would gain a total of almost $1tn.373 The lack
of tax collection undermines the fight against inequality in the countries
that most need public investment to achieve national development and
reduce poverty.
Tax collection in developing countries is also undermined by a lack of
government capacity. Sub-Saharan African countries would need to employ
more than 650,000 additional tax officials for the region to have the same ratio
of tax officials to population as the OECD average.374 Unfortunately, no more
than 0.1 percent of total Official Development Assistance (ODA) is channelled
into reforming or modernizing tax administrations,375 and programmes that
would strengthen public financial management, tax collection and civil
society oversight are not prioritized.
Tax breaks: A multitude of tax privileges, but only for the few
The ‘race to the bottom’ on corporate tax collection is a large part of the
problem. Multilateral agencies and finance institutions have encouraged
developing countries to offer tax incentives – tax holidays, tax exemptions and
free trade zones – to attract foreign direct investment (FDI). Such incentives
have greatly undermined their tax bases.
In 1990, only a small minority of developing countries offered tax incentives;
by 2001 most of them did.376 The number of free trade zones offering
preferential tax arrangements to investors has soared in the world’s poorest
countries. In 1980, only one out of 48 sub-Saharan African countries had a free
trade zone; by 2005, this had grown to 17 countries; and the race continues.377
In 2012, Sierra Leone’s tax incentives for just six firms were equivalent to 59
percent of the country’s entire budget, and more than eight times its spending
on health and seven times its spending on education.378 In 2008/09, the
Rwandan government authorized tax exemptions that could have been used
to double health and education spending.379
This race to the bottom is now widely seen as a disaster for developing
countries, tending to benefit the top earners far more, as well as cutting
revenue for public services.380 Developing countries are more reliant on
corporate tax revenues and less able to fall back on other sources of revenue
like personal income tax, meaning any decline hits them hardest.381 Recently
the IMF has demonstrated that the ‘spillover’ effects that tax decisions made in
one country have on other countries can significantly undermine the corporate
tax base in developing countries, even more so than in OECD countries.382
Tax havens and tax dodging: A dangerous combination
Failures in the international tax system pose problems for all countries.
Well‑meaning governments attempting to reduce inequality through
progressive tax policies are often hamstrung by a rigged international
84
SECTION 1 2 3 WHAT CAN BE DONE
approach to tax coordination. No government alone can prevent corporate
giants from taking advantage of the lack of global tax cooperation.
Tax havens are territories that maintain a high level of banking secrecy. They
charge little or no tax to non-resident companies and individuals, do not
require any substantial activity to register a company or a bank account, and
do not exchange tax information with other countries. Tax dodging by MNCs and
wealthy individuals robs countries, rich and poor, of revenue that should rightly
be invested to address pressing social and economic problems. Tax havens are
intentionally structured to facilitate this.
They are also widely used. Great Britain’s top 100 companies own about 30,000
subsidiary corporations and 10,000 of these are located in tax havens.383 Ugland
House in the Cayman Islands is home to 18,857 companies, famously prompting
President Obama to call it ‘either the biggest building or the biggest tax scam
on record’.384 Similarly, the Virgin Islands has 830,000 registered companies,
despite a total population of just 27,000. At least 70 percent of Fortune 500
companies have a subsidiary in a tax haven.385 Big banks are particularly
egregious. Perhaps Bank of America needs a new name – it operates 264
foreign subsidiaries in tax havens, 143 in the Cayman Islands alone.386
Tax havens facilitate the process of ‘round tripping’,. To take one example, more than
half of FDI invested in India is channelled through tax havens and most of it
from Mauritius.387 Forty percent – a total of $55bn – is from just one building
in the heart of the capital Port Louis.388
Tax havens also facilitate transfer mispricing, the most frequent form of
corporate tax abuse, where companies deliberately over-price imports
or under-price exports of goods and services between their subsidiaries.
Deliberate transfer mispricing constitutes aggressive tax avoidance, but it is
nearly impossible for developing country tax authorities to police the ways in
which companies set the prices of goods and services exchanged between
subsidiaries, especially when it is most of the time hidden behind excessive
brand, patents or management fees.
Every year Bangladesh loses $310m in potential corporate taxes due to transfer
mispricing. This lost revenue could pay for almost 20 percent of the primary
education budget in a country that has only one teacher for every 75 primary
school-aged children.389
The true extent of the financial losses that all countries sustain due to tax
avoidance by MNCs may be impossible to calculate. But conservative estimates
put it high enough to achieve the Millennium Development Goals (MDGs)
twice over.390
Worryingly, this trend shows no sign of slowing down. Profits registered by
companies in tax havens are soaring, indicating that more and more taxes are
being artificially and intentionally paid in these low tax and low transparency
jurisdictions. In Bermuda, declared corporate profits went from 260 percent of
85
SECTION 1 2 3 WHAT CAN BE DONE
GDP in 1999 to more than 1,000 percent in 2008, and in Luxembourg, they rose
from 19 to 208 percent over the same time span.391
The richest individuals are able to take advantage of the same tax loopholes
and secrecy. In 2013 Oxfam estimated that the world lost approximately $156bn
in tax revenue as a result of wealthy individuals’ moving assets into offshore
tax havens.392 This is not only a ‘rich-country’ illness. Wealthy Salvadorans, from
a country where 35 percent of the population lives in poverty,393 are estimated
to hide $11.2bn in tax havens.394
There is no way for governments to make sure that these global companies and
rich individuals are paying their fair share of taxes while tax havens are open
for business.
Why has there not been a tax revolution yet?
Tax policy is prone to vested interests, particularly the disproportionate
influence of business lobbies and wealthy elites opposed to any form of more
progressive taxation at the national and global level. As early as 1998, the
OECD recognized that tax competition and the use of tax havens were harmful,
and expanding at an alarming rate.395 But in the face of intense lobbying from
groups representing the interests of tax havens, from tax havens themselves,
and from rich country governments, the OECD’s attempts to coordinate action
on taxation had been largely abandoned by 2001.396
International tax reform has come back to the top of the international agenda
since the 2008 financial crisis. There has been widespread public outrage
over a number of high-profile companies, including Apple397 and Starbucks,398
and others, that have been exposed for dodging their taxes and cheating the
system. In 2012, G20 governments commissioned the OECD again to propose
action to curb profit shifting and other tricks exploited by MNCs that erode
governments’ tax bases – leading to the current Base Erosion and Profit
Shifting (BEPS) process. If done correctly, BEPS could provide much-needed
coherence in the international tax architecture and could help to reduce
corporate tax dodging practices, to the benefit of rich and poor countries alike.
However, the process is in grave danger because it represents the interests
of rich countries and is open to undue influence from corporate and economic
elites. At the end of 2013, the OECD opened consultations to ‘stakeholders’399
to comment on a number of draft rules, including those on country-by-
country reporting. Almost 87 percent of submissions on this issue came from
the business sector, and unsurprisingly they were almost all opposed to the
proposal. Overall, only five contributions came from developing countries,
with the remaining 130 from rich countries.400
There are still strong vested interests that are standing in the way
of true reform.
THE HIGH ROAD: HOPE FOR A FAIRER FUTURE
Despite the shady network of tax havens and the strong resistance to reform,
there are signs of hope. Some countries are taking the high road and adopting
86
SECTION 1 2 3 WHAT CAN BE DONE
fiscal policies that tackle inequality. There is also strong recognition among
credible actors that the global tax system is not working.
Sailing against strong winds
Almost nine months after Macky Sall’s election as President of Senegal in
2012, the country adopted a new tax code to raise revenue to finance public
services. This reform simplified the tax rules, increased corporate income tax
from 25 to 30 percent, reduced personal income tax for the poorest and raised
it by 15 percent for the richest. While more reform is needed in Senegal, the
participatory approach taken –including many rounds of consultation with
representatives from the business community and civil society – has opened
the door for other progressive reforms that can tackle inequality, notably a
review of the mining codes to tackle low royalties paid by mining companies.401
In 2005, the newly elected government of Uruguay, led by President José
Mújica, set about reforming the country’s regressive tax system. Consumption
taxes were reduced, coverage of personal income taxes was broadened,
corporate income taxes were consolidated, and some taxes were discontinued.
As a result, the tax structure was significantly simplified and tax rates on the
poorest and the middle class were lowered, while the top earners saw their
rates rise. Today, inequality measured in after-tax income is starkly lower.402
Despite this domestic progress, however, Uruguay remains a global tax haven,
facilitating billions in tax avoidance elsewhere.403
These reforms show that where there is political will, policies can move in the
right direction, ensuring that those who have more – corporations and rich
individuals – pay more taxes.
International consensus is shifting
In the face of constrained budgets and public outrage, international consensus
is also shifting. Despite the limitations of the BEPS process described above,
the fact that the G8, G20 and OECD took up this agenda in 2013 demonstrates a
clear consensus that corporate taxation is in need of radical reform. The OECD’s
analysis also demonstrates that there is a need to redefine international rules
in order to curb profit-shifting, and to ensure companies pay taxes where
economic activity takes place and value is created.404
The IMF is also reconsidering how MNCs are taxed, and in a recent report
recognized the need to shift the tax base towards developing countries.405
They also acknowledged that the ‘fair’ international allocation of tax revenue
and powers across countries is insufficiently addressed by current initiatives.
OECD, USA and EU processes are also making progress on tax transparency
to lift the veil of secrecy that surrounds the global tax system. European
institutions have led the way by adopting a reporting system for European
banks, agreeing that information, such as where they have subsidiaries, how
much profit they make and where they pay taxes, should be public information,
especially after many of these banks were rescued with public money. The
G8 has made progress on registries of beneficial ownership, with some
public registries moving ahead. And a new global standard for the automatic
exchange of tax information has been agreed by the G20.
87
SECTION 1 2 3 WHAT CAN BE DONE
Alternative proposals that are pushing governments and institutions to
go further are also being put on the table. The IMF has recently looked at
‘worldwide unitary taxation’, an alternative tax method promoted by academics
and some civil society organizations to ensure that companies pay tax where
economic activity takes place.406 Ten EU countries have agreed to work together
to put a Financial Transaction Tax in place, which if applied to a broad range of
transactions, could dampen speculative trading and raise €30–35bn per year.407
The debate around global and national wealth taxes has been brought to
popular attention by Thomas Piketty’s book Capital in the Twenty-First Century,
where he proposes a global wealth tax to curb excessive wealth inequality.
He proposes a sliding scale starting at 0.1 percent for those with fortunes of
less than €1m, moving up to 10 percent for those with ‘several hundred million
or several billion euros’.408
The idea of wealth taxes was also proposed to the Brazilian congress in 2013
by the Brazilian ruling party in the wake of riots.409 In 2012, it was reported
that the IMF was considering a one-time 10 percent wealth levy, in order to
return many European countries to pre-crisis public debt-to-GDP ratios, but
its support for the proposal was quickly denied.410 The economic and financial
crises, and Capital in the Twenty-First Century, have undoubtedly started a
serious debate about taxing wealth to tackle economic inequality..411
More than numbers: Tax is about our model of society
‘How people are taxed, who is taxed and what is taxed tell more about
a society than anything else.’
Charles Adams412
Taxes are essential sources of revenue to fund the services, infrastructure,
and ‘public goods’ that benefit us all, and can be the glue between citizen
and state. Governments must rebuild trust in the tax system, and demonstrate
that when tax and public spending are done right, they can form the fabric of
a decent and fair society, and deliver for everyone fairly.
Reforms in Lagos State, Nigeria have demonstrated that the vicious cycle of
mistrust towards governments can be stopped. Since coming to power in May
2007, Governor Babatunde Fashola has invested in roads and education, and
communicated to the 15 million inhabitants that those public services were
financed by taxes. Fashola has remained highly popular and was re-elected in
2011 with a large majority. In 2011, an impressive 74 percent of Lagosians were
satisfied with the way that Governor Fashola has spent their tax money so far.
This shows that, although the willingness of the public to pay taxes is low in
many developing countries where governments are typically viewed as wasteful
and corrupt, willingness can be rapidly generated by effective fiscal reforms.413
These are signs of hope for the future. But, as ever, turning rhetoric and debate
into action will require sufficient political mobilization to oblige governments to
stand in solidarity with the 99 percent, and against the special interests that
resist reform.
88
SECTION 1 2 3 WHAT CAN BE DONE
A notice above the pharmacy window at the
Ola During Hospital for children reads ‘Free
2.4
For Children Under 5’, Freetown, Sierra Leone
(2011). Photo: Aubrey Wade/Oxfam
HEALTH AND EDUCATION:
STRONG WEAPONS IN THE
FIGHT AGAINST INEQUALITY
Public services, like healthcare and education, are essential
for fighting poverty and inequality.
89
SECTION 1 2 3 WHAT CAN BE DONE
HANA: WEAK HEALTH SYSTEMS
G
CASE STUDY COST THE POOREST THEIR LIVES
Babena Bawa was a farmer from Wa East district; a remote and
underdeveloped area in the upper-west region of Ghana, where seven
health centres serve a population of nearly 80,000 people. There are
no hospitals, no qualified medical doctors and only one nurse for every
10,000 people. In May 2014, Babena died of a snake bite that would
have been easily treatable, had any of the health centres in his district
stocked the necessary anti-venom. Instead his last hours on earth were
spent in a desperate race against time to reach the regional hospital,
120km away. The road to the regional centre was too poor and the
journey too long, and he died before making it to the hospital.
The story of Babena stands in stark contrast to that of presidential
candidate Nana Akufo-Addo. When faced with heart problems in 2013,
he was able to fly to London for special treatment.
Public services have the power to transform societies by enabling people
to claim their rights and to hold their governments to account. They give
people a voice to challenge unfair rules that perpetuate economic inequality,
and to improve their life chances.
It is estimated that if all women had a primary education, child marriage and
child mortality could fall by a sixth, while maternal deaths could be reduced
by two‑thirds.414 Moreover, evidence shows that public services can be great
equalizers in economic terms, and can mitigate the worst impact of today’s
skewed income and wealth distribution. OECD countries that increased
public spending on services through the 2000s successfully reduced income
inequality and did so with an increasing rate of success.415 Between 2000
and 2007, the ‘virtual income’ provided by public services reduced income
inequality by an average of 20 percent across the OECD.416
Long-term trends in poorer countries echo these findings. Studies show
that taking the ‘virtual income’ from healthcare and education into account
also decreases real income inequality by between 10 and 20 percent in five
Latin American countries: Argentina, Bolivia, Brazil, Mexico and Uruguay.417
In 11 out of 12 Asian countries studied, government health spending was
found to be ‘inequality reducing.’418 Education played a key role in reducing
inequality in Brazil,419 and has helped maintain low levels of income inequality
in South Korea.420
However, the extent to which public services are able to achieve their
inequality-busting potential depends on how they are designed, financed
and delivered. Unfortunately today, in too many cases, the policy choices
being made punish the poor, privilege elites, and further entrench
pre‑existing economic inequality.
90
SECTION 1 2 3 WHAT CAN BE DONE
THE LOW ROAD: CUTS, FEES, PRIVATIZATION
AND MEDICINES FOR THE FEW
Universal public services are a strong tool in the fight against inequality.
“
Even tiny out-of-pocket
charges can drastically
But the domination of special interests and bad policy choices – budget reduce [poor people’s] use of
cuts, user fees and privatization – can make inequality much worse. needed services. This is both
unjust and unnecessary.
Low levels of public spending and cuts JIM YONG KIM
PRESIDENT OF THE
Governments in many countries are falling far short of their responsibilities.
WORLD BANK GROUP421
The Indian government spends almost twice as much on its military as on
“
health.422 In Africa, only six countries have so far met the Abuja commitment to
allocate 15 percent of government spending to health. Between 2008 and 2012
more than half of developing countries reduced spending on education, while
two-thirds decreased spending on health.423
There is also an imbalance, which skews public spending on health and
education in favour of the already better-off urban areas, and away from
investing in schools and health centres in poorer rural areas. Better quality
services tend to be concentrated in big cities and towns. In Malawi, where the
level of public spending per primary school child is among the world’s lowest,
a shocking 73 percent of public funds allocated to the education sector
benefit the most educated 10 percent of the population.424
When public services are not free at the point of use, millions of ordinary
people are excluded from accessing healthcare and education. Every year,
100 million people worldwide are pushed into poverty because they have to
pay out-of-pocket for healthcare.425 A health emergency can doom a family
to poverty or bankruptcy for generations. Paying for healthcare exacerbates
economic inequality in rich countries too: in the USA, medical debt contributed
to 62 percent of personal bankruptcies in 2007.426
“
Fees still cost some people the earth
School fees have been shown to be a common deterrent to enrolment, I went for a cataract
especially at secondary school level, where they persist more widely. This is operation. They told me it
because the poorest simply cannot afford to send their children to schools costs 7,000 Egyptian pounds.
that charge fees, even when such fees are considered ‘low’. All I had was seven so
I decided to go blind.
Women and girls suffer most when fees are charged for public services. In many
A 60-YEAR OLD WOMAN
societies, their low status and lack of control over household finances mean
IN A REMOTE VILLAGE IN EGYPT
they are last in line to benefit from an education or receive medical care. Even
“
the World Bank Group – a long time promoter of user fees – has altered its pro-
fee stance. Yet they continue to exist in many of the world’s poorest countries.
91
SECTION 1 2 3 WHAT CAN BE DONE
EALTH CARE COSTS BANKRUPT
H
CASE STUDY THE POOREST IN ARMENIA
The Hovhannisyan family in rural community
of Verin Getak, Armenia (2013).
Photo: Oxfam in Armenia
In 2010, total spending on healthcare represented 1.62 percent of
Armenia’s budget. This under-investment has left people with no
choice but to make substantial out-of-pocket payments to meet
their healthcare needs.
The high cost of healthcare in Armenia has forced Karo and his wife
Anahit into a dire financial situation. Anahit suffers from arterial
hypertension and a prolapsed uterus requiring surgical intervention,
while Karo has had to live through a myocardial infarction and continues
to suffer from complications caused by his diabetes. They do not qualify
for subsidized care, and, as a result of their health conditions, they have
been forced to take out expensive loans, and to sell off jewellery and
livestock. With each health problem that arises, the family has been
pushed further and further into debt and poverty.
Dangerous distractions
Significant amounts of money are being diverted from the public purse to
bolster the for-profit private sector through cash subsidies and tax breaks.
In India, numerous private hospitals contracted and subsidized by the state
to provide free treatment to poor patients are failing to do so.427 In Morocco,
a recent rapid increase in private schools, supported through government
funds and tax breaks, has gone hand-in-hand with widening disparities in
educational outcomes. In 2011, the poorest rural children were 2.7 times less
likely to learn basic reading skills than the richest children in urban areas;
since 2006, this gap has increased by 20 percent.428
Developing country governments are also increasingly entering into expensive
and risky public-private partnerships. Lesotho is a striking example of how this
strategy can divert scarce public resources away from where they are needed
most, driving up inequality in a country that is already one of the most unequal
in the world.429
92
SECTION 1 2 3 WHAT CAN BE DONE
EALTH PUBLIC-PRIVATE PARTNERSHIP
H
CASE STUDY THREATENS TO BANKRUPT THE LESOTHO
MINISTRY OF HEALTH
The Queen Mamohato Memorial Hospital, in Lesotho’s capital Maseru,
was designed, built, financed and now operates under a public–private
partnership (PPP) that includes delivery of all clinical services. The
PPP was developed under the advice of the International Finance
Corporation, the private sector investment arm of the World Bank
Group. The promise was that the PPP would provide vastly improved,
high-quality healthcare services for the same annual cost as the old
public hospital.
Three years on, the PPP hospital and its three filter clinics:
• Cost $67m per year – at least three times what the old public
hospital would have cost today – and consume 51 percent of the
total government health budget;
• Are diverting urgently needed resources from health services in rural
areas where three-quarters of the population live and mortality rates
are rising;
• Are expecting to generate a 25 percent rate of return on equity
for the shareholders and a total projected cash income 7.6 times
higher than their original investment. Meanwhile, the Government of
Lesotho is locked into an 18-year contract.
The cost escalation has necessitated a projected 64 percent increase
in government health spending over the next three years. Eighty-three
percent of this increase can be accounted for by the budget line that
covers the PPP. This is a dangerous diversion of scarce public funds from
nurses, rural health clinics and other proven ways to get healthcare
to the poorest and reduce inequality.
For more information see: A. Marriott (2014) ‘A Dangerous Diversion: will
the IFC’s flagship health PPP bankrupt Lesotho’s Ministry of Health?’,
Oxfam,
Rich-country governments and donor agencies – including the World Bank
Group, USAID, the UK Department for International Development, and the
European Union – are also pushing for greater private sector involvement in
service delivery.430 This can only lead to one thing: greater economic inequality.
In fact, high levels of private-sector participation in the health sector have
been associated with higher overall levels of exclusion of poor people from
treatment and care. In three of the best performing Asian countries that have
met or are close to meeting Universal Health Coverage – Sri Lanka, Malaysia
and Hong Kong – the private sector is of negligible value to the poorest fifth
of the population.431 Recent and more detailed evidence from India has shown
that among the poorest 60 percent of women, the majority turn to public
sector facilities to give birth, while the private sector serves those in the top
40 percent.432 Private services benefit the richest most, rather than those most
in need, and have the impact of increasing economic inequality.
93
SECTION 1 2 3 WHAT CAN BE DONE
In education, there is a growing enthusiasm for so-called ‘Low-Fee Private
Schools’ (LFPS). However, these schools are prohibitively expensive for the
poorest families and are widening the gap between rich and poor. In Ghana,
sending one child to the Omega chain of low-fee schools would take up 40
percent of household income for the poorest.433 For the poorest 20 percent
of families in Pakistan, sending all children to LFPS would cost approximately
127 percent of each household’s income.434 The trends are similar in Malawi435
and rural India.436 Poor families will also often ‘hedge their bets’ by prioritizing
one or two children437 and it is usually girls who lose out. A study in India
found that 51 percent of boys attended LFPS, compared with just 34 percent
of girls.438
The wealthiest are able to opt-out and buy healthcare and education outside
of the public system. This undermines the social contract between citizen and
state, and is damaging for democracy. When only the poorest people are left
in public systems, the largely urban upper-middle class (i.e. those with greater
economic and political influence) have no self-interest in defending spending
on public services and fewer incentives to pay taxes. This sets in motion
a downward spiral of deteriorating quality, and a risk that structural inequalities
will be made worse, as the rich become even more divorced from the reality
of a suffering ‘underclass’.439
The Argentinean education system offers a cautionary tale of this two-tiered
future. A gradual increase in income inequality has gone hand-in-hand with
increased segregation in education.440 Evidence from Chile also showed that
the introduction of an opt-out option damaged the efficiency and equity of
the entire healthcare system.441
International rules threaten public services
As with taxation, international rules can undermine domestic policy.
International education and health service corporations have long lobbied
at the World Trade Organization for international rules that require countries
to open up their health and education sectors to private commercial interests,
and recently Wikileaks exposed plans for 50 countries to introduce a Trades
in Services Agreement that would lock in the privatization of public services.442
More immediately, the intellectual property (IP) clauses of current trade and
investment agreements, which oblige governments to extend patents on life-
saving medicines, are squeezing government health budgets in developing
countries, rendering them unable to provide many much-needed treatments.
For example, the majority of the 180 million people who are infected with
Hepatitis C cannot benefit from effective new medicines because they live
in the global south where neither patients nor governments can afford the
$1,000 per day medical bill.443 In Asia, medicines comprise up to 80 percent
of out-of-pocket healthcare costs.444 And while poor countries are hit hardest
by high medicine prices, rich countries are not immune. In Europe, government
pharmaceutical spending increased by 76 percent between 2000 and 2009,445
with some countries now refusing to offer new cancer medicines to patients
due to high prices.
94
SECTION 1 2 3 WHAT CAN BE DONE
Strong IP protection also stifles generic competition – the most effective
and sustainable way to cut prices. It was only after Indian generic companies
entered the HIV medicine market that prices dropped from $10,000 per patient
per year to around $100 – finally making it possible for donors and governments
to fund treatment for over 12 million people.446 Yet developing countries are
being pressed to sign new trade and investment deals, like the Trans-Pacific
Partnership, which further increase IP protection, putting lives on the line and,
in the end, leading to a wider gap between rich and poor.
The interests that are served when the public interest is not
At both a national and global level, powerful coalitions of interests are making
the rules and dictating the terms of the debate. Rich country governments
and MNCs use trade and investment agreements to further their own interests,
creating monopolies that hike up the prices of medicines and force developing
countries to open up their healthcare and education sectors to private
commercial interests.
In South Africa, private health insurance companies have been accused of
lobbying against a new National Health Insurance scheme that promises to
provide essential healthcare to all.447 In 2013, the US-based pharmaceutical
company Eli Lilly filed a $500m law suit against the Canadian government for
invalidating patents for two of its drugs.448
The fact that only 10 percent of pharmaceutical R&D expenditure is devoted to
diseases that primarily affect the poorest 90 percent of the global population449
is a stark reminder that big drug companies are dictating priorities to suit
their own commercial interests at the expense of public health needs. It is
no accident that there is no cure for Ebola, as there has been virtually no
investment in finding one for a disease predominantly afflicting poor people
in Africa.450 In Europe, the pharmaceutical industry spends more than €40m
each year to influence decision making in the EU, employing an estimated
220 lobbyists.451 Often their influence is helped by their close connections to
power. For example, there is a well-known revolving door between the US Trade
Representative office, which sets trade policies and rules, and the powerful
Pharmaceutical Research and Manufacturers of America.452
Margaret Chan, Director General of the World Health Organization (WHO),
put it well in 2014: ‘Something is fundamentally wrong in this world when
a corporation can challenge government policies introduced to protect the
public from a product [tobacco] that kills. If [trade] agreements close access
to affordable medicines, we have to ask: Is this really progress at all, especially
with the costs of care soaring everywhere?’453
95
SECTION 1 2 3 WHAT CAN BE DONE
Within countries, decisions on how much governments spend on public
services and who ultimately benefits, are shaped by power struggles between
groups with competing interests. All too often, the needs of wealthy elites
are put first and progressive public service reforms are resisted. In many Latin
American countries, once health insurance was established for formal-sector
workers, attempts to expand coverage were challenged by existing members
who do not want to see their benefits ‘diluted’.
Only 10% of
pharmaceutical
R&D spend...
...Is devoted to diseases
that primarily Affect the poorest
90% of the global population
96
SECTION 1 2 3 WHAT CAN BE DONE
THE HIGH ROAD: RECLAIMING
THE PUBLIC INTEREST
Governments must take back control of public policy and ensure that the
design, financing and delivery of public services policy are done in the public
interest, so they can meet their inequality-busting potential. There are
countries around the world offering good examples and hope that the high road
is possible. For governments to take this road, mobilized citizens must weigh
in on policy choices that, to date, have been dominated by vested interests.
Universal Health Coverage
The growing momentum around Universal Health Coverage (UHC) – under which
all people should get the healthcare they need without suffering financial
hardship – has the potential to vastly improve access to healthcare and drive
down inequality.
In 2013, Margaret Chan, described UHC as ‘the single most powerful concept
that public health has to offer’.454 At the World Bank, President Jim Yong Kim has
been unequivocal that UHC is critical to fighting inequality, saying it is ‘central
to reaching the [World Bank] global goals to end extreme poverty by 2030 and
boost shared prosperity.’455
Some governments are already taking action. China, Thailand, South Africa
and Mexico are among the emerging economies that are rapidly scaling up
public investment in healthcare. Many low-income countries have introduced
free healthcare policies for some or all of their citizens as a first step towards
UHC, for example by removing fees for maternal and child-health services. The
countries making most progress towards UHC have prioritized public financing
of healthcare from general taxation, rather than relying on insurance premiums
or out-of-pocket payments by individuals. Every step on this road is a step
that can reduce economic inequality significantly, giving everyone access
to healthcare.
Before Thailand’s Universal Coverage Scheme was introduced in 2002 nearly
a third of the population had no health coverage;456 most of them were
employed informally and were too poor to pay insurance premiums. The Thai
government moved to finance coverage from general tax revenues, and in just
10 years reduced the proportion of the population without health coverage to
less than four percent.457 This was a progressive reform; in the first year, the
amount of money the poorest were spending each month on healthcare costs
was more than halved.458 The percentage of households forced into poverty
through excessive health payments dropped from 7.1 percent in 2000 to
2.9 percent in 2009.459 Infant and maternal mortality rates plummeted.
97
SECTION 1 2 3 WHAT CAN BE DONE
CASE STUDY FREE HEALTHCARE IN NEPAL
A group of young mothers wait with their children
for a check-up at a small rural public health
clinic, Makwanpur, Nepal (2010).
Photo: Mads Nissen/Berlingske
Beginning in 2005, the Government of Nepal dramatically improved
access to healthcare by removing fees for primary healthcare services
(including essential medicines), and by providing cash incentives for
women to give birth in a health facility. In Nepal’s poorest districts the
proportion of women giving birth in a health centre more than tripled
from six percent to 20 percent in just four years.460 Before the reforms,
the richest 20 percent of women were six times more likely to deliver in
a health facility compared to the poorest 20 percent of women. This ratio
halved when charges for deliveries were removed.461
‘I have been a health worker for 18 years. After free maternal health
services were introduced the number of patients increased dramatically..’
Nurse Midwife, Surkhet, Nepal
There have even been victories over the pharmaceutical industry’s stubborn
efforts to block access to affordable medicines. In 2013, the Indian Supreme
Court rejected a patent on Glivec®/Gleevec®, a cancer treatment developed
by Novartis. Patients suffering chronic myeloid leukaemia can now take generic
versions of Glivec for only $175 per month – nearly 15 times less than the
$2,600 charged by Novartis and a price that should make it possible for the
government to afford to treat patients.462
Promising progress in education
Since the Education For All movement and the adoption of the MDGs in 2000,
the world has seen impressive progress in the number of children gaining
primary education. Through increased donor support, domestic spending
and debt relief, a wave of countries have been able to eliminate school fees,
accelerating access to education for the poorest children. For example,
in Uganda, enrolment rose by 73 percent in just one year – from 3.1 million
98
SECTION 1 2 3 WHAT CAN BE DONE
to 5.3 million – following the abolition of school fees.463 Fee abolition is critical
to tackling economic inequality, and boosting opportunities for the poorest.
However, the quality of the education on offer has suffered in those countries
which have failed to match the increase in enrolment with adequate
investments in trained teachers, facilities and materials – a situation made
more difficult by faltering donor commitments and falling government budgets
due to the global economic crisis. This risks reinforcing inequalities in the
quality of education between the public and private sectors, and between
the poorest and wealthiest children.
Beyond school fee abolition, additional targeted investments are needed
to provide the most marginalized children with high-quality education.
These include extra funding for schools in rural and under-served areas,
policies to address other financial barriers to poor children’s access to
education (such as uniforms, transportation and learning materials),
and more accountability for education quality through active community
involvement in school management.
Some countries are leading the way. For example, Brazil has championed
reforms that increase access to good quality education and allocate more
spending to the education of poor children, often in indigenous and black
communities.464 These reforms have helped to reduce inequality of access
since the mid-1990s: the average number of years spent in school by the
poorest 20 percent of children has doubled – from four years to eight years.465
Investment in education and healthcare played a key part in Brazil’s recent
success in reducing inequality.
A number of East Asian countries, including South Korea, Japan and Singapore,
have implemented programmes specifically designed to promote equitable
learning, including investing in high-quality teachers. Even the poorest
students are now learning above the minimum threshold.466 There is solid
evidence that making equity an explicit goal of education policy can lead
to improved educational outcomes across the board.
Public investment in healthcare and education for all citizens is a powerful
tool for addressing inequality, and these examples demonstrate that change
is possible, even in the face of powerful special interests.
Aid can tackle inequality and political capture
Taxation and domestic resource mobilization are critical to boosting public
spending. For some countries, harnessing aid and investing it well, for instance
into good-quality public services that citizens need and demand, has also
helped to reduce poverty and inequality through supporting national public
service plans and boosting public spending.
In 2004, just over a quarter of the aid received by Rwanda – a country that had
spent 10 years rebuilding national institutions and economic stability following
the 1994 genocide – was budget support: long-term aid that can support
health and education systems, as well as institution strengthening. Steady
growth in budget support up to 2004 allowed the government to eliminate fees
for primary and lower-secondary school education, increase spending
99
SECTION 1 2 3 WHAT CAN BE DONE
on treatment for people living with HIV and AIDS, and provide agricultural loan
guarantees to farmers.467
In many developing countries, aid also plays an influential role in both the
economy and politics. As such, when donors actively seek to invest in
accountable governance and effective citizen engagement, aid can also help
to counteract political capture.
The USA, for instance, is seeking to focus agriculture investments in the north
of Ghana – an historically poor region – channelling these through local district
councils, in an effort to make the councils more responsive to local farmer
input. In parallel, the USA is also supporting farmer associations to demand
responsiveness from district councils; as a result, district councils are now
demanding more support from central government.
This kind of aid is crucial, but, since 2009, aid to civil society organizations
has stagnated at around 14 percent of total aid flows by OECD DAC members.468
Meanwhile, the longer term trend is of donors increasing aid to the private
sector; multilateral aid to the private sector alone has increased ten-fold
since the early 1990s.469 This is a worrying trend that skews priorities away
from supporting public spending on good governance, public services,
small‑scale agriculture and other inequality-busting public goods.
100
SECTION 1 2 3 WHAT CAN BE DONE
Ensanche Luperon, candy seller, departs every
afternoon to sell sweet coconut candy, despite
living with a disability that hinders his mobility and
2.5 speech, Dominican Republic (2014).
Photo: Pablo Tosco/Oxfam
FREEDOM FROM FEAR
The development successes of recent decades have
lengthened life expectancies and decreased birth rates
across much of the developing world. However, this
is now putting a strain on informal support systems,
leaving millions of people in desperate situations.
Elderly people, older women in particular, face
harsh conditions, as do children and people unable
to work due to disability or lack of job opportunities.
101
SECTION 1 2 3 WHAT CAN BE DONE
“
CASE STUDY ZAMBIA: THE POWER OF PENSIONS
Tiziwenji Tembo is 75, and lives in the Katete district of Zambia. The true measure of any
Eleven of her 15 children are dead, and she now cares for four society can be found in
grandchildren. Until recently, she had no regular income and she and how it treats its most
her grandchildren often went without food. Her children often refused vulnerable members.
to go to school because they did not have uniforms and books, and
MAHATMA GANDHI
their fellow students would laugh at them. Their lives were transformed,
”
however, when she began to receive a regular pension worth $12 per
month, which has enabled her family to eat more regularly, buy
school uniforms and repair their house.470
Social protection often involves governments providing money or in-kind
benefits – child benefits, old-age pensions and unemployment protection,
for instance – that, like healthcare and education, put ‘virtual income’ into
the pockets of those who need it most, mitigating an otherwise skewed income
distribution. It is not only central to reducing economic inequality, but also
to making society as a whole more caring and egalitarian, and less based
on individualism.
After the Second World War, the majority of wealthy nations introduced large-
scale, often universal, social protection systems, that guaranteed a basic
income to all citizens and offered insurance against unemployment, old age
and disability, building a path ‘from cradle to grave’. In the USA, the introduction
of social security and pensions in the 1930s dramatically reduced levels
of poverty among the elderly.
The 2008 financial crisis prompted the establishment of the Social Protection
Floor Initiative, led by the ILO and WHO. The initiative encourages countries
to offer basic income security for the unemployed, all children, the elderly
and persons with disabilities or who are otherwise unable to earn a decent
living. However, recent figures show that more than 70 percent of the world’s
population is not adequately covered by social protection.471
TOWARDS UNIVERSAL COVERAGE
Universal coverage has been the ambition in most wealthy countries, rather
than targeted benefits for the needy. This has often been for political reasons:
giving benefits to all increased a sense of national cohesion and solidarity;
it ensured the support of the middle classes and avoided the stigmatization
of means-testing.
Deciding who is deserving of benefits is a complex, ever-changing and often
divisive exercise, which has its own costs and can be subject to fraud. One
study shows that targeting is less efficient in low-income countries, owing
to high leakage, under-coverage and administrative costs. A staggering
25 percent of targeted programmes are found to be regressive and, in Africa,
targeted programmes transfer eight percent less revenue to the poor than
universal ones.472 Moreover, targeted programmes are usually aimed at the
102
SECTION 1 2 3 WHAT CAN BE DONE
household level, meaning that women and vulnerable groups, such as the
elderly, can be undermined in the process.
Despite this, in recent decades smaller, targeted, means-tested benefits have
become increasingly favoured, particularly by the World Bank and the IMF. This
is based on the much more limited role for government envisioned by market
fundamentalists and the view that universal benefits are unaffordable for many
countries. It also fits with the ever more widespread perception that welfare
benefits inhibit work and that the focus should be on individuals having to
stand on their own feet and not be stifled by the ‘nanny state’.473
Linking the provision of benefits to particular conditions or behaviours,
such as getting children immunized or sending them to school, is becoming
increasingly popular. However, there is no evidence that this works, and, as
with poverty targeting, it requires significant administration and a system of
sanctions that must be enforced.474 Implicit in the approach is the judgement
that firstly poor people will not make the right choices, and secondly that they
can be persuaded to make behavioural changes with money.
All countries should be working towards permanent universal social protection
systems, which reduce vulnerability and increase resilience to shocks.
Mechanisms that can scale-up rapidly at times of crisis, when a basic level
of protection is not enough, should also be further pursued. A good interim
path would be to guarantee social protection to categories of people; for
example, providing benefits to all mothers or all people over a certain age.
This would reduce debate and the stigma attached to means-testing to
identify who is most needy.
Many developing countries now have levels of income that are on par with
those in Europe when universal schemes were introduced there, challenging
the idea that these benefits are unaffordable. Multiple studies have also
shown that basic levels of social protection are affordable across the
developing world.475
Things are already changing. Over the past two decades, middle-income
countries have expanded social security on a massive scale. China has nearly
achieved universal coverage of old-age pensions, while India has instituted
an employment guarantee for its rural population, benefiting hundreds of
millions of people.476 One study found that social protection was responsible
for a quarter of the reduction in Brazil’s Gini coefficient.477
The time has certainly come for all countries to broaden social protection
as a critical tool for reducing inequality, and to ensure the most vulnerable
are not left behind.
103
SECTION 1 2 3 WHAT CAN BE DONE
Bin Deshweri and Girijar presenting for NGO Samarpan
Jan Kalayan Samiti in Konch, Uttar Pradesh, India (2007).
Photo: Rajendra Shaw/Oxfam
2.6
ACHIEVING ECONOMIC
EQUALITY FOR WOMEN
In rich and poor countries alike women perform the majority
of unpaid labour, are over-represented in part-time and
precarious work, and are often paid less than men for doing
the same job. Even in societies that are considered to have
achieved high levels of gender equality overall, women
face significant income and influence gaps.478 The right mix
of policies is needed to eliminate the barriers that inhibit
women’s economic equality. Yet, all too often, policymakers
do not take into account the potential impact that policy
measures will have on women.
104
SECTION 1 2 3 WHAT CAN BE DONE
THE LOW ROAD: GENDER-BLIND
POLICY PRESCRIPTIONS
Failure to consider the particular situation of women and girls can unwittingly
lead governments to reinforce gender inequalities or end up giving with one
hand while taking away with the other. In China, successful efforts to create
new jobs for women were accompanied by cutbacks in state and employer
support for childcare and elderly care, which conversely increased women’s
unpaid work.479
Fiscal policy can also have unintended negative impacts on women and girls.
Tax cuts designed to stimulate economic growth, whether made to income
taxes or to corporate taxes, benefit men far more than women because the
largest benefits of such cuts go to those with the highest incomes and
corporate share ownership. A recent study in Ghana found that an indirect tax
on kerosene, used for cooking fuel in low-income urban and rural households,
is paid mostly by women.480
However, direct taxes on those that can most afford them are essential,
as countries with reduced tax revenues have less capacity to deal with
economic crises, and end up having to introduce austerity measures to
balance their budgets. When austerity budgets call for reduced public sector
employment, these layoffs hit women hardest because they are heavily
represented in the public sector. When austerity cuts reduce public services,
not only does this place an undue burden on women, it also makes it more
difficult for them to get a job. According to research conducted on the impact
of austerity in Europe,481 after the financial crisis mothers of small children were
less likely to be employed than before and more likely to attribute their lack of
employment to cuts to care services.482
Governments have come together time and again to commit to eradicating
gender inequality. The Convention on the Elimination of all Forms of
Discrimination against Women obliges states to eliminate discrimination
and differences in treatment between women and men ‘by all appropriate
means’. In addition, the 1995 Beijing Platform for Action calls for an approach
to macroeconomic and development policy which addresses the needs and
efforts of women in poverty and promotes a ‘more equitable distribution of
productive assets, wealth, opportunities, income and services’.483 Now is the
time to make good on these commitments.
THE HIGH ROAD: THE RIGHT POLICIES CAN
PROMOTE WOMEN’S ECONOMIC EQUALITY
Many of the policies that reduce economic inequality also have a huge impact
on reducing gender inequality. Free primary education and free healthcare
disproportionately benefit women and girls. Public services are more used
by women; they ensure the state takes some of the burden of care away
from women, whether it is healthcare or childcare. Social protection grants,
such as universal child benefits, also have a big impact on gender inequality.
Regulations around minimum wages and job security, as well as those that
guarantee paid holiday, sick leave and maternity leave, all help to narrow the
105
SECTION 1 2 3 WHAT CAN BE DONE
gap between women and men. Again, women are the main beneficiaries of
these, as they are the ones most likely to work in insecure or low-paid jobs.
Progressive taxation also benefits women more, as it means the burden of
tax falls on rich men, while the public services it pays for more often benefit
poorer women.
Understanding the differential impact of public policies and public spending
decisions on women and men is essential to maximizing the positive impact of
policies on reducing gender inequality, as well as tackling economic inequality.
Governments need to undertake gender impact analyses based on sex-
disaggregated data. South Africa did so and then introduced a child-support
grant for the primary caregivers of young children from poor households. The
grants reach poor, black and rural women better than previous measures.484
In India, the Ministry of Agriculture introduced a gender-budgeting programme
for rural women, who are the major producers of food, with significant
participation by those women. As a result, in 2000 the National Agriculture
Policy encouraged state governments to direct at least 30 percent of their farm
budget allocations to women farmers, and set minimum standards for their
access to irrigation subsidies, training, credit and farming-related governance
structures. Strengthening women’s role in farm programmes and communities
has enhanced the food and economic security of their families.485
South Korea has introduced a number of measures for women workers,
including lengthening pre- and post-natal maternity leave and paternity
leave, becoming the first country in East Asia to do so. Return to Work Centres
provide women with employment information, vocational training and childcare
services, and generous subsidies encourage employers to hire and retain
female workers before, during and after pregnancy.486 Nevertheless, the gap
in wages between women and men remains very high and progress in narrowing
it over the last 40 years has been slower than expected, showing that far more
needs to be done.487
South Korea’s rapid economic growth since the 1960s has been fuelled
by labour-intensive exports that have employed mainly women. In theory,
sustained high demand for female labour, coupled with narrowing gender
educational gaps, should lead to much more progress towards achieving wage
parity than has been observed over the last 40 years. Progress, however, has
been very slow in South Korea (as it has been in other East Asian economies,
including Japan, Hong Kong, China and Singapore).
106
SECTION 1 2 3 WHAT CAN BE DONE
CASE STUDY L OW-FEE CHILDCARE IN QUEBEC
In 1997, the Canadian province of Quebec created a low-fee childcare
programme (costing only $7 (CAD) per child per day) to improve the status
of women and poor families, and to contribute to building a better labour
force. Over the following years, the proportion of children in Quebec
under the age of four attending daycare has risen sharply – from 18
percent in 1998 to 53 percent in 2011. Elsewhere in Canada attendance
rates have remained constant at around 20 percent for children up to
the age of five.
The most significant impact has been on women’s employment
and earning potential. Between 1996 and 2011, the rate of female
employment increased faster in Quebec than in the rest of Canada. In
Quebec, the number of mothers participating in the labour force rose
faster than that of women without children, which was not the case in
Canada as a whole. Moreover, the relative poverty rate of families headed
by single mothers fell from 36 to 22 percent, and their median real after-
tax income rose by 81 percent.
One study estimated that in 2008 nearly 70,000 more mothers held
jobs than would have been the case without universal access to low-
fee childcare – equivalent to an increase of 3.8 percent in women’s
employment. The same study estimated that Quebec’s GDP was about
1.7 percent ($5bn (CAD)) higher as a result, and that the tax revenue that
the Quebec and federal governments received due to that additional
employment significantly exceeded the programme’s cost.488 This reform
was good for women, boosted the economy and promoted women’s
economic equality.
A transformational shift is needed in the design and implementation of policies
to eradicate the barriers that inhibit women’s economic equality. Government
must address the care responsibilities predominately shouldered by women,
ensure fair and decent work with equal pay for all, redress women’s unequal
access to assets and finance, reform discriminatory land and inheritance laws,
and end violence against women at home and in the work place.
107
SECTION 1 2 3 WHAT CAN BE DONE
Women protesting at the Tunisian
Constituent Assembly, demanding
parity in election law, Tunisia (2014).
2.7 Photo: Serena Tramont/Oxfam
PEOPLE POWER: TAKING
ON THE ONE PERCENT
In this report we have shown how the massive
concentration of economic resources in the hands of a few
people can have negative consequences for all of society,
including the threat it presents to accountable governance.
Those with money can use it to buy power and to rig rules,
regulations and policies in their favour, creating a cycle of
growing economic inequality. Politicians and institutions
that should represent citizens and keep inequality in check
are instead being influenced by the rich and powerful,
resulting in policies and actions that further widen the
gap between rich and poor.
108
SECTION 1 2 3 WHAT CAN BE DONE
The global alliance of civil society groups CIVICUS has reported an increase in
threats to civil society space in recent years,489 something that Oxfam has seen
firsthand in its work with civil society organizations around the world. This
takes many different forms, including direct repression, the introduction of
legal restrictions on legitimate civil society action, funding restrictions and,
in some cases, a crackdown of communications technology.490
Despite this, people around the world are coming together in ever greater
numbers to take back power. This can be seen in the mass of protests that
have sprung up across the world in the past few years,491 where hundreds of
“
People are not tolerating
the way a small number of
thousands of people took to the streets to vent their frustration about the lack economic groups benefit from
of services and their lack of voice.492 This discontent is reflected in opinion the system. Having a market
polling conducted by Oxfam and others, which clearly reflects that people economy is really different
around the world continue to be deeply concerned that their governments are from having a market
acting not in their interests, but on behalf of national and international elites.493 society. What we are asking
for, via education reform,
The good news is that political capture and economic inequality are not is that the state takes on
inevitable. History has shown time and again that the antidote to the a different role.
capture of power is the mobilization of empowered and informed active
CAMILA VALLEJO
citizens.495 This makes it a crucial ingredient in the fight against inequality.
VICE-PRESIDENT OF THE
There are numerous examples of citizens and civil society organizations
STUDENT FEDERATION OF THE
across the world holding their governments to account and demanding more
UNIVERSITY OF CHILE494
inclusive and representative policy making. Below are three such cases from
”
Chile, Hungary and Iceland.
Chile: Protests bring education reform and a new government
The biggest public demonstrations to hit Chile since the return of democracy
in 1990 erupted during 2011. Initially spurred by discontent over the cost
of education, they grew to encompass concerns about deep divisions of
wealth (Chile is the most unequal country in the OECD496) and the control of
government by business interests.497 A coalition of students and trade unions
mobilized 600,000 people in a two-day strike demanding reform. Elections
at the end of 2013 brought in a new government that included key members
“
of the protest movement, on a platform of reducing inequality and reforming
public education.498
The government has
failed the average person
Hungarians block user fees and privatization
in Iceland. It protects
In 2006, the Hungarian government proposed health service reforms including the interests of financial
hospital closures, the introduction of user fees, and the creation of regional, institutions while it couldn’t
part-private insurance funds. After parliament passed a first law to introduce care less about normal people
patient fees and fees for other public services, including university education, who have no job, no income
campaigners gained enough signatures to force two referenda in 2008, which and have lost the ability to
eventually led the government to abandon the attempt.499 feed their family.
BALDUR JONSSON
Iceland: Popular participation in country’s political evolution A PROTESTOR IN ICELAND500
”
In early 2010, a series of popular protests against the proposed mass bailout of
Iceland’s three main commercial banks forced the newly elected government
– who had pledged to shelter low- and middle-income groups from the worst of
the financial crisis – to hold a referendum on the decision. Ninety three percent
of Icelanders rejected a proposal that the people (rather than the banks) should
pay for the bankruptcy.
109
SECTION 1 2 3 WHAT CAN BE DONE
Formal provisions for public participation in the political process were
introduced and led the government to crowd-source a new constitution.
The process included selecting citizens at random for an initial forum, holding
elections for a constitutional council, making the draft constitution available
online and sharing it through social media to allow people to comment.
The new constitution, which includes new provisions on equality, freedom
of information, the right to hold a referendum, the environment and public
ownership of land, was put to referendum in 2012 and approved.501
CASE STUDY HOW BOLIVIA REDUCED INEQUALITY
Bolivian indigenous groups descend from El Alto
to La Paz demanding a constituent assembly to
rewrite the Bolivian constitution (2004).
Photo: Noah Friedman Rudovsky
Bolivia was, until recently, a country where poverty and inequality sat
alongside racial discrimination against the country’s majority indigenous
population, who were largely excluded from political decision making.502
After a decades-long struggle by Bolivia’s social movements and civil
society organizations, the country’s first-ever indigenous president,
Evo Morales, took office in 2006.
Social movements pushed for the creation of a radical new constitution,
which enshrined a series of political, economic and social rights,
including extending provisions for participatory and community-
based governance.
110
SECTION 1 2 3 WHAT CAN BE DONE
(CASE STUDY CONTINUED)
This was accompanied by a range of new progressive social
programmes funded by renegotiating the country’s contracts for its
oil and gas at a time of high global commodity prices.503 A much larger
number of people now benefit from the exploitation of the country’s
natural resources.
The government, responding to the demands of the people, used the
natural resource windfall to invest in infrastructure, targeted social
programmes and increases in the universal pension entitlement.504
It has also raised the minimum wage, and increased public spending
on healthcare and education. Even though more spending on these
services is needed, poverty505 and inequality506 in the country have fallen
continually for the past 10 years.
Significant challenges remain. To date, the oil and gas windfall has
allowed the government to avoid the issue of tax reform, where
significant redistributive and sustainable potential remains.507 This
means that the country’s economic model has so far been almost
entirely based on revenue from extractive industries, which in the long-
run can undermine sustainable, pro-poor development.
111
Women on their way to work in the rice fields in River Gee county, Liberia (2012).
Photo: Ruby Wright/Oxfam
3
TIME TO ACT
And end extreme inequality
SECTION 1 2 3 TIME TO ACT
Today’s extremes of inequality are bad for everyone. For the poorest people in
society though – whether living in sub-Saharan Africa or the richest country in
the world – the chance to emerge from extreme poverty and live a dignified life
is fundamentally blocked by extreme inequality.
Oxfam is calling for concerted action to build a fairer economic and political
system. A system that values the many by changing the rules and systems
created by the few that have led to today’s crisis of inequality; a system which
levels the playing field through policies that redistribute money and power.
As outlined in Section 2, there are many concrete steps that governments and
institutions can take to start closing the gap between the haves and have-
nots. This is not an exhaustive agenda, but, if committed to, these steps could
start to reduce economic inequality.
Governments, institutions, multinational corporations (MNCs) and civil society
organizations must come together to support the following changes, before we
are tipped irrevocably into a world that caters only to the privileged few, and
consigns millions of people to extreme poverty.
1) MAKE GOVERNMENTS WORK FOR CITIZENS
AND TACKLE EXTREME INEQUALITY
Working in the public interest and tackling extreme inequality should be
the guiding principle behind all global agreements and national policies
and strategies. Effective and inclusive governance is crucial to ensuring
that governments and institutions represent citizens rather than organized
business interests. This means curbing the easy access that corporate
power, commercial interests and wealthy individuals have to political
decision making processes.
Governments and international institutions should agree to:
• A standalone post-2015 development goal to eradicate extreme economic
inequality by 2030 that commits to reducing income inequality in all
countries, such that the post-tax income of the top 10 percent is no more
than the post-transfer income of the bottom 40 percent.
• Assess the impact of policy interventions on inequality:
• Governments should establish national public commissions on
inequality to make annual assessments of policy choices – regulation,
tax and public spending, and privatization – and their impact on
improving the income, wealth and freedoms of the bottom 40 percent;
• Institutions should include measures of economic inequality in all policy
assessments, such as the IMF in their article IV consultations;
• Publish pre- and post-tax Gini data (on income, wealth and consumption)
and income, wealth and consumption data for all deciles and each of the
top 10 percentiles, so that citizens and governments can identify where
economic inequality is unacceptably high and take action to correct it;
113
SECTION 1 2 3 TIME TO ACT
• Implement laws that make it mandatory for governments to make national
policies and regulations and bilateral and multilateral agreements available
for public scrutiny before they are agreed;
• Implement mechanisms for citizen representation and oversight in
planning, budget processes and rule making, and ensure equal access
for civil society – including trade unions and women’s rights groups –
to politicians and policy makers;
• Require the public disclosure of all lobbying activities and resources spent
to influence elections and policy making;
• Guarantee the right to information, freedom of expression and access
to government data for all;
• Guarantee free press and support the reversal of all laws that limit reporting
by the press or target journalists for prosecution.
Corporations should agree to:
• End the practice of using their lobbying influence and political power to
promote policies that exacerbate inequality and instead promote good
governance and push other groups to do the same;
• Make transparent all lobbying activities and resources spent to influence
elections and policy making;
• Support conditions that allow civil society to operate freely and
independently, and encourage citizens to actively engage in the
political process.
2) PROMOTE WOMEN’S ECONOMIC EQUALITY
AND WOMEN’S RIGHTS
Economic policy is not only creating extreme inequality, but also entrenching
discrimination against women and holding back their economic empowerment.
Economic policies must tackle both economic and gender inequalities.
Governments and international institutions should agree to:
• Implement economic policies and legislation to close the economic
inequality gap for women, including measures that promote equal pay,
decent work, access to credit, equal inheritance and land rights, and
recognize, reduce and redistribute the burden of unpaid care;
• Systematically analyze proposed economic policies for their impact on girls
and women; improve data in national and accounting systems – including
below the household level – to monitor and assess such impact (for
example on the distribution of unpaid care work);
• Prioritize gender-budgeting to assess the impact of spending decisions on
women and girls, and allocate it in ways that promote gender equality;
114
SECTION 1 2 3 TIME TO ACT
• Implement policies to promote women’s political participation, end
violence against women and address the negative social attitudes
of gender discrimination;
• Include women’s rights groups in policy making spaces.
Corporations should agree to:
• End the gender pay gap and push other corporations to do the same;
• Ensure access for decent and safe employment opportunities for women,
non-discrimination in the workplace, and women’s right to organize;
• Recognize the contribution of unpaid care work, and help reduce the
burden of unpaid care work disproportionately borne by women, by
providing child and elderly care and paid family and medical leave, flexible
working hours, and paid parental leave;
• Support women’s leadership, for example by sourcing from women-led
producer organizations, supporting women to move into higher roles and
ensuring women occupy managerial positions;
• Analyze and report on their performance on gender equality, for example,
through the Global Reporting Initiative’s Sustainability Reporting Guidelines
and the UN Women Empowerment Principles.
3) PAY WORKERS A LIVING WAGE AND
CLOSE THE GAP WITH SKYROCKETING
EXECUTIVE REWARD
Hard-working men and women deserve to earn a living wage. Corporations are
earning record profits worldwide and levels of executive reward have soared.
Yet many of the people who make their products, grow their food, work in their
mines or provide their services earn poverty wages and toil in terrible working
conditions. We must see global standards, national legislation and urgent
corporate action to provide workers with more power.
Governments and international institutions should agree to:
• Move minimum wage levels towards a living wage for all workers;
• Include measures to narrow the gap between minimum wages and living
wages in all new national and international agreements;
• Tie public procurement contracts to companies with a ratio of highest
to median pay of less than 20:1, and meet this standard themselves;
• Increase participation of workers’ representatives in decision making in
national and multinational companies, with equal representation for women
and men;
115
SECTION 1 2 3 TIME TO ACT
• Develop action plans to tackle forced labour in workplaces within
their borders;
• Set legal standards protecting the rights of all workers to unionize
and strike, and rescind all laws that go against those rights.
Corporations should agree to:
• Pay their workers a living wage and ensure workers in their supply chain
are paid a living wage;
• Publish the wages paid in their supply chains and the number of workers
who receive a living wage;
• Publish data on the ratio of highest to median pay, and aim to meet the ratio
of 20:1 in each country of operation;
• Build freedom of association and collective bargaining into the company’s
human rights due diligence;
• End the practice of using their political influence to erode wage floors
and worker protections, uphold worker rights in the workplace, and value
workers as a vital stakeholder in corporate decision making;
• Track and disclose roles played by women in their operations and
supply chain;
• Agree an action plan to reduce gender inequality in compensation
and seniority.
4) SHARE THE TAX BURDEN FAIRLY TO LEVEL
THE PLAYING FIELD
The unfair economic system has resulted in too much wealth being
concentrated in the hands of the few. The poorest bear too great a tax
burden, while the richest companies and individuals pay far too little. Unless
governments correct this imbalance directly, there is no hope of creating
a fairer future for the majority in society. Everyone, companies and individuals
alike, should pay their taxes according to their real means, and no one should
be able to escape taxation.
Governments and international institutions should agree to:
• Increase their national tax to GDP ratio, moving it closer to their maximum
tax capacity, in order to mobilize greater domestic public revenue;
• Rebalance direct and indirect taxes, shifting the tax burden from labour
and consumption to capital and wealth, and the income derived from these
assets, through taxes such as those on financial transactions, inheritance
and capital gains. International institutions should promote and support
such progressive reforms at the national level;
116
SECTION 1 2 3 TIME TO ACT
• Commit to full transparency of tax incentives at the national level and
prevent tax privileges to MNCs where the cost/benefit analysis is not
proven to be in favour of the country;
• Adopt national wealth taxes and explore a global wealth tax on the richest
individuals globally and regionally, and commit to using this revenue to fight
global poverty;
• Assess fiscal policies from a gender-equality perspective.
5) CLOSE INTERNATIONAL TAX LOOPHOLES AND
FILL HOLES IN TAX GOVERNANCE
Today’s economic system is set up to facilitate tax dodging by MNCs and
wealthy individuals. Tax havens are destroying the social contract by allowing
those most able to contribute to society opt out of paying their fair share.
Until the rules around the world are changed, this will continue to drain
public budgets and undermine the ability of governments to tackle inequality.
However, any process for reform must deliver for the poorest countries.
A multilateral institutional framework will be needed to oversee the global
governance of international tax matters.
Governments and international institutions should agree to:
• Ensure the participation of developing countries in all reform processes
on an equal footing;
• Commit to prioritizing the eradication of tax avoidance and evasion
as part of an agenda to tackle the unfair economic systems that
perpetuate inequality;
• Support national, regional and global efforts to promote tax transparency
at all levels, including making MNCs publish where they make their profits
and where they pay taxes (through mandatory country-by-country reporting
that is publicly available), as well as who really owns companies, trusts and
foundations (through disclosure of beneficial ownership);
• Automatically exchange information under a multilateral process that will
include developing countries from the start even if they can’t provide such
data themselves;
• Combat the use of tax havens and increase transparency, by adopting
a common, binding and ambitious definition of what a tax haven is, as well
as blacklists and automatic sanctions against those countries, companies
and individuals using them;
• Ensure taxes are paid where real economic activity takes place; adopt
an alternative system to the current failed arm’s length principle of
taxing companies;
117
SECTION 1 2 3 TIME TO ACT
• Only grant tax breaks where there has been an impact assessment of
added-value to the country and a binding process to disclose and make
public all tax incentives;
• Promote the establishment of a global governance body for tax matters
to ensure tax systems and the international tax architecture works in the
public interests of all countries, to ensure effective cooperation and close
tax loopholes.
Corporations should agree to:
• Stop using tax havens;
• Support national, regional and global efforts to promote tax transparency at
all levels, including publishing where they make profits and where they pay
taxes (mandatory country-by-country reporting that is publicly available).
6) ACHIEVE UNIVERSAL FREE PUBLIC SERVICES
FOR ALL BY 2020
The high cost of healthcare and medicines drives a hundred million people
into poverty every year. When user fees are charged for schooling, some
children can access high-quality private education, but the majority make do
with poor-quality state education, creating a two-tiered system. Privatization
further entrenches the disparities between the poorest and the richest,
and undermines the ability of the state to provide for all.
Governments and international institutions should agree to:
• Guarantee free high-quality healthcare and education for all citizens,
removing all user fees;
• Implement national plans to fund healthcare and education, by spending
at least 15 percent of government budgets on healthcare and 20 percent
on education. Donor governments must mirror these allocations in bilateral
aid, and international institutions should promote equivalent social
spending floors;
• Implement systems of financial-risk pooling to fund healthcare via tax and
avoid health insurance schemes that are based on voluntary contributions;
• Stop new and review existing public incentives and subsidies for healthcare
and education provision by private for-profit companies;
• Implement strict regulation for private sector healthcare and education
facilities to ensure safety and quality, and to prevent them from stopping
those who cannot pay from using the service;
• Exclude healthcare, medicines, medical technologies, knowledge and
education from all bilateral, regional or international trade and investment
agreements, including those which lock national governments into private
healthcare and education provision;
118
SECTION 1 2 3 TIME TO ACT
• Ensure that women’s health needs are prioritized, sexual and reproductive
rights are upheld, and that bilateral aid is not permitted to constrain
women’s access to reproductive health services.
Corporations should agree to:
• Stop lobbying for the privatization of vital public services, including
healthcare and education;
• Work with government efforts to regulate private healthcare providers
to ensure their positive contribution to Universal Health Coverage.
7) CHANGE THE GLOBAL SYSTEM FOR RESEARCH
AND DEVELOPMENT (R&D) AND FOR PRICING OF
MEDICINES, TO ENSURE ACCESS FOR ALL TO
APPROPRIATE AND AFFORDABLE MEDICINES
Relying on intellectual property as the only stimulus for R&D keeps the
monopoly on making and pricing medicines in the hands of big pharmaceutical
companies. This endangers lives and leads to a wider gap between rich
and poor.
Governments and international institutions should agree to:
• Agree a global R&D treaty which makes public health – not commercial
interest – the decisive factor in financing R&D;
• Allocate a percentage of their national income to scientific research,
including R&D for medicines;
• Exclude strict intellectual property rules from trade agreements and refrain
from all measures that limit government’s policy space to implement
public health measures and increase their access to medicine, medical
technologies, knowledge, health and education services;
• Break monopolies and encourage affordable pricing of medicines via
generic competition;
• Scale-up investment in national medicine policy development and drug
supply chains.
Pharmaceutical companies should agree to:
• Be transparent about the cost of R&D, and look for new ways to finance R&D
beyond intellectual property;
• Stop national and international lobbying for private corporate gains at the
expense of public health.
119
SECTION 1 2 3 TIME TO ACT
8) IMPLEMENT A UNIVERSAL SOCIAL
PROTECTION FLOOR
Social protection is central not only to reducing economic inequality, but also
as a way to make society more caring and egalitarian, and to address horizontal
inequalities. For the very poorest and most vulnerable there must be a universal
and permanent safety net that is there for them in the worst times.
Governments and international institutions should agree to:
• Provide universal child and elderly care services, to reduce the burden of
unpaid care work on women and complement social protection systems;
• Provide basic income security for children, the elderly and those who are
unemployed or unable to earn a decent living, through universal child
benefits, unemployment benefits and pensions;
• Ensure the provision of gender-sensitive social protection mechanisms
to provide a safety net for women, in ways that provide an additional means
of control over household spending.
9) TARGET DEVELOPMENT FINANCE TOWARDS
REDUCING INEQUALITY AND POVERTY, AND
STRENGTHENING THE COMPACT BETWEEN
CITIZENS AND THEIR GOVERNMENT
Finance for development has the potential to reduce inequality when it is well-
targeted; when it complements government spending on public services, such
as healthcare, education and social protection. It can also help strengthen
the government–citizen compact, improve public accountability and support
citizen efforts to hold their government to account.
Donor governments and international institutions should
agree to:
• Increase investment in long-term, predictable development finance,
supporting governments to provide universal free public services for
all citizens;
• Invest in strengthening public administrations to raise more domestic
revenue, through progressive taxation for redistributive spending;
• Measure programmes on how well they strengthen democratic participation
and the voice of people to challenge economic and social inequalities (such
as gender and ethnicity).
120
SECTION 1 2 3 NOTES
15. ‘Forbes (2014) ‘The World’s Billionaires’,
NOTES
16. M. Nsehe (2014) ‘The African Billionaires 2014’,.
com/sites/mfonobongnsehe/2014/03/04/the-african-
1. Based on ‘Figure 4.4: Levels of infant mortality rate in 2007 by billionaires-2014; Calculations by L. Chandy and H. Kharas,
province’, in UNDP and Statistics South Africa, ‘MDG 4: Reduce The Brookings Institution. Using revised PPP calculations
Child Mortality’, from earlier this year, this figure estimates a global poverty
GOAL%204-REDUCE%20CHILD%20MORTALITY.pdf line of $1.55/day at 2005 dollars,
blogs/up-front/posts/2014/05/05-data-extreme-
2. National Planning Commission, ‘Divisive effects of povertychandy-kharas
institutionalised racism’,.
asp?relid=85; and World Bank (2006) ‘World Development 17. The WHO calculated that an additional $224.5bn would have
Report 2006: Equity and Development’, World Bank Group, allowed 49 low-income countries to significantly accelerate progress towards meeting health-related MDGs and this
WDSContentServer/IW3P/IB/2005/09/20/ could have averted 22.8 million deaths in those countries.
000112742_20050920110826/Rendered/ Thirty nine out of 49 countries would have been able to reach
PDF/322040World0Development0Report02006.pdf the MDG 4 target for child survival, and at least 22 countries
would have been able to achieve their MDG 5a target for
3. Statistics South Africa (2012) ‘Census 2011’, maternal mortality. WHO (2010) ‘Constraints to Scaling Up the Health Millennium Development Goals: Costing and Financial
P030142011.pdf Gap Analysis’, Geneva: World Health Organization,
4. B. Harris et al (2011) ‘Inequities in access to health care
in South Africa’, Journal of Public Health Policy (2011) WHO_finalreport.pdf A 1.5 percent tax on the wealth of the
32, S102–23, world’s billionaires (applied to wealth over $1bn) between
v32/n1s/full/jphp201135a.html 2009 and 2014 would have raised $252bn. Oxfam calculations
based on Forbes data (all prices in 2005 dollars).
5. P. Piraino (2014) ‘Intergenerational earnings mobility and
equality of opportunity in South Africa’, Southern Africa 18. A 1.5 percent tax on billionaires’ wealth over $1bn in 2014
Labour and Development Research Unit, University of would raise $74bn, calculated using wealth data according
Cape Town, to Forbes as of 4 August 2014. The current annual funding
handle/11090/696/2014_131_Saldruwp.pdf?sequence=1 gap for providing Universal Basic Education is $26bn a year
according to UNESCO, and the annual gap for providing key
6. World Bank (2006) op. cit. health services (including specific interventions such as
maternal health, immunisation for major diseases like HIV/
7. Gini data from World Bank database. Gini coefficient AIDS, TB and malaria, and for significant health systems
for South Africa was 0.56 in 1995 and 0.63 in 2009, strengthening to see these and other interventions delivered) in 2015 is $37bn a year according to WHO. See
8. B. Milanovic (2009) ‘Global Inequality and the Global Inequality UNESCO (2014) ‘Teaching and Learning: Achieving Quality for
Extraction Ratio: The Story of the Past Two Centuries’ Policy All 2013/14’, EFA Global Monitoring Report,.
Research Working Paper 5044, Washington, D.C: World Bank, unesco.org/images/0022/002256/225660e.pdf, and WHO (2010), op. cit.
1813-9450-5044 19. To derive the Gini coefficients, the authors took the poverty
9. Calculated based on B. Milanovic (2013) ‘All the Ginis Dataset headcounts and the mean income/consumption figures for
(Updated June 2013)’, 2010, and established what Gini coefficient is compatible
EXTERNAL/EXTDEC/EXTRESEARCH/0,,contentMDK:22301380~ with those two numbers if income/consumption has a
pagePK:64214825~piPK:64214943~theSitePK:469382,00.html lognormal distribution in the country (i.e. if log income/
consumption follows a bell curve). Gini coefficients were
10. F. Alvaredo, A. B. Atkinson, T. Piketty and E. Saez (2013) India (0.34), Indonesia (0.34) and Kenya (0.42). For the GDP/
‘The World Top Incomes Database’, capita projections, the authors used IMF World Economic Outlook April 2014 current-dollar PPP figures, adjusted for
US CPI inflation in 2010–12. For the poverty projections,
11. Warren Buffett, in an interview for CNN, September 2011. the authors used those done by The Brookings Institution,
12. Credit Suisse (2013) ‘Global Wealth Report 2013’, Zurich: using Brookings spreadsheet, ‘Country HC & HCR revisions –
Credit Suisse,. 05.14’, received 21 July 2014; except China, India, Indonesia
com/tasks/render/file/?fileID=BCDB1364-A105-0560- headcounts from L. Chandy e-mail, 22 July 2014; 2010 means
1332EC9100FF5C83; and Forbes’ ‘The World’s Billionaires’, from Brookings spreadsheet, ‘Poverty means_2010’, received (accessed on 16 22 July 2014; conversion factors from GDP/capita growth to
December 2013). When this data was updated a few months mean consumption/income growth from L. Chandy, N. Ledlie
later by Forbes, the rich had already become richer and it and V. Penciakova (2013) op. cit., p.17. For these projections
took just the richest 66 people to equal the wealth of the the authors have used the global extreme poverty line of
poorest. The disparities between the rich and the poor have $1.79 in 2011 dollars ($1.55 in 2005 dollars) because of the
become increasingly evident. anticipated adjustment in the global extreme poverty line
forbesinsights/2014/03/25/the-67-people-as-wealthy-as- (up from $1.25). $1.79 was calculated by The Brookings
the-worlds-poorest-3-5-billion Institution based on new data from the International Price
Comparison Programme and the World Bank’s extreme
13. Forbes (2014) ‘The World’s Billionaires’, op. cit. (accessed in poverty line methodology. For more information see:
March 2013, March 2014 and August 2014).
05-data-extreme-poverty-chandy-kharas
14. Forbes (2014) ‘The World’s Billionaires: #2 Bill Gates’, 20. Ibid.
(accessed August 2014).
121
SECTION 1 2 3 NOTES
21. Based on unpublished calculations by L. Chandy using 32. R. Wilkinson and K. Pickett (2010) The Spirit Level: Why
the same methodology as used in L. Chandy, N. Ledlie Equality is Better for Everyone, London: Penguin, p.59.
and V. Penciakova (2013) ‘The Final Countdown:
Prospects for Ending Extreme Poverty By 2030’, 33. E. Godoy (2010) ‘Millennium Goals Far Off for Mexico’s
Washington, D.C.: The Brookings Institution, Indigenous Population’, Inter Press Service, 18 October,-
Reports/2013/04/ending%20extreme%20poverty% mexicos-indigenous-population/
20chandy/The_Final_Countdown.pdf 34. The Demographic and Health Surveys Program,
22. Africa Progress Panel (2012) ‘Jobs, Justice and Equity;
Seizing Opportunities In Times of Global Change’, Switzerland: 35. The Demographic and Health Surveys Program (2011)
Africa Progress Panel, p.6, ‘Ethiopia: Standard DHS, 2011’,
publications/policy-papers/africa-progress-report-2012 what-we-do/survey/survey-display-359.cfm
23. Africa Progress Panel (2013) ‘Africa Progress 36. R. Wilkinson (2011) ‘How economic inequality harms
Report 2013: Equity in Extractives – Stewarding societies’, TED Talk,
Africa’s natural resources for all’, Geneva: Africa
Progress Panel, 37. M. Corak (2012) ‘Inequality from Generation to Generation:
wp-content/uploads/2013/08/2013_APR_Equity_in_ The United States in Comparison’,.
Extractives_25062013_ENG_HR.pdf wordpress.com/2012/01/inequality-from-generation-to-
generation-the-united-states-in-comparison-v3.pdf
24. K. Deininger and L. Squire (1998) ‘New ways of looking at
old issues: inequality and growth’, Journal of Development 38. S. A. Javed and M. Irfan (2012) ‘Intergenerational Mobility:
Economics, 57(2):259–287; A. Alesina and D. Rodrik (1994) Evidence from Pakistan Panel Household Survey’, Islamabad:
‘Distributive Politics and Economic Growth’, The Quarterly Pakistan Institute of Development Economics, p.13–14,
Journal of Economics 109(2):465–90; R. Benabou (1996)
‘Inequality and Growth’, Working Paper 96-22, C.V. Starr
Center for Applied Economics, New York: New York University, 39. J. Stiglitz (2012) The Price of Inequality: How Today’s Divided; Society Endangers Our Future, Penguin, p.23.
A. Banerjee and E. Duflo (2003) ‘Inequality and Growth: 40. World Economic Forum (2014) ‘Global Risks 2013’,
What can the data say?’, NBER Working Papers, Cambridge: Switzerland: World Economic Forum, p.9,.
National Bureau of Economic Research, weforum.org/docs/WEF_GlobalRisks_Report_2014.pdf; J. Ostry, A. Berg and
C. Tsangardies (2014) ‘Redistribution, Inequality and Growth’, 41. S.V. Subramanian and I. Kawachi (2006) ‘Whose health is
IMF staff discussion note, IMF, affected by income inequality? A multilevel interaction; analysis of contemporaneous and lagged effects of state
Asian Development Bank (ADB) (2014) ‘ADB’s support for income inequality on individual self-rated health in the
inclusive growth’, Thematic Evaluation Study, ADB, United States’, Health and Place, 2006 Jun;12(2):141–56.
42. R. Wilkinson and K. Pickett (2010) op. cit., p.25. Wilkinson and
25. See, for example, A. Berg and D. Ostry (2011) ‘Warning! Pickett’s research focused on OECD countries (a grouping
Inequality May Be Hazardous to Your Growth’, of rich countries), yet the same negative correlation- between inequality and social well-being holds true
and-growth; T. Persson and G. Tabellini (1994) ‘Is Inequality in poorer countries.
Harmful for Growth?’, American Economic Review 84(3):
600–621; A. Alesina and D. Rodrik (1994) ‘Distributive Politics 43. N. Hanauer (2014) ‘The Pitchforks are Coming … For Us
and Economic Growth’, The Quarterly Journal of Economics Plutocrats’,
(1994) 109 (2): 465–90. the-pitchforks-are-coming-for-us-plutocrats-108014.
html#.U_S56MVdVfY
26. M. Kumhof and R. Rancière (2010) ‘Inequality,
Leverage and Crises’, IMF Working Paper, IMF, 44. UN Office on Drugs and Crime (UNODC) (2011) ‘Global Study on Homicide’, Vienna: UNODC,
27. F. Ferreira and M. Ravallion (2008) ‘Global Poverty and Homicide/Globa_study_on_homicide_2011_web.pdf
Inequality: A review of the evidence’, Policy Research
Working Paper 4623, Washington, D.C.: The World Bank 45. UNDP (2013) ‘Human Development Report for Latin America
Development Research Group Poverty Team,. 2013–2014’, New York: UNDP,
worldbank.org/doi/pdf/10.1596/1813-9450-4623 content/rblac/en/home/idh-regional
28. Data based on World Bank, ‘World Development Indicators’, 46. J. Stiglitz (2012) op. cit., p.105.- 47. P. Engel, C. Sterbenz and G. Lubin (2013) ‘The 50 Most Violent
development-indicators Cities in the World’, Business Insider, 27 November,
29. E. Stuart (2011) ‘Making Growth Inclusive’, Oxford: Oxfam-
International,; R. Gower, C. Pearce and the-world-2013-11?op=1
K. Raworth (2012) ‘Left Behind By the G20? How inequality 48. UNDP (2013) op. cit.
and environmental degradation threaten to exclude poor
people from the benefits of economic growth’, Oxford: Oxfam, 49. T. Dodge (2012) ‘After the Arab Spring: Power Shift in the Middle East?’, LSE Ideas,
publications/reports/SR011.aspx
30. F. Ferreira and M. Ravallion (2008) op. cit.
50. Latinobarometro (2013) ‘Latinobarómetro Report 2013’,
31. Ibid.
122
SECTION 1 2 3 NOTES
51. M. Carney (2014) ‘Inclusive Capitalism: Creating a sense of 68. P. De Wet (2014) ‘Mining strike: The bosses eat, but we are
the systemic’, speech given by Mark Carney, Governor of the starving’, Mail & Guardian,-
Bank of England, at the Conference on Inclusive Capitalism, 15-mining-strike-the-bosses-eat-but-we-are-starving
London, 27 May.
69. International Trade Union Congress (2014) ‘Frontlines Report’,
52. For more on this see: T. Piketty (2014) Capital in the Twenty ITUC,-
First Century, Cambridge: Harvard University Press. 14549?lang=en
53. Speaking at the opening session of the 27th international 70. R. Wilshaw et al (2013) ‘Labour Rights in Unilever’s Supply
congress of CIRIEC, Sevilla 22-24 September, 2008, Chain: From compliance to good practice’, Oxford: Oxfam,--
8292.2009.00389.x.pdf supply-chain; R. Wilshaw (2013) ‘Exploring the Links between
International Business and Poverty Reduction: Bouquets
54. UNCTAD (2012) ‘Trade and Development Report, 2012’, and beans from Kenya’, Oxford: Oxfam and IPL, http://
Geneva: United Nations, p.V, oxfam.org/sites/oxfam.org/files/rr-exploring-links-ipl-
PublicationWebflyer.aspx?publicationid=210 poverty-footprint-090513-en.pdf; IDH (2013) ‘Understanding
55. K. Watkins (1998) ‘Economic Growth with Equity: Lessons Wage Issues in the Tea Industry, Oxfam and Ethical Tea
from East Asia’, Oxford: Oxfam, p.75, Partnership’, Oxford: Oxfam,
policy/understanding-wage-issues-tea-industry
56. D. Ukhova (2014) ‘After Equality: Inequality trends and policy
responses in contemporary Russia’, Oxford: Oxfam, 71. ILO (2011) ‘A new era of social justice, Report of the Director- General, Report I(A)’, International Labour Conference, 100th
Session, Geneva, 2011.
57. J. Stiglitz (2012) op. cit., p.160.
72. L. Mishel and M. Walters (2003) ‘How Unions Help all Workers’,
58. M.F. Davis (2012) ‘Occupy Wall Street and international human EPI,
rights’, School of Law Faculty Publications, Paper 191, 73. Source: Instituto de Pesquisa Economica Aplicada,
and Departamento Intersindical de Estatica e Estudos
59. S. Tavernise (2010) ‘Pakistan’s Elite Pay Few Taxes, Widening Socioeconomicas, Brazil,. An online
Gap’, The New York Times, data set produced by IPEA, see also:
world/asia/19taxes.html?pagewanted=all&_r=0
74. Economist Intelligence Unit (2013) ‘Ecuador: Quick
60. M. Wolf, K. Haar and O. Hoedeman (2014) ‘The Fire Power of View – Minimum wage rise in the pipeline’, the
the Financial Lobby: A Survey of the Size of the Financial Economist,.
Lobby at the EU level’, Corporate Europe Observatory, The aspx?articleid=1101039494&Country=Ecuador&topic=
Austrian Federal Chamber of Labour and The Austrian Trade Industry&subtopic=Consumer%20goods
Union Federation,
default/files/attachments/financial_lobby_report.pdf 75. S. Butler (2014) ‘Chinese shoppers’ spend could double to
£3.5tn in four years’, the Guardian,
61. Carlos Slim’s near-monopoly over phone and internet business/2014/jun/03/chinese-shoppers-spend-double-
services charges some of the highest prices in the OECD, four-years-clothing-western-retailers
undermining access for the poor. OECD (2012) ‘OECD Review
of Telecommunication Policy and Regulation in Mexico’, OECD 76. Wagemark, ‘A brief history of wage ratios’,
Publishing,
62. UNRISD (2010) ‘Combating Poverty and Inequality’, Geneva: 77. ECLAC (2014) ‘Compacts for Equality: Towards a
UNRISD/UN Publications, Sustainable Future’, Thirty-fifth Session of ECLAC,
63. IDH (2014) ‘Raising wages for tea industry workers’, presentation/files/ppt-pactos-para-la-igualdad-ingles.pdf
case study,. The Gini coefficient is a measure of inequality where a rating
php?id=497 of 0 represents total equality, with everyone taking an
equal share, and a rating of 1 would mean that one person
64. In addition to the millions of men and women whose has everything.
livelihoods depend on waged income, around 1.5 billion
households depend on smallholder or family farming 78. D. Itriago (2011) ‘Owning Development: Taxation to fight
(including pastoralists, fisherfolk and other small-scale poverty’, Oxford: Oxfam,; IMF (2014)
food producers). While Oxfam works extensively in support ‘Fiscal Policy and Income Inequality’, IMF Policy Paper, Figure
of smallholders (see for example: Oxfam (2011) ‘Growing 8, Washington, D.C.: IMF,
a Better Future: Food Justice in a Resource-constrained eng/2014/012314.pdf
World’, Oxfam,
growing-better-future), this report is primarily concerned 79. Oxfam new calculations based on IMF calculations on tax
with issues facing people on low incomes in waged labour. effort and tax capacity. A simulation has been undertaken
to estimate how much revenue could be collected if the tax
65. J. Ghosh (2013) ‘A Brief Empirical Note of the Recent revenue gap is reduced by 50 percent by 2020. Assuming
Behaviour of Factor Shares in National Income, that GDP (in $ at current prices) expands at the same average
Global & Local Economic Review, 17(1), p.146, annual growth rate recorded in the biennium 2011–2012; and that tax capacity remains constant at the level presented
in IMF figures.
66. High Pay Centre,
(accessed August 2014). 80. J. Watts (2013) ‘Brazil protests: president to hold
emergency meeting’, the Guardian,
67. Living Wage Foundation, ‘Living Wage Employers’,- protests-president-emergency-meeting
123
SECTION 1 2 3 NOTES
81. Institute of Policy Analysis and Research-Rwanda (2011) 94. G. Verbist, M. F. Förster and M. Vaalavuo (2012) ‘The
‘East African Taxation Project: Rwanda Country Case Impact of Publicly Provided Services on the Distribution
Study’, IPAR-Rwanda, of Resources: Review of New Results and Methods’, OECD
actionaid/rwanda_case_study_report.pdf Social, Employment and Migration Working Papers, No. 130,
OECD Publishing, p.60,-
82. See US Senate Committee, Homeland Security & issues-migration-health/the-impact-of-publicly-provided-
Governmental Affairs (2013) ‘Permanent Sub-Committee on services-on-the-distribution-of-resources_
Investigations, May 2013 Hearing Report, 15 October 2013’, 5k9h363c5szq-en
media/levin-mccain-statement-on-irelands-decision-to- 95. N. Lustig (2012) ‘Taxes, Transfers, and Income Redistribution
reform-its-tax-rules in Latin America’, Inequality in Focus 1(2): July 2012, World
Bank,
83. See UK Parliament, Public Accounts Committee inquiry, HM Resources/InequalityInFocusJuly2012FINAL.pdf
Revenue and Customs Annual Report and Accounts, Inquiry
Tax Avoidance by Multinational Companies, November 2012, 96. OECD Secretariat (2010) ‘Growth, Employment and Inequality in Brazil, China, India and South Africa: An Overview’, OECD,
cmpubacc/716/71605.htm. Also
Ramos showed that between 1995 and 2005 education
84. For full details of Oxfam’s calculations and methodology was the most important element explaining the decline in
see: Oxfam (2013) ‘Tax on the ‘private’ billions now stashed wage inequality in Brazil. See: Ramos (2006) ‘Desigualdade
away in havens enough to end extreme world poverty de rendimentos do trabalho no Brasil, de 1995 a 2005’ in R.
twice over’, 22 May, Barros, M. Foguel and G. Ulyssea (eds.) Sobre a recente queda
pressreleases/2013-05-22/tax-private-billions-now- da desigualdade de renda no Brasil, Brasília: IPEA.
stashed-away-havens-enough-end-extreme
97. H. Lee, M. Lee and D. Park (2012) ‘Growth Policy and Inequality
85. President Obama, Remarks by the President on International in Developing Asia: Lesson from Korea’, ERIA Discussion
Tax Policy Reform 4 May 2009, Paper Series,
press_office/Remarks-By-The-President-On-International-
Tax-Policy-Reform 98. K. Xu et al (2007) ‘Protecting households from catastrophic
health spending’, Health Affairs, 26(4): 972–83.
86. EquityBD (2014) ‘Who Will Bell the Cat? Revenue Mobilization,
Capital Flight and MNC’s Tax Evasion in Bangladesh’, Position 99. C. Riep (2014) ‘Omega Schools Franchise in Ghana:
Paper, Dhaka: Equity and Justice Working Group, “affordable” private education for the poor or for-; profiteering?’ in I. Macpherson, S. Robertson and G. Walford
see also: C. Godfrey (2014) ‘Business among friends: (eds.) (2014) Education, Privatisation and Social Justice:
Why corporate tax dodgers are not yet losing sleep over case studies from Africa, South Asia and South east Asia,
global tax reform’, Oxford: Oxfam, Oxford: Symposium Books,
books/bookdetails.asp?bid=88
87. Analysis from Forum Civil, Oxfam partner in Senegal working
on fair taxation, 100. The research undertaken by Justice Quereshi concluded
India’s corporate hospitals were ‘money minting machines’.
88. For more details see: C. Godfrey (2014) op. cit. From Qureshi, A.S. (2001) ‘High Level Committee for Hospitals
89. IMF (2014) ‘Spillovers in International Corporate Taxation’, in Delhi’, New Delhi: Unpublished Report of the Government
IMF Policy Paper, of Delhi.
eng/2014/050914.pdf 101. A. Marriott (2014) ‘A Dangerous Diversion: will the IFC’s
90. S. Picciotto, ‘Towards Unitary Taxation of Transnational flagship health PPP bankrupt Lesotho’s Ministry of Health?’,
Corporations’, Tax Justice Network, (December 2012), Oxford: Oxfam, 102. A. Marriott (2009) ‘Blind Optimism: Challenging the myths
Taxation_1-1.pdf about private health care in poor countries’, Oxford: Oxfam,
91. C. Adams (1993) For Good and Evil: The Impact of Taxes on the; World Bank (2008) ‘The Business of
Course of Civilization, Lanham: Madison Books. Health in Africa : Partnering with the Private Sector to
Improve People’s Lives’, International Finance Corporation,
92. The European Commission proposed a tax of 0.1 percent Washington, DC: World Bank,.
on transactions of shares and bonds and 0.01 percent on org/curated/en/2008/01/9526453/business-health-africa-
derivatives. See: partnering-private-sector-improve-peoples-lives
taxation/other_taxes/financial_sector/index_en.htm;
The German Institute for Economic Research (DIW) 103. R. Rannan-Eliya and A. Somantnan (2005) ‘Access
calculated that this would raise €37.4bn,. of the Very Poor to Health Services in Asia: Evidence
de/documents/publikationen/73/diw_01.c.405812.de/ on the role of health systems from Equitap’, UK: DFID
diwkompakt_2012-064.pdf Health Systems Resource Centre,
home&id=19917&type=Document#.VBBtVsJdVfY
93. A 1.5 percent tax on billionaires’ wealth over $1bn in 2014
would raise $74bn, calculated using wealth data according 104. A. Cha and A. Budovich (2012) ‘Sofosbuvir: A New Oral Once-
to Forbes as of 4 August 2014. The current annual funding Daily Agent for The Treatment of Hepatitis C Virus Infection’,
gap for providing Universal Basic Education is $26bn a year Pharmacy & Therapeutics 39(5): 345–352,.
according to UNESCO, and the annual gap for providing key nih.gov/pmc/articles/PMC4029125
health services (including specific interventions such as 105. Speech by World Bank Group President Jim Yong Kim at the
maternal health, immunisation for major diseases like HIV/ Government of Japan-World Bank Conference on Universal
AIDS, TB and malaria, and for significant health systems Health Coverage, Tokyo, 6 December 2013,.
strengthening to see these and other interventions org/en/news/speech/2013/12/06/speech-world-bank-
delivered) in 2015 is $37bn a year according to WHO. group-president-jim-yong-kim-government-japan-
See: UNESCO (2014) op.cit., and WHO (2010) op. cit. conference-universal-health-coverage
124
SECTION 1 2 3 NOTES
106. S. Limwattananon et al (2011) ‘The equity impact of 118. I. Osei-Akoto, R. Darko Osei and E. Aryeetey (2009) ‘Gender
Universal Coverage: health care finance, catastrophic and Indirect tax incidence in Ghana’, Institute of Statistical,
health expenditure, utilization and government subsidies Social and Economic Research (ISSER) University of Ghana,
in Thailand’, Consortium for Research on Equitable referenced in J. Leithbridge (2012) ‘How women are being
Health Systems, Ministry of Public Health, affected by the Global Economic Crisis and austerity measures’, Public Services International Research Unit,
University of Greenwich,
107. See BBC News, Business (2013) ‘Novartis: India rejects sites/default/files/upload/event/EN_PSI_Crisis_Impact_
patent plea for cancer drug Glivec’, 1 April, Austerity_on_Women.pdf
119. D. Elson and R. Sharp (2010) ‘Gender-responsive budgeting
108. L. Bategeka and N. Okurut (2005) ‘Universal Primary and women’s poverty’, in: S. Chant (ed.) (2010) International
Education: Uganda’, Policy brief 10, London: Overseas Handbook of Gender and Poverty: Concepts, Research, Policy,
Development Institute, Cheltenham: Edward Elgar, p.524–25.
files/odi-assets/publications-opinion-files/4072.pdf
120. P. Fortin, L. Godbout and S. St-Cerny (2012) ‘Impact
109. B. Bruns, D. Evans and J. Luque (2012) ‘Achieving World of Quebec’s Universal Low Fee Childcare Program on
Class Education in Brazil: The Next Agenda’, Washington Female Labour Force Participation, Domestic Income and
D.C.: The World Bank, Government Budgets’, Université de Sherbrooke, Working
BRAZILINPOREXTN/Resources/3817166-1293020543041/ Paper 2012/02,
FReport_Achieving_World_Class_Education_Brazil_ fileadmin/sites/chaire-fiscalite/documents/Cahiers-de-
Dec2010.pdf recherche/Etude_femmes_ANGLAIS.pdf
110. K. Watkins and W. Alemayehu (2012) ‘Financing for a Fairer, 121. W. Wilson (2012) ‘Just Don’t Call Her Che’, The New York
More Prosperous Kenya: A review of the public spending Times,
challenges and options for selected Arid and Semi-Arid student-protests-rile-chile.html?pagewanted=all&_r=0
counties’, The Brookings Institution,
research/reports/2012/08/financing-kenya-watkins 122. CIVICUS (2014) ‘State of Civil Society Report 2014: Reimagining
Global Governance’,
111. G. Ahobamuteze, C. Dom and R. Purcell (2006) ‘Rwanda uploads/2013/04/2013StateofCivilSocietyReport_full.pdf
Country Report: A Joint Evaluation of General Budget Support
1994–2004’, 123. Oxfam’s polling from across the world captures the belief
uploads/attachment_data/file/67830/gbs-rwanda.pdf of many that laws and regulations are now designed to
benefit the rich. A survey in six countries (Spain, Brazil, India,
112. Z. Chande (2009) ‘The Katete Social Pension’, unpublished South Africa, the UK and the USA) showed that a majority of
report prepared for HelpAge International, cited in S. Kidd people believe that laws are skewed in favour of the rich –
(2009) ‘Equal pensions, Equal rights: Achieving universal in Spain eight out of 10 people agreed with this statement.
pension coverage for older women and men in developing Also see Latinobarometro 2013:
countries’, Gender & Development, 17:3, 377–88,
124. OECD (2014) ‘Society at a Glance: OECD Social Indicators’,
113. ILO (2014) ‘World Social Protection Report 2014/15: Building
economic recovery, inclusive development and social
justice’, Geneva: ILO,- 125. CIVICUS, ‘Civil Society Profile: Chile’,
reports/world-social-security-report/2014/WCMS_245201/
lang--en/index.htm
126. G. Long (2014) ‘Chile’s student leaders come of age’,
114. ILO (2008) ‘Can low-income countries afford basic social BBC News,-
security?’, Social Security Policy Briefings, Geneva: ILO, america-26525140
127. CIVICUS (2014) ‘Citizens in Action 2011: Protest as
115. S. Wakefield (2014) ‘The G20 and Gender Equality: How the Process in The Year of Dissent’, p.53,
G20 can advance women’s rights in employment, social cdn/2011SOCSreport/Participation.pdf
protection and fiscal policies’, Oxford: Oxfam International
and Heinrich Böll Foundation, p.7, 128. Based on ‘Figure 4.4: Levels of infant mortality rate in 2007 by
province’, in UNDP and Statistics South Africa, ‘MDG 4: Reduce
116. See: A. Elomäki (2012) ‘The price of austerity – the impact Child Mortality’,
on women’s rights and gender equality in Europe’, GOAL%204-REDUCE%20CHILD%20MORTALITY.pdf
European Women’s Lobby,
spip.php?action=acceder document&arg=2053&cle= 129. National Planning Commission, op. cit; World Bank (2006)
71883f01c9eac4e73e839bb512c87e564b5dc735&file= op. cit.
pdf%2Fthe_price_of_austerity_-_web_edition.pdf 130. Statistics South Africa (2012) op. cit.
117. A. Elomäki (2012) op. cit. In 2010, the employment rate for 131. B. Harris et al (2011) ‘Inequities in access to health care in
women with small children was 12.7 percent lower than South Africa’, Journal of Public Health Policy (2011) 32, S102–
women with no children, compared to 11.5 percent lower in 23,
2008. In 2010, 28.3 percent of women’s economic inactivity full/jphp201135a.html
and part-time work was explained by the lack of care
services against 27.9 percent in 2009. In some countries 132. P. Piraino (2014) op. cit.
the impact of the lack of care services has increased
significantly. In Bulgaria it was up to 31.3 percent in 2010 133. World Bank (2006) op. cit.
from 20.8 percent in 2008; in the Czech Republic up to 16.7 134. Africa Progress Panel (2012) op. cit.
percent from 13.3 percent.
135. Warren Buffett, in an interview for CNN, September 2011.
136. Calculated based on B. Milanovic (2013) op. cit.
125
SECTION 1 2 3 NOTES
137. Gini data from World Bank database, Gini coefficient 154. N. Hanauer (2014) ‘The Pitchforks are Coming … For Us
for South Africa was 0.56 in 1995 and 0.63 in 2009, Plutocrats’, Politico, story/2014/06/the-pitchforks-are-coming-for-us-
plutocrats-108014.html#.U_S56MVdVfY
138. For a further discussion of the relative merits of these
measures see A. Sumner and A. Cobham (2013) ‘On inequality, 155. Forbes (2014) ‘The World’s Billionaires: #2 Bill Gates’,
let’s do the Palma, (because the Gini is so last century)’,- (accessed August 2014).
palma-because-the-gini-is-so-last-century
156. Wealth-X and UBS (2013) ‘Wealth-X and UBS Billionaire
139. B. Milanovic (2009) op. cit. Census 2013’,
140. M. Cummins and I. Ortiz (2011) ‘Global Inequality: Beyond 157. Forbes (2014) ‘The World’s Billionaires: #2 Bill Gates’,
the Bottom Billion’, Social and Economic Working Paper,
New York: Unicef, (correct as of August 2014).
Global_Inequality.pdf
158. Wealth data from Forbes
141. Ibid. Population data is for 2007 or most recently available (),
data, in PPP constant 2005 international dollars according as of 4 August 2014. Calculations by Oxfam. Percentage
to the global accounting model. return rates are indicative of what could be earned in
a modest fixed-rate low risk return account, 5.35 percent
142. Calculated based on B. Milanovic (2013) op. cit. reflects what these more savvy investors achieved in a year
143. Based on available data over the past 30 years. F. Alvaredo, between July 2012 and June 2013. See: Wealth-X and UBS
A. B. Atkinson, T. Piketty and E. Saez (2013) ‘The World Census (2013) op. cit.
Top Incomes Database’,. 159. See:
parisschoolofeconomics.eu
160. Oxfam calculations, based on Wealth data from Forbes,
144. Calculated using World Bank data (accessed 2 July 2014) downloaded 4 August 2014. French GDP in 2013 was $2.7tn,
and F. Alvaredo, A. B. Atkinson, T. Piketty and E. Saez (2013) based on IMF Word Economic Outlook.
op. cit. The combined total of the bottom 40 percent across
Nigeria, India, and China is 1,102,720,000. 161. The WHO calculated that an additional $224.5bn would have
allowed 49 low-income countries to significantly accelerate
145. Calculated using World Bank data (accessed 2 July 2014) progress towards meeting health-related MDGs and this
and F. Alvaredo, A. B. Atkinson, T. Piketty and E. Saez (2013) could have averted 22.8 million deaths in those countries.
op. cit. The combined total of the bottom 40 percent across Thirty nine out of 49 countries would have been able to reach
Nigeria, India, and China is 1,102,720,000. the MDG 4 target for child survival, and at least 22 countries
146. Merrill Lynch and CapGemini (2013), Capgemini Lorenz would have been able to achieve their MDG 5a target for
Curve Analysis, 2013, New York: CapGemini, maternal mortality. WHO (2010) op. cit. A 1.5 percent tax on the wealth of the world’s billionaires (applied to wealth over
$1bn) between 2009 and 2014 would have raised $252bn.
147. Forbes (2014) ‘The World’s Billionaires’, Oxfam calculations based on Forbes data (all prices in 2005 dollars).
148. A. Gandhi and M. Walton (2012) ‘Where do Indian Billionaires 162. A 1.5 percent tax on billionaires’ wealth over $1bn in 2014
Get Their Wealth’, Economic and Political Weekly, Vol would raise $74bn, calculated using wealth data according
XLVII, No 40, Mumbai: EPW Research Foundation, http:// to Forbes as of 4 August 2014. The current annual funding
michaelwalton.info/wp-content/uploads/2012/10/Where- gap for providing Universal Basic Education is $26bn a year
Do-Indias-Billionaires-Get-Their-Wealth-Aditi-Walton.pdf according to UNESCO, and the annual gap for providing key
health services (including specific interventions such as
149. Forbes (2013) ‘India’s Richest List’, maternal health, immunisation for major diseases like HIV/ AIDS, TB and malaria, and for significant health systems
150. M. Nsehe (2014) ‘The African Billionaires 2014’, strengthening to see these and other interventions delivered) in 2015 is $37bn a year according to WHO.
the-african-billionaires-2014 See: UNESCO (2014) op.cit., and WHO (2010) op. cit.
151. Calculations by Laurence Chandy and Homi Kharas, Brookings 163. A quarter of the world’s 1.1 billion poor people are landless.
Institution. Using revised PPP calculations from earlier this See: International Fund for Agricultural Development (IFAD)
year, this figure estimates a global poverty line of $1.55/day ‘Empowering the rural poor through access to land’, Rome:
at 2005 dollars. L. Chandy and H. Kharas (2014) ‘What Do New IFAD,
Price Data Mean for the Goal of Ending Extreme Poverty?’, 164. L. Ravon (forthcoming, 2014) ‘Resilience in the Face of- Food Insecurity: Reflecting on the experiences of women’s
data-extreme-poverty-chandy-kharas organizations’, Oxfam Canada.
152. Credit Suisse (2013) ‘Global Wealth Report 2013’, Zurich: 165. The World Bank (2008) ‘World Bank Development Report 2008:
Credit Suisse,. Agriculture for Development’, Washington, D.C.: The World
com/tasks/render/file/?fileID=BCDB1364-A105-0560- Bank,
1332EC9100FF5C83; and Forbes’ ‘The World’s Billionaires’, Resources/WDR_00_book.pdf (accessed on 16
December 2013). 166. Russia Today (2013) ‘Sugar producer tops Russia’s largest
landowner list’, 17 May,-
153. Forbes (2014) ‘The World’s Billionaires’, op. cit. (accessed largest-land-sugar--428
in March 2013, March 2014 and August 2014).
167. Defined here as over 100 hectares.
126
SECTION 1 2 3 NOTES
168. The Transnational Institute (TNI) for European Coordination 182. K. Deininger and L. Squire (1998) op. cit.; A. Alesina
Via Campesina and Hands Off the Land Network (2013) ‘Land and D. Rodrik (1994) op. cit.; R. Benabou (1996) op. cit.;
Concentration, land-grabbing and people’s struggles in A. Banerjee and E. Duflo (2003) op. cit.; J. Ostry, A. Berg and
Europe’, C. Tsangardies (2014) op. cit.; Asian Development Bank (2014)
op. cit.
169. FAO (2013) ‘The State of Food Insecurity in the World 2013:
The multiple dimensions of food insecurity’, Rome: Food 183. A. Berg and J. Ostry (2011) ‘Inequality and Unstable Growth:
and Agriculture Organization, Two Sides of the Same Coin?’, IMF Staff Discussion Note, IMF,
sofi/2013/en;
J. Ostry, A. Berg and C. Tsangarides (2014), op. cit.
170. To derive the Gini coefficients in Figure 3, the authors took
the poverty headcounts and the mean income/consumption 184. A. Berg and J. Ostry (2011) op. cit.
figures for 2010, and established what Gini coefficient is
compatible with those two numbers if income/consumption 185. M. Kumhof and R. Rancière (2010) ‘Inequality, Leverage
has a lognormal distribution in the country (i.e., if log and Crises’, IMF Working Paper, IMF,
income/consumption follows a bell curve). Gini coefficients
were Brazil (0.54), China (0.35), India (0.34), Indonesia 186. See, for example, A. Berg and D. Ostry (2011) op. cit.;
(0.34), Mexico (0.42), South Africa (0.59) and Kenya (0.42). T. Persson and G.databaseTabellini (1994) ‘Is Inequality
For the GDP/capita projections, the authors used IMF World Harmful for Growth?’, American Economic Review 84(3):
Economic Outlook April 2014 current-dollar PPP figures, 600–621; Alesina and Rodrik (1994), op. cit.
adjusted for US CPI inflation in 2010-12. For the poverty
projections, the authors used those done by The Brookings 187. E. Stuart (2011) ‘Making Growth Inclusive’, Oxford: Oxfam
Institution, using Brookings spreadsheet, ‘Country HC & International,
HCR revisions – 05.14’, received 21 July 2014; except China,
India, Indonesia headcounts from L. Chandy e-mail, 22 July 188. Asian Development Bank (ADB) (2011) op. cit.
2104; 2010 means from Brookings spreadsheet, ‘Poverty 189. F. Ferreira and M. Ravallion (2008) op. cit.
means_2010’, received 22 July 2014; conversion factors
from GDP/capita growth to mean consumption/income 190. Data based on World Bank, ‘World Development Indicators’,
growth from L. Chandy, N. Ledlie and V. Penciakova (2013) op.-
cit., p.17. For these projections the authors have used the development-indicators
global extreme poverty line of $1.79 in 2011 dollars ($1.55
in 2005 dollars) because of the anticipated adjustment in 191. Africa Progress Panel (2013) ‘Africa Progress Report 2013.
the global extreme poverty line (up from $1.25). $1.79 was Equity in Extractives: Stewarding Africa’s natural resources
calculated by The Brookings Institution based on new data for all’, Africa Progress Panel, p.28,
from the International Price Comparison Programme and the
World Bank’s extreme poverty line methodology. For more africa-progress-report-2013
information see: 192. F. Ferreira and M. Ravallion (2008) op. cit.
posts/2014/05/05-data-extreme-poverty-chandy-kharas
193. E. Stuart (2011), op. cit.; R. Gower, C. Pearce and K. Raworth
171. L. Chandy, N. Ledlie and V. Penciakova (2013) op. cit. (2012) ‘Left Behind By the G20? How inequality and
172. Unpublished calculations based on the methodology and environmental degradation threaten to exclude poor people
model developed in L. Chandy, N. Ledlie and V. Penciakova from the benefits of economic growth’, Oxford: Oxfam,
(2013) op. cit.
173. This is comparing the wealth of the bottom half of the 194. Represented by a Gini coefficient of 0.2, a level which many
population from the Credit Suisse yearbook with the Forbes Eastern European countries had in the 1980s and Nordic
data, as downloaded in March 2014. countries have now. F. Ferreira and M. Ravallion (2008) op. cit.
174. See the World Bank’s World database, 195. Represented by a Gini coefficient of 0.6, about the level in Angola.
175. Oxfam’s own calculations. See Note 170. 196. Represented by a Gini coefficient of 0.4, about the level in
Uganda or Singapore.
176. Africa Progress Panel (2013) ‘Africa Progress
Report 2013: Equity in Extractives – Stewarding 197. F. Ferreira and M. Ravallion (2008) op. cit.
Africa’s natural resources for all’, Geneva: Africa 198. K. Raworth (2012) ‘A Safe and Just Space for Humanity:
Progress Panel, Can We Live Within the Doughnut?’, Oxfam Discussion Paper,
wp-content/uploads/2013/08/2013_APR_Equity_in_ Oxford: Oxfam,
Extractives_25062013_ENG_HR.pdf
199. See, for example: D. Hillier and G. Castillo ( 2013)
177. Ibid. ‘No Accident: Resilience and the inequality of risk’,
178. Ibid. Oxford: Oxfam,
179. World Health Organization, Global Health 200. This 30 percent of people consume an average of
Observatory Data Repository, 6.5 global hectares of productive space per person. N. Kakar, Permanent Observer to the United Nations of the
International Union for Conservation of Nature. quoted in
180. Ibid. Royal Government of Bhutan (2012) The Report of the High-
Level Meeting on Wellbeing and Happiness: Defining a New
181. This is part of the theory behind Nobel prize-winning Economic Paradigm, New York: The Permanent Mission of
economist Simon Kuznets’ famous ‘Kuznets curve’, and the Kingdom of Bhutan to the United Nations, p.52.
implies that it is unnecessary and ineffective for developing
economies to worry about growing inequality as with time
it will reduce of its own accord.
127
SECTION 1 2 3 NOTES
201. F. Pearce (2009) ‘Consumption dwarfs population as main 221. R. Wilkinson (2011) op. cit.
environmental threat’, 15 April, the Guardian, 222. J. Stiglitz (2012) op. cit.
consumption-versus-population-environmental-impact 223. M. Corak (2012) op. cit
202. 224. Data on social mobility is restricted to fathers and sons.
203. In addition, they are likely to account for an even higher 225. S. A. Javed and M. Irfan (2012) ‘Intergenerational Mobility:
proportion of historical contributions. D. Satterthwaite (2009) Evidence from Pakistan Panel Household Survey’, Islamabad:
‘The implications of population growth and urbanization Pakistan Institute of Development Economics, pp.13-14,
for climate change’, Environment and Urbanization,
Vol. 21(2),
satterthwaite_2009.pdf 226. R. Wilkinson and K. Pickett (2010) The Spirit Level:
Why Equality is Better for Everyone, London: Penguin.
204. N. Kakar, in Royal Government of Bhutan (2012) op. cit.
227. R. Wilkinson and K. Pickett (2010) op. cit., p.59.
205. J. Martinson and A. Gani (2014) ‘Women at Davos: What’s
happening to the numbers?’, the Guardian, 17 January, 228. Wilkinson and Pickett’s research focused on OECD countries (a grouping of rich countries), yet the same negative
interactive/2014/jan/17/women-davos-numbers-world- correlation between inequality and social well-being holds
economic-forum true in poorer countries.
206. UN Women (2012) ‘2011-2012 Progress of the World’s Women. 229. S.V. Subramanian and I. Kawachi (2006) ‘Whose health
Factsheet: Global’,- is affected by income inequality? A multilevel interaction
content/uploads/2011/06/EN-Factsheet-Global-Progress- analysis of contemporaneous and lagged effects of state
of-the-Worlds-Women.pdf income inequality on individual self-rated health in the
United States’, Health Place, 12(2):141-56,
207. ILO (2011) ‘A new era of social justice, Report of the Director-
General, Report I(A)’, International Labour Conference,
100th Session, Geneva, 2011. 230. R. Wilkinson and K. Pickett (2010) op. cit.
208. UN Women (2012), op. cit. 231. Ibid, p.25.
209. P. Telles (2013) ‘Brazil: Poverty and Inequality. Where to 232. Ibid.
next?’, Oxfam,-
inequality-where-to-next 233. Data provided by the Equality Trust,
210. UNDP (2013) ‘Humanity Divided: Confronting Inequality
in Developing Countries’, New York: UNDP, Chapter 5, 234. E. Anderson (2009) ‘What Should Egalitarians Want?’, Cato Unbound,
Reduction/Inclusive%20development/Humanity%20Divided/ elizabeth-anderson/what-should-egalitarians-want
HumanityDivided_Ch5_low.pdf 235. Ibid.
211. S. Wakefield (2014) op. cit. 236. World Values Survey,
212. P. Telles (2013) op. cit. 237. UNAH-IUDPAS,
213. P. Das (2012) ‘Wage Inequality in India: Decomposition by 238. The homicide rate for Spain is 0.7 per 100,000, OECD Better
Sector, Gender and Activity Status’, Economic & Life Index,
Political Weekly, Vol XLVII, No 50,
files/pdf/2012_47/50/Wage_Inequality_in_India.pdf 239. Freedom House (2012) ‘Freedom in the World: Honduras
Overview’,-
214. World Bank (2012) ‘World Development Report 2012: Gender world/2012/honduras#.U-jP9eNdWgo
Equality and Development’, Washington, D.C.: The World
Bank, pp.85–87, 240. J. Johnston and S. Lefebvre (2013) ‘Honduras Since the
INTWDR2012/Resources/7778105-1299699968583/ Coup: Economic and Social Outcomes’, Washington, D.C.:
7786210-1315936222006/Complete-Report.pdf Centre for Economic and Policy Research,
publications/reports/honduras-since-the-coup-economic-
215. Office for National Statistics (2014) ‘Inequality in Healthy Life and-social-outcomes
Expectancy at Birth by National Deciles of Area Deprivation:
England, 2009-11’, p.1, 241. I. Ali and J. Zhuang (2007) ‘Inclusive Growth Toward a Prosperous Asia: Policy Implications’, ERD Working Paper
No. 97, Manila: Asian Development Bank,
216. The Demographic and Health Surveys (DHS) Program (2011) publications/inclusive-growth-toward-prosperous-asia-
‘Ethiopia: Standard DHS, 2011’, policy-implications
what-we-do/survey/survey-display-359.cfm
242. R. Wilkinson and K. Pickett (2010) op. cit. p.234-5; Centre for
217. E. Godoy (2010) op. cit. Research on Inequality, Human Security and Ethnicity (2010)
218. T.M. Smeeding, R. Erikson and M. Janitl (eds.) (2011) ‘Horizontal inequalities as a cause of conflict: a review of
Persistence, Privilege and Parenting: The Comparative CRISE findings’, p.1,
Study of Intergenerational Mobility, New York: Russell crise-ib1; Institute for Economics and Peace (2011),
Sage Foundation. ‘Structures of Peace: identifying what leads to peaceful
societies’, Figure 5, p.16,
219. J. Stiglitz (2012) The Price of Inequality: How Today’s Divided wp-content/uploads/2011/09/Structures-of-Peace.pdf
Society Endangers Our Future, London: Penguin.
243. UN Office on Drugs and Crime (UNODC) (2011) op. cit.
220. M. Corak (2012) op. cit.
244. UNDP (2013) op. cit.
128
SECTION 1 2 3 NOTES
245. P. Engel, C. Sterbenz and G. Lubin (2013) op. cit. 267. FAO (2013) op. cit.
246. UNDP (2013) op. cit. 268. D. Ukhova (2014) op. cit.
247. A. Smith (1776) An Inquiry into the Nature and Causes 269. A. Izyumov (2010) ‘Human Costs of Post-communist
of the Wealth of Nations (1904 5th ed.), Book I Chapter Transition: Public Policies and Private Response’, Review of
VIII, London: Methuen & Co., Ltd., Social Economy, 68(1): 93–125, pdf/10.1080/00346760902968421#.U-Y1eBb0Rpk
248. J. Stiglitz (2012) op. cit., p.105. 270. A. Franco-Giraldo, M. Palma and C. Álvarez-Dardet (2006)
‘Efecto del ajuste estructural sobre la situación de salud
249. Centre for Research on Inequality, Human Security and en América Latina y el Caribe, 1980–2000’ [‘Impact of
Ethnicity (2010) op. cit. structural adjustment on the health situation in Latin
250. T. Dodge (2012) op. cit. America and the Caribbean, 1980-2000’], Revista e Salud
2(7), pp.291-9,
251. D. Hillier and G. Castillo (2013) op. cit., p.16. arttext&pid=S1020-49892006000500001
252. UNDP (2013) ‘Human Development Report for Latin America 271. UNCTAD (2012) op. cit.
2013–2014 Executive Summary’, New York: UNDP, p.16, 272. CEPAL (1999) ‘Balance preliminar de las economías
docs/Research%20and%20Publications/IDH/IDH-AL- de América Latina y el Caribe’ [‘Preliminary assessment
ExecutiveSummary.pdf of the economies of Latin America and the Caribbean’],
Santiago de Chile: CEPAL,
253. C. Provost (2014) ‘Gated communities fuel Blade Runner
dystopia and “profound unhappiness”’, the Guardian,
2 May, 273. K. Watkins (1998) op. cit.
may/02/gated-communities-blade-runner-dystopia- 274. N. Lustig, L. Lopez-Calva, E. Ortiz-Juarez (2013)
unhappiness-un-joan-clos ‘Deconstructing the Decline of Inequality in Latin America’,
254. D. Hillier and G. Castillo (2013) op. cit. Tulane University Working Paper Series 1314,
255. UNDP, Unicef, Oxfam and GFDRR ‘Disaster risk
reduction makes development sustainable’, 275. R. Assaad and M. Arntz (2005) ‘Constrained Geographical Mobility and Gendered Labor Market Outcomes
prevention/UNDP_CPR_CTA_20140901.pdf Under Structural Adjustment: Evidence from Egypt’,
World Development, 33 (2005):3, p.431-54.
256. J. Rawls (1971) A Theory of Justice, chs. 2 and 13, Cambridge:
Harvard University Press. 276. I. Traynor (2012) ‘Eurozone demands six-day week
for Greece’, the Guardian, 4 September,
257. UN Office for Disaster Risk Reduction (UNISDR) (2014)
‘New pact must integrate DRR and national development’, eurozone-six-day-week-greece
277. M.F. Davis (2012) op. cit.
258. Latinobarometro (2013) ‘Latinobarómetro Report 2013’, viewcontent.cgi?article=1191&context=slaw_fac_pubs
278. S. Tavernise (2010) ‘Pakistan’s Elite Pay Few Taxes,
259. J. Stiglitz (2012) op. cit., p.160. Widening Gap’, The New York Times, 18 July,.
260. M. Carney (2014) ‘Inclusive Capitalism: Creating a sense of html?pagewanted=all&_r=0
the systemic’, speech given by Mark Carney, Governor of the
Bank of England, at the Conference on Inclusive Capitalism, 279. U. Cheema (2012) ‘Representation without Taxation! An
London, 27 May, analysis of MPs’ income tax returns for 2011’, Islamabad:
Documents/speeches/2014/speech731.pdf Centre for Peace and Development Initiatives / Centre
for Investigative Reporting in Pakistan,
261. For more on this see, T. Piketty (2014) Capital in the Twenty- Electronic%20Copy.pdf; AFP (2012) ‘Report unmasks tax
First Century, Cambridge: Harvard University Press. evasion among Pakistan leaders’, The Tribune, 12 December,
262. Speaking at the opening session of the 27th international-
congress of CIRIEC, Seville, 22-24 September 2008, evasion-among-pakistan-leaders- 280. Carlos Slim’s near-monopoly over phone and internet
8292.2009.00389.x.pdf services charges some of the highest prices in the OECD,
263. T. Cavero and K. Poinasamy (2013) ‘A Cautionary Tale: undermining access for the poor. OECD (2012) ‘OECD Review
The true cost of austerity and inequality in Europe’, of Telecommunication Policy and Regulation in Mexico’, OECD
Oxford: Oxfam International, Publishing,
264. World Bank database, 281. Ibid.
SI.POV.GINI, Gini rose from 0.29 to 0.38. 282. Forbes Billionaire List (2014) ‘India Richest’,
265. M. Lawson (2002) ‘Death on the Doorstep of the Summit’,
Oxford: Oxfam, 283. A. Gandhi and M. Walton (2012) ‘Where Do India’s Billionaires
266. M.L. Ferreira (1999) ‘Poverty and Inequality During Get Their Wealth?’, Economic and Political Weekly, Vol.
Structural Adjustment in Rural World Bank Policy Research XLVII, No. 40,-
Working Paper 1641, Washington, D.C.: The World Bank Policy billionaires-get-their-wealth.html
Research Department Transition Economics Division, http:// 284. From a speech by Christine Lagarde at the Richard Dimbleby
elibrary.worldbank.org/doi/book/10.1596/1813-9450-1641 Lecture in London in February 2014,
external/np/speeches/2014/020314.htm
129
SECTION 1 2 3 NOTES
285. OECD (2014) ‘Society at a Glance 2014: OECD Social 304. D. Ukhova (2014) ‘After Equality: Inequality trends and policy
Indicators’, OECD Publishing, responses in contemporary Russia’, Oxford: Oxfam,
OECD2014-SocietyAtAGlance2014.pdf
286. M. Gilens and B.I. Page (2014) ‘Testing Theories of American 305. N. Lustig, L. Lopez-Calva, E. Ortiz-Juarez (2013) op. cit.
Politics: Elites, Interest Groups, and Average Citizens’,
Perspectives on Politics, 306. World Bank (2012) ‘Shifting gears to accelerate prosperity in
people/documents/TestingTheoriesOfAmericanPolitics Latin America and the Caribbean’, Washington, D.C.: World
FINALforProduction6March2014.pdf Bank,
document/LAC/PLB%20Shared%20Prosperity%20FINAL.pdf
287. M. Wolf, K. Haar and O. Hoedeman (2014) op. cit.
307. T. Piketty (2014) op. cit.
288. J. Hobbs (2012) ‘Paraguay’s Destructive Soy Boom’,
The New York Times, Opinion Pages,. 308. Forbes (2014) ‘Forbes Releases 28th Annual World’s
com/2012/07/03/opinion/paraguays-destructive-soy- Billionaires Issue’,
boom.html?_r=0 2014/03/03/forbes-releases-28th-annual-worlds-
billionaires-issue
289. Oxfam, ‘With no land to cultivate, young people in Curuguaty,
Paraguay, have no future’, 309. S. Steed and H. Kersley (2009) ‘A Bit Rich’, New Economics
Foundation,
290. J. Hobbs (2012) op. cit.; E. Abramson (2009) ‘Soy: A Hunger for entry/a-bit-rich
Land’, NACLA,
310. Worldwide women spend 2–5 hours per day more on unpaid
291. Behind only Singapore and Qatar. Source: World Bank care work than men (cited ILO (2014) op. cit.)
database,
311. R. Wilkinson and K. Pickett (2010) op. cit.
292. IMF (2014) ‘IMF Executive Board Concludes 2013 Article
IV Consultation with Paraguay’, Press Release, 312. R. Fuentes-Nieva and N. Galasso (2014) ‘Working for the Few: Political capture and economic inequality’, Oxford: Oxfam,
293. Inter-Parliamentary Union and UN Women (2014) ‘Progress for
women in politics, but glass ceiling remains firm’, UN Women, 313. Ibid.- 314. Africa Progress Panel (2012) ‘Jobs, Justice and Equity;
for-women-in-politics-but-glass-ceiling-remains-firm Seizing Opportunities In Times of Global Change’, Switzerland:
294. World Bank (2014) ‘Voice agency and empowering women Africa Progress Panel, p.6,
and girls for shared prosperity’, World Bank Group, publications/policy-papers/africa-progress-report-2012 315. J. M. Baland, P. Bardan and S. Bowles (eds.) (2007) Inequality,
Gender/Voice_and_agency_LOWRES.pdf cooperation, and environmental sustainability, Princeton:
295. A. Hussain (2003) ‘Pakistan Human Development Report’, UNDP, Princeton University Press.- 316. UNRISD (2010) ‘Combating Poverty and Inequality’, Geneva:
development-report-2003 UNRISD/UN Publications,
296. See, for example, F. Luntz (2007) The Words that Work: It’s 317. In addition to the millions of men and women whose
Not What You Say, it’s What People Hear, New York: Hyperion. livelihoods depend on waged income, around 1.5 billion
For more examples see: households depend on smallholder or family farming
297. J. Carrick-Hagenbarth and G. Epstein (2012) ‘Dangerous (including pastoralists, fisherfolk and other small-scale
Interconnectedness: Economists’ conflicts of interest, food producers). While Oxfam works extensively in support
ideology and financial crisis’, Cambridge Journal of of smallholders (see for example: Oxfam (2011) ‘Growing
Economics 36 (2012): 43–63. a Better Future: Food Justice in a Resource-constrained
World’, Oxford: Oxfam,
298. K. Deutsch Karlekar and J. Dunham (2014) ‘Freedom of the growing-better-future), this report is primarily concerned
Press 2014: Press Freedom at the Lowest Level in a Decade’, with issues facing people on low incomes in waged labour.
Freedom House,
files/FOTP2014_Overview_Essay.pdf 318. P. De Wet (2014) ‘Mining strike: The bosses eat, but we are
starving’, Mail & Guardian,-
299. N. MacFarquhar (2014) ‘Russia Quietly Tightens Reins on Web 15-mining-strike-the-bosses-eat-but-we-are-starving
With “Bloggers Law”’, The New York Times,.
com/2014/05/07/world/europe/russia-quietly-tightens- 319. High Pay Centre,
reins-on-web-with-bloggers-law.html?_r=0 (accessed August 2014).
300. M. F. Davis (2012) op. cit. 320. Living Wage Foundation, ‘Living Wage Employers’,
301. Civicus (2013) ‘State of Civil Society 2013: Creating an
enabling environment’, Civicus, 321. J. Ghosh (2013) op. cit.; an elaboration from data generated by the UN Global Policy Model (2013).
04/2013StateofCivilSocietyReport_full.pdf 322. M. Lavoie and E. Stockhammer (eds.) (2014) ‘Wage-led
302. Ibid. Growth: An equitable strategy for economic recovery’, ILO,-
303. S. Gärtner and S. Prado (2012) ‘Inequality, trust and the publications/WCMS_218886/lang--en/index.htm
welfare state: the Scandinavian model in the Swedish mirror’,
Department of Economic History, University of Gothenburg, 323. E. Chirwa and P. Mvula (Unpublished report, 2012) ‘Understanding wages in the tea industry in Malawi’,
1389/1389332_g--rtner_prado-2012-hs.pdf Wadonda Consultant.
130
SECTION 1 2 3 NOTES
324. Oxfam and Ethical Tea Partnership (2013) ‘Understanding 340. Good Electronics (2014) ‘Samsung’s no union policy claims
Wage Issues in the Tea Industry’, Oxford: Oxfam, another life’,. This takes into account wage samsung2019s-no-union-policy-claims-another-life
increases since the research was conducted by Ergon
Associates in 2011. 341. Source: Instituto de Pesquisa Economica Aplicada,
and Departamento Intersindical de Estatica e Estudos
325. R. Anker and M. Anker (2014) ‘Living Wage for rural Malawi Socioeconomicas, Brazil,. An online
with Focus on Tea Growing area of Southern Malawi’, data set produced by IPEA, see also
Fairtrade International (Western Cape, South Africa),
Fairtrade and Social Accountability International (Dominican 342. Economist Intelligence Unit (2013) op. cit.
Republic), and Fairtrade, Sustainable Agriculture Network/ 343. FAO, Working Group on Distribution of Value,
Rainforest Alliance and UTZ Certified (Malawi), economic/worldbananaforum/working-groups/wg02/en
resources/LivingWageReport_Malawi.pdf 344. Camera de Comercio de Guayaquil, ‘Boletin Economico’,
326. IDH (2014) ‘Raising wages for tea industry workers’, Salario%20Digno%20y%20las%20PYMES.pdf
case study,.
php?id=497 345. S. Butler (2014) ‘Chinese shoppers’ spend could double to
£3.5tn in four years’, The Guardian,
327. International Trade Union Congress (2014) op. cit. business/2014/jun/03/chinese-shoppers-spend-double-
328. R. Wilshaw et al (2013) op. cit.; R. Wilshaw (2013) op. cit.; four-years-clothing-western-retailers
IDH (2013) op. cit. 346. See: R. Wilshaw (2013) op. cit., ‘Unilever Response and
329. Fairtrade International (2013) ‘Living Wage Reports’, Commitments’, pp.94–95; IPL commitments in R. Wilshaw (2013) ‘Exploring the Links between International Business
and Poverty Reduction: Bouquets and beans from Kenya’, op.
330. This research was undertaken by Richard and Martha Anker. cit.; Ethical Tea Partnership press release for ‘Understanding
They also assessed the value of in-kind benefits and Wage Issues in the Tea Industry’,
other factors influencing worker’s pay. Their reports are pressroom/pressreleases/2013-05-02/new-coalition-
available at formed-address-low-wages-tea-industry
331. R. Pollin, J. Burns and J. Heinz (2002) ‘Global Apparel 347. See: H&M, ‘A fair living wage for garment workers’,
Production and Sweatshop Labor: Can Raising Retail Prices
Finance Living Wages?’, Cambridge Journal of Economics, commitments/responsible-partners/fair-living-wage.html.
cgi?article=1012&context=peri_workingpapers; Workers 348. Living Wage Foundation,
Rights Consortium (2005) ‘The Impact of Substantial Labor employers. There has been an increase in the number of FTSE
Cost Increases on Apparel Retail Prices’,. 100 companies accredited as living wage employers from six
columbia.edu/committees_dan/external/wrc1105.pdf in December 2013 to 15 in August 2014.
332. A. Osborne (2012) ‘CEOs and their salaries: because they’re 349. Email to Oxfam, 4th August 2014.
worth it...?’, The Telegraph, 350. Alta Garcia, ‘What is a Living Wage?’
newsbysector/banksandfinance/9002561/CEOs-and-their-
salaries-because-theyre-worth-it....html
351. S. Maher (2013) ‘The Living Wage: Winning the Fight for Social
333. J. Schmitt and J. Jones (2012) ‘Low-wage Workers are Justice’, War on Want,-
Older and Better Educated Than Ever’, Center for Economic work/sweatshops-and-plantations/free-trade-zones-in-
and Policy Research, sri-lanka/17978-report-the-living-wage
publications/min-wage3-2012-04.pdf; and data
collected by Oxfam America. 352. R. Wilshaw (2013) op. cit.
334. Quote taken from Fight for 15, 353. L. Riisgaard and P. Gibbon (2014) ‘Labour Management on. The campaign Contemporary Kenyan Cut Flower Farms: Foundations of an
argues that US tax payers are forced to pay nearly $7bn Industrial-Civic Compromise’, Journal of Agrarian Change,
a year when fast food workers depend on public assistance, Vol. 14(2), pp.260–85.
354. S. Barrientos (forthcoming, 2014) ‘Gender and Global Value
335. Economic Policy Institute (EPI) (2014) ‘As union membership Chains: Economic and Social Upgrading in Agri-Food’, Global
declines, inequality rises’,- Governance Programme.
membership-declines-inequality-rises
355. B. Evers, F. Amoding and A. Krishnan (2014) ‘Social and
336. Oxfam America (2014) ‘Working Poor in America’, Boston: economic upgrading in floriculture global value chains:
Oxfam,- flowers and cuttings GVCs in Uganda’, Capturing the Gains
publications/working-poor-in-america Working Paper 2014/42,
publications/workingpapers/wp_201442.htm
337. L. Mishel and M. Walters (2003) op. cit.
356. D. Card and A. Krueger (1993) ‘Minimum Wages and
338. R. Wilshaw (2010) ‘Better Jobs in Better Supply Chains’, Employment: A Case Study of the Fast Food Industry in New
Oxford: Oxfam, Jersey and Pennsylvania’, American Economic Review,
339. S. Labowitz and D. Baumann-Pauly (2014) ‘Business as Vol. 84(4), pp.772–93,;
usual is not an option: Supply chains sourcing after Rana A. Dube, T.W. Lester and M. Reich (2010) ‘Minimum Wage
Plaza’, Stern Center for Business and Human Rights, Effects Across State Borders: Estimates Using Contiguous Counties’, IRLE Working Paper No. 157-07,
documents/con_047408.pdf
131
SECTION 1 2 3 NOTES
357. Huffington Post (2014) ‘Even Goldman Sachs Analysts 372. See OECD statistics for tax per GDP ratio in OECD countries,
Say A Minimum Wage Hike Wouldn’t Be A Big Job Killer’,-- change-previous-year.htm; and IMF (2014) op. cit. for tax per
minimum-wage_n_5077677.html GDP ratio in developing economies.
358. See, for example, M. Reich, P. Hall and K. Jacobs (2003) ‘Living 373. Oxfam new calculations based on IMF calculations on tax
wages and economic performance: The San Francisco Airport effort and tax capacity. A simulation has be undertaken to
model’, Institute of Industrial Relations,. estimate how much revenue could be collected if the tax
edu/research/livingwage/sfo_mar03.pdf; W. Cascio (2006) revenue gap is reduced by 50 percent by 2020. Assuming
‘The High Cost of Low Wages’, Harvard Business Review, that GDP (in $ at current prices) expands at the same average annual growth rate recorded in the biennium 2011–2012; and
that tax capacity remains constant at the level presented
359. Wagemark, ‘A brief history of wage ratios’, in IMF figures.
374. Christian Aid and Tax Justice Network – Africa (2014) ‘Africa
360. P. Hodgson (2014) ‘Rhode Island tries to legislate Rising? Inequalities and the essential role of fair taxation’,
sky‑high CEO pay away’, Fortune Magazine,- inequality-report-Feb2014.pdf
361. Employee Ownership Association data, 375. IMF, OECD, UN and the World Bank (2011) ‘Supporting the Development of More Effective Tax Systems: A report to the
employee-ownership-index G-20 development working group by the IMF, OECD, UN and
362. National Center for Employee Ownership (2004) ‘Employee World Bank’, p.21,
ownership and corporate performance: A comprehensive 376. N. Shaxson (2012) Treasure Islands: Tax Havens and the Men
review of the evidence’, Journal of employee ownership law Who Stole the World, London: Vintage Books.
and finance, Vol. 14(1); Employer Ownership Association
(2010) ‘The employee ownership effect: review of the 377. M. Keen and M. Mansour (2009) ‘Revenue Mobilization
evidence’, Matrix Evidence. in Sub-Saharan Africa: Challenges from Globalization’,
IMF Working Paper, p.21,
363. J. Lampel, A. Bhalla and P. Jha (2010) ‘Do Employee-Owned
Businesses Deliver Sustainable Performance?’, London: Cass
Business School; Matrix (2010) ‘The Employee Ownership 378. M. Curtis (2014) ‘Losing Out: Sierra Leone’s massive
Effect: a Review of the Evidence’, London: Matrix Evidence; revenue loses from tax incentives’, London: Christian Aid,
R. McQuaid et al (2013) ‘The Growth of Employee Owned-
Businesses in Scotland’, Report to Scottish Enterprise. tax-incentives-080414.pdf
364. Richard Wilkinson, co-author of The Spirit Level, in a talk 379. Institute of Policy Analysis and Research-Rwanda (2011)
to Oxfam staff, July 2014. ‘East African Taxation Project: Rwanda Country Case
Study’, IPAR-Rwanda,
365. ECLAC (2014) op. cit. actionaid/rwanda_case_study_report.pdf
366. In Figure 12, the measurement of the Gini coefficient has 380. V. Tanzi and H. Zee (2001) ‘Tax Policy for Developing
been changed from between 0 and 1 to between 0 and Countries’, IMF Economic Issues No. 27,
100, in order to accurately display the percentage change
before and after taxes and transfers. Comisión Económica
para América Latina y el Caribe (CEPAL) (2014) ‘Compacts 381. C. Godfrey (2014) op. cit.
for Equality: Towards a Sustainable Future’, Santiago de
Chile: United Nations, p.36, 382. IMF (2014) op. cit.
xml/8/52718/SES35_CompactsforEquality.pdf 383. See: A. Prats, K. Teague and J. Stead (2014) ‘FTSEcrecy: the
367. See: IMF (2014) ‘Spillovers in International Corporate culture of concealment through the FTSE’, London: Christian
Taxation’, IMF Policy Paper, Aid,
pp/eng/2014/050914.pdf; OECD (2013b) ‘Addressing base 384. President Obama, Remarks by the President on International
erosion and profit shifting’, OECD Publishing,- Tax Policy Reform, 4 May 2009,
ilibrary.org/taxation/addressing-base-erosion-and-profit- press_office/Remarks-By-The-President-On-International-
shifting_9789264192744-en Tax-Policy-Reform
368. D. Itriago (2011) op. cit. 385. R. Phillips, S. Wamhoff and D. Smith (2014), ‘Offshore Shell
369. Coordinadora Civil, ‘Nicaragua based on living conditions Games 2014: The Use of Offshore Tax Havens by Fortune 500
survey’, INIDE (Instituto Nacional de Formación de Desarrollo) Companies’, Citizens for Tax Justice and U.S. PIRG Education Fund,
EMNV%202009.pdf; combined with J. C. Gómez Sabaini (2003) 386. Ibid.
‘Nicaragua: Desafios Para La Modernizacion Del Sistema
Tributario’, Banco Interamericano Desarrollo, 387. IMF (2014) op. cit.
388. A. Sasi (2012) ‘40% of India’s FDI comes from this bldg’,
370. IMF (2014) ‘Fiscal Policy and Income Inequality’, IMF Policy The Indian Express, 21 August,
Paper, Figure 8, Washington, D.C.: IMF,- comes-from-this-bldg/990943
371. J. Watts (2013) ‘Brazil protests: president to hold 389. EquityBD (2014) op. cit.
emergency meeting’, the Guardian,-
protests-president-emergency-meeting
132
SECTION 1 2 3 NOTES
390. In C. Godfrey (2014) op. cit., Oxfam estimated the tax gap for 403. Uruguay was initially included in the G20 blacklist of tax
developing countries at $104 billion every year and corporate havens as a financial centre that had committed to – but
income tax exemptions at $138 billion a year. These losses not yet fully implemented – the international tax standards.
combined could pay twice over the $120 billion needed to It was removed only five days later after providing a full
meet the Millennium Development Goals related to poverty, commitment to exchange information to the OECD standards.
education and health, as calculated by the OECD (2012) However, the country has strict financial secrecy laws,
‘Achieving the Millennium Development Goals: More money including one of the world’s tightest bank-secrecy statutes,
or better policies (or both)?’, OECD Issue Paper, which forbids banks from sharing information, except in rare cases. See Tax Justice Network (2013) ‘Financial Secrecy
Index: Narrative Report on Uruguay’,
391. M.P. Keightley (2013) ‘An Analysis of Where American
Companies Report Profits: Indications of Profit Shifting’
CRS Report for Congress, Congressional Research Service, 404. OECD (2013b) op. cit.
405. IMF (2014) op. cit.
392. For full details of Oxfam’s calculations and methodology
see: Oxfam (2013) ‘Tax on the ‘private’ billions now stashed 406. S. Picciotto (2012) op. cit.
away in havens enough to end extreme world poverty 407. The European Commission proposed a tax of 0.1 percent
twice over’, 22 May, on transactions of shares and bonds and 0.01 percent on
pressreleases/2013-05-22/tax-private-billions-now- derivatives. See:
stashed-away-havens-enough-end-extreme taxation/other_taxes/financial_sector/index_en.htm
393. Data taken from World Bank database, 408. T. Piketty (2014) op. cit., p.572.
409. Reuters (2013) ‘Brazil’s ruling party to propose tax on large
394. M. Cea and F. Kiste (2014) ‘El Salvador “oculta” $11,200 fortunes’, 26 June,
millones en paraísos fiscales’, El Mundo,. economy-brazil-wealth-idUSL2N0F21P220130626
com.sv/el-salvador-oculta-11200-millones-en-paraisos-
fiscales based on James Henry calculations in J.S. Henry 410. See K. Rogoff (2013) ‘Why Wealth Taxes are Not Enough’,
(2012) ‘The Price of Offshore Revisited’, Tax Justice Network,- rogoffon-the-shortcomings-of-a-one-time-wealth-
Revisited_120722.pdf tax#FpTcXurUs6odiUl2.9; and IMF (2013) ‘IMF Statement
on Taxation’, Press Release No. 13/427,
395. OECD (1998) op. cit.
396. J. Sharman (2006) Havens in a Storm: The Struggle for Global 411. A 1.5 percent tax on billionaires’ wealth over $1bn in 2014
Tax Regulation, Ithaca and London: Cornell University Press. would raise $74bn, calculated using wealth data according
397. See US Senate Committee Homeland Security & to Forbes as of 4 August 2014. The current annual funding
Governmental Affairs (2013) ‘Permanent Sub-Committee on gap for providing Universal Basic Education is $26bn a year
Investigations, May 2013 Hearing Report, 15 October 2013’, according to UNESCO, and the annual gap for providing key health services (including specific interventions such as
media/levin-mccain-statement-on-irelands-decision-to- maternal health, immunisation for major diseases like HIV/
reform-its-tax-rules AIDS, TB and malaria, and for significant health systems
strengthening to see these and other interventions
398. See UK Parliament (2012) Public Accounts Committee – delivered) in 2015 is $37bn a year according to WHO.
Nineteenth Report, HM Revenue and Customs: Annual Report See: UNESCO (2014) op.cit., and WHO (2010) op. cit.
and Accounts, Tax Avoidance by Multinational Companies, 412. C. Adams (1993) For Good and Evil: The Impact of Taxes on
cmpubacc/716/71605.htm the Course of Civilization, Lanham: Madison Books.
399. Consultations are open to all non-formal OECD/ 413. iiG (2011) ‘Raising revenue to reduce poverty’,
non-G20 members. Briefing Paper 16, Oxford: iiG,-
400. C. Godfrey (2014) op. cit. briefingpaper-16-raising-revenue-to-reduce-poverty.pdf
401. Analysis from Forum Civil, Oxfam partner in Senegal working 414. UNESCO (2013) ‘Education Transforms Lives’,
on fair taxation: Education For All Global Monitoring Report, Paris: OECD,
402. Uruguay now has the largest differences in inequality excel/dme/Press-Release-En.pdf
before and after taxation in the LAC region, showing that its
progressive fiscal policy is efficient in reducing inequality. 415. G. Verbist, M.F. Förster and M. Vaalavuo (2012) op. cit.
N. Lustig et al (2013) ‘The Impact of Taxes and Social
Spending on Inequality and Poverty in Argentina, Bolivia, 416. Ibid.
Brazil, Mexico, Peru and Uruguay: An Overview’, Commitment 417. N. Lustig (2012) op. cit.
to Equity Working Paper N.13,.
org/publications_files/Latin%20America/CEQWPNo13%20 418. R. Rannan-Eliya and A. Somantnan (2005) ‘Access of the Very
Overview%20Aug%2022%202013.pdf. In 2013, its Gini Poor to Health Services in Asia: Evidence on the role of health
coefficient dropped nine basic points from 0.49 to 0.40. systems from Equitap’, DFID Health Systems Resource Centre,.
VDF945SwKa1
133
SECTION 1 2 3 NOTES
419. OECD Secretariat (2010) op. cit.. Also Ramos showed that 435. UNESCO (2009) ‘EFA Global Monitoring Report 2009:
between 1995 and 2005 education was the most important Overcoming Inequality: Why Governance Matters’, Paris:
element explaining the decline in wage inequality in Brazil. UNESCO, p.166,
See: Ramos (2006) ‘Desigualdade de rendimentos do trabalho themes/leading-the-international-agenda/efareport/
no Brasil, de 1995 a 2005’ in R. Barros, M. Foguel and G. reports/2009-governance
Ulyssea (eds.) Sobre a recente queda da desigualdade de
renda no Brasil, Brasília: IPEA. 436. Ibid. For the two-thirds of Malawi’s population that live
below the poverty line, even the moderate fees charged in
420. H. Lee, M. Lee and D. Park (2012) op. cit. urban low-fee private schools would cost them one-third
of their available income. In rural areas of Uttar Pradesh,
421. World Bank Group President Jim Yong Kim, Speech at World India, the cost would be even greater. It is estimated that for
Health Assembly, Geneva, 21st May 2013, ‘Poverty, Health an average family in the bottom 40 percent of the income
and the Human Future’, distribution, educating all their children at a low-fee school
speech/2013/05/21/world-bank-group-president-jim- would cost around half of their annual household salary.
yong-kim-speech-at-world-health-assembly
437. Lower-income families tend to have larger families and
422. Goverment of India spends 1.3 percent on health, sending all their children to LFPS is financially impossible.
and 2.4 percent on the military. World Bank database, 438. J. Härmä and P. Rose (2012) ‘Low-fee private primary
schooling affordable for the poor? Evidence from rural
423. M. Martin and R. Watts (2013) ‘Putting Progress at Risk? MDG India’ in S.L. Robertson et al (eds.) (2012) Public Private
spending in developing countries’, Development Finance Partnerships in Education: New Actors and Modes
International (DFI) and Oxfam, p.28, of Governance in a Globalizing World, Cheltenham:
424. UNESCO (2014) ‘Teaching and Learning: Achieving Quality for Edward Elgar Publishing.
All 2013/14’, EFA Global Monitoring Report,. 439. T. Smeeding (2005) ‘Public Policy, Economic Inequality,
unesco.org/images/0022/002256/225660e.pdf and Poverty: The United States in Comparative Perspective’,
425. K. Xu et al (2007) op. cit. Social Science Quarterly, Vol. 86 (suppl): 955-83.
426. D.U. Himmelstein et al. (2009) ‘Medical Bankruptcy in the 440. UNESCO (2014) op. cit.
United States, 2007: Results of a National Study’, The 441. E. Missoni and G. Solimano (2010) ‘Towards Universal Health
American Journal of Medicine, 122:741–6,. Coverage: the Chilean experience’, World Health Report 2010:
com/article/S0002-9343(09)00404-5/abstract Background Paper 4, Geneva: World Health Organization,
427. The research undertaken by Justice Quereshi concluded
India’s corporate hospitals were ‘money minting machines’. healthreport/4Chile.pdf
From A.S. Qureshi (2001) ‘High Level Committee for Hospitals 442. Public Services International (2014) ‘Wikileaks confirms
in Delhi’, New Delhi: Unpublished Report of the Government TISA alarm raised by PSI’,-
of Delhi. confirms-tisa-alarm-raised-psi
428. The Global Initiative for Economic, Social and Cultural 443. A. Cha and A. Budovich (2012) op. cit.
Rights ‘Privatization of education in Morocco breaches
human rights: new report’, 444. Y. Lu et al (2011) ‘World Medicines Situation 2011: Medicines
privatization-of-education-in-morocco-breaches-human- Expenditures’, Geneva: World Health Organization, p.6,
rights-new-report-2
world_medicine_situation.pdf; E. Van Doorslaer, O O’Donnell
429. World Bank (2010) ‘Lesotho – Sharing growth by reducing and R. Rannan-Eliya (2005) ‘Paying out-of-pocket for
inequality and vulnerability: choices for change – a poverty, health care in Asia: Catastrophic and poverty impact’,
gender, and social assessment’, Report No. 46297-LS, Equitap Project: Working Paper #2,
Washington DC: World Bank,.
org/curated/en/2010/06/12619007/lesotho-sharing-
growth-reducing-inequality-vulnerability-choices-change- 445. S. Vogler et al (2011) ‘Pharmaceutical policies in European
poverty-gender-social-assessment countries in response to the global financial crisis’, Southern
Med Review 4(2): 69–79.
430. A. Marriott (2009) op. cit.; World Bank (2008) op. cit.
446. WHO, with UNICEF and UNAIDS (2013) ‘Global Update on
431. R. Rannan-Eliya and A. Somantnan (2005) op. cit. HIV Treatment 2013: Results, impact and opportunities’,
432. L. Chakraborty, Y. Singh and J.F. Jacob (2013) ‘Analyzing Geneva: World Health Organization,.
Public Expenditure Benefit Incidence in Health Care: Evidence org/en/media/unaids/contentassets/documents/
from India’, Levy Economics Institute, Working Papers Series unaidspublication/2013/20130630_treatment_report_en.pdf
No. 748,- 447. M. Mackay (2012) ‘Private sector obstructed plans
public-expenditure-benefit-incidence-in-health-care for NHI scheme – claim’, Sowetan Live,
433. C. Riep (2014) op. cit.-
sector-obstructed-plans-for-nhi-scheme---claim
434. B.R. Jamil, K. Javaid, B. Rangaraju (2012) ‘Investigating
Dimensions of the Privatisation of Public Education in 448. Public Citizen (2013) ‘U.S. Pharmaceutical Corporation Uses
South Asia’, ESP Working Paper Series 43, Open Society NAFTA Foreign Investor Privileges Regime to Attack Canada’s
Foundations, p.22,. Patent Policy, Demand $100 Million for invalidation of Patent’,
org/files/WP43_Jamil_Javaid&Rangaraju.pdf;
HAI, Oxfam, MSF (2011) ‘The Investment Chapter of the
EU‑India FTA: Implications for Health’, HAI Europe,-
June-2011-Fact-Sheet-The-Investment-Chapter-of-the-
EU-India-FTA-Implications-for-Health.pdf
134
SECTION 1 2 3 NOTES
449. P. Stevens (2004) ‘Diseases of poverty and the 465. K. Watkins and W. Alemayehu (2012) op. cit.
10/90 gap’, International Policy Network, 466. OECD (2012) ‘PISA 2012 Results: Excellence through Equity:
InternationalPolicyNetwork.pdf Giving Every Student a Chance to Succeed Volume II’,-
450. See, for example:- volume-ii.htm
vaccine-treatment-africa
467. G. Ahobamuteze, C. Dom and R. Purcell (2006) op. cit.
451. Health Action International Europe and Corporate Europe
Observatory (2012) ‘Divide and Conquer: A look behind 468. Figure refers to 2009–11 share of total ODA to and through
the scenes of the EU pharmaceutical industry lobby’, civil society organizations. O. Bouret, S. Lee and I. McDonnell
Health Action International Europe and Corporate Europe (2013) ‘Aid for CSOs. Aid at a Glance – Flows of official
Observatory, development assistance to and through civil society
files/28_march_2012_divideconquer.pdf organisations in 2011’, OECD Development Cooperation
Directorate,
452. Z. Carter (2011) ‘Bill Daley’s Big Pharma History: Drugs, for%20CSOs%20Final%20for%20WEB.pdf
Profits And Trade Deals’, Huffington Post, http://
huffingtonpost.com/2011/09/28/bill-daley-big-pharma- 469. P. Davies (2011) ‘The Role of the Private Sector in
trans-pacific-partnership_n_981973.html; G. Greenwald the Context of Aid Effectiveness’, OECD, p.17,
(2012) ‘Obamacare architect leaves White House for
pharmaceutical industry job’, The Guardian, 470. Z. Chande (2009) op. cit.
obamacare-fowler-lobbyist-industry1 471. ILO (2014) ‘World Social Protection Report 2014/15: Building
economic recovery, inclusive development and social
453. Address by Dr Margaret Chan, Director-General, to the Sixty- justice’, Geneva: ILO,
seventh World Health Assembly, Geneva, 19 May 2014, public/---dgreports/---dcomm/documents/publication/ wcms_245201.pdf
3-en.pdf
472. D. Coady, M. Grosh and J. Hoddinott (2004) ‘Targeting
454. Address by Dr Margaret Chan, Director-General, to the Sixty- Outcomes Redux’, The World Bank Research Observer, Vol.
fifth World Health Assembly, Geneva, 21 May 2012, 19, No. 1, pp.61–85, abs/10.1093/wbro/lkh016?journalCode=wbro
455. Speech by World Bank Group President Jim Yong Kim at the 473. See, for example: BBC News Magazine (2011) ‘A Point
Government of Japan-World Bank Conference on Universal of View: In defence of the nanny state’, 4 February,
Health Coverage, Tokyo, 6 December 2013,
speech-world-bank-group-president-jim-yong-kim- 474. C. Arnold with T. Conway and M. Greenslade (2011) ‘Cash
government-japan-conference-universal-health-coverage Transfers: Evidence Paper’, UK Department for International
Development,.
456. V. Tangcharoensathien et al (2007) ‘Achieving universal uk/+/http:/dfid.gov.uk/Documents/publications1/
coverage in Thailand: what lessons do we learn? A case cash-transfers-evidence-paper.pdf.
study commissioned by the Health Systems Knowledge nationalarchives.gov.uk/+/http:/dfid.gov.uk/Documents/
Network’, Geneva: World Health Organization, publications1/cash-transfers-evidence-paper.pdf
media/universal_coverage_thailand_2007_en.pdf 475. ILO (2008) op. cit.
457. D.B. Evans, R. Elovainio and G. Humphreys (2010) ‘World 476. A. de Haan (2013) ‘The Social Policies of Emerging Economies:
Health Report: Health systems financing, the path to Growth and welfare in China and India’, Working Paper 110,
universal coverage’, Geneva: World Health Organization, p.49, International Policy Centre for Inclusive Growth, UNDP,.
pdf?ua=1
477. N. Lustig et al (2013) op. cit.
458. S. Limwattananon et al (2011) op. cit.
478. Human Development Report, ‘Gender Inequality Index’,
459. Health Insurance System Research Office (2012) ‘Thailand-
Universal Coverage Scheme: Achievements and Challenges. gii; World Economic Forum, The Global Gender Gap Report,
An independent assessment of the first 10 years (2001-
2010)’, Synthesis Report, p.79,
topics/health-politics-and-trade-unions/development- 479. S. Wakefield (2014) op. cit.
and-health-determinants/development-and-health- 480. Institute of Statistical, Social and Economic Research,
determinants/thailand2019s-universal-coverage-scheme- University of Ghana (2009) Gender and Indirect Tax incidence
achievements-and-challenges in Ghana, referenced in J. Leithbridge (2012) op. cit.
460. T. Powell-Jackson et al (2010) ‘An early evaluation of the 481. A. Elomäki (2012) op. cit.
Aama “Free Delivery Care” Programme’, Unpublished report
submitted to DFID, Kathmandu. 482. A. Elomäki (2012) op. cit. In 2010, the employment rate for
women with small children was 12.7 percent lower than
461. Ibid. women with no children, compared to 11.5 percent lower in
462. See BBC News, Business (2013) ‘Novartis: India 2008. In 2010, 28.3 percent of women’s economic inactivity
rejects patent plea for cancer drug Glivec’, 1 April, and part time work was explained by the lack of care services against 27.9 percent in 2009. In some countries the impact
of the lack of care services has increased significantly.
463. L. Bategeka and N. Okurut (2005) op. cit. In Bulgaria it was up to 31.3 percent in 2010 from 20.8
percent in 2008; in the Czech Republic up to 16.7 percent
464. B. Bruns, D. Evans and J. Luque (2012) op. cit. from 13.3 percent.
135
SECTION 1 2 3 NOTES
483. The Fourth World Conference on Women (1995) ‘Beijing 502. J. Crabtree and A. Chaplin (2013) Bolivia: Processes of
Declaration and Platform for Action’, Paragraph 58, Change, London: Zed books.
503. The country’s largest gas fields saw a complete reversal in
484. D. Elson and R. Sharp (2010) ‘Gender-responsive budgeting shares, with 82 percent for the government and 18 percent
and women’s poverty’, In: S. Chant (ed.) (2010) International for the companies.
Handbook of Gender and Poverty: Concepts, Research, bp134-lifting-the-resource-curse-011209.pdf
Policy, Cheltenham: Edward Elgar, pp.524–25.
504. J. Crabtree and A. Chaplin (2013) op. cit.
485. Ministry of Women and Child Development (2007) ‘Gender
Budgeting Hand Book for Government of India Ministries 505. World Bank,
and Departments’, Government of India, pp.55-56, 506. ECLAC (2013) ‘Social Panorama of Latin America’,
GB%20Handbook%20and%20Manual/Hand%20Book.pdf SocialPanorama2013.pdf
486. K. Goulding (2013) ‘Gender dimensions of national 507. N. Lustig (2012) op. cit.
employment policies: A 24 country study’, Geneva: ILO,
documents/publication/wcms_229929.pdf
487. Of particular note is South Korea’s continued wide gap of
38.9 percent. Korea’s rapid economic growth since the 1960s
has been fuelled by labour-intensive exports that have
employed mainly women. See: UNDP (2013) ‘Humanity Divided:
Confronting Inequality in Developing Countries’, United
Nations Development Programme,
dam/undp/library/Poverty%20Reduction/Inclusive%20
development/Humanity%20Divided/HumanityDivided_Full-
Report.pdf
488. P. Fortin, L. Godbout and S. St-Cerny (2012) op. cit.
489. CIVICUS (2014) ‘State of Civil Society Report 2014: Reimagining
Global Governance’,
uploads/2013/04/2013StateofCivilSocietyReport_full.pdf
490. Ibid.
491. Ibid.
492. Ibid.
493. Oxfam’s polling from across the world captures the belief
of many that laws and regulations are now designed to
benefit the rich. A survey in six countries (Spain, Brazil, India,
South Africa, the UK and the USA) showed that a majority of
people believe that laws are skewed in favor of the rich –
in Spain, eight out of 10 people agreed with this statement.
Also see: Latinobarometro (2013),
494. W. Wilson (2012) op. cit.
495. CIVICUS (2014) op. cit.
496. OECD (2014) ‘Society at a Glance: OECD Social Indicators’,
497. CIVICUS, ‘Civil Society Profile: Chile’,
498. G. Long (2014) ‘Chile’s student leaders come of
age’, BBC News,
499. D. Hall (2010) ‘Why we Need Public Spending’,
Greenwich: PSIRU, p.59,
500. O. Valdimarsson (2010) ‘Icelanders Hurl Eggs at Parliament
in Mass Protests’, Bloomberg,
news/2010-10-04/icelanders-hurl-eggs-red-paint-at-
parliament-walls-as-thousands-protest.html
501. CIVICUS (2014) ‘Citizens in Action 2011: Protest as
Process in The Year of Dissent’, p.53,
136
The widening gap between rich and poor is at a tipping point.
It can either take deeper root, jeopardizing
Oxfam is an international confederation of © Oxfam International October 2014
17 organizations networked together in more than
90 countries, as part of a global movement for change, This report and information about the Even It Up campaign
to build a future free from the injustice of poverty: can be found at:
Oxfam America Although this publication is subject to copyright,
Oxfam Australia the text may be freely used for political advocacy and
Oxfam-in-Belgium campaigns, as well as in the area of education and
Oxfam Canada research, provided that the source is acknowledged
Oxfam France in full. The copyright holder requests that any such use
Oxfam Germany is reported in order to assess its impact. Any copying
Oxfam GB in other circumstances, or its use in other publications,
Oxfam Hong Kong as well as in translations or adaptations, may be carried
Oxfam India out after obtaining permission; the payment of a fee
Oxfam Intermón may be required.
Oxfam Ireland
Oxfam Italy Please contact policyandpractice@oxfam.org.uk
Oxfam Japan
Oxfam Mexico The information contained in this document is
Oxfam New Zealand accurate at the time of printing.
Oxfam Novib
Oxfam Quebec
For further information, please write to any
of the organizations or visit
Published by Oxfam GB for Oxfam International under
ISBN 978-1-78077-721-4 in October 2014.
Oxfam GB, Oxfam House, John Smith Drive, Cowley,
Oxford, OX4 2JY, United Kingdom.
Oxfam GB is registered as a charity in England and Wales
(no. 202918) and in Scotland (SCO 039042) and is a member
of Oxfam International.
|
https://pt.scribd.com/document/340825645/Even-it-Up-Time-to-end-extreme-inequality
|
CC-MAIN-2018-26
|
refinedweb
| 51,302
| 52.7
|
Please read the documentation and code of IBM's WSTK. It is hard but worth it!
:-) Please do remember that XML is just fancy ASCII, made very complicated by
mumbo-jumbo lovers (-: Also study Soap Code and you will see how 'Deployment
Descriptors' IMHO simplify things by encapsulating lots of complexity. Soap is
work in progress and IMHO there will never be sufficient documentation.)
Regards - George
lukas.severin@valtech.se wrote:
> OK, but still it would be nice to know what the syntax is of this
> mumbo-jumbo.. What does it mean ?
>
> -----Original Message-----
> From: Aldo Bergamini [mailto:aaberga@nb-a.com]
> Sent: Thursday, September 28, 2000 2:30 PM
> To: soap-user@xml.apache.org
> Subject: Re: How to use deployment descriptor with ibm's
> java-implementation
>
> lukas.severin@valtech.se is believed to have said on 9/28/00 1:19 PM:
>
> >I find no documentation for how this is constructed in the release. The url
> >given () does not exist ...
> >
> >So my question is, what is the purpose of this dd, what is its syntax (i.e.
> >dtd) and how do I use it ?
>
> To the best of my knowledge this kind of URL exists just for the purpose
> of identifying an XML namespace.
>
> They are not expected to exist on the net; it's a conventional use of the
> uniqueness and ownership of domain names...
>
> Rgds
> Aldo
|
http://mail-archives.apache.org/mod_mbox/xml-soap-user/200010.mbox/%3C39D7B242.99C2FA7C@pop.mpls.uswest.net%3E
|
CC-MAIN-2016-36
|
refinedweb
| 230
| 66.94
|
"TemplateMaschine" is a free open source tool which processes templates written in C# and outputs the results to either a file or a string. Other software of this category include CodeSmith or the Java-based Velocity template engine.
It's a tool perfectly suitable for MDSD (Model Driven Software Development) resp. MDA (Model Driven Architecture) and can be used for a variety of applications of code generation including
Short-spoken, it can be used to relieve you from all kind of boring and error prone "cut-and-paste" programming.
We start with a simple example, which consists of the following files:
So, here's the driver code:
using System;
using TemplateMaschine;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
// Load a template from file 'Sample.template'
// and compile it
Template myTemplate = new Template("Sample.template");
// Process the template with no arguments
// and write output to file 'SampleOutput.txt'
myTemplate.Generate(null, "SampleOutput.txt");
}
}
}
Here comes the template:
This is the first line
<% string[] greetz = new string[] {"Hello", "this", "is",
"my", "first", "template"};
foreach(string greet in greetz)
{ %>
Here comes the text: <%=greet%>
<% } %>
This is the last line
Now, call run.bat which compiles the files and executes the sample driver using the following commands:
C:\> csc /t:library TemplateMaschine.csC:\> csc /t:exe /r:TemplateMaschine.dll SampleDriver.csC:\> sampledriver.exe
Now have a look at 'SampleOutput.txt', which should have appeared in your directory:
This is the first line
Here comes the text: Hello
Here comes the text: this
Here comes the text: is
Here comes the text: my
Here comes the text: first
Here comes the text: template
This is the last line
Here are some more examples that show enhanced features (for a complete list of features, see the documentation section):
Requirements:
Sources can be found at sourceforge.net project page
Please send me your
If you like the software I would be very pleased if you donate me an amount of your choice to support my work. Thank you very much in advance!
|
http://www.stefansarstedt.com/templatemaschine.html
|
crawl-002
|
refinedweb
| 337
| 57.3
|
fay-dom alternatives and similar packages
Based on the "Fay" category.
Alternatively, view fay-dom alternatives based on common mentions on social networks and blogs.
fay-base9.9 4.8 fay-dom VS fay-baseA proper subset of Haskell that compiles to JavaScript
fay9.9 4.8 fay-dom VS fayA proper subset of Haskell that compiles to JavaScript
fay-jquery8.5 0.0 fay-dom VS fay-jqueryjQuery bindings for Fay (experimental)
snaplet-fay7.9 0.0 L1 fay-dom VS snaplet-fayFay integration for Snap that provides automatic (re)compilation during development
fay-builder5.5 0.0 fay-dom VS fay-builderPut Fay configuration in your projects .cabal file and compile on program startup or when building with Cabal
fay-uri5.3 0.0 fay-dom VS fay-uriPersistent FFI bindings for using jsUri in Fay
fay-ref3.0 0.0 fay-dom VS fay-refLike IORef but for Fay
fay-websockets1.2 0.0 fay-dom VS fay-websocketsWebsockets FFI library for Fay
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of fay-dom or a related project?
README
fay-dom
A FFI wrapper for DOM functions for use with Fay. It includes functions for the more commonly used DOM features. See fay-jquery if you want wrappers for jQuery.
Usage
Just install it with cabal:
$ cabal install fay-dom
Then include it at the top of your
file.hs:
import DOM
fay-dom uses fay-text so you probably want to enable
OverloadedStrings and
RebindableSyntax when using this package.
Finally, build the javascript including the package, as explained on the wiki:
$ fay --package fay-text,fay-dom file.hs
Development Status
Rudimentary at the moment. Functions will be added when people find the need for them. A lot of what this library could do already exists in fay-jquery, but if anyone wants to write Fay without jQuery feel free to add whatever is missing.
Contributions
Fork on!
Any enhancements are welcome.
The github master might require the latest fay master, available at faylang/fay.
|
https://haskell.libhunt.com/fay-dom-git-alternatives
|
CC-MAIN-2021-43
|
refinedweb
| 361
| 58.99
|
You can subscribe to this list here.
Showing
5
results of 5
Hey,
I've installed msys and mingw on a new computer. I'm trying to compile a
linux lib that I've ported to windows. On my computer at home, there is no
problem, but on this one I get that warning message:
/bin/sh ../../libtool --mode=link gcc -g -O2 -L/usr/local/lib -o
libeet.la -rpath /usr/local/lib -no-undefined -version-info 9:10:9
eet_lib.lo eet_data.lo eet_image.lo eet_memfile.lo eet_utils.lo -lz -ljpeg
-liberty -lwsock32
*** Warning: linker path does not have real file for library -liberty.
*** I have the capability to make etc...
and only the static lib is built.
Usually, when I get that warning, I try to provide the shared lib (here,
the shared lib of libiberty) or I rename the shared lib (like zlib1.dll
renamed to libz.dll, so that the linker is happy). It always works.
But I can't remember what I did on my home computer for libiberty, where
there is no problem (my home computer is far away from me right now :) ).
I use mingw 5.1.3 (candidate). I looked in the archives of binutils and
gcc-core packages, but I didn't find that shared lib of libiberty. Google
can't help me too.
does someone know what I should do ?
thank you
Vincent Torri
Thanks. That helped out a lot. :-)
The \ is escaping the *. This works on every other platform, including
Windows with other compilers. Using '*' and "*" have the same results. In
any case, using _CRT_glob is a good work around for now.
On 7/26/07, Danny Smith <dannysmith@...> wrote:
>
> > \*
>
>
> This, from the samples dir in mingw-runtime src, shows how how to turn off
> globbing:
>
> #include <stdlib.h>
> #include <stdio.h>
> #include <windows.h>
>
> /* This line turns off automatic command line globbing. */
> int _CRT_glob = 0;
>
> int
> main (int argc, char* argv[])
> {
> int i;
>
> printf ("Command line (via GetCommandLine) \"%s\"\n",
> GetCommandLine());
> for (i = 0; i < argc; i++)
> {
> printf ("Argv[%d] \"%s\"\n", i, argv[i]);
> }
>
> return 0;
> }
>
>
>
> Another way is to quote the arguments.
>
>
> HTH
> Danny
>
Brandon Sneed wrote, quoting me:
>> Huh? It's a tarball, just like from any other mirror. Its contents
>> comprise precompiled executables, not source. (If it were source, it
>> would have been called gdb-6.6-src.tar.bz2).
>
> i was implying it was an exe inside. he seemed to get the point,
Indeed.
> though i could've been clearer.
You posted a link to a specific mirror, with an implied statement that
the version of the tarball there was, in some special way, different from
the version on other mirrors; it isn't, and I just wanted to clarify that.
I also saw, and took the opportunity to post a reminder to Dave Murphy,
that he hasn't yet posted a source tarball, which we require to avoid any
issues with GPL conformance.
Cheers,
Keith.
[mailto:mingw-users-bounces@...] On Behalf Of George =
Rhoten
Sent: Thursday, 26 July 2007 6:29 p.m.
To: MinGW-users@...
Subject: [Mingw-users] Why is MinGW escaping the command line arguments?
>.=20
>
> -x \*
This, from the samples dir in mingw-runtime src, shows how how to turn =
off globbing:
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
/* This line turns off automatic command line globbing. */
int _CRT_glob =3D 0;
int
main (int argc, char* argv[])
{
int i;
printf ("Command line (via GetCommandLine) \"%s\"\n",
GetCommandLine());
for (i =3D 0; i < argc; i++)
{
printf ("Argv[%d] \"%s\"\n", i, argv[i]);
}
return 0;
}
Another way is to quote the arguments.
HTH=20
Danny \*
When our tool is built with Microsoft Visual C++ on Windows, Cygwin's gcc on
Windows, Linux, Solaris, Mac OS X, BSD, AIX, HP-UX, z/OS, i5/OS and several
other platforms, this argument is passed to our compiled tool as a literal
asterisk.
When our tool is built with MinGW, this asterisk is turned into a list of
files in the current directory.
Since the same tool can be built with Visual C++ with the same Cygwin based
makefiles, and this problem doesn't happen in that scenario, I have a
feeling that that MinGW is mangling the arguments. Is there a way to turn
this "feature" off?
George
|
http://sourceforge.net/p/mingw/mailman/mingw-users/?viewmonth=200707&viewday=26
|
CC-MAIN-2014-41
|
refinedweb
| 719
| 75.2
|
When way in which your workflows are achieved has been re-designed in many cases to fit better with the ArcGIS platform and the Web GIS model as it has evolved today.
This topic outlines areas of the API that have undergone considerable changes and to provide guidance for re-factoring 10.2.x code for a 100.x app. Although this topic doesn't cover every change, it will help you get over some major migration hurdles. It will also help you decide whether functionality required for your app is available in 100.x.
Changes to for details.
In ArcGIS Runtime SDK for .NET, at 10.2.7, the Map and Scene objects were split out from the controls that display them (MapView and SceneView) in order to facilitate a Model-View-ViewModel (MVVM) architecture for your apps. At 100.0.0, this change was adopted by all ArcGIS Runtime SDKs. If your app was created with ArcGIS Runtime SDK for .NET 10.2.7, this will not affect your migration to 100.x.
Views
The GeoView base class, inherited by MapView and SceneView, is solely responsible for display and interaction, separating concerns from the model objects (Map and Scene) and allowing the APIs to be simplified and harmonized between the 2D and 3D worlds. GeoView contains graphics overlays, as well as operations, to easily identify features and graphics without having to write any layer type specific code. At 100.0.0, this change was adopted by all ArcGIS Runtime SDKs. If your app was created with ArcGIS Runtime SDK for .NET 10.2.7, this will not affect your migration to 100.x.
Loadable
The ILoadable ensures that graphics are always displayed on top of everything else in the view, even when layers are reordered or the map is changed. Graphics in an overlay are also reprojected, conforming to the spatial reference assigned to the view. Starting at 100.0.0, graphics may only be displayed in a GraphicsOverlay, GraphicsLayer is no longer available.
The guide topic Add graphics overlays to your app provides code for creating graphics overlays and adding them to the map. You can see the code for adding and working with graphics in a graphics overlay in Add graphics and text to graphics overlays.
Also at 100.x, there is a tables
ServiceFeatureTable now has a FeatureRequestMode that is like.
ServiceFeature graphics for an example of using these methods.
Geoprocessing
The 10.2.x Geoprocessor class has been replaced with GeoprocessingTask in 100.x. The task can create a geoprocessing job that tracks progress of the server processing. You can listen for status changes as the job progresses, and respond when it's complete by reading the results (outputs) from the job. The process is outlined in the following steps.
- Create a new GeoprocessingTask. displays content from ENC (Electronic Navigational Charts) data in S-57 format. In addition to displaying and identifying features, you can change various display settings for view groups, text, and other elements (such as isolated dangers, contours, color scheme, and so on). In 10.2.x, this functionality is available in the Esri.ArcGISRuntime.Hydrographic namespace. At 100.2.0, you'll find the same API in Esri.ArcGISRuntime.Hydrography.
Offline MobileMapPackage class, is a set of items bundled together for transport, often for use in offline workflows..
One change you will notice from the previous Identity challenge samples. Web in the guide.
Minor changes
Many of the breaking changes you will encounter when migrating your app from 10.2.x to 100.x are due to classes moving to a different namespace or changes to class or member names. This section describes some of the reorganizing and renaming in the API between these versions.
Namespace changes
Some of the namespaces that were available in 10.2.x of ArcGIS Runtime SDK for .NET have been removed. Usually, the classes that existed in these namespaces have been moved elsewhere. Sometimes, the same functionality exists at 100.x but has been implemented in a new class.
- Esri.ArcGISRuntime.Layers.
|
https://developers.arcgis.com/net/latest/wpf/guide/migrate-to-100-x-from-10-2-x.htm
|
CC-MAIN-2018-30
|
refinedweb
| 678
| 66.84
|
Pygal Tutorial: Part 1
Hi ML Enthusiasts! Today, in this part 1 of Pygal tutorial, we will be working on visualizing data using Pygal plots. From today, I will be introducing new feature to my blog posts, i.e., explaining Python codes and concepts through Jupyter notebooks. They are great for step-by-step analysis of the codes as well as the concepts. So, this is how it goes:
Visualizing data using Pygal
Pygal installation
Installing Pygal requires lxml library as a pre-requisite and then Pygal can be installed using pip. For doing so, run the following commands:
conda install lxml
pip install pygal
Importing Pygal
Next thing to be done is to import the pygal library in our notebook and setting an alias ‘py’ for it. This can be done by the following code:
import pygal as py
Line charts in Pygal
Now, let’s learn how to create a line chart using pygal. For doing so, we use the Line() function of Pygal. We use this by creating an object of pygal.Line() and using that object, we create the title, x-labels, y-labels etc for that chart. The code for creating the line chart is given below:
line = py.Line() line.title = "Salary variation of Shweta in the past 5 years" #Set the title of the line chart line.x_labels = (2014, 2015, 2016, 2017, 2018) #Setting the labels for x-axis line.add('Salary in lakhs in INR', [None, 3, 5, 8, 10, 15]) #Setting the salary values to be plotted on graph line.render_to_file("salary_variation.svg") #This saves the chart in the current library in the file salary_year_variation.svg stacked_line.render_in_browser()
The chart will get created and will be stored in a file named as “salary_year_variation.svg” in the library your jupyter notebook is saved. You can go and open the file with Google Chrome. Notice that when you hover over the line, the line becomes bold. When you hover over the points, you will be able to see the description of the points getting popped up.
Stacked line charts using Pygal
The code for the same is given below:
import numpy as np #importing numpy package with alias as 'np' import pandas as pd #importing pandas package with alias as 'pd'
We will do the analysis on house area vs price of houses based on their areas. We will be preparing our own datasets in this case. First, by using the random module of numpy, we will generate house_area in square feet with lowest value being 1000 sq. ft. and highest area being 1800 sq.ft.(Suppose a locality has house areas in this range only). This generates an array of arrays. To make the manipulations easier, we will use list() function to convert the array of arrays into list of arrays. The code for this is given below:
Generating house_area array
house_area = list(np.random.randint(low= 1000, high= 1800, size= (10,1))) house_area
[array([1186]), array([1798]), array([1377]), array([1258]), array([1371]), array([1079]), array([1520]), array([1303]), array([1304]), array([1060])]
Now, we will convert this list of arrays into list of floats using float() function. Please note that we have used list comprehension in both the steps. The output we get for the same is given below:
house_area = [float(l) for l in house_area] house_area
[1186.0, 1798.0, 1377.0, 1258.0, 1371.0, 1079.0, 1520.0, 1303.0, 1304.0, 1060.0]
Sorted function
Now, we will sort the house_area by using sorted() function.
house_area = sorted(house_area) house_area
[1060.0, 1079.0, 1186.0, 1258.0, 1303.0, 1304.0, 1371.0, 1377.0, 1520.0, 1798.0]
Generating price in lakhs
Now that we have generated house_area, we will generate the random prices for them.
price_in_lakhs = list(np.random.randint(low= 50, high= 100, size= (10,1))) price_in_lakhs
[array([70]), array([77]), array([99]), array([56]), array([52]), array([88]), array([67]), array([99]), array([86]), array([78])]
price_in_lakhs = [float(l) for l in price_in_lakhs] price_in_lakhs
[70.0, 77.0, 99.0, 56.0, 52.0, 88.0, 67.0, 99.0, 86.0, 78.0]
price_in_lakhs = sorted(price_in_lakhs) price_in_lakhs
[52.0, 56.0, 67.0, 70.0, 77.0, 78.0, 86.0, 88.0, 99.0, 99.0]
Normalizing the data
Now that we have both of them ready, let’s normalize them in order to make the comparison easy. The formula for normalisation is
x_normalised = (x-min(x))/range(x).
Since the list is sorted, Max(x) can be found by using x-1 and min(x) can be found using x0. Range(x) = max(x) – min(x). The code for this is as follows:
range_house_area = house_area[-1] - house_area[0] normalized_house_area = [(l - house_area[0])/range_house_area for l in house_area] normalized_house_area
[0.0, 0.025745257452574527, 0.17073170731707318, 0.2682926829268293, 0.32926829268292684, 0.33062330623306235, 0.42140921409214094, 0.42953929539295393, 0.6233062330623306, 1.0]
range_price_in_lakhs = price_in_lakhs[-1] - price_in_lakhs[0] normalized_price_in_lakhs = [(l - price_in_lakhs[0])/range_price_in_lakhs for l in price_in_lakhs] normalized_price_in_lakhs
[0.0, 0.0851063829787234, 0.3191489361702128, 0.3829787234042553, 0.5319148936170213, 0.5531914893617021, 0.723404255319149, 0.7659574468085106, 1.0, 1.0]
Obtaining the plot
Now that we have both the variables/features ready, let’s make stacked line chart for both of them. The code for this is as follows:
stacked_line = py.Line() stacked_line.title = "House area and price relation analysis" stacked_line.x_labels = map(str, range(0, 1)) #Setting the x-axis range from 0 to 1 and converting them into string. stacked_line.add('Normalized house areas', normalized_house_area) stacked_line.add('Normalized price in lakhs', normalized_price_in_lakhs) stacked_line.render_to_file("stacked_line.svg") stacked_line.render_in_browser()
Run the above code in your own notebook and you will be able to see below charts getting rendered/popped-up in your browser window:
So guys, with this we conclude our tutorial. Stay tuned for part 2 of pygal where we will talk about more interesting visualization techniques! For more updates and news related to this blog as well as to data science, machine learning and data visualization, please follow our facebook page by clicking this link.
|
https://mlforanalytics.com/2018/04/09/pygal-tutorial-part-1/
|
CC-MAIN-2021-21
|
refinedweb
| 1,012
| 63.19
|
Programming languages with dependent types allow us to specify powerful properties of values using the type system. By employing the Curry–Howard correspondence, we can also use these languages as proof languages for higher-order logics. In this blog post, I want to demonstrate that Haskell as supported by the Glasgow Haskell Compiler (GHC) can give us almost the same features.
The complete article can be seen as a kind of literate program. Extracting all code snippets and glueing them together yields a valid Haskell module. For your convenience, you can download the complete code as an ordinary Haskell source code file.
Prerequisites
Plain Haskell 2010 is not enough for emulating dependent types. We need support for generalized algebraic data types and for type synonym families. Furthermore, we want to use operator syntax on the type level for making our code easier to read. We declare the necessary language extensions:
{-# LANGUAGE GADTs, TypeFamilies, TypeOperators #-}
We want to define better typed versions of certain Prelude functions. For convenience, we want them to have the same names as their Prelude counterparts. Therefore, we hide the corresponding Prelude functions:
import Prelude hiding (head, tail, (++), (+), replicate)
Since Haskell does not come with a type for natural numbers, we make use of the natural-numbers package:
import Data.Natural
We are now ready to turn to the actual development.
Dependently typed programming
Dependent types are types that are parameterized by values. In Haskell, however, parameters of types have to be types again. So we represent values by types. Let us look how this works for natural numbers. The usual ADT declaration of natural numbers uses two data constructors
Zero and
Succ. These data constructors become type constructors now:
data Zero data Succ nat
Note that it does not matter what values the types
Zero and
Succ cover. It is most reasonable to leave these types empty.
Now we define a list type with a length parameter almost like we would do in Agda:
data List el len where Nil :: List el Zero Cons :: el -> List el len -> List el (Succ len)
If we let GHCi compute the type of
Cons 'H' $ Cons 'i' $ Cons '!' $ Nil ,
for example, it will correctly answer with
List Char (Succ (Succ (Succ Zero))) .
We can drop the static length information from lists by converting them to Haskell’s ordinary list type:
toList :: List el len -> [el] toList Nil = [] toList (Cons el els) = el : toList els
Using
toList, we implement a
Show instance for displaying values of type
List in GHCi:
instance (Show el) => Show (List el len) where show = show . toList
Let us actually make use of the length parameter in list types. We first construct a function
head, which can only be applied to non-empty lists and thus cannot fail:
head :: List el (Succ len) -> el head (Cons el _) = el
The type of the corresponding function
tail also shows that the length of a list’s tail is one less than the length of the original list:
tail :: List el (Succ len) -> List el len tail (Cons _ els) = els
A more advanced example of using static length information is list concatenation. Let us construct a dependently typed version of the well-known
++-operator. Its type should specify that the length of the result is the sum of the lengths of the arguments. So we have to implement addition of type-level naturals. We introduce a type synonym family for this:
infixl 6 :+ type family nat1 :+ nat2 :: * type instance Zero :+ nat2 = nat2 type instance Succ nat1 :+ nat2 = Succ (nat1 :+ nat2)
We can now define list concatenation as follows:
infixr 5 ++ (++) :: List el len1 -> List el len2 -> List el (len1 :+ len2) Nil ++ list = list Cons el els ++ list = Cons el (els ++ list)
Note that the type checker guarantees that our implementation of concatenation really fulfills the length constraint expressed in the type.
We want to implement a dependently typed version of the Prelude function
replicate, which takes a natural number
len and some value
val and returns a list that contains
len times the value
val. Its desired type would be
(len : Nat) -> el -> List el len
in an Agda-like language. This type gives the first argument the name
len. Since
len is used in the result type, the type of a result depends on the concrete argument.
The problem for our Haskell emulation of dependent types is that the
len argument of the function must be a value, while the
len parameter of
List must be a type. So we have to link value-level naturals and type-level naturals. We do this by defining a type
Nat with one parameter such that for each n ∈ ℕ with a type-level representation
nat, the type
Nat nat contains exactly one value, which represents n:
data Nat nat where Zero :: Nat Zero Succ :: Nat nat -> Nat (Succ nat)
If we ask GHCi for the type of the value
Succ (Succ (Succ Zero)) ,
we get the answer
Nat (Succ (Succ (Succ Zero))) ,
which demonstrates that the value is now reflected at the type level.
As in the case of
List, we can define a conversion function for forgetting the type parameter of
Nat, and a
Show instance based on it:
toNatural :: Nat nat -> Natural toNatural Zero = 0 toNatural (Succ nat) = succ (toNatural nat) instance Show (Nat nat) where show = show . toNatural
Analogously to the implementation of
(++), we can implement addition for values of type
Nat:
infixl 6 + (+) :: Nat nat1 -> Nat nat2 -> Nat (nat1 :+ nat2) Zero + nat2 = nat2 Succ nat1 + nat2 = Succ (nat1 + nat2)
However, we actually wanted to implement a dependently typed
replicate. We can do this as follows:
replicate :: Nat len -> el -> List el len replicate Zero _ = Nil replicate (Succ len) el = Cons el (replicate len el)
The definition of
Nat ensures that the first argument of
replicate and the type variable
len represent the same natural number. So the type of
replicate guarantees that the first argument determines the length of the result list.
Theorem proving
Theorem proving in a dependently typed programming language works by exploiting the Curry–Howard correspondence. Propositions correspond to types and their proofs correspond to expressions of the corresponding types. In this blog post, we will only discuss how to prove equations. Proving other things works analogously.
Let us first define the equality predicate. We can define a predicate by introducing a corresponding GADT. The data constructors of this GADT serve as atomic proofs, their types correspond to axioms. A type constructor
(:==) that implements equality is defined as follows:
infix 4 :== data val1 :== val2 where Refl :: val :== val
We implement a
Show instance for
(:==) that enables us to show the only possible normal form of an equality proof, which is
Refl:
instance Show (val1 :== val2) where show Refl = "Refl"
We will now prove that 0 is a right unit of addition, that is,
∀n ∈ ℕ . n + 0 = n .
It might seem reasonable to give the proof the polymorphic type
nat :+ Zero :== nat .
However, the proof has to be done by induction, so that we would have to do pattern matching on the natural number parameter. We cannot do pattern matching on a type, so we have to pass the natural number represented by
nat as a value of type
Nat nat. We implement the proof as follows:
rightUnit :: Nat nat -> nat :+ Zero :== nat rightUnit Zero = Refl rightUnit (Succ nat) = case rightUnit nat of Refl -> Refl
As a second and last example, we proof that addition is associative, that is,
∀n₁, n₂, n₃ ∈ ℕ . (n₁ + n₂) + n₃ = n₁ + (n₂ + n₃) .
The Haskell code is as follows:
assoc :: Nat nat1 -> Nat nat2 -> Nat nat3 -> (nat1 :+ nat2) :+ nat3 :== nat1 :+ (nat2 :+ nat3) assoc Zero nat2 nat3 = Refl assoc (Succ nat1) nat2 nat3 = case assoc nat1 nat2 nat3 of Refl -> Refl
Note that we pass all three natural numbers involved as values of
Nat, although we only do pattern matching on the first one. The reason is that we have to specify the second and third number in the recursive call. If we would not do this, they would have to be inferred, which turns out to be impossible.
So have we shown that Haskell can replace Agda if we are willing to write a bit of boilerplate code? Not really. A crucial property of Agda, which is important for proving theorems, is that all values are fully defined. In Haskell, however, values may be partially or completely undefined. In particular, the value ⊥, which denotes undefinedness, is an element of every type. So every proposition has at least one proof, which makes our logic inconsistent.
A solution is to accept a value as a proof only if it does not contain ⊥. We can check if ⊥ is present by evaluating the value completely. This succeeds if and only if there is no ⊥. There are two problems with this approach. First, it causes a runtime overhead, which is not necessary when using a language like Agda. Second, complete evaluation is not possible for arbitrary functions, since it would mean applying the functions in question to all possible arguments. Since function types correspond to implications, and implications occur often in general statements, this is a serious drawback.
So theorem proving is obviously something that should be left to languages that can handle it better than Haskell can. That said, I think that it is nevertheless fun to see how far we can go with present-day Haskell.
As it turns out, your Haskell theorems do not need to use values, thus solving your ⊥-problem. You can use logic programming with type classes to prove theorems. Also, your method of theorem proving also fails to ensure the type safety of the theorem statements themselves.
:+could still be extended invalidating the truth of the theorems in it’s previous uses. The solution to these two problems is posted here:
I do really like this method however, the syntax seems much cleaner.
I could surely extend
:+, like this, for example:
However, this would not really invalidate my theorems. The fact that 0 is a right unit of addition, for example, is encoded by the Haskell type
Nat nat -> nat :+ Zero :== nat.
If I pass a value of type
Nat ()to the proof of this theorem, I will receive ⊥ as the result, since the only value of type
Nat ()is ⊥, and thus the pattern matching done by the proof will fail. However, I have to check every alleged proof for bottoms anyhow.
The approach you present in Logic Programming with GADTs and Classes seems to be very similar to mine. The
Listtype you define there is completely analogous to my
Nattype. The difference is that you use classes with functional dependencies where I use type synonym families. As a result, you implement the different cases of
appendvia different instance declarations, while in my definition of
(+), I use the fact that pattern matching on GADT values restricts the type parameters of the GADT.
I cannot see how the definition of the
Isoclass in Almost LF in Haskell really ensures that the only
natwith
Iso Nat natare the type-level natural numbers. I could very well do this:
Note that even the informal requirement that
intoand
outofform an isomorphism is fulfilled, since both
Nat Bogusand
Bogusare empty.
That said, it is possible to prevent a Haskell-encoded predicate from being extended. I describe a generic approach to this in Subsection 6.2 of Generic Record Combinators with Static Type Checking.
Instead of using this generic implementation, you can also specialize it manually for each predicate. For example, you can define a natural number predicate as follows:
Note that the type of
specialize_Natis isomorphic to
All_Nat item -> forall nat . (Nat nat) => item nat.
The informal requirement for instances of
Natis that
closed_Natand
specialize_Natare inverses of each other.
If you try to make the
Bogustype from above an instance of
Nat, you will run into problems. There is no implementation of
specialize_Natthat preserves the property that
closed_Natand
specialize_Natare each other’s inverses. Actually, there is no type-correct implementation of
specialize_Natexcept ⊥.
Unless I am incorrect, in the ⊥ instance, the only difference between the class solution and the data family solution is that in the class solution, because the proofs are entirely on the level of types, they all get automatically evaluated at compile time, rather than having to add a check for ⊥ manually to run at runtime.
For ensuring classes are closed:
If you have
Iso Nat Bogus,
outof :: Nat Bogus -> Bogus. So you could define it as,
outof _ = ⊥yes. What is (or should have been), what kept these closed was that the module did not export
intoand
outof. Your solution is also cool, but I think still suffers the problem of requiring that every type have its own module (unless you want to perform bottom checks).
If you are doing proofs at the type level using classes, then you probably do not need to evaluate proof terms at runtime. When I said that your class-based and my type-family-based solution were similar, I only referred to how we implement functions like
appendand
(+)on both the type- and the value-level. I think in your blog posts you did not show how to actually proof things, did you?
If your module does not export
intoand
outof, you can still give the instance declaration for
Iso Nat BogusI showed, since this declaration does not contain any method implementations.
Unfortunately, my approach suffers from the need of bottom checks even if I put stuff related to a particular type in a separate module. Someone else can always write something like this:
So let us use Agda for proofs.
No, In my post my focus was not on theorem proving, just that an embedding of “Sort of LF” was possible, considering that we don’t have termination or totality checking in either of our cases. I’m only using the runtime to show that we can use this technique to meta program Haskell, and not just prove properties of Haskell.
I’m working under the assumption of “-Werror” being used, since the compiler can perform that check.
|
https://jeltsch.wordpress.com/2012/04/30/dependently-typed-programming-and-theorem-proving-in-haskell/
|
CC-MAIN-2015-35
|
refinedweb
| 2,351
| 58.52
|
This is the last installment of a four-part series of articles on the basics of creating and publishing reports using SQL Server Reporting Services:
- Part 1, provided a step-by-step guide to basic report creation
- Part 2 took a tour of some of the core SSRS features and functions that you’ll need to develop dynamic reports
- Part 3 focused entirely on the visual controls
Part 4 focuses on the Report Definition Language (RDL), publishing reports, and Report Builder 3.0. First, you’ll examine the component parts of a typical RDL file and learn how to use your knowledge of RDL to refine and customize your reports, if necessary.
You’ll then learn about deploying reports to the built-in site for SSRS, Report Manager. There are other ways to publish reports, such as within SharePoint, but this article will focus on the most basic mechanism.
Finally, you’ll take a look at Report Builder 3.0 Tool, the ad-hoc reporting tool that ships with SQL Server Reporting Services 2008 R2 and later. This report-building tool allows end-users to build custom reports based on report parts and shared datasets. Confused? Fear not, all will become clear!
Getting Started
In order to follow the examples, you will need to have the SQL Server database engine, SQL Server Reporting Services, and SQL Server Data Tools – BI (SSDT-BI) correctly installed and configured. If you need some help with this, please refer back to the links in Part 1 of this series. Next, download the code file for this article (see the Code Download link above). The code file contains two sample Visual Studio projects and a SQL Script for creating the
ReportDemo database. If you’ve not done so already, go ahead and create the database using the
ReportingDemoDatabaseScript.sql. You will not be creating any new reports from scratch in this article but instead using reports that were created in the Projects from Parts 1 and 3, all of which are included in the code download file.
Report Definition Language
If you really wanted to, you could develop SSRS reports in a vanilla text editor like Notepad. I don’t recommend it, though. Microsoft provides great tools that make report development easy with a drag-and-drop interface. However, every once in a while, there is a reason to take a look at the actual code and maybe even tweak it a bit. To do that, it helps to understand what you are looking at when you do take a peek at the code.
The definition of RDL provided by MSDN is succinct and hard to better, so I’ll use it here:
“A report definition contains data retrieval and layout information for a report. Report Definition Language (RDL) is an XML representation of this report definition.”
Report Definition Language (RDL) is an XML-based schema for defining reports, and the reports that SSRS generates from the SSDT-BI report designer are basically just XML. Each report has a body and will have a header and footer if defined.:.
Inside a typical RDL file
You don’t have to be an XML guru to understand the RDL file, and the easiest way to get familiar with the basics of RDL is to dive right in and take a look at the component part of a typical RDL file, in this case the RDL for the
ExpressionReport.rdl report that you developed back in Part 2, and which is included in the download project.
In SQL Server Data Tools – BI, open the ChartProject report solution, from the code download, navigate to the sample report, MyChart.rdl, in the solution explorer, right-click and select the View Code option. This opens the report in XML mode. The full XML for this file can be found in the code download bundle, but Figure 1 shows contents of the file with all nodes collapsed.
Figure 1
After the document element, the RDL files breaks down into the following major sections:
Document Element– defines the name of the report and the schema to which our RDL must conform
Body– defines all of the report items
Page– page headers and footers, if used
DataSources– defines all dedicated and shared data sources
DataSets– defines each data set used in the report
Parameters– all parameters defined for the report
Code
– any custom code, such as custom functions
At the very top of the code is the
Document element, as shown in Figure 2.
Figure 2
The document element is called
Report – no surprise there. It references two XML namespaces:
-
-
These namespaces explicitly define what is allowed inside the RDL document from an XML standpoint. To see this in action, I added an invalid tag to the report and received the error message shown in Figure 3.
Figure 3
Since the change I made did not conform to the published schema, the change was immediately flagged as an error because the report definition is now invalid.
NOTE: It is possible to create custom report items with a .NET language. See this MSDN article for more details.
You can expand the XML to review the code of any of the sections of the report. You’ll see all the properties that you are familiar with as well as some that may be new to you. Figure 4 shows a nice example from the
DataSets section of the
MyChart RDL file, displaying the actual query for the dataset.
Figure 4
Writing your own RDL
Now you have a good idea of the RDL that is written behind the scenes when the SQL Report Designer is doing its thing. This understanding of the report designer gives you the ability to manually tweak a report when necessary. I’ve only had to do this once or twice in over 10 years. One example I remember quite well involved a sub-report that, on the Report Manager site, was located in a different folder than the main report. The only way I could embed the sub-report was to manually change the link inside the XML. However, knowing RDL empowers you in other ways too. You are not restricted to using the Visual Studio Report designer, because SSRS Reports are not in some proprietary format. If you wish, you can roll your own report builder tool or RDL generator.
Configuring Reports for Deployment
Developing reports on your own computer can be quite fun and sometimes challenging, but the reports are not useful until they are published to a location that is accessible to the people who need to see the reports. There are many ways to publish reports, including to SharePoint or within custom applications. However, the easiest way to publish and manage reports is with the built-in Report Manager. This is also called Native Mode deployment. Report Manager is a small web site that can run on a separate web server or on the SQL Server that is hosting the SSRS databases. Starting with 2008, SSRS is not dependent on Internet Information Services (IIS) which makes DBAs more comfortable deploying it on the same server as the database engine.
Viewing the Reporting Services Configuration
The first article in the series walked through installing and configuring Report Manager and so if you have followed along you probably have Report Manager running on your computer right now. It’s a great tool for learning how to publish reports to your own computer, before presenting them to the real world.
To make sure Report Manager is configured and running, launch SQL Server Reporting Services Configuration Manager and connect to the Reporting Server instance, which in my case is a SQL Server running as a default instance, so MSSQLSERVER is the correct instance name.
Figure 5
After clicking Connect, you can review the various properties and settings of the Report Server. Click Web Service URL to find the URL of the report server to which you will deploy your reports.
Figure 6
Click Report Manager URL to see the URL for viewing and managing reports, as shown in Figure 7.
Figure 7
If SSRS and Report Manager are not configured, go back to the first article in the series to configure them before continuing to the next section.
Configuring a Report Project for Publication
The process of publishing, or deploying, an SSRS project copies the reports, data sources, and datasets to Report Manager. Once the reports are published, they can be viewed by anyone with the correct permissions. In this section, you’ll configure deployment of your reports to Report Manager, running on your local computer. The steps for deploying to a site in your enterprise network are the same; you’ll just have to modify the location.
In SQL Server Data Tools – BI, open ChartProject from the download. To deploy the ChartProject reports, you must configure the location of Report Manager in the project properties. Within the Solution Explorer, right-click on ChartProject, the project name, and select Properties. In the TargetServerURL property, fill in the Web Service URL you found earlier (see Figure 6). When deploying to a network location in your company, you may need to get the URL value from your DBA. Figure 8 shows the properties I am using. I have replaced my computer name with “localhost”.
Figure 8
In Figure8, you’ll see that there are several other target folders. For example, the TargetDatasourceFolder property shows where all of the shared data sources will end up in Report Manager. By default, the TargetReportFolder has the same name as the project but you can change this value if required.
Take a look at the OverwriteDatasets property, which is set to False. In many cases, you will create reports against a development or QA server instead of production. When this value is False, it will not let you overwrite an existing datasource with the same name. This will prevent your development settings from changing the production settings.
Click OK to accept the change to the URL.
Local Security Issues
When working on Windows 7 or 8, you may try to perform tasks that need Administrator permissions. Even if your account is an administrator account, those operations are blocked by default. This is not a bug, but a security feature to prevent malicious code from operating on your system.
This security feature will prevent you from publishing and viewing reports on Report Manager locally. One way to get around this is to launch SSDT-BI by holding down the shift key and right-clicking on the link, and then select Run as administrator. You will then be able to publish reports locally. When launching your favorite web browser to view Report Manager, you will need to do the same thing.
There is a way to set permissions for your account in SSRS to avoid this issue. Follow the directions in this MSDN article to learn more.
Deploying Reports
Now that the TargetServerURL is configured in your project, and you have addressed the local security issue, you are ready to publish some reports! Right-click the project name inside the Solution Explorer and select Deploy. The Output window should pop up to show you the status. Once my reports were deployed, I saw the messages in Figure 9.
Figure 9
If your reports did not deploy, you will have to review the error messages and troubleshoot. Most of the time, the problems stem from an incorrect or missing TargetServerURL or from permissions issues.
Viewing the Published Reports
Now that you have published the reports, you will want to view them on the Report Manager site. Launch your favorite web browser and navigate to the Report Manager URL (see Figure 7). If you receive an error message about permissions, review the previous “Local Security Issues” section.
If everything worked as expected, Report Manger should display the contents of the Home folder (the top-level folder in the Report Server folder hierarchy). In this case, you should see within it two sub-folders, as shown in Figure 10.
Figure 10
Click the ChartProject folder. You will see all of the reports from the project. Click one of the reports to run it. At this point, if you have errors connecting to the report, you can navigate to the data source set up in the Data Sources folder to troubleshoot the connection.
If the ReportDemo database and the Report Manager site are all located on the same server, such as your laptop, your credentials should work to run the report. If they are located on separate servers, your network account credentials from the Report Manager will not pass through to the database. This is called the “double-hop” problem. There are two ways around this issue. The easiest, but least secure way, is to use SQL Server security instead of AD security in the report. The other method is to configure Kerberos Authentication. Talk to your network administrators. When learning how to develop reports, I recommend running everything on one computer.
Figure 11 shows the Indicators report and the breadcrumb trail at the top for navigating back to any of the folders.
Figure 11
None of these reports have parameters, but if they did, the parameter controls would be found right above the report.
You have deployed the entire project, but you can deploy just one report if you wish. To do so, just right-click the report and select Deploy. You can also redeploy the project or a report, after making changes. If you redeploy, the reports will be overwritten without a prompt.
Securing Reports
You have seen how easy it is to publish reports to Report Manager directly from SSDT-BI. However, it is very important that only the correct eyes see the reports. On your own computer, you will not need to worry about security, but you may need to configure it on your enterprise wide SSRS deployment. In many companies, the person developing reports is not the same person securing them. However, it is useful to understand how the security works, even if it is not your job, just in case you are called in to help troubleshoot an issue.
You can set up permissions at the folder or report level. I strongly recommend that permissions are set up only at the folder level. You allow users to view reports in a given folder by assigning the appropriate roles, either to individual users or to an Active Directory group of which the user is a member. I recommend giving permissions at the AD level, not to individuals.
By default, folders and reports inherit permissions from folders higher in the hierarchy. For example, if the Everyone network group has permission to run reports at the Home folder level, then Everyone also has permission to view reports in all sub-folders, unless you enforce security by overriding the default permissions on each sub-folder, so that only the appropriate users can view the reports in each one.
There are many ways to do this but, for example, within the Home folder you might create folders for specific departments, and then assign permissions to the AD group for the departments. Inside the department folders you could have a Managers folder with reports only for managers. Figure 12 shows how this might look for the IT department.
Figure 12
Once the folders are in place, hover older a folder name to bring up a dropdown list of tasks and select Security (or open the appropriate folder, select Folder Settings from the top menu, and then open the Security page). Figure 13 shows the Security page, though note that you will only see groups such as the Everyone group if you are running in a network with Active Directory.
Figure 13
Click Edit Item Security and you will be prompted with a message telling you that you will break the inheritance from the parent folder. Click OK. Click New Role Assignment. This opens a page where you can assign roles to a named user or AD group, as shown in Figure 14.
Figure 14
To allow a user or group to view reports only, assign the Browser role. Remember that when assigning permission to a folder, all the reports in the folder will inherit those permissions. Always assign permissions to folders, not reports, to keep security manageable.
There are also two roles at the instance level: System Administrator and System User. To manage these permissions, click the Site Settings link at the top right of the page. The System User site role and the folder Report Builder role are needed by users who need to run Report Builder.
Managing Reports
There are so many factors that you can control in SSRS, that it is impossible to cover all of them in this article. Hover over a report name so that the drop-down list of tasks appears. Select Manage. Eight topic areas appear that you can manage, as shown in Figure 15.
Figure 15
You can set up subscriptions for automatically delivered reports, cache reports that run frequently with data that doesn’t often change, and much more.
Using Report Builder 3.0
Most of the time, a developer creates a report based on a set of requirements and then publishes the report where the person requesting it can run it. However, you may also have heard the term “self-service BI”, which means to give the end users the ability to create their own reports and dashboards. Report Builder 3.0 is a self-service BI tool.
Report Builder 3.0 enables the user to select from pre-defined datasets and report parts or to design reports from scratch. The user can use the simple drag-and-drop interface to build custom reports, wizards, or design a report with the same techniques that you use.
Starting in 2005, Report Builder has been a component of SSRS. The original versions of Report Builder required Data Models, basically a view of the data that could be used. All previous versions of Report Builder, along with Data Models, have been deprecated. Unlike the previous versions, Report Builder 3.0 looks and works almost exactly like the developer tool, SSDT-BI.
Report Builder is a great way to let end-users who know little or no T-SQL build their own reports. You can provide predefined parameter lists, data sources, datasets, and even tables and visual elements that they can use to build custom reports.
Here are the differences between Report Builder 3.0 and SSDT-BI:
- SSDT-BI allows you to work with projects of multiple reports while you can work with only one report at a time with Report Builder 3.0.
- SSDT-BI has an interface that is familiar to developers while Report Builder 3.0 looks more like Office.
- You can publish Report Parts with SSDT-BI. You can utilize Report Parts with Report Builder 3.0.
- SSDT-BI can integrate with source control programs while Report Builder 3.0 cannot.
- Report Builder 3.0 has more wizards than SSDT-BI.
Publishing Report Parts
In this exercise, you are going publish some report parts that will allow the end-users to create and customize their own reports. If you have followed along in this article, the ChartProject project should be configured for deployment. You will also need to configure the FirstProject. Go back to the “Viewing the Reporting Services Configuration” and “Configuring the Project for Publishing” sections to learn how to set up the properties.
Reports are composed of objects such as tables, and charts. Not only can you publish entire reports, you can also publish the individual objects so that they can be reused within Report Builder 3.0. You have seen that data sources are automatically deployed when you deploy a project. If the project has datasets, they are also deployed automatically when deploying the project.
You must mark each part of the report that you want to publish. Open up FirstProject from the downloaded code. Double-click the ParameterReport report to open it in the Design tab. From the menu, select Report | Publish Report Parts. This dialog allows you to choose which components of the report to publish as individual items and to rename them. Select StateCD and Tablix1. Click the word Tablix1 and change the name to Customers, as shown in Figure 16
Figure 16
Click OK to dismiss the dialog box. Right-click the project name and choose Deploy. If the deployment is successful, open Report Manager where you should see a new folder called Report Parts and one called FirstProject, as shown in Figure 17.
Figure 17
The FirstProject folder should contain all the reports from the project. The Report Parts folder should contain those two parts you marked for publishing, as shown in Figure 18.
Figure 18
Now open up the ChartProject. Double-click the MyChart report to open it in design view. Open the Publish Report Parts dialog found in the Report menu. Select Chart1, but change the name to SalesChart. Figure 19 shows how the dialog should look. Click OK.
Figure 19
Repeat the process with the Gauge report. Publish the gauge and name it SalesGauge. Also repeat the process with the Map report. Publish the map and name it SalesMap. Deploy the project.
Create a Custom Report with Report Builder Getting Started dialog.
Figure 20
For now, select Blank Report. The Report Builder interface is similar to the one found in SSDT-BI, but ribbons have replaced menus and some windows. You still have the Report Data window, but the toolbox items are found on the Insert tab. There is no need for a Solution Explorer because you can work on only one report at a time. Figure 21 shows how the blank report and the layout look.
Figure 21
On the left side of the Insert ribbon, click Report Parts. This opens a Report Part Gallery on the right. Click the search button, a magnifying glass, to show all of the available published parts. You can also use the search box to filter the list.
Figure 22
The person creating the report can drag whichever items they need to see on the report, for example, to build a dashboard. If they have the skills, they can also create data sources and datasets.
To build the first report, drag in the SalesChart and SalesGauge. When you do, the data source and datasets are automatically added to the report.
Figure 23
On the Home ribbon, click Run to view the report. To publish the report, click the Save button. The Save as Report dialog box allows you to publish the report or save the report file locally.
Figure 24
Publish the report by naming it RB1 and clicking Save. Now go back to Report Manager to confirm that the report you created shows up, as shown in Figure 25. You may need to refresh the page to see the report.
Figure 25
Close Report Builder and launch it again. Select Blank Report. This time add the Customers table to the report. Look at the Parameters section of the Report Data window. The parameter was automatically added for you. Run the report to see how it looks and then publish it.
To really get the most benefit from Report Builder 3.0, you will have to do some planning and work. Are there several parameter lists that would be beneficial for multiple reports? Are there several visual items that can be filtered by the same parameters so that they can create an interactive dashboard? By working with the business users and understanding the data, you can create a valuable resource for your company.
Conclusion
I hope this tutorial series has given you some insight into the capabilities of SQL Server Reporting Services. There are many more features for you to discover. Just to name a few, I suggest you look into click-through reports, report caching and report subscriptions.
Happy reporting…!
|
https://www.red-gate.com/simple-talk/sql/reporting-services/sql-server-reporting-services-basics-deploying-reports/?utm_source=simpletalk&utm_medium=weblink&utm_content=ssrsbasics1
|
CC-MAIN-2019-22
|
refinedweb
| 3,997
| 62.88
|
Content
All Articles
Python News
Numerically Python
Python & XML
Community
Database
Distributed
Education
Getting Started
Graphics
Internet
OS
Programming
Scientific
Tools
Tutorials
User Interfaces
ONLamp Subjects
Linux
Apache
MySQL
Perl
PHP
Python
BSD
Building Decision Trees in Python
Pages: 1, 2, 3, 4, 5
With most of the preliminary information out of the way, you can now look at the actual decision tree algorithm. The following code listing is the main function used to create your decision tree:
def create_decision_tree(data, attributes, target_attr, fitness_func):
"""
Returns a new decision tree based on the examples given.
"""
data = data[:]
vals = [record[target_attr] for record in data]
default = majority_value(data, target_attr)
# If the dataset is empty or the attributes list is empty, return the
# default value. When checking the attributes list for emptiness, we
# need to subtract 1 to account for the target attribute.
if not data or (len(attributes) - 1) <= 0:
return default
# If all the records in the dataset have the same classification,
# return that classification.
elif vals.count(vals[0]) == len(vals):
return vals[0]
else:
# Choose the next best attribute to best classify our data
best = choose_attribute(data, attributes, target_attr,
fitness_func)
# Create a new decision tree/node with the best attribute and an empty
# dictionary object--we'll fill that up next.
tree = {best:{}}
# Create a new decision tree/sub-node for each of the values in the
# best attribute field
for val in get_values(data, best):
# Create a subtree for the current value under the "best" field
subtree = create_decision_tree(
get_examples(data, best, val),
[attr for attr in attributes if attr != best],
target_attr,
fitness_func)
# Add the new subtree to the empty dictionary object in our new
# tree/node we just created.
tree[best][val] = subtree
return tree
The create_decision_tree function starts off by declaring three variables: data, vals, and default. The first, data, is just a copy of the data list being passed into the function. The reason I do this is because Python passes all mutable data types, such as dictionaries and lists, by reference. It's a good rule of thumb to make a copy of any of these in order to keep from accidentally altering the original data. vals is a list of all the values in the target attribute for each record in the data set, and default holds the default value that is returned from the function when the data set is empty. That is simply the value in the target attribute with the highest frequency, and thus, the best guess for when the decision tree is unable to classify a record.
create_decision_tree
data
vals
default
The next lines are the real nitty-gritty of the algorithm. The algorithm makes use of recursion to create the decision tree, and as such it needs a base case (or, in this case, two base cases) to prevent it from entering an infinite recursive loop. What are the base cases for this algorithm? For starters, if either the data or attributes list is empty, then the algorithm has reached a stopping point. The first if-then statement takes care of this case. If either list is empty, then the algorithm returns a default value. (Actually, for the attributes list, check to see whether it has only one attribute in it, because the attributes list also contains the target attribute, which the decision tree never uses; that is what the tree should predict.) It returns the value with the highest frequency in the data set for the target attribute. The only other case to worry about is when the remaining records in the data list all have the same value for the target attribute, in which case the algorithm returns that value.
attributes
if-then
Those are the base cases. What about the recursive case? Well, when everything else is normal (that is, the data and attributes lists are not empty and the records in the list of data still have multiple values for the target attribute), the algorithm needs to choose the "next best" attribute for classifying the test data and add it to the decision tree. The choose_attribute function is responsible for picking the "next best" attribute for classifying the records in the test data set. After this, the code creates a new decision tree containing only the newly selected "best" attribute. Then the recursion takes place. In other words, each of the subtrees is created by making a recursive call to the create_decision_tree function and adding the returned tree to the newly created tree in the last step.
choose_attribute
The first step in this process is getting the "next best" attribute from the set of available attributes. The call to choose_attribute takes care of this step. The next step is to create a new decision tree containing the chosen attribute as the root node. All that remains to do after this is to create the subtrees for each of the values in the best attribute. The get_values function cycles through each of the records in the data set and returns a list containing the unique values for the chosen attribute. Next, passes to the create_decision_tree function along with the list of remaining attributes (minus the currently selected "next best" attribute). The call to create_decision_tree will return the subtree for the remaining list of attributes and the subset of data passed into it. All that's left is to add each of these subtrees to the current decision tree and return it.
best
get_values
get_examples
val
If you're not used to recursion, this process can seem a bit strange. Take some time to look over the code and make sure that you understand what is happening here. Create a little script to run the function and print out the tree (or, just alter test.py to do so), so you can get a better idea of how it's functioning. It's really a good idea to take your time and make sure you understand what's happening, because many programming problems lend themselves to a recursive solution--you just may be adding a very important tool to your programming arsenal.
That's about all there is to the algorithm; everything else is just helper functions to the main algorithm. Most of the functions should be fairly self-explanatory, with the exception of the ID3 heuristic.
Pages: 1, 2, 3, 4, 5
Next Page
Sponsored by:
© 2017, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
|
http://archive.oreilly.com/pub/a/python/2006/02/09/ai_decision_trees.html?page=3
|
CC-MAIN-2017-43
|
refinedweb
| 1,087
| 57.71
|
#include <berryIApplication.h>
Bootstrap type for an application. An IApplication represent executable entry points into an application. An IApplication can be configured into the Platform's
org.blueberry.osgi.applications extension-point.
Clients may implement this interface.
Definition at line 33 of file berryIApplication.h.
Starts this application with the given context and returns a result. This method must not exit until the application is finished and is ready to exit. The content of the context is unchecked and should conform to the expectations of the application being invoked.
Applications can return any object they like. If an
Integer is returned it is treated as the program exit code if BlueBerry is exiting.
Note: This method is called by the platform; it is not intended to be called directly by clients.
Forces this running application to exit. This method should wait until the running application is ready to exit. The Start should already have exited or should exit very soon after this method exits
This method is only called to force an application to exit. This method will not be called if an application exits normally from the Start method.
Note: This method is called by the platform; it is not intended to be called directly by clients.
Exit object indicating normal termination
Definition at line 39 of file berryIApplication.h.
Exit object requesting that the command passed back be executed. Typically this is used to relaunch BlueBerry with different command line arguments. When the executable is relaunched the command line will be retrieved from the
BlueBerry.exitdata system property.
Definition at line 51 of file berryIApplication.h.
Exit object requesting platform restart
Definition at line 44 of file berryIApplication.h.
|
https://docs.mitk.org/nightly/structberry_1_1IApplication.html
|
CC-MAIN-2022-21
|
refinedweb
| 281
| 51.14
|
When implementing sssd on SL7 we had to decide how to manage the configuration file (
/etc/sssd/sssd.conf) used by sssd. Starting and stopping of the daemon itself is done by systemd. We considered a custom component, but sssd.conf uses an INI-file syntax and LCFG already has lcfg-inifile for just such configuration. Any custom component would be largely duplicating the work done by lcfg-inifile.
It is also quite difficult to write a sensible specific component for something like sssd, where the number of options are many and varied (see
sssd.conf(5) and the additional man pages referenced at the end). The danger is that you implement specific resources for the features you personally require and add more and more to this as time passes
(see lcfg-openldap for how this can end up looking). It was thought, in this case, that a more generic approach was better suited.
Intitially we used lcfg-inifile (with a few local modifications, since implemented upstream). What this doesn’t give us, however, is namespace separation (i.e. it would be easy to break sssd when configuring inifile resources for another purpose). We decided to look into sub-classing the lcfg-inifile component in order to use its functionality, and at the same time adding anything specific to sssd on top.
This is surprisingly easy to do, providing the component is written in perl and the component code is delivered in a perl module.
To inherit the resources from the parent component, we added the following to sssd.def:
#include "mutate.h" #include "inifile-2.def" !schema mSET(@LCFG_SCHEMA@)
This means that the sssd component supports all the resources provided by lcfg-inifile.
We also add the following resources:
!files mSET(sssd) file_sssd /etc/sssd/sssd.conf owner_sssd root group_sssd root mode_sssd 0600 purge_sssd no useservice_sssd yes onchange_sssd sssd restart
This essentially hard-codes the configuration file, ownership, permissions and behaviour when the file changes (all of this can of course be overridden).
It would have been nice to have been able to mandate that the sssd.conf file has an [sssd] section, with something like this in sssd.def:
!sssd_sections mSET(sssd)
This doesn’t work as planned, however, as this is a default value and in LCFG these are only applied if the value is not set in any other place. This would mean that any subsequent mutation (e.g. an mADD of other sections) would lead to the default value never being used. Header files will be used for any such initial configuration.
Other than the schema, the other aspect of sub-classing is the code itself. This is implemented using standard perl sub-classing, e.g. For sssd we have no additional code so LCFG::Component::Sssd simply looks like this:
package LCFG::Component::Sssd; # -*- perl -*- use strict; use warnings; use v5.10; our $VERSION = '@LCFG_VERSION@'; use base qw(LCFG::Component::Inifile); 1;
If we require custom code, then we could add our own methods (calling the parent class’s method(s) as required).
One thing which would be nice to be able to add for a sub-classed component is additional validation for some resources. This is quite difficult in this case, as we can’t mandate what resources are named, particularly when taglists are involved. It would probably require a custom, non sub-classed component to be written, with all that this entails. My personal opinion is that a syntax-checking tool [1] is a better approach to a complex system such as sssd.
[1]
|
http://blog.inf.ed.ac.uk/toby/2015/02/13/the-sssd-component-and-sub-classing/
|
CC-MAIN-2019-47
|
refinedweb
| 592
| 64.61
|
Mallett wrote:
>?
I'm gathering "glLib.glLibLight" is your code. You'll have a __del__
method on one of those objects that tries to call e.g. an OpenGL
function. During interpreter shutdown the global namespaces of modules
are cleared out so that every name is set to None. Your __del__ method
is trying to call a function by name and the result is an attempt to
call the None object. If you need to have access to a function in a
__del__ method you need to arrange to be sure that function is available
(e.g. by binding as an argument) or check that it is non-null before
calling it, or catch the error in the __del__.
Incidentally, it is generally better to use weakrefs rather than __del__
methods, as __del__ methods prevent garbage collection from operating if
there is a loop in your object references. See the vbo module for an
example of usage, though as I read it I realize that it's not properly
handling cases where the namespace is cleared out before it's called
either. (Should catch the errors to make it safe).
HTH,
Mike
--
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder?
Ian
Thanks.
The problem was that __del__() tried to call an OpenGL function (to disable
the light). Going "del Light1" before exiting fixed the problem.
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
|
https://sourceforge.net/p/pyopengl/mailman/message/22019410/
|
CC-MAIN-2017-26
|
refinedweb
| 268
| 74.59
|
I have just installed spicework and just setting it up. I would like the ability to go to inventory click on a machine and then select rdp from trouble shooting like in the video. However i have no such option. is it a plugin or something or am i just missing something?
Feb 12, 2010 at 7:08 UTC
And the device you are trying to troubleshoot is defined as a Workstation?
6 Replies
Feb 12, 2010 at 6:31 UTC
Keep IT Simple Technology Group is an IT service provider.
Did you read - ?
Feb 12, 2010 at 6:42 UTC
yes but i don't have the option from my trouble shooting section as the video shows. how do you enable this feature.
Thanks in advance
Feb 12, 2010 at 6:47 UTC
Are you sure you are on the correct screen? Go to Inventory, then Workstations, then pick one of your Windows PCs. The remote Control option should be there on the lower right.
The option will only show on certain areas of Spiceworks, so make sure you are on the correct screen.
Feb 12, 2010 at 6:55 UTC
def on the same screen as video as you said. But its not thier.
Feb 12, 2010 at 7:08 UTC
And the device you are trying to troubleshoot is defined as a Workstation?
Feb 12, 2010 at 7:16 UTC
Thanks lee
It was not the correct type..
Thanks once again
|
https://community.spiceworks.com/topic/88973-how-do-you-add-rdp-to-trouble-shooting-tools
|
CC-MAIN-2017-13
|
refinedweb
| 244
| 83.56
|
Red Hat Bugzilla – Bug 1313210
Cinder volume could not be attached to disk before the '60s' timeout duration on containerized openshift
Last modified: 2016-05-12 12:30:51 EDT
Description of problem:
On container installed AEP, pods with cinder volume can not be attached to disk within the 60s timeout duration. Could not reproduce this on RPM installed environments on same OpenStack.
Version-Release number of selected component (if applicable):
openshift v3.1.1.908
kubernetes v1.2.0-alpha.7-703-gbc4550d
etcd 2.2.5
How reproducible:
Always
Steps to Reproduce:
1. Have environments properly configured openstack as cloud provider
2. Create a PVC which dynamically creates a PV
oc create -f
3. After PV and PVC are bound, create a pod
oc create -f
4. oc get pods; oc get events
Actual results:
After step 4: Pod is in status 'ContainerCreating'.
Events showed timeout error.
FIRSTSEEN LASTSEEN COUNT NAME KIND SUBOBJECT REASON SOURCE MESSAGE
11m 11m 1 cinderpd Pod Scheduled {default-scheduler } Successfully assigned cinderpd to openshift-163.lab.eng.nay.redhat.com
10m 29s 10 cinderpd Pod FailedMount {kubelet openshift-163.lab.eng.nay.redhat.com} Unable to mount volumes for pod "cinderpd_jhou(5fd1dab6-df7f-11e5-9f0d-fa163e554a2b)": Could not attach disk: Timeout after 60s
10m 29s 10 cinderpd Pod FailedSync {kubelet openshift-163.lab.eng.nay.redhat.com} Error syncing pod, skipping: Could not attach disk: Timeout after 60s
The node logs showed:
```
Mar 01 15:55:33 openshift-163.lab.eng.nay.redhat.com docker[18282]: E0301 15:55:33.049298 18326 kubelet.go:1716] Unable to mount volumes for pod "cinderpd_jhou(b0fa55bb-df82-11e5-9f0d-fa163e554a2b)": Could not attach disk: Timeout after 60s; skipping pod
Mar 01 15:55:33 openshift-163.lab.eng.nay.redhat.com docker[18282]: E0301 15:55:33.049317 18326 pod_workers.go:138] Error syncing pod b0fa55bb-df82-11e5-9f0d-fa163e554a2b, skipping: Could not attach disk: Timeout after 60s
Mar 01 15:55:33 openshift-163.lab.eng.nay.redhat.com docker[18282]: I0301 15:55:33.049382 18326 server.go:577] Event(api.ObjectReference{Kind:"Pod", Namespace:"jhou", Name:"cinderpd", UID:"b0fa55bb-df82-11e5-9f0d-fa163e554a2b", APIVersion:"v1", ResourceVersion:"3198", FieldPath:""}): type: 'Warning' reason: 'FailedMount' Unable to mount volumes for pod "cinderpd_jhou(b0fa55bb-df82-11e5-9f0d-fa163e554a2b)": Could not attach disk: Timeout after 60s
```
Expected results:
Should be able to mount before timeout occurs.
Additional info:
I failed to set up OpenShift in OpenStack running as containers. Internal OS1 cloud is slow as hell and ansible script fails at various stages.
Can you please give me access to a machine, where it is reproducible so I can take a look? Or teach me how to provision one, I heard you have some scripting around it.
Finally, I am able to reproduce it. It's indeed caused by containerized openshift-node. When it attaches a cinder (or any other) volume to the host, it expects appropriate device created in /dev. Since openshift runs in a container, it does not see real /dev/ but the container one. And it times out waiting for the attached device.
As a solution, I would propose to run openshift-node with "docker run -v /dev:/dev". Or OpenShift/Kubernetes must be changed to look for devices in configurable directory, not hardcoded /dev/.
The same should happen also on GCE or with containerized OpenShift attaching iSCSI, Ceph RBD or any other block device. AWS might be protected from this error as device names are assigned by kubelet (and thus do not need to be loaded from /dev) - I did not check this as running containerized OpenShift is quite painful.
Jianwei, I am still very interested in some automated way how to run containerized OpenShift on OpenStack and/or AWS, especially with nightly builds.
So, can anyone add "-v /dev/:/dev" to /etc/systemd/system/openshift-node.service when running node as container? Is it a good idea?
Reassigning to Contaners component.
experimental patch:
Adding Scott to cc:. You're the last one who updated the .service files - can you please look at it?
The mountpoint check should be running in the host mount namespace -- why do we need to mount in /dev?
Because volume plugins are not aware of running in container. Only mounter is.
Why is this assigned to me? Jon? This looks to be specific to the container.
Fixed by
Assigning to Scott, he did the fix. No development work should be needed now, we're just waiting for QE to the bug is really fixed.
This should be in OSE v3.2.0.7 that was build and pushed to qe today.
Tested on
openshift v3.2.0.7
kubernetes v1.2.0-36-g4a3f9c5
etcd 2.2.5
Steps were same with bug description.
Pod status remained in 'ContainerCreating'
# oc get pods
NAME READY STATUS RESTARTS AGE
cinderpd 0/1 ContainerCreating 0 10m
Run docker exec interactively in the node container, tailf the /var/log/messages, found following errors:
```
Mar 24 06:56:06 openshift-111 atomic-openshift-node: I0324 06:56:06.904016Mount' Unable to mount volumes for pod "cinderpd_jhou(8d277d8b-f1ad-11e5-af25-fa163e4f5f19)": exit status 32
Mar 24 06:56:06 openshift-111 atomic-openshift-node: I0324 06:56:06.904103Sync' Error syncing pod, skipping: exit status 32
```
Went to the openstack console -> volumes, the UI showed that the volume was in-use and was attached to my node 'openshift-111.lab.eng.nay.redhat.com'. But openshift thought it was a failed mount.
Furthermore, the PV I created was dynamically provisioned, the pod was stuck in 'ContainerCreating', so I deleted the pod and pvc, the provisioned PV and volume were left behind, they were not deleted.(If this is later considered another issue, I will open another bug to track).
There is something wrong with OpenShift nsenter mounter, I'll look at it.
Fixed mounter:.
Waiting for review.
Merged as origin PR:
Merge failed. Please try merging again.
8501 just merged
Should be in atomic-openshift-3.2.0.18-1.git.0.c3ac515.el7. This has been built and staged for qe.
Verified on containerized setup of
openshift v3.2.0.18
kubernetes v1.2.0-36-g4a3f9c5
etcd 2.2.5
Run reproduce steps, this bug is not reproduced now. Mark.
|
https://bugzilla.redhat.com/show_bug.cgi?id=1313210
|
CC-MAIN-2018-17
|
refinedweb
| 1,048
| 59.7
|
Forum Index
Summary: auto ref returns a reference its own stack
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: normal
Priority: P2
Component: DMD
AssignedTo: nobody@puremagic.com
ReportedBy: reachzach@gmail.com
--- Comment #0 from Zach the Mystic <reachzach@gmail.com> 2013-02-19 10:54:14 PST ---
I'm conservatively marking this 'normal' although it actually seems 'major' to
me.
Monarch Dodra has said that this code compiles:
import std.typecons;
auto ref foo(T)(auto ref T t)
{
return t[0];
}
void main()
{
int* p = &foo(tuple(1, 2));
}
Our concern is that p could only be pointing to the vaporized stack at this point. tuple(1,2) is a rvalue struct type, which means that function 'foo' should be interpreting its parameter 't' as a value, not a reference. t[0] therefore is a derived from a value type, which should not be returnable by ref.
Value parameters should not be returnable by 'ref'. That is an obvious stack-breaking maneuver. I don't know exactly where the problem is at this point, or if there are multiple unsafe operations here:
1) auto ref parameter assumed to be a reference when spec says its a value
2) index of a tuple not understood to be derived from a value parameter (i.e.
local)
3) 'auto ref' completely defeating its purpose by returning a reference to a
value
4) some syntactical ambiguity with '&foo(tuple(1,2))' which I'm not aware of
5) taking the address of something returned as a value
--
Configure issuemail:
------- You are receiving this mail because: -------
|
http://forum.dlang.org/thread/bug-9537-3@http.d.puremagic.com%2Fissues%2F
|
CC-MAIN-2016-36
|
refinedweb
| 267
| 51.28
|
How to get a variable from plugin.tag
On 15/03/2013 at 15:55, xxxxxxxx wrote:
Hello everybody,
i feel a bit stupid, but I have no idea and I do not really know the right keywords for finding solutions.
I have a plugin.tag, which is doing some stuff and storing that stuff in a list.
Now Id like to continue to work with the list in a python-tag. How can I get that list from the plugin?
For example:
class PlgTAG(plugins.TagData) : list_ = ["Hello", 12.3, "Everybody"] def Init(self, node) : return True def Message(self, node, type, data) : return True ...
Thanks and greetings
rown
On 15/03/2013 at 16:05, xxxxxxxx wrote:
In what context exactly do you want to retrieve the list? Your example is not very meaningful.
On 15/03/2013 at 16:38, xxxxxxxx wrote:
Hello Niklas,
yes, you are right. The example isnt meaningful. Id like to do something like this:
class PlgTAG(plugins.TagData) : list_ = [] def Init(self, node) : return True def Message(self, node, type, data) : return True def AnyFunctionToDefineList(self, ... ) : self.list_ = ["Hello", 12.3, "Everybody"]
PythonTag
import c4d #Welcome to the world of Python def main() : tag = The plugintag list_ = tag.GetTheListSomehow() Do stuff with list_
On 16/03/2013 at 00:50, xxxxxxxx wrote:
Your plugin tag must be attached to an object in the scene, it can't exist on its own. So in your python tag, you could do something like:
* look for the first active object in the scene
* check to see if it has your plugin tag attached to it
* if it does, get the list
How you get the list depends on what it is. If it's an InExclude list, you can get the tag's BaseContainer, then get the list from that. If it's an array (as you showed in your code) you'll have to make it available to other objects in some way. Then the python tag can get hold of the list and do whatever with it.
It's easy in C++ but I'm not sure if the same method works in Python. In C++ you would probably make the array private, then provide getter/setter functions to let another object access it. Or do it the dirty way of just making the array public, then anything can access it but without any checks on the plugin's part as to what they do with it.
On 16/03/2013 at 02:09, xxxxxxxx wrote:
Hello spedler,
thanks for reply. I know how to get my tag in python-tag and checking if its attached and so. The example is just an example.
Originally posted by xxxxxxxx
If it's an array (as you showed in your code) you'll have to make it available to other objects in some way.
But thats what I want. I do not know anything about C++, so Ive to take a look what private means and getter/setter is.
Is C++ -> public the same as Python -> global? If so, Im still not sure how to call the list/array from python tag.
Thanks very much
rown
On 16/03/2013 at 02:46, xxxxxxxx wrote:
It doesn't work with Python unfortunately. We do not have access to the NodeData of a plugin in
Python, or better say we can not get the NodeData from a BaseList2D object! It would be possible
with a bit of hacking, but it's not very "beautiful".
You could exchange information via a Python module or a c4dtools.library.Library class. I do
not recommend the first one. An example for the c4dtools Library to be put in your Python plugin
file:
# # Python Plugin File # import c4d import weakref import c4dtools class PluginTag(c4d.plugins.TagData) : op = None instances = [] def Init(self, op) : self.instances.append(weakref.ref(self)) self.list_ = [] self.op = op return True def Free(self) : try: self.instances.remove(weakref.ref(self)) except ValueError: pass # ... class MyLibrary(c4dtools.library.Library) : class Meta: # Global unique identifier! name = 'my-super-duper-cool-library' def get_plugin_tags(self) : return PluginTag.instances[:] # # Python Tag (or just somewhere else than the plugin file) # import c4dtools lib = c4dtools.load_library('my-super-duper-cool-library') for data in lib.get_plugin_tags() : data = data() # dereference the weakref if not data: continue print data.list_
Note that this only works when you place the c4dtools module somewhere the Python Interpreter
can always find it, and not as a local distributed dependency as described in this article.
On 16/03/2013 at 03:15, xxxxxxxx wrote:
Hey Niklas,
thank you very much. I´ll try your lines.
But one other question. Is it easier/allowed to exchange information between NodeData(plugin.tag) and BaseData(command.tag)?
On 16/03/2013 at 03:24, xxxxxxxx wrote:
the most common approach would be messages for such a problem. both the sending
and the recieving class would implement a message method and therefore had to be
derived from a c4d class which implements such a method. but i have never tried this
from a script (python-tag).
On 16/03/2013 at 03:24, xxxxxxxx wrote:
Hi rown,
yes it is allowed, but limited in Python. You can easily exchange data within C++ between the
plugin classes.
@Ferdinand:
You can not send a Python object via messages (from Python). But actually.. it's a good idea. This
would be possible to implement I think. Maybe they can add it for R15.
On 16/03/2013 at 04:29, xxxxxxxx wrote:
i am not talking about sending the instance, but his data, some arrays or whatever.
and aside from that. the data contains pyobjects, not sure if i do understand pyobjects
correctly, but aren't they meant to hold references to methods and such stuff too ?
never went down very far this rabbit hole, sending some variables always has been
enough for me.
or i musunderstood this thread, i thought he has pluginclass a with member b. now he
wants to read b from somewhere only knowing the gelistnode instance associated with
his plugin.
On 16/03/2013 at 04:35, xxxxxxxx wrote:
Hi Ferdiand,
Holy Sh*t I really didn't know that was possible!
import c4d MY_MSG = 5000140436 class Test(c4d.plugins.ObjectData) : def Message(self, op, msg, data) : if msg == MY_MSG: data.do_stuff() return True class Foo(object) : def do_stuff(self) : print "Foo.do_stuff()" def main() : op.Message(MY_MSG, Foo())
And you knew that? I always thought that was not possible (didn't try it out since now, though)!
That's so awesome!
On 16/03/2013 at 04:44, xxxxxxxx wrote:
Seriously, is that in the documentation?! I never read it anywhere! From several reasons and
thinkings I concluded it would not be possible. I see, I should just have tried it out!
Anyway, rown, something like this should work then:
MSG_GIMMELIST = 10000234 # Unique Identifier from the Plugincafe! class PlgTAG(plugins.TagData) : list_ = [] def Init(self, node) : return True def Message(self, node, type, data) : if type == MSG_GIMMELIST: data.value = self.list_ return True def AnyFunctionToDefineList(self, ... ) : self.list_ = ["Hello", 12.3, "Everybody"]
MSG_GIMMELIST = 10000234 # Unique Identifier from the Plugincafe! class ValueBox(object) : def __init__(self, value=None) : super(ValueBox, self).__init__() self.value = value def main() : tag = op.GetTag(c4d.Tplg) box = ValueBox() tag.Message(MSG_GIMMELIST, box) print box.value
Best,
-Niklas
On 16/03/2013 at 05:05, xxxxxxxx wrote:
IT IS UNBELIEVABLE!!!
Thank you both very much! Thanks Devil for letting Niklas know that and thanks Niklas for letting me know how it works.
Greetings
rown
On 16/03/2013 at 05:09, xxxxxxxx wrote:
My thanks go to Ferdinand as well, I never would've known that if he wouldn't have told me. :)
On 16/03/2013 at 06:35, xxxxxxxx wrote:
lol, you are welcome. and no i didn't know it exactly, but i assumed it. yannick showed here
once how to unpack pyobject data from a message method, which led me to some reading
about the pyobject class.
|
https://plugincafe.maxon.net/topic/7036/7946_how-to-get-a-variable-from-plugintag
|
CC-MAIN-2020-40
|
refinedweb
| 1,349
| 75.81
|
Middleware¶
Middleware is an essential part of any modern web framework. It allows you to modify requests and responses as they pass between the client and your server.
You can imagine middleware as a chain of logic connecting your server to the client requesting your web app.
Version Middleware¶
As an example, let's create a middleware that will add the version of our API to each response. The middleware would look something like this:
import HTTP final class VersionMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Response { let response = try next.respond(to: request) response.headers["Version"] = "API v1.0" return response } }
We then supply this middleware to our
Droplet.
import Vapor let config = try Config() config.addConfigurable(middleware: VersionMiddleware(), name: "version") let drop = try Droplet(config)
Tip
You can now dynamically enable and disable this middleware from your configuration files.
Simply add
"version" to the
"middleware" array in your
droplet.json file.
See the configuration section for more information.
You can imagine our
VersionMiddleware sitting in the middle of a chain that connects the client and our server. Every request and response that hits our server must go through this chain of middleware.
Breakdown¶
Let's break down the middleware line by line.
let response = try next.respond(to: request)
Since the
VersionMiddleware in this example is not interested in modifying the request, we immediately ask the next middleware in the chain to respond to the request. This goes all the way down the chain to the
Droplet and comes back with the response that should be sent to the client.
response.headers["Version"] = "API v1.0"
We then modify the response to contain a Version header.
return response
The response is returned and will chain back up any remaining middleware and back to the client.
Request¶
The middleware can also modify or interact with the request.
func respond(to request: Request, chainingTo next: Responder) throws -> Response { guard request.cookies["token"] == "secret" else { throw Abort(.badRequest) } return try next.respond(to: request) }
This middleware will require that the request has a cookie named
token that equals
secret or else the request will be aborted.
Errors¶
Middleware is the perfect place to catch errors thrown from anywhere in your application. When you let the middleware catch errors, you can remove a lot of duplicated logic from your route closures. Take a look at the following example:
enum FooError: Error { case fooServiceUnavailable }
Say there is a custom error that either you defined or one of the APIs you are using
throws. This error must be caught when thrown, or else it will end up as an internal server error (500) which may be unexpected to a user. The most obvious solution is to catch the error in the route closure.
app.get("foo") { request in let foo: Foo do { foo = try getFooFromService() } catch { throw Abort(.badRequest) } // continue with Foo object }
This solution works, but it would get repetitive if multiple routes need to handle the error. Luckily, this error could be caught in a middleware instead.
final class FooErrorMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { return try next.respond(to: request) } catch FooError.fooServiceUnavailable { throw Abort( .badRequest, reason: "Sorry, we were unable to query the Foo service." ) } } }
We just need to add this middleware to our droplet's config.
config.addConfigurable(middleware: FooErrorMiddleware(), name: "foo-error")
Tip
Don't forget to enable the middleware in your
droplet.json file.
Now our route closures look a lot better and we don't have to worry about code duplication.
app.get("foo") { request in let foo = try getFooFromService() // continue with Foo object }
Route Groups¶
For more granularity, Middleware can be applied to specific route groups.
let authed = drop.grouped(AuthMiddleware()) authed.get("secure") { req in return Secrets.all().makeJSON() }
Anything added to the
authed group must pass through
AuthMiddleware. Because of this, we can assume all traffic to
/secure has been authorized. Learn more in Routing.
Configuration¶
You can use the configuration files to enabled or disable middleware dynamically. This is especially useful if you have middleware that should, for example, run only in production.
Appending configurable middleware looks like the following:
let config = try Config() config.addConfigurable(middleware: myMiddleware, name: "my-middleware") let drop = Droplet(config)
Then, in the
Config/droplet.json file, add
my-middleware to the
middleware array.
{ ... "middleware": { ... "my-middleware", ... }, ... }
If the name of the added middleware appears in the middleware array it will be added to the server's middleware when the application boots.
The ordering of middleware is respected.
Manual¶
You can also hardcode your middleware if you don't want to use configuration files.
import Vapor let versionMiddleware = VersionMiddleware() let drop = try Droplet(middleware: [versionMiddleware])
Advanced¶
Extensions¶
Middleware pairs great with request/response extensions and storage. This example shows you how to dynamically return either HTML or JSON responses for a Model depending on the type of client.
Middleware¶
final class PokemonMiddleware: Middleware { let view: ViewProtocol init(_ view: ViewProtocol) { self.view = view } func respond(to request: Request, chainingTo next: Responder) throws -> Response { let response = try next.respond(to: request) if let pokemon = response.pokemon { if request.accept.prefers("html") { response.view = try view.make("pokemon.mustache", pokemon) } else { response.json = try pokemon.makeJSON() } } return response } } extension PokemonMiddleware: ConfigInitializable { convenience init(config: Config) throws { let view = try config.resolveView() self.init(view) } }
Response¶
And the extension to
Response.
extension Response { var pokemon: Pokemon? { get { return storage["pokemon"] as? Pokemon } set { storage["pokemon"] = newValue } } }
In this example, we added a new property to response capable of holding a Pokémon object. If the middleware finds a response with one of these Pokémon objects, it will dynamically check whether the client prefers HTML. If the client is a browser like Safari and prefers HTML, it will return a Mustache view. If the client does not prefer HTML, it will return JSON.
Usage¶
Your closures can now look something like this:
import Vapor let config = try Config() config.addConfigurable(middleware: PokemonMiddleware.init, name: "pokemon") let drop = try Droplet(config) drop.get("pokemon", Pokemon.self) { request, pokemon in let response = Response() response.pokemon = pokemon return response }
Tip
Don't forget to add
"pokemon" to your
droplet.json middleware array.
Response Representable¶
If you want to go a step further, you can make
Pokemon conform to
ResponseRepresentable.
import HTTP extension Pokemon: ResponseRepresentable { func makeResponse() throws -> Response { let response = Response() response.pokemon = self return response } }
Now your route closures are greatly simplified.
drop.get("pokemon", Pokemon.self) { request, pokemon in return pokemon }
Middleware is incredibly powerful. Combined with extensions, it allows you to add functionality that feels native to the framework.
|
https://docs.vapor.codes/2.0/http/middleware/
|
CC-MAIN-2019-09
|
refinedweb
| 1,108
| 50.43
|
Abstract base class for GUI action classes. More...
#include <RGuiAction.h>
Abstract base class for GUI action classes.
Such classes represent a GUI action that can be used to start a tool. One GUI action class may be assigned to multiple GUI elements, for example a menu, a toolbutton and a context menu.
Each GUI action can have multiple commands assigned to it. These commands can be used to trigger the action from a command line.
Each GUI action can have multiple shortcuts assigned to it. Shortcuts are 'traditional' key combinations that can be used to trigger the action. e.g. Ctrl + Z, Ctrl + N, ...
Cleans up all GUI action objects.
start.
This is typically used when the user presses the Tab key in a command line to complete a started command. For example entering "li<tab>" will result in the command to be completed to "line".
scriptFile.
Initializes the GUI action texts (for menus, tooltips, ...).
This function is called whenever the text of the action changes.
Checks or unchecks this action.
Sets the command(s) that can trigger this action from a command line.
Enables or disables the action.
Enables or disables the action.
\par Non-Scriptable:
This function is not available in script environments.
Sets the action icon to the given icon file.
If
on is true, this action requires a document to be open.
The GUI element(s) can for example be grayed out if no document is open.
If
on is true, this action requires a selection to operate on.
The GUI element(s) can for example be grayed out if no selection is present.
Sets the script file to be used for this action.
This is only used for script based actions.
Sets the shortcut(s) for this action.
Sets the status tip of this action.
The status tip is shown in the status bar of the application when the mouse cursor hovers of a menu entry.
Sets the tooltip for this action.
Tooltips are shown when the mouse cursor hovers over a GUI element for some time.
Called when the action is triggered (e.g.
This should be called when the action is triggered, i.e.
a button is pressed or a menu chosen).
a GUI element is activated (button pressed, menu selected, etc).
Triggers the first action in the list of actions that is registered to use the given command.
Triggers the first action in the list of actions that is based on the given
scriptFile.
found &&
Called by the document whenever the focus changed from one MDI to another.
Implements RFocusListener.
Called by the document whenever the current clipboard changes.
Implements RSelectionListener.
Called by the document whenever the current transaction stack changes.
Implements RTransactionListener..
|
http://www.qcad.org/doc/qcad/3.0/developer/class_r_gui_action.html
|
CC-MAIN-2015-18
|
refinedweb
| 452
| 68.67
|
Consuming a C# class in F#
May 7, 2017 Leave a comment
F# and C# can work together pretty easily. Say that your domain classes are contained in a C# class library called Project.Domains. Let’s take the following Product class as an example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project.Domains { public class Product { public Product(string name, int price) { Name = name; Price = price; } public string Name { get; } public int Price { get; } public double CalculateDiscountedPrice(double percentageOff) { double discount = Price * percentageOff; return Price - discount; } } }
You can add a project reference to the Project.Domains C# library from an F# project. Rebuild the solution and then you can open the domain library with the F# open statement. It has the same purpose as a C# using statement:
open Project.Domains
From then on the C# classes in the Project.Domains library can be consumed with F# syntax:
let product = new Product("Table", 1000) let discountedPrice = product.CalculateDiscountedPrice(0.2) printfn "Discounted price: %f" discountedPrice
discountedPrice will be 800 as expected.
View all F# related articles here.
|
https://dotnetcodr.com/2017/05/07/consuming-a-c-class-in-f/
|
CC-MAIN-2022-40
|
refinedweb
| 188
| 51.55
|
When you surf the web, send an email, or log in to a laboratory computer from another location on campus a lot of work is going on behind the scenes to get the information on your computer transferred to another computer. The in-depth study of how information flows from one computer to another over the Internet is the primary topic for a class in computer networking. However, we will talk about how the Internet works just enough to understand another very important graph algorithm.
Figure 1: Overview of Connectivity in the Internet
Figure 1 shows you a high-level overview of how communication on the Internet works. When you use your browser to request a web page from a server, the request must travel over your local area network and out onto the Internet through a router. The request travels over the Internet and eventually arrives at a router for the local area network where the server is located. The web page you requested then travels back through the same routers to get to your browser. Inside the cloud
Each router on the Internet is connected to one or more other routers. So if you run the traceroute command at different times of the day, you are likely to see that your information flows through different routers at different times. This is because there is a cost associated with each connection between a pair of routers that depends on the volume of traffic, the time of day, and many other factors. By this time it will not surprise you to learn that we can represent the network of routers as a graph with weighted edges.
Figure 2: Connections and Weights between Routers in the Internet
Figure 2 shows a small example of a weighted graph that represents the interconnection of routers in the Internet. The problem that we want to solve is to find the path with the smallest total weight along which to route any given message. This problem should sound familiar because it is similar to the problem we solved using a breadth first search, except that here we are concerned with the total weight of the path rather than the number of hops in the path. It should be noted that if all the weights are equal, the problem is the same. instance variable in the Vertex class. The dist instance.
Figure 3: Tracing Dijkstra’s Algorithm
Figure 4: Tracing Dijkstra’s Algorithm
Figure 5: Tracing Dijkstra’s Algorithm
Figure 6: Tracing Dijkstra’s Algorithm
Figure 7: Tracing Dijkstra’s Algorithm
Figure 8: Tracing Dijkstra’s Algorithm :math:` O((V+E) log(V))`.. Figure 9 illustrates the broadcast problem.
Figure 9: Figure 9.
Figure 10: Minimum Spanning Tree for the Broadcast Graph :math:`T` is not yet a spanning tree Find an edge that is safe to add to the tree Add the new edge to :math: in Listing 2. Prim’s algorithm is similar to Dijkstra’s algorithm in that they both use a priority queue to select the next vertex to add to the growing graph.
Listing 2
from pythonds.graphs import PriorityQueue, Graph, Vertex def prim(G,start): pq = PriorityQueue() for v in G: v.setDistance(sys.maxsize) v.setPred(None) start.setDistance(0) pq.buildHeap([(v.getDistance(),v) for v in G]) while not pq.isEmpty(): currentVert = pq.delMin() for nextVert in currentVert.getConnections(): newCost = currentVert.getWeight(nextVert) \ + currentVert.getDistance() if v in pq and newCost<nextVert.getDistance(): nextVert.setPred(currentVert) nextVert.setDistance(newCost) pq.decreaseKey(nextVert,newCost)
The following sequence of figures (Figure 11 thru Figure 17) shows the algorithm in operation on our sample tree. We begin with the starting vertex as A. The distances to all the other vertices are initialized to infinity. Looking at the neighbors of A we can update distances to two of the additional vertices B and C because the distances to B and C through A are less than infinite. This moves B and C to the front of the priority queue..
Figure 11: Tracing Prim’s Algorithm
Figure 12: Tracing Prim’s Algorithm
Figure 13: Tracing Prim’s Algorithm
Figure 14: Tracing Prim’s Algorithm
Figure 15: Tracing Prim’s Algorithm
Figure 16: Tracing Prim’s Algorithm
Figure 17: Tracing Prim’s Algorithm
|
http://interactivepython.org/courselib/static/pythonds/Graphs/graphshortpath.html
|
CC-MAIN-2014-42
|
refinedweb
| 710
| 60.75
|
State Drift Detection using Terraform
Your infrastructure, just like the real world, is constantly changing. But differentiating between an expected and an unexpected change can be difficult. How can you tell them apart? A firewall rule change may be intentional and expected or it may be the initial sign of a malicious activity. Distinguishing between these two types of change was a challenge we faced early on in ACL, but surprisingly, no great solution existed for it.
Sure there are lots of solutions that can monitor your infrastructure and notify you of changes, but no great solution that can monitor and filter for events you care about. This is because most products and services do not understand your infrastructure’s context and requirements. They can either alert you of universally suspicious activities, i.e. non-MFA logins, or simply create an easy way to see infrastructure changes so you can spot unexpected activities manually, i.e. firewall rule changes. They focus on events and making it easy for you to digest them, rather than focusing on the state of your infrastructure and comparing it against your intended state.
Imagine you had an event stream for important actions in AWS, such as AWS CloudTrail. You could see lots of firewall (security group) changes, lots of permission (IAM) changes, but how will you know at end-of-day that your infrastructure is in the state you expect it to be? That’s where event stream based solutions begin to fall apart. They can be valuable when each event is focused on suspicious activities, but when regular activities are mixed into it, an event stream provides minimal value.
At ACL, we weren’t content with accepting this limitation and continuing to develop our infrastructure without assurance that our infrastructure will remain in its intended state. We wanted to be rest assured that at end of the day, everything was setup as intended by our infrastructure code. To address this at ACL, we devised a simple technique with Terraform which we internally call State Drift Detection.
Terraform — Infrastructure as Code
At ACL we’re a DevOps cultured company, and part of that translates into ACL developing its infrastructure via code. When it comes to AWS infrastructure management via code, there are two primary candidates: AWS CloudFormation and Terraform. At ACL, we’ve opted for Terraform. Both of these tools, at their core, are quite simple. You use their syntax to define the sort of AWS resources you’d like to create and voilà it’s done.
For example, the following code will create a Security Group named
allow_all with access on port 80 from your VPC’s network. Not a secure example, but keeping it simple to demonstrate the idea.
resource "aws_security_group" "allow_all" {
name = "allow_all"
description = "Allow all HTTP inbound traffic"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["10.0.0.0/16"]
}
}
What’s interesting about Terraform is its distinct steps of planning and applying. You can see beforehand exactly what Terraform plans to do in AWS, and if you are happy with it, you can apply it.
$ terraform plan
$ terraform apply
After applying, Terraform maintains a snapshot of the state of resources it provisioned. This is stored in a
.tfstate file and is used as the baseline for future
plan and
apply executions.
In order for Terraform to accurately tell you its plan, it will first refresh its state with the real-world infrastructure, so it can tell you exactly what it will do when applied. This was a feature I did not truly appreciate at first.
After a while of using Terraform, I realized, if I ever wanted to know if something had unintentionally changed in our infrastructure, I just needed to run
plan and see if Terraform intended to do anything. If anything was changed intentionally, then it would have been in the source code and Terraform would not plan to do anything. However, if anyone changed any part of our AWS infrastructure manually, Terraform’s
plan would identify it and let us know. In other words, if our AWS infrastructure drifted from its expected state, then Terraform’s
plan would detect it.
Hmm… could I automate this too? What if I had our internal task runner (i.e. Jenkins) run this on a continuous basis and let us know if anything changed? That’d give me a lot of sanity! And that’s how our internal capability of State Drift Detection was born.
State Drift Detection
Now that you understand the problem we are trying to solve, let’s demonstrate how we can easily setup State Drift Detection using Terraform.
Terraform’s plan command has an option called -detailed-exitcode.
Using this option, you can use the exit code of
terraform plan -detailed-exitcode to identify if Terraform plans to make any changes or not. Thus, to setup State Drift Detection, simply have your task runner (e.g. Jenkins) clone your Terraform repository and run
terraform plan -detailed-exitcode on it and fail the task based on the exit code. Once you’ve got that going, hook your task runner into Slack and voilà State Drift Detection!
The hardest part of getting State Drift Detection going is having your infrastructure coded in Terraform. If you already have that, you’re all set! If you don’t have that, you need to invest the time. I recommend prioritizing the AWS resources you care about and gradually bringing them into Terraform. Fortunately, Terraform has an
import command to speed up the process, and unlike CloudFormation, you can import your AWS resources rather than needing to create new ones. In fact, this is why ACL chose Terraform over CloudFormation in the first place.
ACL’s Scenario
At ACL, we use Terraform to perform State Drift Detection on dozens of Terraform “projects”. As the person responsible for our infrastructure, it gives me a lot of sanity knowing everything is set up as intended. Without this, it’d be extremely difficult to know whether all our 5 production AWS regions + 2 development AWS regions are in sync and configured correctly.
We still complement our State Drift Detection with an event stream solution, since not all important AWS activities are state based, i.e. Root user logins. We simply don’t rely on that event stream to do everything for us. Combining State Drift Detection with a traditional event stream monitoring solution has proved itself invaluable in our ability to stay sane and secure in our fast-pace DevOps cultured company.
As a fellow infrastructure developer, I hope this technique gives you some sanity too!
|
https://medium.com/build-acl/state-drift-detection-using-terraform-d0383628d2ea
|
CC-MAIN-2017-34
|
refinedweb
| 1,101
| 62.58
|
optional 1.0.0-beta.2
An optional/maybe type with safe dispatchingrange semantics
To use this package, run the following command in your project's root directory:
Optional type for D with safe dispatching and NotNull type
Full API docs available here
- Features
- Summary
- Motivation for Optional
- Scala we have a Swift comparison
- Examples
Features
@nogcand
@safe
- Shows the intent of your code that may or may not return a value
Optional!int fun() {} // Might return an int, or might not
- Includes a generic
orrange algorithm:
auto a = some(3); auto b = a.or(7); auto c = a.or(some(4)); c.or!(() => writeln("c is empty"));
- Use pattern matching
fun.match!( (int value) => writeln("it returns an int"), () => writeln("did not return anything"), );
- Safely call functions on classes that are null, structs that don't exist, or
std.typecons.Nullable
class C { int fun() { return 3; } } Optional!C a = null; oc(a).fun; // no crash, returns no!int
- Forwards any operator calls to the wrapped typed only if it exists, else just returns a
none
Optional!int a = 3; Optional!int b = none; a + 3; // evaluates to some(6); b + 3; // evaluates to no!int;
int f0(int) { return 4; } auto a0 = some(&f0); // return some(4)
- Compatible with
std.algorithmand
std.range
fun.each!(value => writeln("I got the value")); fun.filter!"a % 2 == 0".each!(value => writeln("got even value"));
Summary
The pupose of this library is to provide an Optional type.
It contains the following constructs:
Optional!T: Represents an optional data type that may or may not contain a value that acts like a range.
oc: A null-safe optional chaining (oc) utility that allows you to chain methos through possible empty objects.
or: A range algorithm that also acts as a coalescing operator
match: Pattern match on optionals
An
Optional!T signifies the intent of your code, works as a range and is therefore usable with Phobos algorithms, and allows you to call methods and operators on your types even if they are null references - i.e. safe dispatching.
Some use cases:
- When you need a type that may have a value or may not (
Optional!Type)
- When you want to safely dispatch on types (
oc(obj).someFunction // always safe)
- When you want to not crash with array access (
some([1, 2])[7] == none // no out of bounds exception)
- When you want to perform an operation if you get a value (
obj.map!doSomething.or!doSomethingElse)
Motivation for Optional
Let's take a very contrived example, and say you have a function that may return a value (that should be some integer) or not (config file, server, find operation, whatever), and then you have functions add1 and add2, that have the requirements that they may or may not produce a valid value. (maybe they do some crazy division, or they contact a server themselves to fetch a value, whatevs).
How can you go about this?
Use pointers?
int* add1(int *v) { // Gotta remember to protect against null if (!v) { return v; } *v += 1; return v; } int* add2(int *v); // might forget to check for null void f() { int* v = maybeGet(); if (v) v = v.add1; if (v) v = v.add2; if (v) writeln(*v); }
You can also replace int with Nullable!int and then instead of `if (v)` you'd have to do `if (!v.isNull)` and instead of `v
you'd do v.get`.
How about ranges?
There's std.range.only:
auto add2(Range)(Range r) if (isInputRange!Range && is(ElementType!Range == int)) // constrain to range type only and int element type? // I need to ensure it has a length of one. // And there's no way to ensure that in compile time without severly constraigning the type { // do we have one element or more now? // what do we do if there's more than one? // do we restrain it at run time to being there? enforce(r.walkLength <= 1); // ?? // Should we map all of it? return v.map!(a => a + 1); // Or just the first? return v.take(1).map!(a => a + 1); // But what do I do with the rest then? } auto add2(Range)(Range r) if (isInputRange!Range) { // same headache as above } void f() { auto v = maybeGet(); // can we assign it to itself? v = v.add1.add2; // No, no idea what it returns, not really the same type // so this... refRange(&v).add1.add2; // ?? // no that won't work (can it?), lets create a new var auto v2 = v.add1.add2 // and let type inference do its thing writeln(v2); // now ok. }
Let's try an Optional!int
auto add1(Optional!int v) { v += 1; return v; } auto add2(Optional!int v); // same as above void f() { auto v = maybeGet().add1.add2; writeln(v); }
Can't I just use a pointer as an optional
Well yes, you can, but you can also stick a pencil up your nostril. It's a bad idea for the following reasons:
- In order to achieve stability, you have to enforce checking for null. Which you cannot do
- Null is part of the value domain of pointers. This means you can't use an optional of null
- The caller doesn't know who owns the pointer returned. Is it garbage collected? If not should you deallocate it?
- It says nothing about intent.
What about
std.typecons.Nullable?
It is not like the
Nullable type in Phobos.
Nullable is basically a pointer and applies pointer semantics to value types. It does not give you any safety guarantees and says nothing about the intent of "I might not return a value". It does not have range semantics so you cannot use it with algorithms in phobos. And it treats null class objects as valid.
It does, however, tell you if something has been assigned a value or not. Albeit a bit counterintuitively, and in some cases nonsensically:
class C {} Nullable!C a = null; writeln(a.isNull); // prints false
With refernece types (e.g., pointers, classes, functions) you end up having to write code like this:
void f(T)(Nullable!T a) { if (!a.isNull) { static if (is(T == class) || (T == interface) || /* what else have I missed? */) { if (a.get !is null) { a.callSomeFunction; } } else { a.callSomeFunction; } } }
Scala we have a Swift comparison
In this section we'll see how this Optional is similar to Scala's
Option[T] and Swift's
Optional<T> type (similar to Kotlin's nullable type handling)
Idiomatic usage of optionals in Swift do not involve treating it like a range. They use optional unwrapping to ensure safety and dispatch chaining. Scala on the other hand, treats optionals like a range and provides primitives to get at the values safely.
Like in swift, you can chain functions safely so in case they are null, nothing will happen:
D: Unfortunately the lack of operator overloading makes dispatching a bit verbose.
class Residence { auto numberOfRooms = 1; } class Person { Optional!Residence residence = new Residence(); } auto john = some(new Person()); auto n = oc(john).residence.numberOfRooms; writeln(n); // prints [1]
Swift
class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john: Person? = Person() let n = john?.residence?.numberOfRooms; print(n) // prints "nil"
Like in Scala, a number of range primitives are provided to help (not to mention we have Phobos as well)
D
auto x = toInt("1").or(0); import std.algorithm: each; import std.stdio: writeln; toInt("1").each!writeln; toInt("1").match!( (i) => writeln(i), () => writeln("😱"), ); // For completeness, the implementation of toInt: Optional!int toInt(string str) { import std.conv: to; scope(failure) return no!int; return some(str.to!int); }
Scala
val x = toInt("1").getOrElse(0) toInt("1").foreach{ i => println(s"Got an int: $i") } toInt("1") match { case Some(i) => println(i) case None => println("😱") } // Implementation of toInt def toInt(s: String): Option[Int] = { try { Some(Integer.parseInt(s.trim)) } catch { case e: Exception => None } }
Examples
The following section has example usage of the various types
Example Optional!T usage
import optional; // Create empty optional auto a = no!int; assert(a == none); ++a; // safe; a - 1; // safe; // Assign and try doing the same stuff a = 9; assert(a == some(9)); ++a; // some(10); a - 1; // some(9); // Acts like a range as well import std.algorithm : map; import std.conv : to; cast(void)some(10).map!(to!double); // [10.0] cast(void)no!int.map!(to!double); // empty auto r = some(1).match!((int a) => "yes", () => "no",); assert(r == "yes");
Example optional chaining usage
// Safely dispatch to whatever inner type is struct A { struct Inner { int g() { return 7; } } Inner inner() { return Inner(); } int f() { return 4; } } auto d = some(A()); // Dispatch to one of its methods oc(d).f(); // calls a.f, returns some(4) oc(d).inner.g(); // calls a.inner.g, returns some(7) // Use on a pointer or reference type as well A* e = null; // If there's no value in the reference type, dispatching works, and produces an optional assert(e.oc.f() == none); assert(e.oc.inner.g() == none);
- Registered by ali akhtarzada
- 1.0.0-beta.2 released 27 days ago
- aliak00/optional
- MIT
- Authors:
-
- Dependencies:
- bolts
- Versions:
- Show all 36 versions
- Download Stats:
6 downloads today
44 downloads this week
207 downloads this month
4448 downloads total
- Score:
- 3.0
- Short URL:
- optional.dub.pm
|
https://code.dlang.org/packages/optional
|
CC-MAIN-2019-39
|
refinedweb
| 1,556
| 67.45
|
Hello, I am trying to get used to the hurdish way of programming. So I started programming some samples that should help me understanding the hurdish way of thinking. But I encountered some problems. I wanted to write a simple client/server program (similar to the one found in the programmers guide to the mach user environment) and I implemented it the following way: <-------------------mig definition-------------------------------> subsystem test 500; routine get_random( server: mach_port_t; out num: int); <---------------------------------------client--------------------> int main() { int r=3; error_t err; mach_port_t server; server=file_name_lookup("/servers/testserver",0,0); if (server==MACH_PORT_NULL) { error(1,errno,"Couldnt open server port\n"); } err=get_random(server,&r); if (err<0) { error(1,errno,"get_random failed %d\n",err); } mach_port_deallocate(mach_task_self(),server); return (0); } <---------------------------------------server--------------------> kern_return_t get_random ( mach_port_t server, int *num ) { db=*num; printf("in get_random:%d\n",db); return KERN_SUCCESS; } int main (int argc, char **argv) { error_t err; mach_port_t bootstrap; struct port_bucket *test_bucket; struct port_class *test_portclass; struct port_info *pi; test_bucket = ports_create_bucket (); test_portclass = ports_create_class (0, 0); err = ports_create_port (test_portclass, test_bucket, sizeof(*pi),&pi ); if (err<0) { error (1, 0, "Couldnt create port:%d\n",err); } ports_manage_port_operations_multithread (pi->bucket, test_server, 0,0,0); return 0; } -------------------------------------------------------------------------- But when I copy the server to /servers/testserver and run the client I get get_random_failed -303 as error. As I understand it the filesystem makes a server available to its clients. So the client should get the server port via file_name_lookup. Since the server already exists and I dont want to write or read from it I pass 0x00 as 2nd and 3rd parameter to file_name_lookup. Since the client doesnt exit in the following 'if' I think that I received a valid handle. Then the client is called and should pass the request over to the server. But nothing happens. I mean its quite clear that the server must be running. So I started it before the client as a background process. So where´s problem ? In my opinion the client wasnt able to contact the server. But why ? The client got a valid port handle. I also thought that perhaps the port handle received via file_name_lookup wasnt the right porthandle and added a err = mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_SEND,&port); in the client code and called the getrandom() with port instead of server but this didnt help. Whats wrong ? Isnt the way I started the server not the hurdish way or is it the way I try to get a valid porthandle of the servers port ? Does anyone know what went wrong ? thanks in advance, Frank
|
http://lists.gnu.org/archive/html/bug-hurd/2002-12/msg00006.html
|
CC-MAIN-2015-11
|
refinedweb
| 419
| 59.74
|
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called.Learned about basic functions in c++, there is more: the inline function. Inline functions are not always important, but it is good to understand them.When the compiler inline-expands a function call, the function’s code gets inserted into the caller’s code stream.
Developer : ijaz Rs khAn & Bilal tahir
Compiler : Microsoft Visual Studio 2013
Comp. Date: 1-11-2015
Source Code#include<iostream.h>// for input output standerd#include<conio.h>//for clrscr()class first// class first{private:// private classint data;//public classpublic:void setdata(int d) { data=d; }void showdata() { cout<<"Data = "<<data<<endl; }};main( )// main function{clrscr();// clear screenfirst object;object.setdata(545);object.showdata();getch();//get char}
if you Face any problem Freely contact us.Give your Feed Back.Thank you.
|
http://m.dlxedu.com/m/detail/30/441637.html
|
CC-MAIN-2018-30
|
refinedweb
| 165
| 50.73
|
: xtod vs: lponlcr
Date: Wed, 27 Nov 2002 18:11:37 GMT References: <m18H6GV-0002PKC@cactus.com>
Jeff Hyman wrote:
> I have a customer that is having a stair-stepping output issue
> to the printer. I am not new to this problem and even have a FAQ
> on the topic. My question has to do with command '/usr/lib/lponlcr'
> which I am not familar with. I have no 'man' pages on this command.
> I am most interested in finding out how it compares to what 'xtod' does...
> if they are even comparable commands.
>
> # lp -dprinter_name ascii_file
> # cat ascii_file | lp -dprinter_name
> # cat ascii_file | xtod | lp -dprinter_name
> # cat ascii_file | /usr/lib/lponlcr | lp -dprinter_name
`xtod` and `lponlcr` are very similar. xtod's source is more
complicated because it responds to the name you run it under (xtod or
dtox). lponlcr is _really_ simple. Aside from a ridiculous copyright
statement about how holy and confidential this stuff is, it's just:
#include <stdio.h>
main()
{
register int c;
while ((c=getchar()) != EOF) {
if (c == '\n')
putchar('\r');
putchar(c);
}
}
xtod also: takes an optional single filename to read from instead of
stdin; and appends a control-Z (DOS EOF marker) to the end of the
output.
I believe DOS Merge comes with another set of these utilities, and VP/ix
probably did, and quite a number of utilities have an embedded ability
to do CRLF translation along with something else they're doing (e.g.
`ftp`). It's a very frequent problem for Unix users, so the wheel has
been reinvented many times.
>Bela<
|
http://aplawrence.com/Bofcusm/1810.html
|
crawl-002
|
refinedweb
| 262
| 72.05
|
Example app
Want to get started with Apollo Client? This page will guide you through your first GraphQL query with Apollo in less than ten minutes. For this example, we’re going to be using:
- Launchpad for our GraphQL server
- CodeSandbox for our example app, Pupstagram
- Apollo Boost, our new zero-config way to start using Apollo
Your first query
First, install
apollo-boost,
graphql &
react-apollo.
npm i apollo-boost graphql react-apollo -S
Next, create your client. Once you create your client, hook it up to your app by passing it to the
ApolloProvider exported from
react-apollo.
import React from 'react'; import { render } from 'react-dom'; import ApolloClient from 'apollo-boost'; import { ApolloProvider } from 'react-apollo'; // Pass your GraphQL endpoint to uri const client = new ApolloClient({ uri: '' }); const ApolloApp = () => ( <ApolloProvider client={client}> <App /> </ApolloProvider> ); render(ApolloApp, document.getElementById('root'));
Awesome! Your ApolloClient is now connected to your app. Let’s create our
<App /> component and make our first query:
import React from 'react'; import { gql } from 'apollo-boost'; import { Query } from 'react-apollo'; const GET_DOG = gql` query { dog(breed: "bulldog") { id breed displayImage } } ` const App = () => ( <Query query={GET_DOG}> {({ loading, error, data }) => { if (loading) return <div>Loading...</div>; if (error) return <div>Error :(</div>; return ( <Dog url={data.dog.displayImage} breed={data.dog.breed} /> ) }} </Query> )
Time to celebrate! 🎉 You just made your first Query component. The Query component binds your GraphQL query to your UI so Apollo Client can take care of fetching your data, tracking loading & error states, and updating your UI via the
data prop. Why don’t you try experimenting with creating more Query components by forking our example app, Pupstagram?
The easiest way to see what Apollo Client and GraphQL can do for you is to try them for yourself. Below is a simple example of a single React Native view that uses Apollo Client to talk to our hosted example app, GitHunt. We’ve embedded it in the page with the Snack editor from Expo.
To start, let’s run the app. There are two ways:
- Click the “Tap to Play” button to run the app in the simulator.
- Open the editor in a new window and install the Expo app to run it on your iOS or Android device.
Either way, the app will automatically reload as you type.
First edit
Fortunately, the app is set up for us to make our first code change. Hopefully, after launching the app you see a view with a scrollable list of some GitHub repositories. This is fetched from the server using a GraphQL query. Let’s edit the query by removing the
# in front of
stargazers_count, so that the app also loads the number of stars from GitHub. The query should now look like this:
{ feed (type: TOP, limit: 10) { repository { name, owner { login } # Uncomment the line below to get number of stars! stargazers_count } postedBy { login } } }
Because in this example we’ve developed the UI in such a way that it knows how to display that new information, you should see the app refresh and show the number of GitHub stars from each repository!
Multiple backends
One of the coolest things about GraphQL is that it can be an abstraction layer on top of multiple backends. The query you did above is actually loading from two totally separate data sources at once: A PostgreSQL database that stores the list of submissions, and the GitHub REST API to fetch the information about the actual repositories.
Let’s verify that the app is actually reading from GitHub. Pick one of the repositories in the list, for example apollographql/apollo-client or facebook/graphql, and star it. Then, pull down the list in the app to refresh. You should see the number change! That’s because our GraphQL server is fetching from the real GitHub API every time, with some nice caching and ETag handling to avoid hitting a rate limit.
Explaining the code
Before you go off and build your own awesome GraphQL app with Apollo, let’s take a look at the code in this simple example.
This bit of code uses the
graphql higher-order component from
react-apollo to attach a GraphQL query result to the
Feed component:
const FeedWithData = graphql(gql`{ feed (type: TOP, limit: 10) { repository { name, owner { login } # Uncomment the line below to get number of stars! # stargazers_count } postedBy { login } } }`, { options: { notifyOnNetworkStatusChange: true } })(Feed);
This is the main
App component that React Native is rendering. It creates an Apollo Link with the server URL, initializes an instance of
ApolloClient, and attaches that to our React component tree with
ApolloProvider. If you’ve used Redux, this should be familiar, since it’s similar to how the Redux provider works.
export default class App { createClient() { // Initialize Apollo Client with URL to our server return new ApolloClient({ link: createHttpLink({ uri: '', }), cache: new InMemoryCache() }); } render() { return ( // Feed the client instance into your React component tree <ApolloProvider client={this.createClient()}> <FeedWithData /> </ApolloProvider> ); } }
Next, we get to a component that is actually dealing with some data loading concerns. Mostly, this is just passing through the
data prop down to
FeedList, which will actually display the items. But there is also an interesting React Native
RefreshControl component here, which uses the built-in
data.refetch method from Apollo to refetch data when you pull down the list. It also uses the
data.networkStatus prop to display the correct loading state, which Apollo tracks for us.
// The data prop here comes from the Apollo HoC. It has the data // we asked for, and also useful methods like refetch(). function Feed({ data }) { return ( <ScrollView style={styles.container} refreshControl={ // This enables the pull-to-refresh functionality <RefreshControl refreshing={data.networkStatus === 4} onRefresh={data.refetch} /> }> <Text style={styles.title}>GitHunt</Text> <FeedList data={data} /> <Text style={styles.fullApp}>See the full app at</Text> <Button buttonStyle={styles.learnMore} onPress={goToApolloWebsite} icon={{name: 'code'}} raised </ScrollView> ); }
Finally, we get to the place that actually displays the items, the
FeedList component. This consumes the
data prop from Apollo, and maps over it to display list items. You can see that thanks to GraphQL, we got the data in exactly the shape that we expected.
function FeedList({ data }) { if (data.networkStatus === 1) { return <ActivityIndicator style={styles.loading} />; } if (data.error) { return <Text>Error! {data.error.message}</Text>; } return ( <List containerStyle={styles.list}> { data.feed.map((item) => { const badge = item.repository.stargazers_count && { value: `☆ ${item.repository.stargazers_count}`, badgeContainerStyle: { right: 10, backgroundColor: '#56579B' }, badgeTextStyle: { fontSize: 12 }, }; return <ListItem hideChevron title={`${item.repository.owner.login}/${item.repository.name}`} subtitle={`Posted by ${item.postedBy.login}`} badge={badge} />; } ) } </List> ) }
Now you’ve seen all of the code you need to build a React Native app that loads a list of items and displays it in a list with pull-to-refresh functionality. As you can see, we had to write very little data loading code! We think that Apollo and GraphQL can help data loading get out of your way so you can build apps faster than ever before.
Next steps
Let’s get you building your own app from scratch! You have two tutorials to go through, and we recommend doing them in the following order:
- Full-Stack GraphQL + React tutorial by Jonas Helfer.
- How to GraphQL by the team and community around Graphcool, a hosted GraphQL backend platform.
Have fun!
|
https://www.apollographql.com/docs/react/recipes/simple-example.html
|
CC-MAIN-2018-22
|
refinedweb
| 1,222
| 55.44
|
No Primitives in java Collection (boxing / unboxing)
<br /> import java.util.*;<br /> public class test {</p> <p> final static int SIZE = 5000000;<br /> final static List list = new ArrayList (SIZE);<br /> final static int[] alist = new int [SIZE];</p> <p> public static void main(String args[]) {</p> <p> int sum = 0;<br /> long start = System.currentTimeMillis();</p> <p> for (int i = 0; i < SIZE; i++) {<br /> alist[i] = i;<br /> }<br /> for (int i = 0; i < SIZE; i++) {<br /> sum += alist[i];<br /> }<br /> long end = System.currentTimeMillis();</p> <p> System.out.println("Array Sum: " + sum + "\nTime: " + (end - start) + "ms");</p> <p> sum = 0;<br /> assert(sum == 0);<br /> start = System.currentTimeMillis();</p> <p> for (int i = 0; i < SIZE; i++) {</p> <p> list.add(i);<br /> }</p> <p> for (int i = 0; i < SIZE; i++) {<br /> sum += list.get(i);<br /> }</p> <p> end = System.currentTimeMillis();</p> <p> System.out.println("List Sum: " + sum + "\nTime: " + (end - start) + "ms");<br /> }<br /> }
Weird behavior: if I don't add -Xmx128m flag, the above code just prints the first print statement and exists, instead of throwing out of memory exception. Is this a bug?
Also, this example shows that Java collection is unusable if the performance is important. It would have been nice if Collection classes could use primitives directly instead of first converting them to wrapper classes.
According to [url=]4753347[/url] this should be fixed in 1.6 (and works with the test program in that report). But fails for your test case, though the exit code is 1.
+1000
I totally agree with mthornton on this one. I believe that cleaning up Generics should be a much higher priority. Currently there is a lot of infighting amongst the Java community about adding new features because of the negative experience that has resulted from Generics. If we clean it up, as mthornton suggests, we would be in a much better position to add new features with a strong consensus.
Please guys, vote for and ask Sun to increase the priority of this bug as soon as possible!
By the way, why does the original code I posted throw out memory exception?
Because an Integer is bigger than an int.
Using [url=]16 bytes[/url] for an Integer, you need 5000000 * 16 ~= 78Mb. I think think Java defaults to 64Mb, so you get an out of memory exception some where in the loop.
If int is [url=]32 bit[/url], you only need ~19.5Mb for that.
Yes it would be nice if generics was extended to primitives. However, for consistency, we first need to reify generics (i.e. add classes which do not erase their type parameters). It is quite a bit of work and currently appears to have low priority.
I have checked out the OpenJDK compiler and have started hacking a change, but currently have very limited spare time (too much real work to do).
In addition I think that a combination of reifying generics and extending them to primitives would allow much of the enormous generics FAQ to be relegated to an historical footnote. Many of the awkward cases that don't currently work, would work as expected. It would also significantly simplify libraries like the fork/join framework which is one of the poster cases for closures.
In practice erased types would be retained for the medium term, so the generics FAQ would still apply when using erasure, but most new code could use reified types.
Using Integer in a Collection class is over 80 times slower than just using ints in an array. I am not sure but the penalty for autoboxing double maybe even larger. autoboxing should have not been added to the language. I suspect that now for backward compatibility reasons, this "feature" cannot be removed.
Also, even if using custom collection classes that allow primitives, another performance flaw is that everything is passed by value.
For example, let's say there is custom Hashtable for primitives that takes
int count = hashMap.get(someWord);
count++;
or maybe
hashMap.get(someWord)++;
an extra put is required...
int count = hashMap.get(someWord);
hashMap.put(someWord, count++);
That means twice slower than the first option since both get and put are used to increment the counter. Am I missing anything?
If you want to update the value in a map the simplest way (in my opinion) is something like this:
class Counter { int value;}
...
Map
String key;
...
Counter count = map.get(key);
if (count == null) {
count = new Counter();
map.put(key, count);
}
count.value++;
Now the put happens only once for each key, so you gain provided the average count is greater than 2.
>class Counter { int value;}
>map.put(key, count);
The problem is creating a new counter object. It's not same as being able to increment primitive. Another way to keep count would be
[code]
Map
String key;
...
int[] count = map.get(key);
if (count == null) {
map.put(key, new int[]{1});
}
else count[0]++; [/code]
In both cases, if count == null, we have one get and one put. That's still two. If primitives could be passed by references, it would need just one put.
map.put(key)++;
Message was edited by: oneguyks
> In both cases, if count == null, we have one get and
> one put. That's still two. If primitives could be
> passed by references, it would need just one put.
>
> map.put(key)++;
>
The closest we could get to that would be a map which had a special action invoked when there is no existing entry. java.util.concurrent.ConcurrentMap implementations have a putIfAbsent method. This could be used like so:
Counter absent = new Counter(1);
ConcurrentMap
...
Counter count = map.putIfAbsent(key, absent);
if (count == null)
absent = new Counter(1);
else
count.value++;
The number of map lookups is now exactly the same as you propose. This does take more memory, but if that matters you should write a special purpose map implementation. That map implementation could return an interface like:
interface Counter {
int getValue();
int incrementValue();
}
Use it enough and HotSpot might inline the interface invocations.
> This does take more memory, but if that
> matters you should write a special purpose map
> implementation.
Or just use:
Ismael
>Or just use:
>
That doesn't solve the lookup problem.
Edit: Not sure maybe it does.
Message was edited by: oneguyks
> >Or just use:
>
> >
> jectIntHashMap.html#increment(K)
>
> That doesn't solve the lookup problem.
>
> Edit: Not sure maybe it does.
Yes it does. You can use increment, adjustValue or adjustOrPutValue depending on your use-case.
Ismael
?
map.adjustOrPutValue(1, 1);
That will start the counter at 1 for a non-existing key and add 1 for an existing key. You can also start at any other number and increment by any other number. Internally the map only computes the hashCode and the insertionIndex once and either puts the value and key in the appropriate array buckets or increments the primitive int in the values array.
All of what I described can be easily verified by inspecting the source code. Trove is open-source and it is designed specifically to deal with cases where the Java collections are too slow and/or take too much space. This is usually only relevant when primitives are being used.
Ismael
>By the way, why does the original code I posted throw out memory exception?
That was a typo. What I meant was why does it NOT throw out memory exception.
It doesn't work without -Xmx128m, but if I don't add -Xmx128m it doesn't throw out memory exception.
Message was edited by: oneguyks
|
https://www.java.net/node/678821
|
CC-MAIN-2015-18
|
refinedweb
| 1,271
| 67.04
|
This is my assignment
Write a class named Fan to model fans. The properties are speed, on, radius, and color. You need to provide the accessor methods for the properties, and the toString method for returning a string consisting of all the string values of all the properties in this class. Suppose the fan has three fixed speeds. Use constants 1, 2, and 3 to denote slow, medium, and fast speeds.
and my professor gave me an outline of the class and what I have to do is Write a client program(test application) to test the Fanclass. In the client program, create a Fan object.
Assign maximum speed, radius 10, color yellow, and turn it on.
Display the object by invoking its toString method.
I have gone till the end, created Fan class without any errors and also a client program to test the class but I cannot display whether the fan is ON/OFF. I simply blind coded the On class here. SO In my test class, I cannot print whether the fan is on or off, it simply shows me an error.
My Fan class is here
public class Fan { public final int SLOW = 1; public final int MEDIUM = 2; public final int FAST = 3; private int speed = SLOW; private boolean on = false; private double radius = 5; private String color = "white"; public Fan ( ) { } public Fan ( int newSpeed, boolean newOn, double newRadius, String newColor ) { setSpeed(newSpeed); setRadius(newRadius); setColor(newColor); } public int getSpeed ( ) { return speed; } public void setSpeed ( int speed ) { if (speed == SLOW) { System.out.println("Speed is 1"); } else if (speed == MEDIUM) { System.out.println("Speed is 2"); } else if (speed == FAST) { System.out.println("Speed is 3(Maximum Speed)"); } else { System.out.println("Invalid Speed"); } } public boolean isOn ( boolean newOn ) { return newOn; } public void setOn ( boolean newOn ) { if (on = false) { System.out.println("Fan is Turned on"); } else { System.out.println("Fan is turned off"); } } public double getRadius ( ) { return radius; } public void setRadius ( double newRadius ) { if (newRadius <= 0) { System.out.println("Radius cannot be zero or negative"); } else { radius = newRadius; } } public String getColor ( ) { return color; } public void setColor ( String newColor ) { color = newColor; } @Override public String toString ( ) { return "Dimensions are" + radius; } }
My Code for testing the class
public class TestApplication { public static void main (String[] args) { Fan testfan1 = new Fan(3, false, 10, "blue"); System.out.println(testfan1.getSpeed() + " " + testfan1.getColor() + " " + testfan1.getRadius() + " " + [COLOR="#FF0000"]testfan1.isOn()[/COLOR]); } }
SO as u see all the code work except testfan1.isOn, error says (req: boolean found: no args), even if I give testfan.isOn(false); no error shows up but it shows up 'false' in the output but I want it to display "Fan is turned on"
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/25653-cannot-print-boolean-value-class.html
|
CC-MAIN-2015-48
|
refinedweb
| 448
| 61.97
|
Embed.
In your
pubspec.yaml file within your Flutter Project:
dependencies: flutube: ^0.4.4
import 'package:flutube/flutube.dart'; final flutubePlayer = Flutube( '<Youtube URL>', aspectRatio: 16 / 9, autoPlay: true, looping: true, );
Please run the app in the
example/ folder to start playing!
showThumbproperty. The default value is
true.
GlobalKey<FlutubeState>
autoStartproperty not work without setting
autoInitializeto true.
example/README.md
Demonstrates how to use the flutube plugin.
For help getting started with Flutter, view our online documentation.
Add this to your package's pubspec.yaml file:
dependencies: flutube: ^0.4.4
You can install packages from the command line:
with Flutter:
$ flutter packages get
Alternatively, your editor might support
flutter packages get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:flutube/flutube.dart';
We analyzed this package on Feb 4, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
Detected platforms: Flutter
References Flutter, and has no conflicting libraries.
Fix
lib/src/flutube_player.dart. (-1 points)
Analysis of
lib/src/flutube_player.dart reported 2 hints:
line 153 col 3: The class 'Future' was not exported from 'dart:core' until version 2.1, but this code is required to be able to run on earlier versions.
line 171 col 39: Avoid using braces in interpolation when not needed.
Format
lib/flutube.dart.
Run
flutter format to format
lib/flutube.dart.
|
https://pub.dartlang.org/packages/flutube/versions/0.4.4
|
CC-MAIN-2019-09
|
refinedweb
| 238
| 52.36
|
for connected embedded systems
usemsg
Change usage message for a command (QNX)
Syntax:
usemsg [-c] loadfile [msgfile]
Options:
- -c
- The usage message is contained in a C source program delimited by:
#ifdef __USAGE ... #endifNote that there are two underscores before USAGE.
- loadfile
- The name of an executable program to extract or insert a usage message. The current PATH environment variable is searched to locate loadfile.
- msgfile
- A text file or a C source file containing a usage message (see -c). If the msgfile name ends in .c, then a C source is assumed. If present, this argument will be used as the name of the message file to insert into the load file. If the msgfile argument is not present, the usage message is read from the load file and printed to standard output.
Description:
The usemsg utility lets you examine or change the usage record contained within a QNX executable program. All utilities supplied with QNX are shipped with a usage message describing their options. This information is kept in a resource record in the load file. Since this usage text is not loaded into memory when the program is run, you can make it as large as 32K characters without affecting the size of your program at runtime.
Users will use the use utility to print usage messages. For example:
use ls use more use sin
Developers may use the usemsg utility to add usage messages to their programs. will be scanned and all text between an #ifdef __USAGE and the next #endif will were links to the same load file they could each have their own usage within the same usage record within the file.
The grammar consists of the special symbol % in the first column followed by an action character as follows:
- %%
- a single %
- %-command
- the start of a specific command
- %=language
- the start of a new language
- %C<tab>
- replace with name of command and a space
- <tab>
- insert spaces equal to the length of the command + 1
To extract the entire usage message, including all languages and the grammar control sequences, you name the loadfile and don't specify a msgfile.
The %-command and %=language are both optional. If both are specified then the %-command would be followed by one or more %=languages followed by another %-command and another set of %=languages..
Examples:
Insert usage message from C source into myprog:
usemsg myprog myprog.c
Extract the entire usage message for sinit, edit the message, then reinsert the changed message:
usemsg sinit >sinitmsg vedit sinitmsg usemsg sinit sinitmsg
|
http://www.qnx.com/developers/docs/qnx_4.25_docs/qnx4/utils/u/usemsg.html
|
crawl-003
|
refinedweb
| 424
| 68.1
|
We have some sophisticated infrastructure that allows us to simulate many peer-to-peer systems, scaling up to millions of nodes in size. The nodes in our simulation run the exact same DRT binary that ships with Windows 7. We can simulate a number of different systems – small networks where nodes come and go, large networks that remain stable, even networks where nodes behave maliciously or drop offline without warning.
In this entry, we’ll focus on two performance metrics (resolve success rate and average hopcount), in two scenarios (stable cloud and dynamic cloud).
. Resolve success rate: # successfully resolved keys/ # issued resolutions
. Average hops: average number of nodes that must be contacted in order to resolve a key
Scenario 1: Stable network with low churn (a private enterprise network or a data center)
In this scenario, the network is stable. Machines rarely join/leave. They stay in network, register/unregister keys, and search for other keys. Here is the result of one sample simulation with 2000 DRT instances (nodes). It shows that the resolve success rate is always above 99.9% (Figure 1), and keys can be found within about 3 hops (Figure 2).
Scenario 2: Network with high churn (an Internet DHT)
Applications deployed in Internet may experience churn: machines can leave, join, or suddenly fail. To understand the performance of the DRT when the system is very dynamic, we simulate higher churn rates than we expect in reality. Nodes frequently join and leave the system. 20% of nodes disappear suddenly – disconnecting without notifying others. The simulations show the DRT maintains a high resolve success rate (>98.5%) (Figure 3) even under such adverse conditions. Searches complete within 6 hops on average (Figure 4), which indicates DRT cache is well maintained.
Thanks!
Xianjin
We.
--Bill
Hi everyone,
I just wanted to post a short list of resources that will help you build peer-to-peer applications for Windows 7.
Download the Windows 7 beta here:. If you haven't tried it yet, be quick! Looks like beta slots are running out.
Donwload the SDK for Windows 7 here:. The SDK includes everything you need to build applications with the Distributed Routing Table - headers, libraries and even a sample.
Access the DRT MSDN Documentation here:. Let us know if you feel concepts are left unexplained or if you have any questions.
This is the first article in a multi-part series describing a design for a distributed hash table (DHT) built with the Distributed Routing Table (DRT), our new Windows 7 peer-to-peer platform piece. If you’re interested in building a DHT of your own using the Distributed Routing Table, or you have questions about these articles, please email me (tylbart@microsoft.com). I can answer questions, point you towards the right documentation and help you get the tools you need to get started.
Distributed Hash Tables have received lots of well deserved attention from academia and industry. They have been used to build some powerful (and sometimes disruptive) software, and have many properties and architectures worthy of deep analysis.
Wikipedia has brief, but informative introduction to DHTs which is worth reading even if you’re an experienced peer-to-peer developer ().
Here’s a DHT definition lifted from the Wikipedia article:.
The Wikipedia article goes on to describe the software components comprised by a typical DHT. There are three basic pieces:
1. A mechanism for finding the machine responsible for a key, value pair when storing or retrieving a piece of content.
2. A protocol for transmitting or downloading a key, value pair.
3. A protocol and a set of algorithms that preserve the key, value pairs while allowing for the arrival and departure of new machines in the distributed system.
The DRT solves problem number (1) and provides tools that make it easier to solve (2) and (3).
The structured overlay (component 1) is perhaps the most keenly studied component in today’s distributed hash tables because it’s a hard piece of software to get right. A lot of Microsoft blood, sweat and tears went into the DRT, but we’ve come emerged with a high quality protocol that can greatly simplify the development of a DHT. The DRT is based on the PNRP protocol, and has benefitted from our years of study of the PNRP cloud on the real Internet. The DRT has been extensively tested for security, reliability, performance and scale. We have world class simulation infrastructure that allows us to test DRT clouds with millions of virtual nodes under adverse network conditions. Finally, we have rebuilt the PNRP component in Windows 7 using the new DRT platform, and we have a new experience using PNRP in remote assistance.
With all this said, the DRT won’t be complete until we get some feedback from you. Please let me know if you would like to test the DRT or build an application of your own (DHT or otherwise) before we ship Windows 7. You can have a big impact on our product!
The rest of the articles in this series will describe how to program the DRT to be an effective overlay for a DHT. We’ll also talk about some protocols and algorithms for content download/upload and replication and look at some alternative DHTs and overlays in production today.
Thanks and have fun!
Perhaps.
-Travis.
Tyler
There’s a little known, but extremely useful feature of PNRP we call extended payload. Every time I explain this feature to someone, their eyes light up. It’s always fun to surprise someone with a tidbit like extended payload, but it disappoints me that more PNRP developers don’t know about this feature already. Time to fix that!
Extended payload allows an application to attach an arbitrary blob of data to a PNRP name at registration time. When a searching application resolves the name, it will download the blob along with the endpoints (addresses and ports) describing the publisher. This is a great way to attach any extra information to your application endpoint that might be needed for the application session. If you were publishing a name identifying a multi-player gaming session, for example, you might include the game level or even level map as extended payload.
It’s important to point out that the extended payload isn’t pushed out into the PNRP cloud. It only lives on the publishers machine, and is only transferred from publisher to resolver at the time of a PNRP name resolution. If your machine is participating in the PNRP cloud by publishing a name, it is helping other nodes to publish and resolve, but it is never hosting extended payload on behalf of another computer. It’s also important to note that the extended payload cannot be tampered with if it is attached to a secure PNRP name, because it is included in a signed message.
If you’re using the native Windows PNRP API, you can register a name with an extended payload using the PeerPnrpRegister function. PeerPnrpRegister takes a PEER_PNRP_REGISTRATION_INFO structure as an argument. The payload member of this structure can be filled out with a blob that will become extended payload. If you’re using System.Net.PeerToPeer, look for the Data property of the PeerNameRegistration and PeerNameRecord classes.
The extended payload cannot exceed 4KB in size, and it’s best to keep your extended payload as small as possible. All PNRP messages are delivered over a UDP transport. This includes the message that carries the extended payload. There is logic in PNRP that breaks up a large extended payload and splits it across multiple UDP packets, allowing you to have a payload greater than 1 MTU. This logic handles message ordering, reassembly and some level of delivery guarantee, but large payloads can hurt performance, especially if the publisher or resolver is on a very lossy network. A PNRP resolve will not complete until the entire extended payload has been transmitted from the publisher to the resolver. If it takes too long to transmit all the pieces of the payload, the whole resolve may fail. If the extended payload is large, the message will be fragmented across multiple UDP packets. A larger number of packets increases the chance that a portion of the message will get lost. Be careful with extended payload, but remember that it’s there if you need it.)
Kevin Hoffman has continued his series about peer-to-peer networking. You can find an index of his posts here:
After his first post, Kevin received a number of queries asking him to differentiate between PNRP and Bonjour. His article, Peer Networking Series - A Closer Look at PNRP vs. Bonjour/ZeroConf, is definitely worth a read. I’d like to add a little to what Kevin has said by sharing a little more about PNRP.
I won’t spend much time explaining how Bonjour and MDNS work. There are lots of references on the web. The Bonjour Wikipedia article is a good place to start.
Bonjour has several pieces. Kevin’s readers seem to be primarily interested in multicast DNS, which works in a single broadcast domain, and dynamic DNS, which works over the internet. PNRP works both within a broadcast domain, using a link local cloud, and across the internet, using the Global_ cloud.
According to, multicast DNS was designed to resemble the wire protocol and programming interface of DNS as closely as possible. In this respect, the Link-local Multicast Name Resolution (LLMNR) is much closer to Bonjour than PNRP. You can read about LLMNR in the following Cable Guy article from November 2006:.
The PNRP protocol and API are very different from DNS, and were designed to provide some extra special features for peer-to-peer application developers. To use these features of PNRP, you’ll have to leave behind at least some of what you know about the DNS protocol and how to write applications that use it. If you’re reading this blog, you’re probably comfortable with the fact that PNRP has its own unique protocol and API, and you’re interested in learning more.
Here are some of the unique features of PNRP (taken from our whitepaper at)
PNRP has the following properties:
· Distributed and serverless for incredible scalability and reliability
PNRP is almost entirely serverless (servers are required only for bootstrapping). PNRP easily scales to billions of names. The system is fault tolerant and there are no bottlenecks.
· Effortless name publication without third parties
DNS name publication requires updates to DNS servers. Most people must contact a server administrator. This takes time and incurs costs. PNRP name publication is instantaneous, effortless, and free.
·.
· Name more than just computers
A PNRP resolution includes an address, port, and possibly an extended payload. With PNRP you can name more than just computers. You can also name services.
· Protected name publication
Names can be published as secured (protected) or unsecured (unprotected) with PNRP. PNRP uses public key cryptography to protect secure peer names against spoofing.
I’d like to point out that PNRP has been implemented as a Winsock Name Space Provider (NSP). This means that you can access PNRP through the standard Winsock Service Provider Interface (SPI) functions, making it possible to build an application that has little or no knowledge of the underlying name resolution technologies. In short, you can access PNRP using the same functions that you use to access DNS. You can resolve PNRP names using the getaddrinfo function. I touched on this topic in the post entitled PNRP and pnrp.net. The PNRP API wraps Winsock functions, and simply makes it easier to write PNRP applications.
I hope this post helps clear things up and gets you excited about our more powerful features.
Thanks again Kevin for your excellent articles.
We’ve included some really neat performance counters that you can use to monitor PNRP. If you’re an application developer, you might use these performance counters to evaluate what impact your use of PNRP will have on the system as a whole. They're also an interesting debugging aid when things go wrong.
To view these counters, open up perfmon (start > run > perfmon.msc). Click on the “Performance Monitor” choice under “Monitoring Tools” in the left hand pane under the heading “Reliability and Performance.” You should see a graph measuring CPU usage over time. You can add the PNRP counters to this graph by right clicking the image and selecting “Add Counters…” from the menu.
The PNRP performance counters can be found under the heading “Peer Networking Resolution Protocol.” On Vista / WS08 there are five of them. Select the counters you’re interested in, and then click the “Add” button. After clicking “Ok” you should return to the original graph which now includes PNRP metrics.
The five counters are…
Bytes received/sec: the number of bytes received by PNRP in the sampling interval (1 second).
Bytes sent/sec: the number of bytes sent by PNRP in the sampling interval (1 second).
Number of IDs registered: the number of names registered by all processes on the system.
Number of resolves: incremented each time an application initiates a PNRP name resolution.
Stale cache entry hits: incremented each time PNRP attempts to contact an unresponsive node when doing internal cache maintenance or when resolving a name.
It’s important to note that the PNRP performance counters report the cumulative results from all clouds. If you publish a name in both the link local, and Global_ clouds, PNRP will use some on-link bandwidth and some internet bandwidth maintaining the names. If your ISP limits your bandwidth every month, you might be interested in PNRP internet bandwidth usage, but you probably don’t care about the on-link bandwidth use which never makes it to the ISP. Unfortunately, the PNRP performance counters lump it all together.
Hi
Kevin Hoffman is a big fan of the Windows P2P technologies, and he's writing a series of P2P blog posts. Check out his latest post on PNRP ...
...and don't miss his article about the WCF Peer Channel ..
If.
Sorry I’ve been gone for a while. I’ve been busy working on some neat new stuff. I can’t wait to tell you about it!
MSDN Magazine has coverage of Peer-to-Peer (P2P) namespace in the upcoming release of the .NET Framework 3.5 (which will ship with Visual Studio® 2008, formerly code-named "Orcas"). Check it out here:
Trademarks |
Privacy Statement
|
http://blogs.msdn.com/p2p/
|
crawl-002
|
refinedweb
| 2,417
| 55.03
|
NAME
SYSCTL_DECL, SYSCTL_INT, SYSCTL_LONG, SYSCTL_NODE, SYSCTL_OPAQUE, SYSCTL_PROC, SYSCTL_STRING, SYSCTL_STRUCT, SYSCTL_UINT, SYSCTL_ULONG, SYSCTL_XINT, SYSCTL_XLONG - Static sysctl declaration functions
SYNOPSIS
#include <sys/types.h> #include <sys/sysctl.h> SYSCTL_DECL(name); SYSCTL_INT(parent, nbr, name, access, ptr, val, descr); SYSCTL_LONG(parent, nbr, name, access, ptr, val, descr); SYSCTL_NODE(parent, nbr, name, access, handler, descr); SYSCTL_OPAQUE(parent, nbr, name, access, ptr, len, fmt, descr); SYSCTL_PROC(parent, nbr, name, access, ptr, arg, handler, fmt, descr); SYSCTL_STRING(parent, nbr, name, access, arg, len, descr); SYSCTL_STRUCT(parent, nbr, name, access, ptr, type, descr); SYSCTL_UINT(parent, nbr, name, access, ptr, val, descr); SYSCTL_ULONG(parent, nbr, name, access, ptr, val, descr); SYSCTL_XINT(parent, nbr, name, access, ptr, val, descr); SYSCTL_XLONG(parent, nbr, name, access, ptr, val, descr);
DESCRIPTION
The SYSCTL_DECL(). New nodes are declared using one of SYSCTL_INT(), SYSCTL_LONG(), SYSCTL_NODE(), SYSCTL_OPAQUE(), SYSCTL_PROC(), SYSCTL_STRING(), SYSCTL_STRUCT(), SYSCTL_UINT(), SYSCTL_ULONG(), SYSCTL_XINT(), and SYSCTL_XLONG(). Each macro accepts a parent name, as declared using_QUAD. All sysctl types except for new node declarations require one or more flags to be set indicating the read and write disposition of the sysctl: CTLFLAG_RD This is a read-only sysctl. CTLFLAG_WR This is a writable sysctl. CTLFLAG_RW This sysctl is readable and writable. CTLFLAG_ANYBODY Any user or process can write to this sysctl. CTLFLAG_SECURE This sysctl can be written to only if the effective securelevel of the process is ≤ 0. CTLFLAG_PRISON This sysctl can be written to by processes in jail(2). CTLFLAG_SKIP When iterating the sysctl name space, do not list this sysctl. CTLFLAG_TUN Also declare a system tunable with the same name to initialize this variable. CTLFLAG_RDTUN Also declare a system tunable with the same name to initialize this variable; however, the run-time variable is read-only..
EXAMPLES
Sample use of. * If sysctl(8) should print this value in hex, use ’SYSCTL_XINT’. */ SYSCTL_INT(_debug_sizeof, OID_AUTO, bio, CTLFLAG_RD, NULL, sizeof(struct bio), "sizeof(struct bio)"); /* * Example of a variable integer value. Notice that the control * flags are CTLFLAG_RW, the variable pointer is set, and the * value is 0. */ static int doingcache = 1; /* 1 => enable the cache */ SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0, "Enable name cache"); /* * Example of a variable string value. Notice that the control * flags are CTLFLAG_RW, that the variable pointer and string * size are set. Unlike newer sysctls, this older sysctl uses a * static oid number. */ char kernelname[MAXPATHLEN] = "/kernel"; /* XXX bloat */ SYSCTL_STRING(_kern, KERN_BOOTFILE, bootfile, CTLFLAG_RW, kernelname, sizeof(kernelname), "Name of kernel file booted"); /* * Example of an opaque data type exported by sysctl. Notice that * the variable pointer and size are provided, as well as a format * string for sysctl(8). */ static l_fp pps_freq; /* scaled frequence offset (ns/s) */ SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD, &pps_freq, sizeof(pps_freq), "I", ""); /* * Example of a procedure based sysctl exporting string * information. Notice that the data type is declared, the NULL * variable pointer and 0 size, the function pointer, and the * format string for sysctl(8). */ SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW, NULL, 0, sysctl_kern_timecounter_hardware, "A", "");
SYSCTL NAMING
When. The semantics chosen for a new sysctl should be as clear as possible, and the name of the sysctl must closely reflect its semantics. Therefore the sysctl name deserves a fair amount of consideration. It should be short but yet representative of the sysctl meaning. If the name consists of several words, they should be separated by underscore characters, as in compute_summary_at_mount. Underscore characters may be omitted only if the name consists of not more than two words, each being not longer than four characters, as in bootfile. For boolean sysctls, negative logic should be totally avoided. That is, do not use names like no_foobar or foobar_disable. They are confusing and lead to configuration errors. Use positive logic instead: foobar, foobar_enable. A temporary sysctl node that should not be relied upon must be designated as such by a leading underscore character in its name. For example: _dirty_hack.
SEE ALSO
sysctl(8), sysctl_add_oid(9), sysctl_ctx_free(9), sysctl_ctx_init(9), sysctl_remove_oid(9)
HISTORY
The sysctl(8) utility first appeared in 4.4BSD.
AUTHORS
The sysctl implementation originally found in BSD has been extensively rewritten by Poul-Henning Kamp in order to add support for name lookups, name space iteration, and dynamic addition of MIB nodes. This man page was written by Robert N. M. Watson.
|
http://manpages.ubuntu.com/manpages/intrepid/man9/SYSCTL_NODE.9freebsd.html
|
CC-MAIN-2014-15
|
refinedweb
| 703
| 54.73
|
Asked by:
Microsoft Reporting vs Crystal Reports
General discussion
Hi all. I'm getting scared and frustrated with Crystal Reporting. I've been using CR for 10+ years, but this last round of 2010 release where it didn't look like CR was going to be part of VS was worrisome to say the least. I know, MS says it will be there, but they told me the same thing about another product and, poof, it was going.
So, my question is: For those of you whom have used both CR and msReporting, what are some of the pros and cons? I read one post where it said msRpt couldn't use multiple tables. Well, for me that seals the deal right there. Hopefully, the post was ancient and this is no longer an issue.
Also, I played with msRpt a bit. I am able to create a viewer and data set with a table adapter fairly easy. But, most of my use of a reporting tool is to report error logs. And those error logs I build in an XML file. I typically create a data set without a table adapter and populate the dataset virtually, (not really using the xsd for anything more than formatting the report). Yet when I tried this same method with the report viewer, it can't "see" the dataset class. I can only assume it would be because of the lack of table adapter.
So, can msRpts work without a table adapter for ad-hoc reporting and dataset construction, how is the speed on large data sets from sql, how does it fair under multiple groups and all that ____?
Thanks.
Greg Kowieski The World On-Line
- Changed type Charles Wang - MSFTModerator Tuesday, May 11, 2010 3:23 AM discussions on MR and CR
All replies
I do alot of reports, most all my work is creating reports. I've been using Crystal and just switched over to MS. The reasons that sold me are smaller install package, faster speed, and built into VS, not necessarily in that order.
The speed issue really suprised me. I set up a test case with a set of master records and then child records in a subreport. I seperated retrieving the data from rendering the report and then created both a Crystal and MS report that were the same. With 10 master records, Crystal was about 0.5 seconds faster to display. With 100 records, MS was half the time of Crystal. As the numbers of master records increased, the gap increased. MS was clearly faster.
I only work with disconnected datasets and not table adaptors. I have to calculated much of the data desired, so I populate a report dataset and then render the report. So there is no problem reporting from a dataset.
Designing in the UI is a bit different, and I'm not sure of the granularity in placement of objects. The only edge I've found for Crystal is they have templated for Avery type labels and I haven't see this yet in MS. Other than that, MS seem to have everything as Crystal, but is faster and deploys smaller.
Documentation on MS seems to be scarce. There is only one book I've found for client side reporting and it's fairly basic.
Seeing that Crystal for VS 2010 is delayed just makes me happier I made the switch.
Bernie
Hi,
we've got to answer that question (CR vs MR) in our team, to. So evaluation is just on it's way...
The picture up to now is (only regarding desktop apps and up to 2008):
-CR seems well documented, more ressources available than MR
-Huge API in CR (just try to print a MR-report without preview, that's ridiculous!)
-CR somehow slower than MR with huge amount of data
-Designing reports against custom BusinessObjects is really worse (Wizard isn't even able to "see" objects in another project!) in CR
-CR's preview integration into our apps is much better than in MR (just try to make your own toolbar!)
-MR's integration in the dev environment is superior to CR (which's habit to implement it's own DB-connection is bad taste)
-Both seem to lack designers, our users can use at runtime from within our apps (not external!) to manipulate reports which we prefer to store in the DB (seems to be quite easy with MR as it's only XML to be stored!) for better managability and deployment.
It seems as if reporting software for .NET isn't really a strongpoint ;-)
Volker
since you use disconnected datasets also, maybe you can help me out. I created an xml schema xsd to be used as my datasource. I'm able to format the report just fine. But I'm getting an error regarding missing data source.
Public Sub showErrorReportMS(ByVal nXmlDataLocation As String) Dim myViewer As New MSReportViewer myViewer.ReportViewer1.ProcessingMode = ProcessingMode.Local Dim rep As LocalReport = myViewer.ReportViewer1.LocalReport ' rep.ReportPath = "MSProcessingReport.rdlc" Dim ds As New DataSet ds.ReadXml(nXmlDataLocation) Dim dsOrders As New ReportDataSource dsOrders.Name = "Order_Data" dsOrders.Value = ds.Tables("Order") rep.DataSources.Add(dsOrders) myViewer.Show() myViewer.ReportViewer1.RefreshReport() End Sub
This is the schema for the report dataset
<?xml version="1.0" encoding="utf-8"?> :sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
If I use rep.ReportPath = "MSProcessingReport.rdlc" I get an error stating it doesn't know where the report is, (its looking in my bin directory). The report is an embedded resource.
So I left out the reportPath and then it indicates "a data source instance has not been supplied for the data source 'xmlProcessedDataSet'. I'm not quite sure why it would not see the datasource I populated with the ds.
Any ideas or simple examples of the method?
Greg Kowieski The World On-Line
Greg,
Here's a method that displays a report. It's actually the button click function from some test code, but it does what you want.
The first thing I see is you are not declairing the report name. In my code see the line;
mrvMicrosoftViewer.LocalReport.ReportEmbeddedResource =
"RV_Tester.rpMicrosoftReport.rdlc";
You need to use the syntax "programname.reportname.rdlc" with your program name and report name.
Does this help any?
Bernie
private void btnCreateMicrosoft_Click(object sender, EventArgs e) { msStartTime = DateTime.Now; try { mrvMicrosoftViewer.LocalReport.ReportEmbeddedResource = "RV_Tester.rpMicrosoftReport.rdlc"; mrvMicrosoftViewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler); mrvMicrosoftViewer.RenderingComplete += new RenderingCompleteEventHandler(RenderingCompleteEventHandler); ReportDataSource rds = new ReportDataSource(); rds.Name = "dsMyData_Patients"; rds.Value = dsData.Tables["Patients"]; mrvMicrosoftViewer.LocalReport.DataSources.Add(rds); //mrvMicrosoftViewer.SetDisplayMode(DisplayMode.PrintLayout); //mrvMicrosoftViewer.ZoomMode = ZoomMode.Percent; //mrvMicrosoftViewer.ZoomPercent = 100; //mrvMicrosoftViewer.ShowProgress = true; //mrvMicrosoftViewer.CurrentPage = 1; this.mrvMicrosoftViewer.RefreshReport(); } catch (Exception ex) { MessageBox.Show(ex.Message, "btnCreateMicrosoft"); } }
Hi Greg,
here's what I did (and it works well):
(It's in the On-Load event of my preview form, whereas the new/konstruktor is called with all that _dt (datatabel, noct dataset), _Sourcename (identical to initial sourcename at designtime), _ReportPath (exact name, incl. evtl. namespace of the rdlc-file) and _Parameters (to set caption of report etc.)) It shold work with already placed viewer control, to.
Dim _rView As ReportViewer = New ReportViewer _rView.Dock = DockStyle.Fill Me.Controls.Add(_rView) With _rView .LocalReport.DataSources.Add(New ReportDataSource(_SourceName, _dt)) .LocalReport.ReportPath = _Path .LocalReport.SetParameters(_Parameters) .RefreshReport() End With
My Report is an embedded ressource, to. Therefore I don't handle a file-system-path, but something like: (be aware of different namespace if used!)
Dim
_printPreview As New frmPrintPreview(_DTProtokoll, "dsLog_Protokoll", "rptErrorLog.rdlc", paras)
HTH?
Volker
Thanks for the help guys! I'm still getting an error. "A data source instance has not been supplied for the data source 'xmlProcessedDataSet'. I was able to get it past the other stuff though.Could this be because I built the report off the dataset xmlProcessedDataSet, (when you bind the report). Do I need to unbind the report or something? When I look at the report data tab, it shows (Built-in-fields, Parameters, images, root). The root has my schema attached to it. It seems like when I issued the Datasources.add(dsOrders) it would have overwritten the old datasource. Perhaps not?
Greg Kowieski The World On-Line
Try adding a new test report and bind it to the dataset. Just throw the fields on the page for testing and see what happen. That might be easier than trying to work though all the connections until you get one that works.
Let us know if the new report works.
Bernie
Hi Greg,
it seems that the error can be reproduced. It appears when I handle a wrong ReportDataSource.Name. The name has to be the same as provided at runtime. So, if you use table 'xyz' from dataset 'abc' for designing your report, you must use 'abc_xyz' as name. In your case you used 'xmlProcessedDataSet' when designing and assign 'Order_Data' at runtime, which isn't a match...
HTH?
Volker
You hit the nail on the Head! I made the following Modification and all is well in the world again.Just in-case I have this problem in the future, you can also change the datsetProperty of the report to the name used in the code.
Greg Kowieski The World On-Line
|
https://social.msdn.microsoft.com/Forums/en-US/4a2d793d-fc33-4ef9-9417-cd59529bf5c5/microsoft-reporting-vs-crystal-reports?forum=vsreportcontrols
|
CC-MAIN-2020-45
|
refinedweb
| 1,554
| 58.38
|
- About virtualenv
- Combine virtualenv with IPython
- Proof by trial
- Conlcusion
- Packages and version
About virtualenv.
Combine virtualenv with IPython
If you don’t know IPython, check it out. It adds powerful features like autocompletion, colors, crazy data visualisation tools, help, source code visualisation of packages and functions, etc. It’s just raw awesomness.
Now, the problem is that virtualenv default behavior is to ignore all packages located in your
/usr/lib/pythonX.X/site-packages directory when creating a new virtualenv, which is precisely where IPython is installed. You thus won’t be able to use IPython in your virtualenv without a little bit of hacking.
There are two ways to make it work:
- the good way
- the bad way
I’ll describe both techniques and you’ll decide which is which.
Install a local IPython in each virtualenv
First, you can install IPython in each new virtualenv, with
$ pip install ipython
That will work well, but the package is quite heavy (~10Mb), and frankly, that could/should be automaded. Another problem I see with this technique is that you might want to push your code on a repository, for other people to be able to contribute. If so, you might want to push the virtualenv content, to simplify them the set-up work. Even if extremely handy, IPython might not be vital for you project, and you should only install required packages in the virtualenv, for the sake of testing.
One IPython to rule them all
Now there’s a trickier solution: we can configure your system IPython, to make it aware of your virtualenv.
This has been extremely well done by Chris Lasher, and all instructions and explanations can be found
here.
The main idea is to check if you’re running in a virtual environment when you launch IPython. If so, add all your virtualenv python environment at the begining of your
PYTHONPATH.
I however encountered a small problem with this method. IPython being in
/usr/lib/python2.7/site-packages directory, my virtualenv was not even aware of an IPython module being installed, and this error was fired even before executing the code shown in Chris’ cool blogpost:
Traceback (most recent call last): File "/usr/bin/ipython", line 30, in <module> import IPython.Shell ImportError: No module named IPython.Shell
Here’s the small hack I did to make everything work.
First I added these lines to my
/usr/bin/ipython file, before importing
IPython.Shell:
import sys if "/usr/lib/python2.7/dist-packages" not in sys.path: sys.path.append("/usr/lib/python2.7/dist-packages")
The
append command will only be executed when I’m launching IPython from a virtualenv, otherwise, the
if statement would not be
True.
Now that
/usr/lib/python2.7/dist-packages is in my
sys.path, I can import
IPython.Shell from my virtualenv.
The code contained in
~/.ipython/virtualenv.py (as described in Chris’ article) will now be executed but still need a “counter-hack”,
to cancel the effects of what we wrote in
/usr/bin/ipython. We need to completely remove
/usr/lib/python2.7/dist-packages from our
PYTHONPATH.
To do that, we’ll add a small snippet in
~/.ipython/virtualenv.py
for item in sys.path: if '/usr/lib/python2.7/dist-packages' in item: sys.path.remove(item)
Here is the final
~/.ipython/virtualenv.py) # Personal hack # Remove /usr/lib/python2.7/dist-packages and associates from the path # Counter the effects of this code, in /usr/bin/ipython # import sys # if "/usr/lib/python2.7/dist-packages" not in sys.path: # sys.path.append("/usr/lib/python2.7/dist-packages") for item in sys.path: if '/usr/lib/python2.7/dist-packages' in item: sys.path.remove(item) #
Proof by trial
Now, let’s try it, to check everything’s working:
balto $ cd path/to/virtualenv/project balto $ source bin/activate (project)balto $ ipython VIRTUAL_ENV -> /path/to/virtualenv/project/lib/python2.7/site-packages Python 2.7.2+ (default, Oct 4 2011, 20:06:09) Type "copyright", "credits" or "license" for more information. IPython 0.10.2 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]:
Conlcusion
Yay. Now, you won’t have to worry about installing IPython when creating a new virtualenv.
To check that everything is working properly, install a package in a fresh virtualenv that you have not installed in your “system” python.
Open two IPython interpreters: one in the virtualenv, one outside, and try to import this newly installed package in both.
The virtualenv IPython should be fine, and the second should fire an
ImportError.
Packages and version
I’m running IPython 0.10.2, Python 2.7.2+, and virtualenv 1.7.1.2.
|
http://isbullsh.it/2012/04/Embed-ipython-in-virtualenv/
|
CC-MAIN-2013-20
|
refinedweb
| 809
| 68.77
|
:
Task.Start hangs in certain conditions.
### Steps to Reproduce:
Install/start the app using the debugger.
Stop the app with the square-in-circle button on the IDE.
Double tap and "kill" the app on the phone.
Tap the app icon to start it - it starts up fine.
Tap the home button to get back to the springboard.
Tap the app icon to start it, and it hangs in task.Start().
### Actual Results:
The app will hang on task.Start()
### Expected Results:
No hang.
### Build Date & Platform:
XI 7.2.4.4
Mono 3.4.0
### Additional Information:
I only have this code as an example, no test case.
> public static NcTask Run (Action action, string name)
> {
> WeakReference taskRef = null;
> Console.WriteLine ("NcTask.Run - A");
> var task = new NcTask (delegate {
> Log.Info (Log.LOG_SYS, "NcTask {0} started.", name);
> action.Invoke ();
> Log.Info (Log.LOG_SYS, "NcTask {0} completed.", name);
> if (!TaskMap.TryRemove (taskRef, out name)) {
> Log.Error (Log.LOG_SYS, "Task {0} already removed from TaskMap.", name);
> }
> });
> Console.WriteLine ("NcTask.Run - B");
> taskRef = new WeakReference (task);
> if (!TaskMap.TryAdd (taskRef, name)) {
> Log.Error (Log.LOG_SYS, "Task {0} already removed from TaskMap.", name);
> }
> Console.WriteLine ("NcTask.Run - C");
> task.Start ();
> Console.WriteLine ("NcTask.Run - D");
> Log.Info (Log.LOG_SYS, "Task {0} started.", name);
> return task;
> }
Where is the app to reproduce with?
@Marek,
Sorry, per my comment in Additional Information, that is the only code I have. I don't have a complete test case.
This code is very incomplete. How do you know task is of type Task I see only NcTask.
After stubbing the user code it works for me fine.
Test code
using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
class NcTask : Task
{
public NcTask (Action d)
: base (d)
{
}
}
class Test
{
static ConcurrentDictionary<WeakReference, string> TaskMap = new ConcurrentDictionary<WeakReference, string> ();
static void Main (string[] args)
{
Run (delegate {
}, "aa");
}
public static NcTask Run (Action action, string name)
{
WeakReference taskRef = null;
Console.WriteLine ("NcTask.Run - A");
var task = new NcTask (delegate {
Console.WriteLine ("NcTask {0} started.", name);
action.Invoke ();
Console.WriteLine ("NcTask {0} completed.", name);
if (!TaskMap.TryRemove (taskRef, out name)) {
Console.WriteLine ("Task {0} already removed from TaskMap.", name);
}
});
Console.WriteLine ("NcTask.Run - B");
taskRef = new WeakReference (task);
if (!TaskMap.TryAdd (taskRef, name)) {
Console.WriteLine ("Task {0} already removed from TaskMap.", name);
}
Console.WriteLine ("NcTask.Run - C");
task.Start ();
Console.WriteLine ("NcTask.Run - D");
Console.WriteLine ("Task {0} started.", name);
return task;
}
}
|
https://bugzilla.xamarin.com/21/21027/bug.html
|
CC-MAIN-2021-39
|
refinedweb
| 403
| 72.12
|
Back to index
#include <errno.h>
#include <shlib-compat.h>
#include "pthreadP.h"
Go to the source code of this file.
Definition at line 26 of file pthread_cond_destroy.c.
{ int pshared = (cond->__data.__mutex == (void *) ~0l) ? LLL_SHARED : LLL_PRIVATE; /* Make sure we are alone. */ lll_lock (cond->__data.__lock, pshared); if (cond->__data.__total_seq > cond->__data.__wakeup_seq) { /* If there are still some waiters which have not been woken up, this is an application bug. */ lll_unlock (cond->__data.__lock, pshared); return EBUSY; } /* Tell pthread_cond_*wait that this condvar is being destroyed. */ cond->__data.__total_seq = -1ULL; /* If there are waiters which have been already signalled or broadcasted, but still are using the pthread_cond_t structure, pthread_cond_destroy needs to wait for them. */ unsigned int nwaiters = cond->__data.__nwaiters; if (nwaiters >= (1 << COND_NWAITERS_SHIFT)) { /* Wake everybody on the associated mutex in case there are threads that have been requeued to it. Without this, pthread_cond_destroy could block potentially for a long time or forever, as it would depend on other thread's using the mutex. When all threads waiting on the mutex are woken up, pthread_cond_wait only waits for threads to acquire and release the internal condvar lock. */ if (cond->__data.__mutex != NULL && cond->__data.__mutex != (void *) ~0l) { pthread_mutex_t *mut = (pthread_mutex_t *) cond->__data.__mutex; lll_futex_wake (&mut->__data.__lock, INT_MAX, PTHREAD_MUTEX_PSHARED (mut)); } do { lll_unlock (cond->__data.__lock, pshared); lll_futex_wait (&cond->__data.__nwaiters, nwaiters, pshared); lll_lock (cond->__data.__lock, pshared); nwaiters = cond->__data.__nwaiters; } while (nwaiters >= (1 << COND_NWAITERS_SHIFT)); } return 0; }
|
https://sourcecodebrowser.com/glibc/2.9/pthread__cond__destroy_8c.html
|
CC-MAIN-2016-44
|
refinedweb
| 239
| 54.08
|
Here solutionStupid Enumerator Tricks - And now for something completely differentMagical Assembler Incantations - Nested functions and anonymous methodsThe Life and Times of a Thread PoolI cut and I cut and it was still too short!Spot the deadlockWading in the shallow end of the pool - Thread Pools). There is still the notion of a TMonitor but only to serve as a way to tie together the "monitor" functionality. Rather than creating one and setting about to locking/unlocking it, you now only need an object instance. For Tiburón, you merely need to call System.TMonitor.Enter(<obj>); or System.TMonitor.Exit(<obj>); among the other related methods.
I’ve contemplated putting these methods directly on TObject itself, but there is the issue with calling these methods when a descendant class has a method of the same name. The code will compile and function normally due to Delphi’s scoping rules, but it could make it harder for users to call those methods in these cases. Thread synchronization should never be done lightly and should require some forethought and planning. A simple rule of thumb is that you should never call unknown code (or code that you’re not entirely sure where it goes and what it does) while holding a lock.
This now paves the way to add some interesting intrinsic functionality such as using this as the basis for "synchronized" methods or even synchronized code blocks similar to the C# lock keyword. While you’ve always been able to create an OS critical section, or use some of the helper classes in SyncObjs.pas, this new mechanism will be available on any object.
I merely design it then write about it… you get to kvetch.
Allen,
Have you seen this?
I hope the name for that feature will change in time for release. We already got a Forms.TMonitor thank you very much.
Dear, Allen
It looks like using syncIdx field of object instance in .NET,
which exists in any instance of .NET object.
May be the best way is not to add any hidden field to Object instance in Delphi.
Just do it by compiler switch like
{$AUTOSYNC ON}.
Maybe, instead of cluttering the generic TObject namespace with many functions, which is a bad idea as you already noted, have a property Monitor (or something more descriptive) that exposes the TMonitor methods:
Self.Monitor.Enter
twm
If the purpose of your blog is to make customers long for the next release –> mission accomplished
AMD Accelerates Application Development with Inaugural Release of Open Source Performance Library:
"…It also offers aggressive internal threading features which manage sophisticated threading models to exploit multi-core and multiprocessor systems…"
Gee, Forms.pas already includes a TMonitor class that holds information about a display monitor. Perhaps (as other posts have already suggested) a more definitive name is in order.
"Gee, Forms.pas already includes a TMonitor class that holds information about a display monitor."
I’d already considered that. The problem is that "Monitor" is also a very commonly accepted vernacular for this exact functionality. As a compromise, there are a set of global functions named something like "MonitorEnter();" or "MonitorTryEnter();"
Allen.
how about TSyncMonitor?
I have found very nice looking parallel library for delphi:
After reading documentation, I can say this is what I need.
The only one thing that I do not like in this library is ParallelFor (they should use nested procedures instead of normal procedures to eliminate global variables).
I think CodeGear should at least consider to buy delphi part to incorporate this to next version of delphi if not take over whole company.
This looks very promising I can’t wait to see how this will be when Tiburon is released.
Great to see the multithreading / paralell programming supporting being spiffed up!
We also need better support to efficiently wait for cross-thread signals in the main VCL thread, and general mechanisms to communicate between threads. Here is my 1999 article and code to target some of these:
<>
IOW, an interface. This is great. Good move.
)"
"I’ve contemplated putting these methods directly on TObject itself, but there is the issue with calling these methods when a descendant class has a method of the same name."
You can avoid this by giving TObject an IMonitor interface. If a programmer need to avoid name collisions further down the heirarchy, he can do so with the "implements" directive.
-d
[...] reminded me of Allen Bauer’s long series of blog posts last year on the "Delphi Parallel Library," which discuss the TMonitor class in detail. He notes: The TMonitor class [...] is now tied directly [...]
Allen, will TApplication, TScreen and TForm ever be thread-safe? I mean, when will we finally be able to create forms in separate threads, having their own modal stack, etc?
Name (required)
Mail (will not be published) (required)
Mail (leave blank) (required)
Website
Server Response from: blogs2.codegear.com
|
http://blogs.embarcadero.com/abauer/2008/02/19/38856
|
crawl-002
|
refinedweb
| 820
| 63.49
|
You (Hiram Lester, Jr.) wrote: > On Tue, 26 Nov 1996, Foteos Macrides wrote: > > > 11-26-96 > > * Added multiple bookmark support along the lines of the patch from Filip M. > > Gieszczykiewicz (address@hidden), plus numerous enhancements of the > > 'o'ptions menu and bookmark handling. - FM Greetings. Eeek.. I forgot to upload the patch for that. So sorry. It's up to 0.09 and the key fix is line #521 or so, fix up the test to be: if (c == 13) if (TLJ_A_subbookmark[0]) /* TLJ 11/12/96 - bug nailed right about here... */ return(0); /* TLJ - assumes default action on ENTER */ else return (-1); if (c == 7) return(-1); if (c == '=') /* let the rest of this function take over and show the menu */ return(select_menu_multi_bookmarks()); CHANGELOG: -----------------chop-with-axe----------------chop-with-axe--------------------- 10. Changes from 0.07 & 0.08 1. Fixed a bug where just hitting return/enter when adding bookmarks would cause a core dump because of an oversight on my part. That is now fixed. 2. Also fixed a STUPID bug when picking bookmarks it would dump if a key out of range was selected... I'm testing this release for idiot bugs like that... 3. New: added a feature such that when you define a new sub-bookmark description and filename, the first time you add a bookmark to it, lynx will include the description of the sub-bookmark in the title of the sub-bookmark file. -----------------chop-with-axe----------------chop-with-axe--------------------- > I went to integrate this into the patch set tonight, and already ran > across a problem. If you enable multi-bookmark support and then 'v'iew > bookmarks and when prompted for bookmark file or list (in advanced mode) > and you just press ENTER, lynx crashes with a signal 11. This happens on [imagine my surprise... I was 10+ layers deep in an altavista search!] > my Linux box, and I'm compiling on the HP right now. Pressing ENTER > should probably act the same as pressing A and take you to the default > bookmark file. Strange, the HP version just says Bookmark file not > defined with the same set of keystrokes. I'm gonna try a make clean and Problem is array range.. c gets 'A' subtracted from it by c = TOUPPER(c) - 'A' and then becomes the index for an array... (bonehead bug comes in) 13-'A' is a negative number... and WHAMO! > remake on my Linux box just to be sure. Ok, it still does it. My > suspicions would be a comparison to a NULL string. I found that Linux was > much more picky about such things than HP-UX: > > if (strcmp(string,"test")) > > will work fing on HP-UX and will fail if string==NULL, Linux however will > coredump under the same conditions. I would look at it, but I need to be > doing homework. :) > > Also, one other thing that should probably be cleaned up is that the > second screen of bookmark files when editing the files is shifted one line > down from the first screen, and it looks slightly awkward when flipping > back and forth between screens. Geez :-) I thought I'd get away with that. You know, I wrote it and I can't track it down (why it happens). I think the part that decides how many lines to show per screen has some int-division problems. It's really noticable when you have a 9 row display (I tried), first screen has 3 entries, second and on ONLY 2... Shoot me! :-) Take care. ; ; To UNSUBSCRIBE: Send a mail message to address@hidden ; with "unsubscribe lynx-dev" (without the ; quotation marks) on a line by itself. ;
|
http://lists.gnu.org/archive/html/lynx-dev/1996-11/msg01002.html
|
CC-MAIN-2015-35
|
refinedweb
| 606
| 80.11
|
26 April 2012 18:28 [Source: ICIS news]
HOUSTON (ICIS)--The April contract price for US purified terephthalic acid (PTA) was assessed lower by ICIS on Thursday at 65.86 cents/lb ($1,452/tonne, €1,104 /tonne), following input by industry sources.
This represents a decrease of 2.34 cents/lb from 68.20 cents/lb ?xml:namespace>
The PTA price is formula-linked to the monthly contract price for upstream paraxylene (PX), with the PTA decrease for April representing 67% of the 3.50 cent/lb decrease in the April PX price.
The US April PX contract price was settled at 78.50 cents/lb DEL USG, down from 82 cents/lb DEL USG in March.
PTA is the principal feedstock for polyethylene terephthalate (PET), which is used to make plastic bottles and polyester fibre.
BP Chemicals and DAK Americas are the only PTA
|
http://www.icis.com/Articles/2012/04/26/9554172/us-april-pta-contract-falls-2.34-centslb-on-lower-px.html
|
CC-MAIN-2014-41
|
refinedweb
| 146
| 75.4
|
Java generic methods help the user to specify a set of related methods using a single method declaration. The user can also specify a set of relatable objects using a single class declaration. Generics in java help in ensuring compile-time safety which helps the programmers to catch invalid arguments during the time of compilation.
Java Generic methods and classes
- All the generic methods include a type parameter section with < > brackets which precede the type of method.
- Each type parameter section has another section that contains one or more type parameters. We separate these parameters by commas. It will specify a generic type name in the program.
- We use the parameters for the return type. They behave like placeholders for all the arguments passed in the generic methods. These arguments are also known as actual type arguments.
- There’s no difference between declarations of generic method’s body. However, the generic type can only represent the reference type and not the primitives such as double, char etc
What are the advantages of generics in Java
Generic class in java enables the use of classes and interfaces to themself turn into parameters. The user performs it while creating other classes or interfaces. The user can reuse the same code multiple times with different inputs with the help of generics.
The class helps to hold a single type of object as it cannot store multiple object types. There is no need for type casting while using generics. Otherwise, we always needed to typecast when not using generics. A good programming strategy suggests the problems should be handled during the compile-time only. So in generics, the issues are checked at the time of compilations, hence there is no scope of any error during the run time.
There’s the use of (?) symbol in generics which means a wildcard element. Wildcard element promotes any type. It is not allowed to use a wildcard as a type argument for a generic method but we can use it as a type of parameter, a field or return type.
Generic class Syntax in java
class Gen<G>{ G obj; void add(G obj){this.obj=obj;} G get(){ return obj;} }
In this syntax, the type G in generic class represents that it can refer to any string, int, or employee type. We use the specified type to store and retrieve data.
The classes ate denoted in the following manner:
T – Type
E – Element
K – Key
N – Number
V – Value
Generic class in Java with example
public class Developerhelps{ public static < E > void printArray( E[] inputArray ) { for(E element : inputArray) { System.out.print(element+" "); } System.out.println(); } public static void main(String args[]) { Integer[] intArray = { 10, 20, 30, 40, 50 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'M', 'E', 'G', 'H', 'A' }; System.out.println("IntArray contains:"); printArray(intArray); System.out.println("doubleArray contains:"); printArray(doubleArray); System.out.println("charArray contains:"); printArray(charArray); } }
The output of the above java code will be:
intArray contains: 10 20 30 40 50 doubleArray contains: 1.1 2.2 3.3 4.4 charArray contains: M E G H A
|
https://www.developerhelps.com/java-generics/
|
CC-MAIN-2021-31
|
refinedweb
| 524
| 56.45
|
npm install create-react-app --global
The new react app is created with
create-react-app react-todo
It’ll create a new folder
react-todowith some files and folders.
package.jsoncontains the list of modules that application uses. Each module performs a function or a set of functions.
node_modulesstores all packages that are listed in package.json.
srccontains all React source code files.
publiccontains static files such as stylesheets and images.
Run this app with
npm start
cd react-todonpm start
You’ll get a Welcome page…
As the instructions say, modify the App.js to make changes.
App.jsis rendered from the
index.jsfile. Consider
App.jsas the container for all other components.
Experience the ToDo app below. Enter the task in the input box, click on add button to add to the list. To remove from the list, click on the todo to be removed.
Go to the
App.jsfile in
src . Remove everything from the return except the parent div. It looks like below
import React, { Component } from 'react' import './App.css' class App extends Component { render() { return ( <div className="App"> </div> ) } } export default App
All components will go inside the div in this return statement.
Todo list is form and a display below as you’ve experienced above.
We create the component
TodoListinside TodoList.js file in the src directory.
We import this is the App.js so that we can put this in the div we’re talking about.
Also, put the TodoList in the div in return statement.
What’s in the TodoList?
import React, { Component } from 'react' class TodoList extends Component { render() { return ( <div className="todoListMain"> <div className="header"> <form> <input placeholder="Task" /> <button type="submit"> Add Task </button> </form> </div> </div> ) } } export default TodoList
You might recognize some redundant divs, don’t worry we’re filling them in a while.
This component creates the form.
It looks like this…
Your output won’t same as mine because of the CSS. I secretly added the CSS to
index.cssfile. It’s basic stuff and we’re not discussing about stylesheet after this. If you want your app styled like in the example, grab the index.css from here…
If you try to add the todo in this app, it’ll just reload the page. This is because the default behavior of the form is to submit to the same page.
We already have a lifeless todo app, which does nothing other than displaying itself.
Here’s what we’ll be doing:
The input items are submitted when the form is submitted. To handle this operation, add the onSubmit to form tag in the TodoList.
This
addItemshould be handled at the App component. It is passed to other components as a prop.
This must exist in App to pass. Create a
addItemproperty in the
App.
We could declare this as an old JavaScript (ES5) like function, but it won’t bind the form with it. We have to bind it manually through the constructor. I’d get rid of this using ES6 like syntax.
We still need the state to hold the array of items. The state makes it easy to render and elements on the page. All components using data will change automatically when the data in state changes.
We also need another state called
currentItemto hold the current value in the memory. It is an object and it also has key along with the text. React uses this key internally to only render the components when there are multiple similar components. The to-do list cannot be rendered without a key as there will be all
lis.
Add a constructor to the
App. Also, add
addItemand
handleInputto the same.
The addItem manages to add to the list, and handleInput manages the change in the input field.
This is what my App.js looks like…
import React, { Component } from 'react' import './App.css' import TodoList from './TodoList' class App extends Component { constructor() { super() this.state = { items: [], currentItem: {text:'', key:''}, } } handleInput = e => { console.log('Hello Input') } addItem = () => { console.log('Hello Add Item') } render() { return ( <div className="App"> <TodoList addItem={this.addItem} /> </div> ) } } export default App
To get the input element we must have a way to refer to it. You might be excited to use querySelector, but the React doesn’t like that. While it’s totally valid, the idea of virtual DOM is not to directly interact with the DOM but the components in the DOM.
To refer to the input, we create a
refwith
inputElement =React.createRef(). Pass this to
TodoListjust like the
addItem
inputElement = {this.inputElement}
Use it as
ref = {this.props.inputElement}in the
TodoList.
If you try the app at this moment, you can see it logs the message from addItem and then reloads. The reloading is the default behavior of the form submission.
To stop this behavior modify the addItem to the following.
addItem = e => { e.preventDefault() console.log('Hello World') }
The
preventDefaultwill prevent reloading from submitting the form.
Here’s all the data we pass to TodoList…
<TodoList addItem={this.addItem} inputElement={this.inputElement} handleInput={this.handleInput} currentItem={this.state.currentItem} />
addItemto handle click on add.
inputElementto refer to this element.
handleInputto handle data on input field on a change
currentItemto display the value of the state set to currentItem.
Here’s what my TodoList.js looks like…
import React, { Component } from 'react' class TodoList extends Component { componentDidUpdate() { this.props.inputElement.current.focus() } render() { return ( <div className="todoListMain"> <div className="header"> <form onSubmit={this.props.addItem}> <input placeholder="Task" ref={this.props.inputElement} value={this.props.currentItem.text} onChange={this.props.handleInput} /> <button type="submit"> Add Task </button> </form> </div> </div> ) } } export default TodoList
We’ll talk about eh ComponentDidUpdatein a while…
formon submit, calls
addItem
refrefers to the current element.
valueis stored as text in the
currentElementobject.
If you do not have
onChangein the component, the field will be read only. We do not want this.
onChangecalls handleInput and that’s next to discuss.
handleInput = e => { const itemText = e.target.value const currentItem = { text: itemText, key: Date.now() } this.setState({ currentItem, }) }
The handleInput gets the event, it gets the value from the input box and sets the state to and object of
currentItem. It has key as current data and text as the input data. The key is Date.now() which is the number of milliseconds from 1970 to now. It can only take a maximum of 1 input per millisecond. That’s enough for our case.
We need this object because we need to store this value to the array
itemswhen user submits the form.
addItem = e => { e.preventDefault() const newItem = this.state.currentItem if (newItem.text !== '') { console.log(newItem) const items = [...this.state.items, newItem] this.setState({ items: items, currentItem: { text: '', key: '' }, }) } }
The
addItemprevents default reload. It gets the value in the input box from the state
currentItem.
Since we do not want to add empty value to our todo, we check for that. If it’s not empty, items array is destructured and
newItemis added.
We have to set this items[] to the state, we call
this.setState. It also makes sense to reset the
currentItemto clear the input box.
ComponentDidUpdateis one of the lifecycle methods in React. We’ve talked about all of them here. ComponentDidUpdate is called to focus on the input box referred by the
inputElementreference. The component is updated on submitting the form.
this.props.inputElement.current.focus()sets the focus in the input area so we can continue typing the next item in the todo list.
We have all the todos in the state, all we need is another component that can render these on the screen.
We’ll call this component
TodoItemsand pass all items as a prop.
Here’s what
TodoItemslooks like…
import React, { Component } from 'react' class TodoItems extends Component { createTasks(item) { return <li key={item.key}>{item.text}</li> } render() { const todoEntries = this.props.entries const listItems = todoEntries.map(this.createTasks) return <ul className="theList">{listItems}</ul> } } export default TodoItems
The function createTasks returns li for each passed item. It uses the key we provided earlier. It will not work with a key at this stage because React must be able to differentiate between the multiple items to re-render the appropriate one.
All these list items are saved to
listItemsusing a mapping function. This gets used in the
ulin return statement.
We have added the ToDo, we probably want to remove some.
We already have the displaying todos in the
TodoItems.js, we make a small modification. Just add an onClick listener to deleteItem with the key.
createTasks = item => { return ( <li key={item.key} onClick={() => this.props.deleteItem(item.key)}> {item.text} </li> ) }
This executes deleteItem with the key as a parameter. The prop has to be passed from the
App.
<TodoItems entries={this.state.items}deleteItem={this.deleteItem}/>
Create a new property in App.js as
deleteItem.
deleteItem = key => { const filteredItems = this.state.items.filter(item => { return item.key !== key }) this.setState({ items: filteredItems, }) }
It filters the received key from the
itemsstate. Then sets the items to filtered items.
|
https://school.geekwall.in/p/9naB_iIb
|
CC-MAIN-2021-10
|
refinedweb
| 1,518
| 61.12
|
SOAP II: Data Encoding Marlon Pierce, Bryan Carpenter, Geoffrey Fox Community Grids Lab Indiana University mpierce@cs.indiana.edu
Review: SOAP Message Payloads • SOAP has a very simple structure: • Envelopes wrap body and optional header elements. • SOAP body elements may contain any sort of XML • Literally, use <any> wildcard to include other XML. • SOAP does not provide specific encoding restrictions. • Instead, provides conventions that you can follow for different message styles. • RPC is a common convention. • Remember: SOAP designers were trying to design it to be general purpose. • SOAP encoding and data models are optional
SOAP’s Abstract Data Model • SOAP data may be optional represented using Node-Edge Graphs. • Edges connect nodes • Have a direction • An edge is labeled with an XML QName. • A node may have 0 or more inbound and outbound edges. • Implicitly, Node 2 describes Node 1. • A few other notes: • Nodes may point to themselves. • Nodes may have inbound edges originating from more than one Node. Node 1 Edge Node 3 Node 2
Nodes and Values • Nodes have values. • Values may be either simple (lexical) or compound. • A simple value may be (for example) a string. • It has no outgoing edges • A complex value is a node with both inbound and outbound edges. • For example, Node 1 has a value, Node 2, that is structured. • Complex values may be either structs or arrays. Node 1 Node 2 (complex) Node 3 Node 4
Complex Types: Structs and Arrays • A compound value is a graph node with zero or more outbound edges. • Outbound edges may be distinguished by either labels or by position. • Nodes may be one of two sorts: • Struct: all outbound edges are distinguished solely by labels. • Array: all outbound edges are distinguished solely by position order. • Obviously we are zeroing in on programming language data structures.
Abstract Data Models • The SOAP Data Model is an abstract model • Directed, labeled graph • It will be expressed in XML. • The graph model implies semantics about data structures that are not in the XML itself. • XML describes only syntax. • Implicitly, nodes in the graph model resemble nouns, while the edges represent predicates. • We will revisit this in later lectures on the Semantic Web.
Graphs to XML • SOAP nodes and edges are not readily apparent in simple XML encoding rules. • Normally, an XML element in the SOAP body acts as both the edge and the node of the abstract model. • However, SOAP does have an internal referencing system. • Use it when pointing from one element to another. • Here, the XML-to-graph correspondence is more obvious.
SOAP header and body tags can be used to contain arbitrary XML Specifically, they can contain an arbitrary sequence of tags, replacing the <any> tag. These tags from other schemas can contain child tags and be quite complex. See body definition on the right. And that’s all it specifies. SOAP thus does not impose a content model. Content models are defined by convention and are optional. <xs:element <xs:complexType <xs:sequence> <xs:any </xs:sequence> <xs:anyAttribute </xs:complexType> Intro: Encoding Conventions
Encoding Overview • Data models such as the SOAP graph model are abstract. • Represented as graphs. • For transfer between client and server in a SOAP message, we encode them in XML. • We typically should provide encoding rules along with the message so that the recipient knows how to process. • SOAP provides some encoding rule definitions: • • But these rules are not required and must be explicitly included. • Note this is NOT part of the SOAP message schema. • Terminology: • Serialization: transforming a model instance into an XML instance. • Deserialization: transforming the XML back to the model.
Encoding is specified using the encodingStyle attribute. This is optional There may be no encoding style This attribute can appear in the envelope, body, or headers. The example from previous lecture puts it in the body. The value is the standard SOAP encoding rules. Thus, each part may use different encoding rules. If present, the envelope has the default value for the message. Headers and body elements may override this within their scope. <soapenv:Body> <ns1:echo soapenv: <!-- The rest of the payload --> </soapenv:Body> Specifying Encoding
Encoding Simple Values • Our echo service exchanges strings. The actual message is encoded like this: • <in0 xsi:Hello World</in0> • xsi:type means that <in0> will take string values. • And string means explicitly xsd:string, or string from the XML schema itself. • In general, all encoded elements should provide xsi:type elements to help the recipient decode the message.
Java examples int a=3; float pi=3.14 String s=“Hello”; SOAP Encoding <a xsi:type=“xsd:int”> 10 </a> <pi xsi:type=“xsd:float”> 3.14 </pi> <s xsi:type=“xsd:string”> Hello </s> Simple Type Encoding Examples
Explanation of Simple Type Encoding • The XML snippets have two namespaces (would be specified in the SOAP envelope typically). • xsd: the XML schema. Provides definitions of common simple types like floats, ints, and strings. • xsi: the XML Schema Instance. Provides the definition of the type element and its possible values. • Basic rule: each element must be given a type and a value. • Types come from XSI, values from XSD. • In general, all SOAP encoded values must have a type.
XML Schema Instance • A very simple supplemental XML schema that provides only four attribute definitions. • Type is used when an element needs to explicitly define its type rather than implicitly, through a schema. • The value of xsi:type is a qualified name. • This is needed when the schema may not be available (in case of SOAP). • May also be needed in schema inheritance • See earlier XML schema lectures on “Polymorphism”
Example for Encoding Arrays in SOAP 1.1 • Java Arrays • int[3] myArray={23,10,32}; • Possible SOAP 1.1 Encoding: <myArray xsi:type=“SOAP-ENC:Array SOAP-ENC:arrayType=“xsd:int[3]”> <v1>21</v1> <v2>10</v2> <v3>32</v3> </myArray>
An Explanation • We started out as before, mapping the Java array name to an element and defining an xsi:type. • But there is no array in the XML schema data definitions. • XSD doesn’t preclude it, but it is a complex type to be defined elsewhere. • The SOAP encoding schema defines it. • We also made use of the SOAP encoding schema’s arrayType attribute to specify the type of array (3 integers). • We then provide the values.
Encoding a Java Class in SOAP • Note first that a general Java class (like a Vector or BufferedReader) does not serialize in XML. • But JavaBeans (or if you prefer, Java data objects) do serialize. • A bean is a class with accessor (get/set) methods associated with each of its data types. • Can be mapped to C structs. • XML Beans and Castor are two popular Java-to-XML converters.
Example of Encoding a Java Bean • Java class class MyBean { String Name=“Marlon”; public String getName() {return Name;} public void setName(String n) {Name=n;} } • Possible SOAP Encoding of the data (as a struct) <MyBean> <name xsi:type=“xsd:string”>Marlon</name> </MyBean>
Structs are defined in the SOAP Encoding schema as shown. Really, they just are used to hold yet more sequences of arbitrary XML. Struct elements are intended to be accessed by name Rather than order, as Arrays. <xs:element <xs:group <xs:sequence> <xs:any </xs:sequence> </xs:group> <xs:complexType <xs:group <xs:attributeGroup </xs:complexType> Structs
As stated several times, SOAP encoding includes rules for expressing arrays. These were significantly revised between SOAP 1.1 and SOAP 1.2. You will still see both styles, so I’ll cover both. The basic array type (shown) was intended to hold 0 or 1 Array groups. <xs:complexType <xs:group <xs:attributeGroup <xs:attributeGroup </xs:complexType> SOAP 1.1 Arrays
Array elements contain zero or more array groups. The array group in turn is a sequence of <any> tags. So the array group can hold arbitrary XML. <xs:group <xs:sequence> <xs:any </xs:sequence> </xs:group> SOAP 1.1 Array Group
The array group itself is just for holding arbitrary XML. The array attributes are used to further refine our definition. The array definition may provide an arrayType definition and an offset. Offsets can be used to send partial arrays. According to the SOAP Encoding schema itself, these are only required to be strings. <xs:attributeGroup <xs:attribute <xs:attribute </xs:attributeGroup> <xs:attribute <xs:attribute <xs:simpleType <xs:restriction </xs:simpleType> SOAP 1.1 Array Attributes
Specifying Array Sizes in SOAP 1.1 • The arrayType specifies only that the it takes a string value. • The SOAP specification (part 2) does provide the rules. • First, it should have the form enc:arraySize. • Encoding can be an XSD type, but not necessarily. • Ex: xsd:int[5], xsd:string[2,3], p:Person[5] • The last is an array of five persons, defined in p. • Second, use the following notation: • [] is a 1D array. • [][] is a array of 1D arrays • [,] is a 2D array. • And so on.
Array encodings have been revised and simplified in the latest SOAP specifications. ArrayType elements are derived from a generic nodeType element. Now arrays have two attributes itemType is the the type of the array (String, int, XML complex type). arraySize <xs:attribute <xs:attribute <xs:attributeGroup <xs:attribute <xs:attribute </xs:attributeGroup> Encoding Arrays in SOAP 1.2
SOAP 1.2 Array Sizes • The arraySize attribute (shown below). The regular expression means • I can use a “*” for an unspecified size, OR • I can specify the size with a range of digits • I may include multiple groupings of digits for multi-dimensional arrays, with digit groups separated by white spaces. <xs:simpleType <xs:restriction <xs:pattern </xs:restriction> </xs:simpleType>
<numbers enc: <number>3 </number> <number>4 </number> </numbers> <numbers enc: <number>3 </number> <number>4 </number> </numbers> Comparison of 1.1 and 1.2 Arrays
As we have seen, both structs and arrays contain a group called commonAttributes. The definition is shown at the right. The ID and the HREF attributes are used to make internal references within the SOAP message payload. <xs:attributeGroup <xs:attribute <xs:attribute <xs:anyAttribute </xs:attributeGroup> SOAP 1.1 Encoding’s Common Attributes
References and IDs • As you know, XML provides a simple tree model for data. • While you can convert many data models into trees, it will lead to redundancy. • The problem is that data models are graphs, which may be more complicated than simple trees. • Consider a typical manager/employee data model. • Managers are an extension of the more general employee class. • Assume in following example we have defined an appropriate schema.
<manager> <fname>Geoffrey</> <lname>Fox</> </manager> <employee> <fname>Marlon</> <lname>Pierce</> <manager> <fname>Geoffrey</> <lname>Fox</> </manager> </employee> <manager id=“GCF”> <fname>Geoffrey</> <lname>Fox</> </manager> <employee> <fname>Marlon</> <lname>Pierce</> <manager href=“#gcf”> </employee> Before/After Referencing(SOAP 1.1 Encoding)
References, IDs and Graphs • References serve two purposes. • They save space by avoiding duplication • A good thing in a message. • They lower the potential for errors. • They also return us to the graph model. • Normal nodes and edges get mapped into one element information item. • Ref nodes actually split the edge and node. employee href=“#gcf” manager
SOAP 1.1 required all references to point to other top level elements. SOPA 1.2 changed this, so now refs can point to child elements in a graph as well as top level elements. See next figure They also changed the tag names and values, so the encoding looks slightly different. <manager id=“GCF”> <fname>Geoffrey</> <lname>Fox</> </manager> <employee> <fname>Marlon</> <lname>Pierce</> <manager ref=“gcf”> </employee> References in SOAP 1.2
<e:Books> <e:Book> <title>My Life and Work </title> <author href="#henryford" /> </e:Book> <e:Book> <title>Today and Tomorrow</title> <author href="#henryford" /> </e:Book> </e:Books> <author id="henryford"> <name>Henry Ford</name> </author> <e:Books> <e:Book> <title>My Life and Work </title> <author id="henryford" > <name>Henry Ford</name> </author> </e:Book> <e:Book> <title>Today and Tomorrow </title> <author ref="henryford" /> </e:Book> </e:Books> SOAP 1.1 and 1.2 Refs
Using SOAP for Remote Procedure Calls
The Story So Far… • We have defined a general purpose abstract data model. • We have looked at SOAP encoding. • SOAP does not provide standard encoding rules, but instead provides a pluggable encoding style attribute. • We examined a specific set of encoding rules that may be optionally used. • We are now ready to look at a special case of SOAP encodings suitable for remote procedure calls (RPC).
RPC is just a way to invoke a remote operation and get some data back. All of your Web Service examples use RPC How do we do this with SOAP? We encode carefully to avoid ambiguity. But it really is just common sense. Information needed for RPC: Location of service The method name The method values The values must be associated with the method’s argument names. Requirements for RPC with SOAP
Location of the Service • Obviously the SOAP message needs to get sent to the right place. • The location (URL) of the service is not actually encoded in SOAP. • Instead, it is part of the transport protocol used to carry the SOAP message. • For SOAP over HTTP, this is part of the HTTP Header: POST /axis/service/echo HTTP/1.0 Host:
RPC Invocation • Consider the remote invocation of the following Java method: • public String echoService(String toEcho); • RPC invocation conventions are the following: • The invocation is represented by a single struct. • The struct is named after the operation (echoService). • The struct has an outbound edge for each transmitted parameter. • Each transmitted parameter is an outbound edge with a label corresponding to the parameter name.
SOAP Message by Hand <env:Envelope xmlns:env=“…” xmlns:xsd=“…” xmlns:xsi=“…” env:encodingStyle=“…”> <env:Body> <e:echoService xmlns:e=“…”> <e:toEcho xsi:type=“xsd:string”>Hello </e:toEcho> </e:echoService> </env:Body> </env:Envelope>
Notes • I have omitted the namespace URIs, but you should know that they are the SOAP, XML, and XSI schemas. • I also omitted the encoding style URI, but it is the SOAP encoding schema. • Required by RPC convention. • I assume there is a namespace (e:) that defines all of the operation and parameter elements. • The body follows the simple rules: • One struct, named after the method. • One child element for each input parameter.
RPC Responses • These follow similar rules as requests. • We need one (and only one) struct for the remote operation. • This time, the label of the struct is not important. • This struct has one child element (edge) for each argument. • The child elements are labeled to correspond to the operational parameters. • The response may also distinguish the “return” value.
RPC Return Values • Often in RPC we need to distinguish one of the output values as the “return value”. • Legacy of C and other programming languages. • We do this by labeling the return type like this: <rpc:result>ex:myReturn</rpc:result> <ex:myReturn xsi:type=“xsd:int”>0</> • The rpc namespace is •
An RPC Response <env:Envelope xmlns:env=“…” xmlns:xsd=“…” xmlns:xsi=“…” env:encodingStyle=“…”> <env:Body> <e:echoResponse xmlns:rpc=“…” xmlns:e=“…”> <rpc:result>e:echoReturn</rpc:result> <e:echoReturn xsi:type=“xsd:string”> Hello </e:echoReturn> </e:echoResponse> </env:Body> </env:Envelope>
Going Beyond Simple Types • Our simple example just communicates in single strings. • But it is straightforward to write SOAP encodings for remote procedures that use • Single simple type arguments of other types (ints, floats, and so on). • Arrays • Data objects (structs) • Multiple arguments, both simple and compound.
Discovering the Descriptions for RPC • The RPC encoding rules are based on some big assumptions: • You know the location of the service. • You know the names of the operations. • You know the parameter names and types of each operation. • How you learn this is out of SOAP’s scope. • WSDL is one obvious way.
Relation to WSDL Bindings • Recall from last WSDL lecture that the <binding> element binds WSDL portTypes to SOAP or other message formats. • Binding to SOAP specified the following: • RPC or Document Style • HTTP for transport • SOAP encoding for the body elements
The WSDL Binding for Echo >
The body element just contains XML. Our WSDL specified RPC style encoding. So we will structure our body element to look like the WSDL method. First, the body contains an element <echo> that corresponds to the remote comnand. Using namespace ns1 to connect <echo> to its WSDL definition Then the tag contains the element <in0> which contains the payload. <soapenv:Body> <ns1:echo soapenv: <in0 xsi: Hello World </in0> </ns1:echo> </soapenv:Body> RPC Style for Body Elements
<wsdl:portType <wsdl:operation </wsdl:operation> </wsdl:portType> <soapenv:Body> <ns1:echo soapenv: <in0 xsi: Hello World </in0> </ns1:echo> </soapenv:Body> Connection of WSDL Definitions and SOAP Message for RPC <wsdl:message <wsdl:part </wsdl:message>
|
https://www.slideserve.com/lynde/soap-ii-data-encoding-powerpoint-ppt-presentation
|
CC-MAIN-2022-05
|
refinedweb
| 2,808
| 58.28
|
execlp()
Execute a file
Synopsis:
#include <process.h> int execlp( const char * file, const char * arg0, const char * arg1, … const char * argn, NULL );
Arguments:
- file
- Used to construct a pathname that identifies the new process image file. If the file argument contains a slash character, the file argument is used as the pathname for the file. Otherwise, the path prefix for this file is obtained by a search of the directories passed as the environment variable PATH.
- arg0, …, argn
- Pointers to NULL-terminated character strings. These strings constitute the argument list available to the new process image. Terminate the list terminated with a NULL pointer. The arg0 argument must point to a filename that's associated with the process.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:.
If the process image file isn't a valid executable object, the contents of the file are passed as standard input to a command interpreter conforming to the system() function. In this case, the command interpreter becomes the new process image.. If the calling process had locked any memory, the locks are released.
The new process doesn't inherit the calling process's default timer tolerance (set by a call to procmgr_timer_tolerance()).
Errors:
- E2BIG
- The argument list and the environment is larger than the system limit of ARG_MAX bytes.
- EACCES
- The calling process doesn't have permission to search a directory listed in file, or it doesn't have permission to execute file, or file's filesystem was mounted with the ST_NOEXEC flag.
- ELOOP
- Too many levels of symbolic links or prefixes.
- ENAMETOOLONG
- The length of file or an element of the PATH environment variable exceeds PATH_MAX.
- ENOENT
- One or more components of the pathname don't exist, or the file argument points to an empty string.
- ENOMEM
- There's insufficient memory available to create the new process.
- ENOTDIR
- A component of file: 2013-09-30
|
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/e/execlp.html
|
CC-MAIN-2013-48
|
refinedweb
| 326
| 56.35
|
You have a number of serious problems with backgrounds on table elements (CSS2, section 17.5.1: ). My three tests: show the following problems: 1) Backgrounds on table-column and table-column-group elements don't work. 2) Transparency on table-cell elements causes the table-row and table-row-group backgrounds to be ignored. This is because of you current inherit hackery in ua.css. I assume if the tables were created in XML, the table-row and table-row-group backgrounds wouldn't work either. 3) Backgrounds are not ignored (as they should be) on empty table-cell elements. If you want table backgrounds to work correctly, you need to paint them in the 6 layers described in the spec (table, table-column-group, table-column, table-row-group (or header or footer), table-row, table-cell) and not use the inherit stuff in ua.css.
chrisd, is this Linux specific?
It's not Linux specific. It's the same on Linux and Windows. I just reported it on Linux. Changing OS and Platform to All.
Moving to M6.
Moving to M8
ua.css, this bug, and and many other table style bugs will be easily fixed after Peter adds a new style rule (in the code) which gets applied after the html style sheet but before the css style sheets.
Fixed with latest checkin. Only works correctly in Standard Mode.
Using 6/14 Apprunner, colors display an indicated on test cases. Verifying bug fixed.
Background attribute of <tr> does not inherit to <td>. (Build 2000062020 Windows 2000) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML lang=ja> <HEAD> <STYLE TYPE="text/css"><!-- tr {background: #80ffff; color: #000000} td {background: #000000; color: #ffffff} --></STYLE> </HEAD> <BODY background=#ffffff> <table> <tr><td>a</td><td></td><td>c</td></tr> <tr><td>a</td><td>b</td><td>c</td></tr> </table> </BODY> </HTML> For HTML above, background color becomes #fffff of body. This should be color of <tr> #80ffff. >These "empty" cells are transparent, letting lower layers shine through. (CSS2 17.5.1)
I'm reopening this bug, since I think this should not be only for standard mode. Are there any pages that depend on table backgrounds not working? We don't want quirks mode to be blatant emulation of Nav4 -- page authors hate Nav4. We only want to emulate the quirks that pages depend on. Also clearing M7 TM and removing peterl from cc: list, but adding Ian.
I think this should be fixed for beta3. Assuming we decide to do it, it should be very easy to do.
One bug report == one issue is one of the golden rules of Bugzilla because it enables independent tracking and prioritization of each issue. David, could you please split this into separate bug reports, one per issue, because not all of these issues are of equal priority. For example, we don't support styles at all on columns or column groups (FUTUREd), so supporting backgrounds on them should be FUTUREd as well. But you can make your case that the other bugs should be of higher priority. Please justify to PDT user/developer impact, any blocking effect on adoption within content, etc.
virtual attinasi
See comment on bug 55264 for yet another reason why this should be fixed in quirks mode too. Regarding ekrock's comment above -- it *is* one issue. It's just that when the fix was checked in, it was for standard mode only (for no apparent reason).
Nominating for mozilla 0.9 to get on people's radar. This is a trivial fix, and I don't see any reason not to make it. We're better off avoiding quirks/standard mode differences that we don't need.
NavQuirks behavior should be kept for <tr bgcolor="x">, though, since all versions of MSIE also render it that way. (And Opera, too.) Do you want CSS2 behavior for /CSS/-applied backgrounds on <tr>?
QA contact update
nomination of mozilla0.9 conflicts w/ target milestone of future. clobbering both and nsbeta3-. Can we please try to get closure on this bug? [bug 46268] should fix this for everything except table rows (a necessary quirk).
what needs to be done on this one?! Hope to see this one fixed soon.
copy from 46268: Just a short quote from the CSS2 spec: 17.6.1 The separated borders model In this model, each cell has an individual border. The 'border-spacing' property specifies the distance between the borders of adjacent cells. *This space is filled with the background of the table element*. Rows, columns, row groups, and column groups cannot have borders (i.e., user agents must ignore the border properties for those elements). I think what IE is doing is just right, they inherit the color into the table cell. I think we should do the same. This would require from fantasai's patch only the nsTableFrame.cpp part in order to paint the cellspacing with the table backgrounds color. I have to admit that the CSS2 spec is not conflict free in this matter and as one can see by the David's posting and the answers, the W3C is not able create a clear specification over two years now. So it is hard to believe that this will change very soon. The honest interpretation of the conflict is that for the collapsed border model as default the space between cell's should be covered by table- , row- , col- etc background, while for the separated border model it deviates from the default model and only the table background is used for the space between the cells.
The WG is looking at this. I hope to have an answer for you on Monday.
We partly removed the table background quirks and now we have the regression bugs, before going any further in this direction we should carefully analyze our painting bugs because the majority of pages use still the quirk mode and switching to the less tested strict mode can create a bunch of regressions.
CSS2 Errata [] | | [2001-08-27] At the end of the section add the following paragraph: | | Note that if the table has 'border-collapse: separate', the background of | the area given by the 'border-spacing' property is always the background | of the table element. See 17.6.1"
*** Bug 113067 has been marked as a duplicate of this bug. ***
*** Bug 119442 has been marked as a duplicate of this bug. ***
*** Bug 119442 has been marked as a duplicate of this bug. ***
We could easily make the strict mode finally compliant to the spec (errata), aka not drawing the cellspacing background, by switching it to the quirks mode rendering. Oh man I love that, sorry David and Hixie if you cant share my joy.
I second a switch to Quirks rendering for Standard mode. It's almost identical to IE and Opera. It won't break pages. Right now, our rendering is incorrect per CSS2, and I think it's pointless to keep it that way. As for making our rendering standards-compliant, the CSS2 spec is too ambiguous about how one would handle, for example TR {background: url(starburst.gif) no-repeat;} IMO, Quirks is good enough for 1.0, it's easy to change, and it's better than what we have now. At the very least, we shouldn't introduce yet another incorrect rendering for page authors to handle.
Created attachment 69072 [details] [diff] [review] temporary fix
Comment on attachment 69072 [details] [diff] [review] temporary fix r=karnaze. fantasia, please run enough visual tests to convince yourself the patch is ok.
I looked at the testcase in bug 46268, all three of dbaron's table background tests, and a testcase with image backgrounds. We render incorrectly per spec, of course, but aside from the column backgrounds, we're consistent with IE5.
Comment on attachment 69072 [details] [diff] [review] temporary fix sr=attinasi (egg-shields up)
Marking nsbeta1+
a=roc+moz
fix checked in
->fantasai
fixed
This bug isn't actually fixed yet. Reopening and moving to future.
*** Bug 116212 has been marked as a duplicate of this bug. ***
*** Bug 134261 has been marked as a duplicate of this bug. ***
*** Bug 137707 has been marked as a duplicate of this bug. ***
*** Bug 137779 has been marked as a duplicate of this bug. ***
Even if you don't solve this bug for every case, could you at least be as standards compliant as IE5 and paint background colors for colgroup and col like IE5 does? I'm trying to classify data using foreground colors for rows and background colors for columns. BTW: There's a lot of discussion here about CSS2 being ambiguous. But I think this bug would be a bug for HTML4/CSS1 as well as HTML4/CSS2. I think that would make Netscape 4.79's behaviour a bug and why carry that into Mozilla 1? I don't think CSS2 is very ambiguous regarding table backgrounds.
> Even if you don't solve this bug for every case, could you at least be as > standards compliant as IE5 and paint background colors for colgroup and col > like IE5 does? Then we would be condoning and spreading IE5's incorrect behavior. IMO, IE5 is not any more standards compliant than we are here. Even if you interpreted according to the scant information in CSS1, background is applied to the element it is specified on, not on a collection of associated elements as IE5 does. > I think this bug would be a bug for HTML4/CSS1 as well as HTML4/CSS2. CSS1 does not bother to specify anything about table rendering; intra-table elements' behavior is effectively outside the scope of that specification.
It's not a CSS problem, it's an HTML4 problem. First, I am not implying that IE is a better browser overall. I appreciate the efforts of mozilla.org to supply a W3C standards-based browser and I'm just trying to help the process. >CSS1 does not bother to specify anything about table rendering; No, but HTML4 DOES specify how <col/> and <colgroup> should behave. Strictly speaking, Navigator4 and Mozilla1RC1 do not conform to HTML4 (and therefore XHTML 1.0 I think) in regards to <col/> or <colgroup>. Neither one correctly displays the sample table in the HTML4.01 spec, and there isn't a single STYLE attribute in that sample. My opinions: As I see it there are three separate issues which may all be one bug or 3 bugs: 1: Mozilla doesn't attempt to paint the background of <COL> or <COLGROUP> 2: Mozilla doesn't properly apply HTML4 attributes to <COL> or <COLGROUP> 3: Mozilla doesn't inherit HTML4 attributes (including STYLE) from <COL> or <COLGROUP> to <TH> or <TD> Items 2 and 3 are clearly addressed in the W3C HTML4.01 specification. Item 1 is clearly addressed in the W3C CSS2 specification. >IMO, IE5 is not any more standards compliant than we are here. Yes, it is in this case. IE5 attempts to do all 3 things I listed above. It correctly shows the sample table from the HTML 4.01 spec. It may not do them perfectly but IMO half a glass is better than an empty glass. >Even if you interpreted according to the scant information in CSS1, >background is applied to the element it is specified on, >not on a collection of associated elements as IE5 does. OK, so IE5 doesn't paint the <col/> background directly. It allows <td> to inherit the background properties from <col/>. Yes, this is inconsistent with CSS2. And the background property is prohibited from being inherited in HTML4.01. But I suggest that since IE5 doesn't apply the background property directly to <col/> it is reasonable to allow it to be inherited by an element that it can apply to. Therefore I think it is one reasonable implementation of HTML4/CSS1. If you disagree, so be it. But tell me how to apply a background or a foreground style to a <col>? >CSS1 does not bother to specify anything about table rendering; >intra-table elements' behavior is effectively outside the scope >of that specification. Correct. It is established first in HTML 4.01 and refined in CSS2, and Mozilla is out of compliance with both of them in regards to <col/>. IE seems to at least comply with HTML4.01 in this instance. Good Luck!
*** Bug 140084 has been marked as a duplicate of this bug. ***
Ok, I discovered bug 915 which covers issues #2 and #3 for HTML attributs. Sorry about venting that here. Issue #1 remains part of this bug. > Item 1 is clearly addressed in the W3C CSS2 specification. It is not clearly adressed in the W3C CSS2 specification, and that is exactly the reason this bug is Futured--until it /is/ clearly addressed.
Nice, clear description of the problems. The collapsed border table model is much simpler, is the default behavior of many browsers, and is (I guess) more commonly used than the separated borders model. Therefore it seems to me that fixing the column backgrounds would be simple enough and important enough to do for the collapsed borders model regardless of the status of the separated borders model. The background-color property doesn't have any of the the patterning issues that you have illustrated in your description. Therefore it seems that implementing the background-color property for both table models would be simple enough and important enough to do regardless of the status of the other background properties. Regarding spanning cells, I think that if cell R1C2 spans across R2C2 then cell R2C2 does not exist. The row background for R2 should be transparent for where R2C2 would be. The row or column background for R1C2 would fill the entire R1C2 cell. BTW: I don't think I would often use backgrounds on both columns and rows in the same table. I think most people would be satisfied if column backgrounds worked as long as there were no row backgrounds to conflict with. You said: "In describing the effects of the background properties, however, the spec is very ambiguous, making it impossible to write a defensibly correct implementation." No wonder moz 1.0 has taken so long. ;) Just kidding. I would say: "In describing the effects of the background properties, however, the spec is somewhat ambiguous, making it possible to write multiple defensibly correct implementations." In short, something is better than nothing. Again, Thank You!
The separated borders model is the default in all browsers I know of, and I don't know of any "real" pages that use the collapsed borders model. There is still a major ambiguity with 'background-color' -- whether or not to break at the cell spacing.
charles allen wrote: > In short, something is better than nothing. from a conversation I had with Chris Karnaze - :. : If, however, we apply the background and not the color, we might wind up with navy text on a forest green background or something like that. In my mind, we should either be compatible with other browsers or undisputably correct in our deviations. Anything we change now would be neither. > I would say: "In describing the effects Yes, I probably should have written it that way. dbaron wrote: > There is still a major ambiguity with 'background-color' -- whether or not to > break at the cell spacing. I thought the Errata cleared that up?
quote: :. Not always true. I have a table where I'm assigning background colors to columns, and foreground colors to rows. This is clearly legal in CSS2. In IE, both get assigned and I have no problem. In Mozilla, only the foreground colors are assigned. If I did not carefully choose my table background color, I would have contrast problems in Mozilla, but not IE. Why not draw background colors for columns the same way quirks mode draws them for rows? This would be extending quirks mode to columns rather than inventing a new method. AFIK this is also the same way IE draws column background colors so you are still not inventing a new method. This would make you more compatible with other browsers, AND more compatible with CSS2 at the same time! A win/win if you ask me. BTW, you are correct that most browsers use separate border model. I didn't believe you, so I proved it to myself. :) However CSS2 specifies the collapsed borders model should be the default. Therefore I would expect it to be default in a CSS2 spec browser. Again, the collapsed borders model is much simpler and I think would be easier to fix. You should fix it and maybe make it the default. Then I would care less about the broken separated borders model.
> However CSS2 specifies the collapsed borders model should be the default. See
*** Bug 149008 has been marked as a duplicate of this bug. ***
*** Bug 172824 has been marked as a duplicate of this bug. ***
*** Bug 175075 has been marked as a duplicate of this bug. ***
Test suite: It's a work in progress; only part A has been written.
Created attachment 105030 [details] [diff] [review] preliminary work So you can see where I'm going with this. Mozilla with the patch passes Part A of the test suite. I still have to run it through as yet unwritten tests for exact image position wrt borders, empty cells, etc. Also, the code needs polish. Of course, I'm not submitting for review yet, but if anyone notices problems with the overall algorithm, it would help to know sooner rather than later. Many thanks to bz for answering silly questions to which any amateur programmer would know the answers. He's saved me hours of frustration.
*** Bug 179086 has been marked as a duplicate of this bug. ***
*** Bug 180404 has been marked as a duplicate of this bug. ***
Created attachment 106551 [details] [diff] [review] patch Not up for checkin just yet. Got some conceptual issues with borders. But the code is more-or-less in its final form.
My first impression of the patch is somehow ambivalent. Probably I am only dumb. @@ -140,8 +140,9 @@ const nsRect& aBorderArea, const nsStyleBorder& aBorder, const nsStylePadding& aPadding, - nscoord aDX, - nscoord aDY, + nscoord aDX = 0, + nscoord aDY = 0, + const nsRect* aClipRect = nsnull, PRBool aUsePrintSettings=PR_FALSE); why we need this aDX = 0 , aDY = 0 ? +class ColumnBGData; + +struct ColGroupBGData { .... do we really need these classes, I would love to see them going away. A malloc inside a paint routine seems to me like a potential performance hit. If we really need those can't we compute them during the reflow? If we can compute them during reflow, why dont we change the existing frame structures. ColumnBGData::~ColumnBGData() +{ + ColGroupBGData* lastColGroup = nsnull; + for (PRInt32 i = 0; i < mNumCols; i++) { + if (mCols[i].mColGroup != lastColGroup) { + lastColGroup = mCols[i].mColGroup; + delete mCols[i].mColGroup; + } + mCols[i].mColGroup = nsnull; + } + delete [] mCols; +} isnt + delete [] mCols; enough? if (bgData.Ok() && bgData.ColGroup(colIndex)->Ok()) { + nsCSSRendering::PaintBackgroundWithSC(aPresContext, aRenderingContext, + bgData.ColGroup(colIndex)->mFrame, aDirtyRect, + bgData.ColGroup(colIndex)->mRect, *bgData.ColGroup(colIndex)->mBackground, + zeroBorder, zeroPadding, 0, 0, &cellRect, PR_FALSE); + } + //Paint row group background + if (rgBG) { + nsCSSRendering::PaintBackgroundWithSC(aPresContext, aRenderingContext, + this, aDirtyRect, rgRect, *rgBG, zeroBorder, zeroPadding, 0, 0, + &cellRect, PR_FALSE); + } + //Paint column background + if (bgData.Ok() && bgData.Col(colIndex)->Ok()) { + nsCSSRendering::PaintBackgroundWithSC(aPresContext, aRenderingContext, + bgData.Col(colIndex)->mFrame, aDirtyRect, bgData.Col(colIndex)->mRect, + *bgData.Col(colIndex)->mBackground, zeroBorder, zeroPadding, 0, 0, + &cellRect, PR_FALSE); + } why do we paint first the colgroup then the row group then the col, I thought the spec requires colgroup col rowgroup + nscoord cellSpacingX = table->GetCellSpacingX(); - x = borderPadding.left; + x = borderPadding.left + cellSpacingX; y = borderPadding.top; availSize.width = aAvailWidth; if (NS_UNCONSTRAINEDSIZE != availSize.width) { - availSize.width -= borderPadding.left + borderPadding.right; + availSize.width -= borderPadding.left + borderPadding.right + (2 * cellSpacingX); This is pure horror for me, this must be wrong. The patch alters the nsTableReflowState. Before we reflow all the children. Probably there should be some comments on those critical places why it does not affect reflow.
> My first impression of the patch is somehow ambivalent. Probably I am only > dumb. Probably you're not asking the right questions. What are you ambivalent toward? What bothers you about it? What would you have prefered? > why we need this aDX = 0 , aDY = 0 ? The arguments don't seem to be used anywhere in the function, and IIRC every function call I've run across (I had to run a search modify all calls passing in the aUsePrintSettings arg) passes in zero. So, I think we should eliminate the arguments. I'm defaulting them to zero for now so most calls won't have to pass those zeros in, and I'll file a bug on taking them out later. > do we really need these classes, I would love to see them going away. A malloc > inside a paint routine seems to me like a potential performance hit. I originally put them in to avoid a performance hit. This is also why all the painting is done in nsTableRowGroupFrame::Paint rather than in the frames' respective classes; there is no need to iterate over all the cells in the table once for the column groups, once more for the columns, another time for the row groups, yet another time for the rows, and once again for the cells themselves. Alternatively the cells could paint everything by calling into parents, but I don't think this is any better than what I'm doing right now. (That method would involve more complicated mRect adjustments.) The paint function is iterating over all the cells in the row group, which in most cases means all of the cells in the table. Instead of recalculating all the column style and frame info for every cell, I'm calculating everything once and storing the info in an array. The storage doesn't cost very much in terms of memory because its created and destroyed in one function call, existing for a very short amount of time. However, it's possible that the time cost in allocating and deallocating the memory might outweigh the savings from storing the calculated values. I don't know what the performance cost is for that. If you think that it's better to call the table frame's GetColFrame and get the background, mRect, and the colgroup frame (and it's background and mRect) for each cell, I can change it. > If we really need those can't we compute them during the reflow? We could, but they don't seem important enough to take up space when we're not painting. > isnt + delete [] mCols; enough? No, because each ColBGData holds a pointer to its parent ColGroupBGData. Suppose I have a colgroup with two columns. If I delete the first ColBGData, it will delete its ColGroupBGData. When I delete the second ColBGData, it will call delete on its pointer to that same ColGroupBGData. Except it's already been deleted, and the space might have been allocated to something else. > why do we paint first the colgroup then the row group then the col, I thought > the spec requires colgroup col rowgroup Yes, you're right. I'll fix that, along with the MOZ_COUNT_CTOR and GetStyleData stuff you mentioned on IRC. > This is pure horror for me, this must be wrong. The patch alters the > nsTableReflowState. Before we reflow all the children. nsTableReflowState is already altered before the children are reflowed by subtracting the border... > Probably there should be some comments on those critical places why it does not > affect reflow. Actually, it does affect reflow. But the end result should be the same as before. CellspacingX is subtracted out of the width, but it's also no longer added to x before reflowing the first cell. I will run the layout regression tests, and that should point out any major miscalculation errors. btw, if you could answer the few questions I've commented in, that would be helpful.
*** Bug 190455 has been marked as a duplicate of this bug. ***
*** Bug 190942 has been marked as a duplicate of this bug. ***
*** Bug 196889 has been marked as a duplicate of this bug. ***
Removing mozilla0.9.9+, mozilla1.0, and nsbeta+ keywords as they are all obsolete by many moons.
Please never again remove keywords you don't know about!
If the keywords do not have the meaning that the "Keywords" page has, then perhaps someone needs to update that page eh???
Could you possibly explain for the other 30-some people who are watching this bug, what does mozilla0.9.9+ mean if it does not mean, "drivers@mozilla.org would like to see these bugs checked in during the [0.9.9] milestone freeze or branch period"? And, what is the meaning of an nsbeta1+ keyword placed there many versions ago? Thank you.
There was a "temporary fix" for this bug that was checked in a while ago to make us, if not correct, at least compatible with the other incorrect rendering engines out there. I believe the keywords apply to that. This bug was then marked FIXED, but I reopened it because it isn't really fixed.
roc, views are seriously broken on tables. I did the best I could, given that they don't paint properly. Relevant testcases are: That's not a background issue, though; content is also missing.
Created attachment 125788 [details] [diff] [review] patch
Created attachment 125789 [details] nsTableUnderlay.h
Created attachment 125790 [details] nsTableUnderlay.cpp ok, Bernd. Fire away! (There are a few things I wasn't sure of; these are marked with XXX.)
Created attachment 125925 [details] nsTableUnderlay.h (Now with More Comments)
Created attachment 125928 [details] nsTableUnderlay.cpp (tweaked)
Ok, so. Explanations: > what will the patch do and what not The patch will fix every standards-mode table background issue I know about except fixed backgrounds on columns/colgroups. Those are broken... Actually, now that I think about it, I might be able to make that work, too. I'll give it a try. The backgrounds are painting--just not properly. So, fixed issues include: - positioning and tiling of background images - painting area (no cellspacing) - layering - views unwittingly giving cells wrong paint flags (bug 191567) > which frames will change their size, Rows, row groups, columns, and colgroups will no longer include outer cellspacing in their dimensions. > why did you implemented it the way you have choosen. I implemented it this way because it seemed more efficient to cache calculated data and make one pass through the table than to have each cell calculate its own set of background data for its row/rowgroup/column/colgroup. Implementing it as a separate class makes it a) easier to understand b) easy to deal with views c) easy to reduce background painting to a single pass once the responsibility for painting borders is moved to the cells > what tests has the already patch seen The patch passes all the tests at with one problem: As aforementioned, views don't paint tables properly so some cells are incompletely painted in the fixed background and opacity tests. I also ran them in quirks mode; I haven't broken anything. Although, I could also fix the way <table> backgrounds leak in quirks border-collapse... > risks Risk of pages breaking is pretty low; the tests I ran are quite comprehensive. Risk of crashes/leaks/other-stupid-mistakes is.. pretty high. I'm a very inexperienced programmer; I wouldn't even rank myself as high as amateur. In addition, I build on Linux, but that's all I use it for, so the patched build hasn't seen extensive use. I'm going to give Bugzilla a break and put up the code at I'll attach the final versions for archiving when we're done. dbaron -- you might want to check, at some point, to make sure my interpretation is ok. After this goes in would probably be easiest, since then you can grab a build and look at the test cases.
> Actually, now that I think about it, I might be able to make [fixed bg on cols] > work, too. Looks like I can do that without much trouble. However, it means I have to cheat a little; I'd have to ignore the bounds of the dirtyRect and paint the whole column/columngroup. Do you want me to do this or should I add col, colgroup { background-attachment: scroll !important; } to html.css instead?
fixed background leak in quirks testcase:
After reading the patch a first time ( 3hours) I believe the code will do the job, however I am still concerned about the performance hit, why do we compute for the whole table and not for the damage area, couldnt we do something similar (call) as below (oh, I thought I converted that into a function a long time ago). and even reuse the damageArea afterwards for BC painting. I will run the paint code after my vacation...
> why do we compute for the whole table and not for the damage area, couldnt we... Added coordinate checks to the loop. If you want, I can make the intersect check in PaintCell into a separate inline function and call the rest of the paint code conditionally based on its return value.
The patch doesnt compile. While the GetView deCOM is easy, GetContinuousLeftBCBorderWidth is used in nsTableUnderlay.cpp but not defined in nsTableFrame.h I think the patch needs to be updated to the tip, sorry for beeing so lame that the patch started to bitrot.
> The patch doesnt compile. Not surprising. It's based on the May 28th source. > I think the patch needs to be updated to the tip I'm trying. :) Mozilla's compiling right now. If I'm lucky, I'll get a working Windows binary and I can start applying the patch. If not.. I guess I'll try to imitate the Windows-Linux build environment I had on my old computer. Pulling the source is working now that I've reinstalled cygwin, and given that, I should be able to get it to work. > sorry for being so lame that the patch started to bitrot. It's ok. I just hope I'll be able to finish this before I leave this weekend...
Created attachment 129063 [details] [diff] [review] Patch (untested)
Created attachment 129064 [details] nsTableUnderlay.h (untested)
Created attachment 129065 [details] nsTableUnderlay.cpp (untested)
It compiles under mingw. More than that, I cannot say; I wasn't able to get a working binary to test with under either Windows or Linux. If you can send me a drop-in replacement of Gecko that I can use with a nightly, I'll test it...
*** Bug 214877 has been marked as a duplicate of this bug. ***
Apologies for duplicating this bug, I hadn't found it from a few searches. However, could someone say what is happening or going to happen? I got a bit lost when people started using the code ;) My basic question is: Will front end web developers be able to style with col? Thanks :) I do try and persuade everyone to use Moz, which is becoming easier when they realise they don't have to get all those ad-programs installed whilst browsing.
> Will front end web developers be able to style with col? Yes, but see This bug will fix background rendering on columns in Standards layout mode.
> This bug will fix background rendering on columns in Standards layout mode. That's great, I now have a related question about horizontal alignment, that you might refer me to another bug for.. Moz seems to ignore horizontal alignment set by the width attribute of col, and any CSS alignment class set on the col. E.g: The CSS section refered to () doesn't cover aligment - fair enough. But it doesn't give any control available for controling columns without using classes set on each cell. In the example above, the names are left aligned, and points are supposed to be right aligned. The alignment attribute of col is in the XHTML DTD (), has this been intentionally left out, or would this be a separate bug? Cheers, I hope I'm being useful, I've been using (& relying on) Moz since version 1, but I'm new to the world of bugzilla. :) -Alastair
Comment 98 is about bug 915, not this bug. It's generally harmful to add unrelated comments to bugs, especially long comments, since they make the real issues in the bug harder to find.
Turning this over to Bernd for review/checkin/etc. The two new files should be MPLed, of course. And please look over comment 85.
Comment on attachment 129063 [details] [diff] [review] Patch (untested) *pokes Bernd* Bernd, will _you_ set the new target milestone? Obviously my guesses are way off.
Created
I've not digested all the changes yet, so a lot of these comments are non-substantive. I've also read only part of the patch. So take these comments with a boulder of salt... Please use more context and use the -p option to diff (-p -u8 is a good way to diff....). That makes patches a lot more readable. >Index: mozilla/content/shared/src/nsStyleStruct.cpp >+#ifdef DEBUG >+ if (mBorderStyle[NS_SIDE_TOP] & BORDER_COLOR_SPECIAL) { >+ NS_WARNING("Clearing special border because BORDER_COLOR_DEFINED is not set"); >+ } >+#endif Are there good reasons not to make that an assertion? Are there ever cases where it could happen that are technically correct? Same for the other sides. >Index: mozilla/layout/html/style/src/nsCSSRendering.h >- PRBool aUsePrintSettings=PR_FALSE); >+ PRBool aUsePrintSettings=PR_FALSE, Toss in spaces around the '=' sign, please? >Index: mozilla/layout/html/document/src/quirk.css >+/* make sure backgrounds are inherited in tables -- see bug 4510*/ >+td, th, tr { >+ background: inherit; >+} Do we really want this quirk? What purpose does it serve? In particular, what would "tr" inherit from (that only comes into play on quirks-mode pages that are setting backgrounds on <tbody> elements; I suspect we want to follow IE there, and I doubt that IE has that quirk, but I could be wrong (no way I can test)). >Index: mozilla/layout/html/table/src/nsTableFrame.h >+ /** Get left continuous border width >+ */ >+ nscoord GetContinuousLeftBCBorderWidth(float aPixelsToTwips, >+ PRBool aGetInner) const; >+ What does that mean, exactly? A clearer explanation is in order here. That is, what is a "left continuous border"? What does aGetInner do? >- unsigned : 19; // unused >+ unsigned mLeftContBCBorder:8; >+ unsigned : 11; // unused I think I'd be happier if this struct were using PRUint32, so you knew you actually _did_ have 32 bits to work with, but that can be a separate patch.... >Index: mozilla/layout/html/table/src/nsTableFrame.cpp >- x = borderPadding.left; >+ x = borderPadding.left + cellSpacingX; > y = borderPadding.top; Why the asymmetry here? Comment it, if there is a good reason. >- availSize.width -= borderPadding.left + borderPadding.right; >+ availSize.width -= borderPadding.left + borderPadding.right >+ + (2 * cellSpacingX); Comment why you have to subtract off the cellspacing? Same for the Y direction? Or perhaps comment where availSize is declared and say what size it actually reflects?
> the patch fails when a rowspan in the border collapsed > table is scrolled into the visible area. Made some changes. See if that works. > the numCols are used later in an assertion Removed change. I think the compiler was complaining that the variable wasn't used -- the assertion doesn't appear in optimized builds, I assume. So therefore, the variable and function call aren't, either. Should I put an #ifdef DEBUG on it? > and the Makefile.in part of the patch is missing Ok, fixed. > -p -u8 is a good way to diff It shall be done. *updates diff4510 script to do that* > Are there good reasons not to make that an assertion? Are > there ever cases where it could happen that are technically > correct? I can't think of any. I guess you want me to switch it over? > Toss in spaces around the '=' sign, please? Done. > Do we really want this quirk? What purpose does it serve? I've wondered about that myself. I think it's only useful for pages that use "background: transparent" on cells to make the table background shine through. > In particular, what would "tr" inherit from... table row group, of course. > I doubt that IE has that quirk, but I could be wrong IE does indeed have that quirk. (I think we're to be the only layout engine that actually layers table backgrounds--although I wouldn't be too surprised if Tasman's team did something like that.) > >+ /** Get left continuous border width > What does that mean, exactly? A clearer explanation is in > order here. Yes, you're quite right about that. I need to spec out the interaction of table backgrounds with table borders. > That is, what is a "left continuous border"? What does aGetInner do? Commented in. Implementation moved inline into nsTableFrame.h > I think I'd be happier if this struct were using PRUint32 Changed. > Why the asymmetry here? Comment it, if there is a good reason. What asymmetry? Between x and y? The cellspacing gets added to the y coordinate during reflow; it's a running count and cellspacing gets added before the child height in the loops. Comment added, anyway. > Comment why you have to subtract off the cellspacing? availSize.width reflects the width available for the children. In tables this means subracting out the cellspacing on the sides as well as the border. (Before this change, cellspacing in the X direction was treated as a shift in the table cell position within the row.) (Updated patch is at ; No guarantee that it'll compile.)
> No guarantee that it'll compile. isnt that an euphimism for just the opposite. :-) the patch at does not compile as a) #define GET_TWIPS_TO_PIXELS(presContext,var) \ float var; \ (presContext)->GetScaledPixelsToTwips(&var); \ + var = 1.0f / var; the additional line is not nessary. (while you are on it, please remove the unessary blank lines from nsTableFrame.h) In content/shared the assertion requires an argument what to test for. I would rewrite that section with out the debug defines and loop over the four sides. > for (PRUint8 Side = NS_SIDE_TOP; Side <= NS_SIDE_LEFT; Side++) { > if (!(mBorderStyle[Side] & BORDER_COLOR_DEFINED)) { > NS_ASSERTION(!(mBorderStyle[Side] & BORDER_COLOR_SPECIAL), > "Clearing special border because BORDER_COLOR_DEFINED is not set"); > SetBorderToForeground(Side); > } While this are peanuts, the patch draws into the cellspacing in separate mode when the table is not completely inside the window (see screenshot)
Created attachment 129900 [details] screenshot of painting inside the cellspacingCreated attachment 129900 [details] screenshot of painting inside the cellspacing
> painting inside the cellspacing I've never seen /that/ before. Is it a regression from the previous patch? > unnecessary blank lines Stupid text editor. I'll fix that, don't worry. :)
this is not a regression it has been like this with attachment 129063 [details] [diff] [review], the trick is the small window
*** Bug 218541 has been marked as a duplicate of this bug. ***
Resummarizing to what I think this bug currently covers. If I'm wrong, please resummarize again.
*** Bug 219404 has been marked as a duplicate of this bug. ***
We're fixing a bit more than that here. Things covered include: - paint table column/colgroup backgrounds - layer backgrounds properly - set up image positioning & repeating bounds correctly - cleaning up <table> background boundaries in Quirks (might as well) I really ought to finish this off. If I don't post a (hopefully finalized) patch by Monday, someone should send me a nice flame or something for being so annoyingly slow... ~_~
Patch updated. And it does compile. However, I don't know if it /works/ since I still get linking errors...
*** Bug 221020 has been marked as a duplicate of this bug. ***
Re comment 104: > I can't think of any. I guess you want me to switch it over? Yes, please. > IE does indeed have that quirk OK. Then it's ok to keep it as a quirk, I guess... If you have an updated patch and are having trouble getting it to link, feel free to mail it to me and I'll look..
I've put the files up at I'll attach them for flagging once Bernd gives his ok, but attaching three files every time I adjust whitespace would probably strain the CC list overmuch...
I cant apply the patch: patch: **** malformed patch at line 790: +nsTableRowGroupFrame::GetContinuousBCB orderWidth(float aPixelsToTwips, could you please create a patch with only diff -u, do you manually edit the patch files ?
I'm patching with diff -p -u8. No, I didn't edit the patch by hand. I just reran cvs diff and uploaded the result. I checked it, too, by running it in reverse and then normally. Is it still causing problems?
*** Bug 224283 has been marked as a duplicate of this bug. ***
patch updated; fixed nsStyleStruct assertions. The border-collapse assertions still go off when I build without the patch, so I don't think I'm causing the problem. Also, it's in a function I don't call..
I tested the patch at . It looks good to me. And it is so much better what mozilla does currently. Thanks a lot. Attach it to the bug. You should ask bz, roc and dbaron as the module owner to look carefully at this. I think, I looked pretty hostile at the patch but this can't be a substitute for a review.
Created attachment 135353 [details] [diff] [review] patch
Created attachment 135354 [details] nsTableUnderlay.h
Created attachment 135355 [details] nsTableUnderlay.cpp
*** Bug 225780 has been marked as a duplicate of this bug. ***
So... is this going to get reviewed in time for 1.6beta or should I set the target to January (1.7alpha)?
fantasai, I definitely won't get to it in time for beta (in the next 40 hours, basically). I'm sorry I dropped the ball on this so badly. :( On the other hand, I feel that this is alpha material in any case. And I will make sure that I've done a review well before 1.7a opens so you can land as soon as it does...
> I'm sorry I dropped the ball on this so badly. :( Eh, don't worry too much about it. I doubt dbaron or roc would've found time, either. And I've taken out several months myself, what with not being able to build for so long... > On the other hand, I feel that this is alpha material in any case. Yeah, I'd prefer to have it checked in during an alpha cycle, too. :)
Comment on attachment 135354 [details] nsTableUnderlay.h Why "nsTableUnderlay"? Wouldn't "nsTableBackgroundPainter" be a better reflection of what's going on? You need a license comment here. >#define BC_BORDER_TOP_HALF_COORD(p2t,px) NSToCoordRound((px - px / 2) * p2t ) You need parens around "px" in that expression, both places (consider what happens if I pass "2-1" as "px". Same for all the other macros here. > * User is expected to loop through elements to be > * painted <em>in layout order</em> (row groups must > * be ordered properly), using Load/Unload functions Perhaps you should clearly document which functions need to be called in which order to paint a cell or whatever objects this paints? An example would probably not hurt either.... > * TableBackgroundPainter will handle position > * translations Meaning into the child's coordinate space? If so, I think it would be better to say that clearly. > TableBackgroundPainter(nsIPresContext* aPresContext, > nsIRenderingContext& aRenderingContext, Why isn't that a pointer? References to interfaces like that make me queasy. > * @param aDeflate - adjustment for frame's rect That's not helpful. Explain why one would want to pass this and what it does. > * @param aSkipSelf - pass this cell; i.e. paint only underlying layers Why would one use this? I would rather you avoided params with default values; people will have a tendency to assume the default value is the correct one. It's better to make them explicit so they have to think about how they are calling the function. > struct TableBackgroundData { > /** Data is valid */ > PRBool Ok() const { return (PRBool)mBackground; } Maybe call this IsOK() ? > /** Destructor; must call Clear first, however */ Why? If this class always has a frame, it can get the prescontext off the frame. So there is no need to pass a prescontext to it, and hence no need for Clear() that I see. Unless mFrame can be null? > /** Calculate and set data values to represent aFrame */ > void Set(nsIPresContext* aPresContext, > nsIRenderingContext& aRenderingContext, > nsIFrame* aFrame); Does aFrame have to be non-null? Is aPresContext really needed here? Could you use a pointer to the nsIRenderingContext instead? > nsIRenderingContext& mRenderingContext; And here.
Comment on attachment 135354 [details] nsTableUnderlay.h > PRBool Ok() const { return (PRBool)mBackground; } Also, that's not cool in general -- casting a pointer to PRBool does not do what you really want it to. Use "return !!mBackground;" instead, I would say.
> PRBool Ok() const { return (PRBool)mBackground; } is uncool as bz said, because it generated random non-zero results on 32-bit systems, and where pointers may be 64 bits but int is 32, it may even generate 0 (PR_FALSE) for a non-null pointer. The !!p trick looks odd enough to people that I've always gone for an explicit null comparison, e.g.: > PRBool Ok() const { return mBackground != nsnull; } Note no need for (PRBool) casting. /be
Comment on attachment 135355 [details] nsTableUnderlay.cpp Need a license. >TableBackgroundPainter::TableBackgroundData::Clear(nsIPresContext* aPresContext) Like I said, just get the prescontext off mFrame and be done with it. > mBorder = nsnull; > mBackground = nsnull; > mFrame = nsnull; > mBorderIsSynth = PR_FALSE; Do you really need to reset all these? > //XXXfr should aRenderingContext be removed from IVFP's param list? Probably. File a bug on that, cc me and roc and dbaron. We probably want to deCOMtaminate that method at the same time too. >inline PRBool >TableBackgroundPainter::TableBackgroundData::ShouldSetBCBorder() Any reason not to just inline this into the header? >TableBackgroundPainter::TableBackgroundData::SetBCBorder(nsMargin& aBorder, > NS_PRECONDITION(aPainter, "null frame"); Change the text to make sense? > nsStyleBorder* styleBorder = new (aPainter->mPresContext) nsStyleBorder; > if (!styleBorder) return NS_ERROR_OUT_OF_MEMORY; > *styleBorder = aPainter->mZeroBorder; Wouldn't nsStyleBorder* styleBorder = new (aPainter->mPresContext) nsStyleBorder(aPainter->mZeroBorder); if (!styleBorder) return NS_ERROR_OUT_OF_MEMORY; be better? >TableBackgroundPainter::TableBackgroundPainter(nsIPresContext* aPresContext, This could use a constructor counter. >TableBackgroundPainter::Init(nsTableFrame* aTableFrame, > NS_ASSERTION(colGroupList.FirstChild(), "table should have at least one colgroup"); Are you sure? What if I'm in XHTML and I just have an <html:table> with nothing inside? Will this assert trigger? What will mNumCols be? Perhaps it would be better to bail early or skip stuff if mNumCols is 0, then assert if mNumCols > 0 and there is no first child? > for (nsTableColGroupFrame* cgFrame = (nsTableColGroupFrame*)colGroupList.FirstChild(); > cgFrame; cgFrame = (nsTableColGroupFrame*)cgFrame->GetNextSibling()) { It's not immediately clear to me what this code is attempting to do. A comment would help a lot here. I assume that you're storing the colgroup info for each col or something? In any case, comments about you're doing this here (and comments in the header when you declare these data structs explaining what they are used for) would be most helpful. > nsresult rv = cgData->SetBCBorder(border, this); > if (NS_FAILED(rv)) return rv; Doesn't that return leak cgData? > mCols[colIndex].mCol.mRect.MoveBy(cgData->mRect.x, cgData->mRect.y); So mCols[colIndex].mCol.mRect is the rect of the col in the coord system of the table? If so, why? Also, this needs to be documented somewhere (eg the header, either where you declare the ColData type or where you declare mCols or whatever you deem appropriate). In fact, it would be good to document the coord systems for all the various members that end up having an nsRect as part of them. > mCols[colIndex].mColGroup = cgData; So the idea is that cgData is allocated in Init() and deallocated in the destructor of this class? That is, the mCols elements have pointers to it, but do not own it? If so, document that clearly here and perhaps where mCols is declared.... > nsresult rv = mCols[colIndex].mCol.SetBCBorder(border, this); > if (NS_FAILED(rv)) return rv; Document that this does NOT leak cgData, since there is now a pointer to it in mCols[colIndex]. I have to admit that I'm not sure quite what's going on with the BC left border (in particular, why you reset to lastLeftBorder every time in the inner loop. Please document that. >TableBackgroundPainter::PaintTable(nsTableFrame* aTableFrame, More BC magic... why exactly do we only sometimes need to set the bcborder? The ShouldSetBCBorder impl should probably document why it uses the criterion it uses. >TableBackgroundPainter::TranslateColumns(nscoord aX, > nscoord aY) This method needs some documentation in the header. > if (eOrigin_TableRowGroup != mOrigin) { It helps to comment which coord space you are transforming to before doing the coord transformations... you're transforming into the row group coord space here, right? > mRenderingContext.Translate(mRowGroup.mRect.x, mRowGroup.mRect.y); > mDirtyRect.MoveBy(-mRowGroup.mRect.x, -mRowGroup.mRect.y); > if (mCols) { > TranslateColumns(-mRowGroup.mRect.x, -mRowGroup.mRect.y); When you translate back in UnloadRowGroup(), you use mRowGroup.mFrame->GetRect() as the rect.. are you guaranteed that the x,y coords of that are the same as the x,y coords of mRowGroup.mRect at this point? If so, assert that here, please. >TableBackgroundPainter::LoadRow(nsTableRowFrame* aFrame) > //else: No translation necessary since we're using row group's coord system Erk. First I hear of that, and I read the header. That needs to be VERY clearly documented somewhere..... I'm not very knowledgeable about BC code, so I can't tell whether what you're doing here with BC is right... if bernd is OK with it, I'm OK with it. >TableBackgroundPainter::PaintCell(nsTableCellFrame* aCell, > nsRect cellRect; > cellRect = aCell->GetRect(); Why two lines? Just put that on one line, please. > //Paint cell background in border-collapse unless told not to. Why only in border-collapse? Please document that somewhere.... I'm wondering about the Pass* functions.... if I decide to call PassRow(), I need to make sure I don't LoadRow() that row, right? Because it looks like if I load a row and then call PassRow() on it, the row's background will be painted. Could we add some debug-only code that asserts that LoadRow() is not called while another row is already loaded, and similarly for row groups, etc?
By the way, I just realized that you have some places where you call Clear() when you don't want to call the destructor. So it's OK to keep Clear(), but the destructor can call it, which would allow callers who plan to just destroy to not bother with having to call Clear().
Comment on attachment 135354 [details] nsTableUnderlay.h One more thing. The various members here need documenting.... It's not clear what role mOrigin plays, what mCols is used for, what mRow and mRowGroup are used for, what mZeroBorder and mZeroPadding are supposed to do, etc.
Comment on attachment 135353 [details] [diff] [review] patch >Index: mozilla/layout/html/table/src/nsTableFrame.h >+ /**"? This would benefit greatly from an example, I think. >+ PRUint32 mLeftContBCBorder:8; Comment that this, like other BC code, rather arbitrarily limits the widths of BC borders? That said, why is this 8 bits? I thought BC borders were currently limited to 6 bits? I've gotten up to the beginning of nsTableFrame::Paint() for now; more later.
> Why isn't that a pointer? References to interfaces like that make me queasy. ... > Could you use a pointer to the nsIRenderingContext instead? Because everything else refers to it that way and I'm copying them. Would you rather have a pointer? > Why? If this class always has a frame, it can get the prescontext off the frame. I didn't think of that.. If it's in the frame, then why is it being passed around the paint functions? > Unless mFrame can be null? hm.. Don't think it would have a generated borderstyle if it did. > Any reason not to just inline this into the header? I wanted to keep all the implementation logic in one file. (It's not just returning a value; it's making a judgement.) >>+ /**"? The left table border (nsTABLEFrame::GetContinuousLEFTBCBorder)--which is also the leftmost column's left border, which is also the leftmost colgroup's left border. It is taking the width of the "table + colgroup + col collapse" -- i.e. the border's width before it collapses with the rowgroups/rows/cells. Continuous because the table/colgroup/col elements necessarily extend across the entire length of the table from top to bottom. (Rowgroup/row/cell borders do not: there can be multiple rowgroup/row/cell borders along this edge of the table.) > I thought BC borders were currently limited to 6 bits? Thanks for all the comments, bz. I'll deal with the rest of them as I fix the problems they point out. :)
> Because everything else refers to it that way and I'm copying them. In that case, I guess keep it as-is (if you're getting passed nsIRenderingContext& yourself in the paint code; I've not looked at that yet). > The left table border (nsTABLEFrame::GetContinuousLEFTBCBorder Put all this in the relevant comments in the patch, please. ;)
I almost forgot... The reason the prescontext is passed around and all that is that there didn't use to be an accessor for it off the frame. But there is one now, and we're slowly moving to eliminating prescontexts from all sorts of function signatures.
> Why "nsTableUnderlay"? Wouldn't "nsTableBackgroundPainter" be a better > reflection of what's going on? *thinks back* I put that there because the header includes border-related things as well. Suppose you explain why bug 149378 is blocked by this. Should I change it to nsTablePainter? (In terms of things in the distant-and-likely-nonexistant-future, I've also contemplated a redesign of BC handling that would find the caching features of the painter most useful. ^^)
> Suppose you explain why bug 149378 is blocked by this. Because the measurements there should be redone once this patch goes in, since it will significantly change the control flow of table painting. > Should I change it to nsTablePainter? That may be a better description of what it does, yes.
Comment on attachment 135353 [details] [diff] [review] patch >Index: mozilla/layout/html/table/src/nsTableFrame.cpp > nsTableFrame::Paint(nsIPresContext* aPresContext, >+ if (eCompatibility_NavQuirks != mode) { You need a comment right before this check explaining why the check is made (that is, what the behavior difference should be between the modes, and why this behavior difference is desired). It looks like we're just doing our old painting in quirks mode and CSS2 painting in standards mode; is there a good reason for this quirk? >+ rv = painter.PaintTable(this, (nsTableRowGroupFrame*)rowGroups.ElementAt(0), >+ (nsTableRowGroupFrame*)rowGroups.ElementAt(numRowGroups-1)); What if numRowGroups is 0? Eg. an XHTML <table> with no <tbody> and no rows... > + if (rg->GetView()) { GetView() is slow. This is why we have HasView(). > + if (row->GetView()) { Same. >+ else if (aDirtyRect.YMost() > rgRect.y + rect.y) { Why that test instead of an Intersects() test (with an appropriately translated rect)? Won't this trigger painting of rows/cells that come completely before the dirty rect? Also, why ">" instead of ">="? >+ rv = painter.PaintCell(cell, (PRBool)cell->GetView()); HasView() > + OrderRowGroups(rowGroups, numRowGroups); > + rv = painter.PaintTable(this, (nsTableRowGroupFrame*)rowGroups.ElementAt(0), > + (nsTableRowGroupFrame*)rowGroups.ElementAt(numRowGroups-1), Again, what if numRowGroups == 0? >+nsTableFrame::SetColumnDimensions(nsIPresContext* aPresContext, Comment clearly in here why the cellSpacingY affects all these heights, please. Also comment why cellspacing affects origins. >+ if (colGroupWidth) { >+ colGroupWidth -= cellSpacingX; >+ } Comment that you are doing this to cancel out the extra cellSpacingX we counted for the last column? >@@ -5740,16 +5816,17 @@ nsTableFrame::CalcBCBorders(nsIPresConte >+ CalcDominateBorder(this, cgFrame, colFrame, nsnull, nsnull, >+ nsnull, PR_TRUE, NS_SIDE_RIGHT, PR_TRUE, t2p, //XXXfr why true? You added this code... why did you use true? Add a clearer XXX comment if needed. >@@ -5878,16 +5992,28 @@ nsTableFrame::CalcBCBorders(nsIPresConte >+ nsnull, PR_TRUE, NS_SIDE_RIGHT, PR_TRUE, t2p, //XXXfr why true? Same. >+ nsnull, PR_TRUE, NS_SIDE_RIGHT, PR_TRUE, t2p, //XXXfr why true? Same. I got up to the "@@ -6087,26 +6228,46 @@ nsTableFrame::CalcBCBorders(nsIPresConte" part. More later.
Comment on attachment 135353 [details] [diff] [review] patch I'm not sure I can usefully review your CalcDominateBorder calls, btw... if you could have bernd look them over, that would be great. >@@ -6087,26 +6228,46 @@ nsTableFrame::CalcBCBorders(nsIPresConte >+ if (!gotRowBorder && 1 == info.rowSpan) { >+ //get continuous row/row group border This could use a nice long comment explaining _why_ you're doing this, not just what you're doing. It's not obvious to me what "gotRowBorder" means at this point, what info.rowSpan really means, and why you care about this particular condition. >Index: mozilla/layout/html/table/src/nsTableRowGroupFrame.h >+ // border widths in pixels in the collapsing border model >+ unsigned mRightContBorderWidth:8; >+ unsigned mBottomContBorderWidth:8; >+ unsigned mLeftContBorderWidth:8; Any reason not to just make these PRUint8? Also, I assume we have very few frames of this type around? Otherwise adding members to them is not so great... If this is something that will be used only rarely, perhaps it could be stored as a property of the frame. If it's something that needs to be accessed often, I guess we need to byte the bullet and just store this? >+inline nscoord >+nsTableRowGroupFrame::GetContinuousBCBorderWidth(float aPixelsToTwips, Is there a good reason to inline this? It seems like a nontrivial bit of code, especially if it's called often. >Index: mozilla/layout/html/table/src/nsTableRowGroupFrame.cpp >+ if (NS_FRAME_PAINT_LAYER_BACKGROUND == aWhichLayer && >+ !(aFlags & (NS_PAINT_FLAG_TABLE_BG_PAINT | NS_PAINT_FLAG_TABLE_CELL_BG_PASS))) { This could use a comment explaining what exactly this check means (as far as I can tell, "Paint() called directly because we have a view" or something like that. >+ if (row->GetView()) { HasView() >+ else if (aDirtyRect.YMost() > rect.y){ Again, why this check as opposed to an intersects check? >+ rv = painter.PaintCell(cell, (PRBool)cell->GetView()); HasView() This whole chunk of code duplicates code in the inner parts of the loops in nsTableFrame. Is there really no way to push this code down into the painter? It could decide whether to run the outer part of the loop based on what the origin is or something... In fact, here you would just call PaintRowGroup() on the painter, and the loop over the rows logic (as well as checking for views) could live in the PaintRowGroup() method, no? I suppose you're trying to have the painter present a more flexible interface, but do we really envision using the extra flexibility? Would there ever be a case when one _would_ want to paint kids with views in this sort of situation? >+void nsTableRowGroupFrame::SetContinuousBCBorderWidth(PRUint8 aForSide, Will this never get called with NS_SIDE_RIGHT? If so, add a debug-only case with an NS_ERROR to that effect. Also, as written this will trigger unhandled value warnings; you may want to add an empty "default" to this switch (and add a return to the third case!). >Index: mozilla/layout/html/table/src/nsTableRowFrame.h >+ unsigned mRightContBorderWidth:8; >+ unsigned mTopContBorderWidth:8; >+ unsigned mLeftContBorderWidth:8; This is increasing the size of nsTableRowFrame, and I _know_ we have lots of those.... is there really no way not to store this state? Perhaps we should have a BC-only class for this like we do for table cells? >+inline void >+nsTableRowFrame::GetContinuousBCBorderWidth(float aPixelsToTwips, >+inline nscoord nsTableRowFrame::GetOuterTopContBCBorderWidth(float aPixelsToTwips) Again, why inline the first of these? Is there any reason these are two separate functions for table rows but combined into a single function for table row groups? It would be better to be consistent, imo. >Index: mozilla/layout/html/table/src/nsTableRowFrame.cpp >+ if (NS_FRAME_PAINT_LAYER_BACKGROUND == aWhichLayer && >+ !(aFlags & (NS_PAINT_FLAG_TABLE_BG_PAINT | NS_PAINT_FLAG_TABLE_CELL_BG_PASS))) { Same comment as for nsTableRowGroupFrame >+ rv = painter.PaintCell(cell, (PRBool)cell->GetView()); HasView(). Once again, this would be better in the painter, imo... >+void nsTableRowFrame::SetContinuousBCBorderWidth(PRUint8 aForSide, Same comments as for table row groups. >Index: mozilla/layout/html/table/src/nsTableColGroupFrame.h >+ PRUint32 mTopContBorderWidth:8; >+ PRUint32 mBottomContBorderWidth:8; PRUint8. >Index: mozilla/layout/html/table/src/nsTableColGroupFrame.cpp >+void nsTableColGroupFrame::SetContinuousBCBorderWidth(PRUint8 aForSide, Similar comments as for row groups. >Index: mozilla/layout/html/table/src/nsTableColFrame.h >+ // border width in pixels >+ PRUint32 mLeftBorderWidth: 8; >+ PRUint32 mRightBorderWidth: 8; >+ PRUint32 mTopContBorderWidth:8; >+ PRUint32 mRightContBorderWidth:8; >+ PRUint32 mBottomContBorderWidth:8; PRUint8. I guess we don't have as many colframes as rowframes in really big tables, so this may be OK.... >+inline nscoord >+nsTableColFrame::GetContinuousBCBorderWidth(float aPixelsToTwips, >+ nsMargin& aBorder) Again, I don't think this should be inlined. >Index: mozilla/layout/html/table/src/nsTableColFrame.cpp >+void nsTableColFrame::SetContinuousBCBorderWidth(PRUint8 aForSide, >+ nscoord aPixelValue) Same comments as for row groups, etc. >Index: mozilla/layout/html/table/src/nsTableCellFrame.cpp >- nsILookAndFeel* look = nsnull; Hey, if you're touching this code anyway, make the thing an nsCOMPtr, eh? >@@ -417,17 +418,17 @@ nsTableCellFrame::Paint(nsIPresContext* >- PRBool paintChildren = PR_TRUE; >+ PRBool paintChildren = PR_TRUE; Why make changes like that? Just muddles up the CVS history.... >@@ -435,17 +436,17 @@ nsTableCellFrame::Paint(nsIPresContext* >- >+ Same. >@@ -1363,18 +1364,19 @@ nsBCTableCellFrame::PaintUnderlay(nsIPre >+ if (aVisibleBackground && >+ (!(aFlags & NS_PAINT_FLAG_TABLE_BG_PAINT) || >+ (aFlags & NS_PAINT_FLAG_TABLE_CELL_BG_PASS))) { Again, need a comment as to what that conditional actually means... >@@ -1389,11 +1391,11 @@ nsBCTableCellFrame::PaintUnderlay(nsIPre >+ aFlags &= ~ (NS_PAINT_FLAG_TABLE_CELL_BG_PASS | NS_PAINT_FLAG_TABLE_BG_PAINT); Why do table cells need to reset this flag? It's not clear what that will do, just by looking at this code. Comment, please.
bernd, if you have thoughts of any kind on using a BC-only table row class that stores the extra border state, please comment... how well is that working out for table cells?
Boris, thanks for your careful review, it shows that comment 121 was correct. BC table cell frames work. I never touched them (Maybe thats the reason why they work). I like the idea to hide the bc burden from ordinary rows in the separate border case. I will review the CalcDominateBorder calls. Btw the empty table background case is bug 227123, and mozilla currently does the right thing, so please no regressions....
s/CalcDominateBorder/CalcDominantBorder/g ? /be
As a separate patch, sure. This one is already pretty big....
I would like to propose to spin of the border collapse part into a separate patch. It will otherwise jeopardize the 1.7a timetable for the whole patch. The border collapse review issues are not new () and when bz (comment 142) and dbaron ( ) try to avoid to review this code it sends out a clear message. And it is really hard to argue when looking at an undocumented function with 14 arguments like CalcDominantBorder () that it might cause comments like //XXXfr why true? To summarize I would prefer if this function can be reorganized before any further calls are added. I filed bug 229883 for this. @@ -927,30 +931,31 @@ public: + PRUint32 mLeftContBCBorder:8; + PRUint32 : 11; // unused } mBits; Why are mLeftContBCBorder not a member of the bcProperty like the other bc widths on a table? this would also eliminate the my objection against @@ -1101,16 +1106,25 @@ inline void nsTableFrame::SetBorderColla +inline nscoord +nsTableFrame::GetContinuousLeftBCBorderWidth(float aPixelsToTwips, + PRBool aGetInner) const why isn't there a Set method. @@ -5782,27 +5859,53 @@ nsTableFrame::CalcBCBorders(nsIPresConte + mBits.mLeftContBCBorder = ownerWidth; this should never happen, mBits should not accessed so directly. Why are the widths for the table not reset together with the other table widths? if (!tableBorderReset[NS_SIDE_TOP]) { 5738 propData->mTopBorderWidth = 0; 5739 tableBorderReset[NS_SIDE_TOP] = PR_TRUE; 5740 } A continuous bc border is that the thinnest continuous line? If yes + //get row continuous borders + CalcDominateBorder(this, info.cg, info.leftCol, info.rg, rowFrame, nsnull, PR_TRUE, NS_SIDE_LEFT, + PR_FALSE, t2p, owner, ownerBStyle, ownerWidth, ownerColor); + rowFrame->SetContinuousBCBorderWidth(NS_SIDE_LEFT, ownerWidth); Why are cell frames here excluded from the computation? Imagine that they have border style hidden. I would expect more some minimum mechanism. My impression is that the exclusion of frames at the CalcDominantBorder calls will create problems once a hidden style is defined on any of those excluded frames.
> To summarize I would prefer if this function can be reorganized before any > further calls are added. I filed bug 229883 for this. If this is done (and it would be fine with me), I would say the calls should still be added per this patch, just ifdefed out. That way lxr searches will show it when bug 229883 is being fixed (and they can be fixed to do the right thing then).
> I would like to propose to spin of the border collapse part into a separate > patch. It will otherwise jeopardize the 1.7a timetable for the whole patch. You want me to extricate the border collapse parts so that we check in one behavior (ignoring borders) and during the next release cycle (1.8a) change it to another (accounting for borders)?? Right now, my main concern wrt release timetables is whether I'll be able to handle all these comments in time for the freeze... :) (I won't have time to work on it this week.) > A continuous bc border is that the thinnest continuous line? No, it is the result of collapsing all the continuous borders on that edge. For vertical lines, this is table, colgroup, column. For horizontal lines, this is table, rowgroup, row. This is done so that backgrounds will line up along the edge. Cell borders are not continuous on a line: they are segments along it. Therefore they don't get counted. For example, setting a thick border on the leftmost cell should not shift the row background over; this way a striped background set on <tr> will line up across rows even if the cells are assigned arbitrary border widths. I really ought to write this up.
For the record, the tests mentioned on this bug so far are currently at: It would be great if we could get some CSS2.1-test-case-guideline-compliant versions of those tests for the CSS2.1 test suite. :-)
Created attachment 140946 [details] nsTablePainter.h (not quite done)
Created attachment 140947 [details] (not quite done) Latest patch will be up at I'm not quite done, but nsTablePainter.* are, minus some comments, mostly ready for review. I'm still going over the nsTableFrame portions of the patch. I'm extremely busy tomorrow, though, so I thought I'd post these for now in case you (bz, bernd) wanted to look it over sooner rather than later. Responses to some of the comments: > Is there any reason these are two separate functions for table rows but > combined into a single function for table row groups? It would be better > to be consistent, imo. Return value is void now, so n/a. > Comment clearly in here why the cellSpacingY affects all these heights, please. > Also comment why cellspacing affects origins. That should be documented in CSS2.1 >+ CalcDominateBorder(this, cgFrame, colFrame, nsnull, nsnull, >+ nsnull, PR_TRUE, NS_SIDE_RIGHT, PR_TRUE, t2p, //XXXfr why true? > > You added this code... why did you use true? I just guessed based on what I saw elsewhere. I don't know what it does, which is why I ask. > Is there a good reason to inline this? It seems like a nontrivial bit of > code, especially if it's called often. It's only called once. > This is increasing the size of nsTableRowFrame, and I _know_ we have lots > of those.... As discussed, I'll file a bug on moving that into a frame property. > - PRBool paintChildren = PR_TRUE; > + PRBool paintChildren = PR_TRUE; > > Why make changes like that? Just muddles up the CVS history.... neater code for the next person to read?
> That should be documented in CSS2.1 Then point to the relevant spec section here.... That at least tells people where to look for the reasons for that code.
@@ -5731,27 +5750,53 @@ nsTableFrame::CalcBCBorders(nsIPresConte . . . +CalcDominantBorder(this, cgFrame, colFrame, nsnull, nsnull, + nsnull, PR_TRUE, NS_SIDE_RIGHT, PR_TRUE, t2p, //XXXfr why true? so what does this code do IMHO, it looks for the table, the colgroupframe and colframe It queries for all of them right border. If the borders are the result of the rules attribute then they should be ignored. Furthermore the owner should be the adjacent frame. Afterwards only the owner width is used. If the request is going for the last PR_TRUE then the answer is it doesnt matter, you need the owner only when you store in the cellmap. If this request is for the first PR_TRUE then it really matters. So we are at the top row and we query for the right side of these frames, only for the rightmost edge we are certain that we hit an outer edge of the table for all others we know that we are inside the table. So in once case this should be PR_TRUE and in the majority of cases PR_FALSE. In the light of bug 43178 I think my comment 147 makes sense because it would free you from fixing this.
Created attachment 141121 [details] [diff] [review] patch newest nsTablePainter is up at I'll attach it once bz says its good enough :)
Comment on attachment 141121 [details] [diff] [review] patch forgot to mention: the only difference between the nsTablePainter files previously attached and the ones I just put up is the comments and a couple lines I swapped in PaintCell (moved the get colIndex part below the empty-cells short-circuit).
Comments on the separate files: > nsTablePainter.h How about calling it mozTableBackgroundPainter.h? ;) > /* aPass params indicate whether to paint the element or to just pass through and They're called aPassThrough. Change the comment accordingly. > * See Public versions for function descriptions Why not just put these private methods down with the other private methods and skip this part? > /** Paint table elements' backgrounds down through table cells > * (Cells themselves will only be painted in border collapse) Maybe better said as "Paint background for the table frame and its children down through the cells (Cells ... ) > /** Paint table row group elements' backgrounds down through table cells > * (Cells themselves will only be painted in border collapse) And then this could be "Paint background for the table row and its children down....." > /** Paint table row elements' backgrounds down through table cells > * (Cells themselves will only be painted in border collapse) Likewise. Feel free to ignore these comments if you think what you wrote is clearer, of course. ;) > /** Calculate and set data all values to represent aFrame (which must be non-null) */ "and set all data values", perhaps? > /** True if need to set border-collapse border; must call Set beforehand */ > PRBool ShouldSetBCBorder(); Which Set? SetFull()? SetFrame()? SetBCBorder()? Some subset thereof? > private: > nsStyleBorder* mSynthBorder; Weird indent; that should line up with the other members. > nsRect mCellRect; //current cell "current cell rect" > nsTablePainter.cpp Same naming issue (make it match the classname). >TableBackgroundPainter::TableBackgroundData::SetBCBorder(nsMargin& aBorder, > mSynthBorder = new (aPainter->mPresContext) > nsStyleBorder(aPainter->mZeroBorder); So... mZeroBorder is just an optimization or something? This is the only thing it's used for, and you could as easily do mSynthBorder = new (aPainter->mPresContext) nsStyleBorder(aPainter->mPresContext); right? >TableBackgroundPainter::TableBackgroundPainter(nsTableFrame* aTableFrame, > mZeroBorder.SetBorderStyle(NS_SIDE_TOP, NS_STYLE_BORDER_STYLE_BLANK); Use STYLE_NONE here. dbaron just removed NS_STYLE_BORDER_STYLE_BLANK anyway. >TableBackgroundPainter::PaintTableFrame(nsTableFrame* aTableFrame, > tableData.mRect.MoveTo(0,0); Add "// Put tableData.mRect in the table frame's coordinate system" before that line. > if (aFirstRowGroup && aLastRowGroup && mNumCols > 0) { > //only handle non-degenerate tables; we need a more robust BC model > //to make degenerate tables' borders reasonable to deal with Weird indent. > aLastRowGroup->GetContinuousBCBorderWidth(mP2t, tempBorder); > border.bottom = tempBorder.bottom; > > nsTableRowFrame* rowFrame = aFirstRowGroup->GetFirstRow(); > if (rowFrame) { Why use the row for top and the rowgroup for bottom? Is there a reason? If so, comment it here. > border.left = aTableFrame->GetContinuousLeftBCBorderWidth(mP2t, PR_TRUE); Likewise -- why use the table's left border but the col's right border above? > nsresult rv = tableData.SetBCBorder(border, this); > if (NS_FAILED(rv)) { > return rv; > } Need to do "tableData.Destroy(mPresContext);" before returning, no? >TableBackgroundPainter::QuirksPaintTable(nsTableFrame* aTableFrame, > if (NS_FAILED(rv)) return rv; > if (rgRect.Intersects(mDirtyRect) && !rg->HasView() > && NS_SUCCEEDED(rv) && isVisible) { No need for the NS_SUCCEEDED check -- it can't fail. ;) > if (NS_FAILED(rv)) return rv; > if (mDirtyRect.YMost() > rowRect.y && !row->HasView() > && NS_SUCCEEDED(rv) && isVisible) { Again, no need for the NS_SUCCEEDED check. Why checking mDirtyRect.YMost() > rowRect.y instead of checking whether the rects intersect? Due to rowspanning cells? If so, please add a short comment to that effect. >TableBackgroundPainter::PaintTable(nsTableFrame* aTableFrame) > mCols = new ColData[mNumCols]; This allocates mCols. Since ColData has no constructor, the mColGroup pointers in all those are uninitialized. > /*Create data struct for column group*/ > cgData = new TableBackgroundData; > if (!cgData) return NS_ERROR_OUT_OF_MEMORY; Now some of the points in mCols are garbage and when you do the deletion loop over mCols in the destructor you will probably crash. I'd add a constructor to ColData that inits the mColGroup pointer to 0. This looks great, fantasai! Thank you very much for the clear up-front explanation of what this class is trying to do! Once you make the changes I just mentioned, these two files are good by me.
> How about calling it mozTableBackgroundPainter.h? ;) Scratch that. mozTableBgPainter.h/cpp, please. The other is just too long.
Comment on attachment 141121 [details] [diff] [review] patch >Index: mozilla/layout/html/table/src/nsTableCellFrame.cpp >-NS_METHOD >+NS_METHOD > nsTableCellFrame::Paint(nsIPresContext* aPresContext, NS_IMETHODIMP, as long as you're changing this. Other than that, looks good to me. sr=bzbarsky. Don't forget to change Makefile.in if when you rename nsTablePainter.cpp
{ns/moz/}TableBackgroundPainter.{cpp,h} seems like fine names to me. The length isn't really a problem. Here are comments on the patch, although I skipped nsTableFrame::CalcBCBorders because it makes my head hurt, and I haven't looked through the new files thoroughly yet. nsStyleStruct.cpp: This should use a loop (probably the FOR_CSS_SIDES macro, which could be moved from nsCSSStruct.h to nsStyleConsts.h). But since that requires changing files in directories you're not otherwise touching, and should probably be done with a bit of other cleanup, I filed bug 233795 to remind myself to do it later. nsCSSRendering.h/cpp: aClipRect should probably be called aBGClipRect, since aClipRect is a reasonably standard name meaning something else nsTableFrame.h: Limiting BC borders to 63 pixels is wrong, and we shouldn't spread that elsewhere. (Same for nsTableRowFrame.h, nsTableRowGroupFrame.h, nsTableColFrame.h, nsTableColGroupFrame.h.) We should at least have a typedef for a pixel size of a BC border so we can find all the places that use PRUint8 or :8. Shouldn't GetContinuousLeftBCBorderWidth use the BC_BORDER_LEFT_HALF_COORD macro for symmetry, and in case the macros change? nsTableFrame.cpp: I dislike the NS_PAINT_FLAG_* business: NS_PAINT_FLAG_TABLE_CELL_BG_PASS is never set, so it can be removed. NS_PAINT_FLAG_TABLE_BG_PAINT can be replaced with a function on each inner table element class that checks if there's a view between that element (inclusive) and the table element (exclusive). But that is probably better done in a later patch (since it would allow the aFlags parameter to be removed throughout layout, I think). The nsTableBackgroundPainter code within nsTableFrame.cpp probably shouldn't be conditioned on the table having visibility visible (although that currently means the NS_PAINT_FLAG_TABLE_BG_PAINT flag isn't set). Instead, the nsTableBackgroundPainter code should be called unconditionally (which it looks like it will handle just fine). Likewise for the descendants with views that use it. Your use of the terms "direct" and "table-called" in comments in three places (nsTableRowGroupFrame::Paint, nsTableRowFrame::Paint, nsBCTableCellFrame::PaintUnderlay) is really making up terminology where we don't need extra terminology. What's happening is that an internal table element has a view (which, for table cells, can be caused by relative positioning, opacity, etc.). You should use the term "view" somewhere in those comments and get rid of the terms "direct" and "table-called". In the code in nsTableRow(Group)?Frame that creates a TableBackgroundPainter, do you want to set the flag tell the rows / cells not to paint? Likewise (as I said before), these calls probably shouldn't be conditional on visibility. nsTableColGroupFrame.cpp: nsTableColFrame guarantees not touching aBorder.left, so you don't need to do the fancy save-and-reassign dance in GetContinuousBCBorderWidth. nsTableColFrame: GetContinuousBCBorderWidth can return void -- nobody uses the result. nsTableCellFrame: I'm guessing Bernd wants you to remove a bunch of the PaintUnderlay-related changes, since they break NS_STYLE_TABLE_EMPTY_CELLS_SHOW_BACKGROUND, although removing the NS_PAINT_FLAG_TABLE_CELL_BG_PASS flag will allow you to remove the aPaintChildren argument. The comments you added about the flags are backwards, but you should notice that when you remove the unneeded one. Also, you're probably better in passing the value of GetStyleTableBorder()->mEmptyCells instead of a boolean and the const nsStyleTableBorder* (to get mEmptyCells again, just like for the boolean). nsTableBackgroundPainter.cpp (just the parts I've read in order to read the rest of the patch): In SetFull, is it really correct to ignore the border if visibility is hidden? That seems wrong. TableBackgroundPainter::QuirksPaintTable incorrectly applies visibility on row groups to rows and cells and visibility on rows to cells. TableBackgroundPainter::QuirksPaintTable compares the frame's rect to the dirty area when it needs to use the overflow area (unioned with the rect, or something -- it's messy). "<dfn>passed</dfn>" seems like a bad term to use because one already passes arguments to functions and paints in multiple passes. How about skipped (which conflicts only with aSkipSides)? Or just "has view"? Likewise aPassThrough / aPass should probably be renamed to aSkip or aHasView. The assertion at the beginning of PaintRow calls itself PaintRowGroup. Also, in both those assertions, "Quirks" isn't a caller, so you should probably say "must not call ... in quirks mode". Have you tested that moving a window over your testcases does the right thing? Try multiple directions, and try movement that's exactly horizontal or exactly vertical? I find the inconsistency in the ways you handle coordinate systems between cells/ rows / row groups / tables to be confusing, and confusion can easily lead to bugs. Perhaps it's better to be consistent with what the rest of the code does (always translate, i.e., get rid of mCellRect and call TranslateContext for rows as well)? Perhaps it's OK the way it is, but this really seems like premature optimization (which is said to be the root of all evil). Could you explain the logic of the changes (which I'm sure are connected) to: * the nsTableReflowState constructor * nsTableFrame::SetColumnDimensions * nsTableRowFrame::ReflowChildren Also, if you want to include added files in your diff, you can just add the following lines to the end of (or anywhere within) layout/html/table/src/CVS/Entries: /nsTableBackgroundPainter.h/0/dummy timestamp// /nsTableBackgroundPainter.cpp/0/dummy timestamp// Once you do that, if you add -N to the options you pass to diff (i.e., diff -Npu8), they should show up in the diff.
As fantasai points out, NS_PAINT_FLAG_TABLE_CELL_BG_PASS is set in the painter, so forget the bit about removing the flags. However, this means nsTableCellFrame::Paint needs to set PaintChildren based on it (just like it now does in one of the two implementations of PaintUnderlay) -- i.e., you need to pull that bit out of the BC version of PaintUnderlay.
> So... mZeroBorder is just an optimization or something? This is the only thing > it's used for, and you could as easily do > mSynthBorder = new (aPainter->mPresContext) > nsStyleBorder(aPainter->mPresContext); > right? Won't work; I need to give the border a width. STYLE_NONE makes it zero-width. And the default width is medium.
(In reply to comment #162) > Won't work; I need to give the border a width. What do you mean? Don't you explicitly assign some border widths immediately after that?
STYLE_NONE means there's no border; i.e. the border width must calculate to zero no matter what it's specified value.
Oh, hm... So do we need to restore STYLE_BLANK then?
I looked at the bc part between and They look OK to me. I am not too worried about NS_STYLE_TABLE_EMPTY_CELLS_SHOW_BACKGROUND changes the only wrong place I already mentioned to fantasai. Just for the record NS_STYLE_TABLE_EMPTY_CELLS_SHOW_BACKGROUND is only available in quirks mode. It emulates the NN4 which has shown the background for empty cells but not the border. NS_STYLE_TABLE_EMPTY_CELLS_SHOW_BACKGROUND is used as default, as soon as empty-cells is either shown or hide this quirk doesn't apply. >Here are comments on the patch, although I skipped >nsTableFrame::CalcBCBorders because it makes my head hurt You are of course involved in the offer I made to boris, if you rereview the 2300 lines of bc code like you did with the overflow stuff, I will bring the code in accordance to your review comments. This seems to me necessary as r=alexsavulov for this type of patch did not ensure at least readability of the code. I filed already bug 229883 and attached a patch to the bug, to get rid of the large numbers of arguments to CalcDominantBorder. But I am weak at these general style coding stuff.
I think STYLE_SOLID will work; PaintBackground doesn't paint the borders, it just uses them for image positioning.
> STYLE_NONE means there's no border; i.e. the border width must calculate to > zero no matter what it's specified value. It must _compute_ to zero, even, so this should happen during the cascade. e.g.: div { border: none 2em red; } span { border: inherit; border-style: solid; } <div><span> test </span></div> ...should not have any border. (We currently do this wrong. It works in Opera.)
Ian, that is off-topic, and this is a long bug. But since you bring it up:
Created attachment 141851 [details] [diff] [review] patch > Your use of the terms "direct" and "table-called" in comments in three The significance of having a view is that it means ::Paint is not called by an ancestor table element, which would have painted the element's background for it. Therefore, I prefer to keep those comments intact. I have, however, added a note about views in the flag declarations. > nsTableColFrame::GetContinuousBCBorderWidth can return void -- nobody uses the result. The painter does. > In SetFull, is it really correct to ignore the border if visibility is > hidden? That seems wrong. Why? If we're not painting the background, then we have no need for the border. > TableBackgroundPainter::QuirksPaintTable compares the frame's rect to > the dirty area when it needs to use the overflow area To the best of my knowledge, backgrounds never overflow their respective elements' mRects. > "<dfn>passed</dfn>" seems like a bad term to use.. aSkip Skip to me implies that the entire section will be skipped over. PassThrough emphasizes that we're going through the section. Changed "passed" to "passed through". > Have you tested that moving a window over your testcases does the > right thing? Yes. > Could you explain the logic of the changes (which I'm sure are > connected) to: Makes the row and column dimensions start at the first cell border edge rather than the table edge. See "Background Boundaries" in
I think you should revert the GetRowGroupFrame change or modify it to compile on win with VC. e:/moz_src/mozilla/layout/html/table/src/nsTableFrame.cpp(1233) : error C2724: 'GetRowGroupFrame' : 'static' should not be used on member functions defined at file scope
The trick is that for static member functions you're supposed to say |static| when you declare it but not when you define it.
somehow VC++ doesnt like the access to the private member variables mPresContext and mZeroBorder at the following snippet. My first guess is that you either need a get function or change the arguments of this function. nsresult TableBackgroundPainter::TableBackgroundData::SetBCBorder(nsMargin& aBorder, TableBackgroundPainter* aPainter) { NS_PRECONDITION(aPainter, "null painter"); if (!mSynthBorder) { mSynthBorder = new (aPainter->mPresContext) nsStyleBorder(aPainter->mZeroBorder); if (!mSynthBorder) return NS_ERROR_OUT_OF_MEMORY; } e:/moz_src/mozilla/layout/html/table/src/nsTablePainter.cpp(209) : error C2248: "mPresContext" : cannot access mPresContext declared in class "TableBackgroundPainter" e:/moz_src/mozilla/layout/html/table/src/nsTablePainter.h(247) : see declaration of 'mPresContext' e:/moz_src/mozilla/layout/html/table/src/nsTablePainter.cpp(210) : error C2248: "mZeroBorder" : cannot access mZeroBorder declared in class "TableBackgroundPainter" e:/moz_src/mozilla/layout/html/table/src/nsTablePainter.h(263) : see declaration of 'mZeroBorder'
Since different versions of the C++ standard have different rules on member access and nested classes, it's best to declare all nested classes or structs this way: class Container { // ... class Nested; friend class Nested; class Nested { // ... }; // ... }; so that the nested class is a friend of its containing class (which does nothing in the current C++ standard, but did something in the 1998 version).
Even then you may need to make those members protected, not private.
Comment on attachment 141851 [details] [diff] [review] patch I removed the static at nsTableRowGroupFrame* nsTableFrame::GetRowGroupFrame(nsIFrame* aFrame, nsIAtom* aFrameTypeIn) further I added struct TableBackgroundData; friend struct TableBackgroundData; before the MOZ_DECL_CTOR_COUNTER(TableBackgroundData) With these changes I could compile it with VC++ 6.0. Then I added a nsTableFrame* table = (nsTableFrame*)aTableFrame->GetFirstInFlow(); nsFrameList& colGroupList = table->GetColGroups(); as the colgroup list is only valid on the first table frame. I wonder if it would be better to incorporate this into the getcolgroups function Further I replaced all PR_FALSE arguments in the PaintBackgroundWithSC calls with PR_TRUE otherwise we would paint the backgrounds during printing even if the user deselected it in the page setup. with those changes r+
Created attachment 142639 [details] [diff] [review] final patch (?) Made all the changes Bernd mentioned, and switched some casts over to NS_STATIC_CAST per dbaron's instructions. r/sr?
So what's the status of the issues raised in comment 160? I assume that last patch addresses them? If so, please let me know and I will try to sr it this Saturday. We seem to have ended up with three reviewers and two reviews that need to happen.... and no one being sure what's going on.
Yeah, the second-to-last patch fixed them. See comment 170. Further responses: > {ns/moz/}TableBackgroundPainter.{cpp,h} Kept as nsTablePainter, per discussion on IRC. > nsStyleStruct.cpp: dbaron says he filed a bug already. > aClipRect should probably be called aBGClipRect Done. > Limiting BC borders to 63 pixels ... typedef for a pixel size of a BC border Typedefed BCPixelSize. > Shouldn't GetContinuousLeftBCBorderWidth use the BC_BORDER_LEFT_HALF_COORD macro Don't see how this comment applies. > The nsTableBackgroundPainter should be called unconditionally. Fixed. > In the code in nsTableRow(Group)?Frame that creates a > TableBackgroundPainter, do you want to set the flag tell the rows / > cells not to paint? Fixed. > don't need to do the fancy save-and-reassign dance in GetContinuousBCBorderWidth. Fixed. > break NS_STYLE_TABLE_EMPTY_CELLS_SHOW_BACKGROUND Fixed. > TableBackgroundPainter::QuirksPaintTable incorrectly applies visibility Fixed. > say "must not call ... in quirks mode". Fixed.
I'll still try to get to this tonight or tomorrow morning, if we want to land this for 1.7b. I personally feel that that's a reasonable course of action. If someone disagrees, please say so...
Boris, I disagree. Due to my limited time (and knowledge) resources, I can't make sure that I have during the the freeze enough resources to iron out more than regression. This code is large, at least IMHO, so my guess is we will have more than just one critical regression.The patch is so clearly alpha material, that I thought it might be possible to get it in in early beta, but I refuse to go days before the freeze. If you could make the sr so that it goes into 1.8a I would be already delighted.
Yeah, I can definitely make sure I sr in time for 1.8a (well before, in fact). I just hate missing the boat two milestones in a row now.... :( But if you have misgivings about this patch, then we shouldn't.
I agree with slipping to 1.8a. This is the kind of thing where we've been wrong forever, and another few months of being wrong the same way is no big deal, and far preferable to the chance of being wrong in a different way for just a few months.
I think we should get this in for 1.7b. We've got plenty of time before 1.7b releases, never mind after it, to see if things go wrong. If they go wrong badly, we can back it out and reland for 1.8a. If it's not serious, a few minor regressions are definitely worth moving towards a process with which we have a chance of attracting new contributors.
Comment on attachment 142639 [details] [diff] [review] final patch (?) Based on diffing diffs and rereading review comments above, sr=dbaron. This is a big patch, we've had a lot of review, and at some point we just need to stop reviewing and check in.
fix checked in, instead of flowers. Happy Intl. Womens Day Fantasai!!
Finally! :) Excellent work all contributors.
Someone should probably go through the dependencies of this bug and see which ones are now fixed. I'm not optimistic, though -- many seem like bogus dependencies.
I added a number of bugs as dependencies because there was not much point of testing them until the patch landed... I'll probably try to go through the deps tonight.
One other question -- what's now implemented for standards mode is a good bit closer to quirks mode than the old version of standards mode background painting. Are there any reasons we still need the quirks? If not, should we file a bug to remove the mode differences when we open for 1.8a?
There was some discussion of that in comment 103, comment 104, comment 115. I would be in favor of removing the quirk in 1.8a and seeing what happens, myself. The non-quirk behavior seems vastly more preferable in most situations I can think of....
This commit have added a "may be used uninitialized" warning on brad TBox: +layout/html/table/src/nsTableFrame.cpp:5679 + `PRBool gotRowBorder' might be used uninitialized in this function
Hmm.. that warning looks correct to me. We should init it (presumably to true, given the following code?)
Hmmm. My guess was that it should be initialized to false, but I'm not sure.
Although, actually, iter.IsNewRow() might be guaranteed to be true the first time through the loop, which would mean it's a bogus warning.
iter.First calls SetNewGroup wich calls SetNewRow which sets mIsNewRow to true, so the call to IsNewRow will for the first cell that is iterated over always be true. However I think given the difficulties to read the border collapse assembly code, I will be more explicit that it is PR_FALSE at the start in the patch for bug 229883, which I delayed to get this patch here up and running first.
Oh, so /this/ is why I had unusually much bugmail. :) Thank you very much, everyone. *doffs hat and bows* So, as for Quirks, I was looking over Tantek's shoulder while he pulled up one of my tests at the Sofitel. I suspect MacIE doesn't do the transparent thing, because it was definitely painting colgroups as colgroup backgrounds and not inherited cell backgrounds. So I'm guessing we should be all right with getting rid of the quirk, although saving it for 1.8a sounds fine to me. Filed bug 237078 on the issue.
(In reply to comment #152) > > This is increasing the size of nsTableRowFrame, and I _know_ we have lots > > of those.... > > As discussed, I'll file a bug on moving that into a frame property. Did that ever get filed?
I think I found a bug in this fix. See bug 267592 happens in mozilla and firefox
|
https://bugzilla.mozilla.org/show_bug.cgi?id=4510
|
CC-MAIN-2017-17
|
refinedweb
| 15,253
| 66.44
|
YES! That's a great example! I feel much better about it now. Thank you again. Marilyn On Fri, 6 Feb 2004, Alan Gauld wrote: > > > In Python lambda can be used to build simple (very simple sadly) > > > anonymous expressions (no statements) which can get used at places > where > > > you think it's not worth writing a function with a name. > > > > Is it only useful in map() and filter() and reduce()? > > No. > > > And other places where you want to hand a little function to a > > function? > > Yes. > > > comp() for example. > > Yes > > > Is there another class of examples? > > GUI programming where you want a widget to do something simple > - like call another method with a predetermined set of values, eg: > > class MyGUI: > def aFancyOne(self,x,y,z) > #.... > def buildGUI(self) > # define lots of other widgets here > self.doIt = Button(parent, text="Doit", > command=lambda : self.aFancyOne(23,42,"DoIt > called")) > self.doAnother = Button(parent, ext = "Another", > command = lambda : > self.aFancyOne(1000,-3,"Help!")) > > > So we see a method taking two parameters being called from the > command functions of two separate widgets with two different > sets of values. > > We could have defined two small functions and passed them instead > but it gets messy: > > def DoItFunc(self): return self.aFancyOne(23,42,"DoIt called") > def AnotherFunc(self): return self.aFancyOne(1000,-3,"Help!") > > then define the widgets like this: > > > self.doIt = Button(parent, text="Doit", command=DoItFunc) > self.doAnother = Button(parent, ext = "Another", command = > AnotherFunc) > > lambda just saves a little typing and keeps the namespace from > getting cluttered. It also meands the hard coding is kept at the > point of use rather than requiring maintenance to be spread over > two parts of the program... > > HTH, > > Alan G. > > --
|
https://mail.python.org/pipermail/tutor/2004-February/028117.html
|
CC-MAIN-2014-10
|
refinedweb
| 284
| 59.5
|
- Contents
- Ba sic Exception Concepts
- Creating Your Own Exceptions
- Exceptions and Transactions
- Logging
- Antipatterns
- Conclusion
- Resources
Should you throw an exception, or return
null? Should you use checked or unchecked exceptions? For many novice to mid-level developers, exception handling tends to be an afterthought. Their typical pattern is usually a simple
try/
catch/
printStackTrace(). When they try to get more creative, they usually stumble into one or more common exception handling antipatterns.
The antipattern concept became popular in the software development community with the release of AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis in 1998. An antipattern draws on real-world experience to identify a commonly occurring programming mistake. It describes the general form of the bad pattern, identifies its negative consequences, prescribes a remedy, and helps define a common vocabulary by giving each pattern a name.
In this article, we'll discuss some fundamental concepts about the different types of Java exceptions and their intended uses. We'll also cover basic logging concepts, especially as they relate to exception handling. Finally, instead of prescribing what to do, we'll focus on what not to do, and take a look at a dozen common exception-handling antipatterns that you are almost certain to find somewhere in your code base.
Basic Exception Concepts
One of the most important concepts about exception handling to understand is that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.
Checked exceptions are exceptions that must be declared in the
throws clause of a method. They extend
Exception and are intended to be an "in your face" type of exceptions. A checked exception indicates an expected problem that can occur during normal system operation. Some examples are problems communicating with external systems, and problems with user input. Note that, depending on your code's intended function, "user input" may refer to a user interface, or it may refer to the parameters that another developer passes to your API.and
NoSuchMethodException. An unchecked exception probably shouldn't be retried, and the correct response is usually to do nothing, and let it bubble up out of your method and through the execution stack. This is why it doesn't need to be declared in a
throws clause. Eventually, at a high level of execution, the exception should probably be logged (see below).
Errors are serious problems that are almost certainly not recoverable. Some examples are
OutOfMemoryError,
LinkageError, and
StackOverflowError.
Creating Your Own Exceptions
Most packages and/or system components should contain one or more custom exception classes. There are two primary use cases for a custom exception. First, your code can simply throw the custom exception when something goes wrong. For example:
throw new MyObjectNotFoundException("Couldn't find object id " + id);
Second, your code can wrap and throw another exception. For example:
catch (NoSuchMethodException e) { throw new MyServiceException("Couldn't process request", e); }
Wrapping an exception can provide extra information to the user by adding your own message (as in the example above), while still preserving the stack trace and message of the original exception. It also allows you to hide the implementation details of your code, which is the most important reason to wrap exceptions. For instance, look at the Hibernate API. Even though Hibernate makes extensive use of JDBC in its implementation, and most of the operations that it performs can throw
SQLException, Hibernate does not expose
SQLException anywhere in its API. Instead, it wraps these exceptions inside of various subclasses of
HibernateException. Using the approach allows you to change the underlying implementation of your module without modifying its public API.
Exceptions and Transactions
EJB 2
The creators of the EJB 2 specification decided to make use of the distinction between checked and unchecked exceptions to determine whether or not to roll back the active transaction. If an EJB throws a checked exception, the transaction still commits normally. If an EJB throws an unchecked exception, the transaction is rolled back. You almost always want an exception to roll back the active transaction. It just helps to be aware of this fact when working with EJBs.
EJB 3
To somewhat alleviate the problem that I just described, EJB 3 has added an
ApplicationExceptionannotation with a
rollback element. This gives you explicit control over whether or not your exception (either checked or unchecked) should roll back the transaction. For example:
@ApplicationException(rollback=true) public class FooException extends Exception ...
Message-Driven Beans
Be aware that when working with message-driven beans (MDBs) that are driven by a queue, rolling back the active transaction also places the message that you are currently processing back on the queue. The message will then be redelivered to another MDB, possibly on another machine, if your app servers are clustered. It will be retried until it hits the app server's retry limit, at which point the message is left on the dead letter queue. If your MDB wants to avoid reprocessing (e.g., because it performs an expensive operation), it can call
getJMSRedelivered()on the message, and if it was redelivered, it can just throw it away.
Logging
When your code encounters an exception, it must either handle it, let it bubble up, wrap it, or log it. If your code can programmatically handle an exception (e.g., retry in the case of a network failure), then it should. If it can't, it should generally either let it bubble up (for unchecked exceptions) or wrap it (for checked exceptions). However, it is ultimately going to be someone's responsibility to log the fact that this exception occurred if nobody in the calling stack was able to handle it programmatically. This code should typically live as high in the execution stack as it can. Some examples are the
onMessage() method of an MDB, and the
main() method of a class. Once you catch the exception, you should log it appropriately.
The JDK has a
java.util.loggingpackage built in, although the Log4j project from Apache continues to be a commonly-used alternative. Apache also offers the Commons Logging project, which acts as a thin layer that allows you to swap out different logging implementations underneath in a pluggable fashion. All of these logging frameworks that I've mentioned have basically equivalent levels:
FATAL: Should be used in extreme cases, where immediate attention is needed. This level can be useful to trigger a support engineer's pager.
ERROR: Indicates a bug, or a general error condition, but not necessarily one that brings the system to a halt. This level can be useful to trigger email to an alerts list, where it can be filed as a bug by a support engineer.
WARN: Not necessarily a bug, but something someone will probably want to know about. If someone is reading a log file, they will typically want to see any warnings that arise.
INFO: Used for basic, high-level diagnostic information. Most often good to stick immediately before and after relatively long-running sections of code to answer the question "What is the app doing?" Messages at this level should avoid being very chatty.
DEBUG: Used for low-level debugging assistance.
If you are using commons-logging or Log4j, watch out for a common gotcha. The
error,
warn,
info, and
debug methods are overloaded with one version that takes only a message parameter, and one that also takes a
Throwable as the second parameter. Make sure that if you are trying to log the fact that an exception was thrown, you pass both a message and the exception. If you call the version that accepts a single parameter, and pass it the exception, it hides the stack trace of the exception.
When calling
log.debug(), it's good practice to always surround the call with a check for
log.isDebugEnabled(). This is purely for optimization. It's simply a good habit to get into, and once you do it for a few days, it will just become automatic.
Do not use
System.out or
System.err. You should always use a logger. Loggers are extremely configurable and flexible, and each appender can decide which level of severity it wants to report/act on, on a package-by-package basis. Printing a message to
System.out is just sloppy and generally unforgivable.
Antipatterns
Log and Throw
Example:
catch (NoSuchMethodException e) { LOG.error("Blah", e); throw e; }
or
catch (NoSuchMethodException e) { LOG.error("Blah", e); throw new MyServiceException("Blah", e); }
or
catch (NoSuchMethodException e) { e.printStackTrace(); throw new MyServiceException("Blah", e); }
All of the above examples are equally wrong. This is one of the most annoying error-handling antipatterns. Either log the exception, or throw it, but never do both. Logging and throwing results in multiple log messages for a single problem in the code, and makes life hell for the support engineer who is trying to dig through the logs.
Throwing Exception
Example:
public void foo() throws Exception {
This is just sloppy, and it completely defeats the purpose of using a checked exception. It tells your callers "something can go wrong in my method." Real useful. Don't do this. Declare the specific checked exceptions that your method can throw. If there are several, you should probably wrap them in your own exception (see "Throwing the Kitchen Sink" below.)
Throwing the Kitchen Sink
Example:
public void foo() throws MyException, AnotherException, SomeOtherException, YetAnotherException {
Throwing multiple checked exceptions from your method is fine, as long as there are different possible courses of action that the caller may want to take, depending on which exception was thrown. If you have multiple checked exceptions that basically mean the same thing to the caller, wrap them in a single checked exception.
Catching Exception
Example:
try { foo(); } catch (Exception e) { LOG.error("Foo failed", e); }
This is generally wrong and sloppy. Catch the specific exceptions that can be thrown. The problem with catching
Exception is that if the method you are calling later adds a new checked exception to its method signature, the developer's intent is that you should handle the specific new exception. If your code just catches
Exception (or worse,
Throwable), you'll probably never know about the change and the fact that your code is now wrong.
Destructive Wrapping
Example:
catch (NoSuchMethodException e) { throw new MyServiceException("Blah: " + e.getMessage()); }
This destroys the stack trace of the original exception, and is always wrong.
Log and Return Null
Example:
catch (NoSuchMethodException e) { LOG.error("Blah", e); return null; }
or
catch (NoSuchMethodException e) { e.printStackTrace(); return null; } // Man I hate this one
Although not always incorrect, this is usually wrong. Instead of returning
null, throw the exception, and let the caller deal with it. You should only return
null in a normal (non-exceptional) use case (e.g., "This method returns null if the search string was not found.").
Catch and Ignore
Example:
catch (NoSuchMethodException e) { return null; }
This one is insidious. Not only does it return
nullinstead of handling or re-throwing the exception, it totally swallows the exception, losing the information forever.
Throw from Within Finally
Example:
try { blah(); } finally { cleanUp(); }
This is fine, as long as
cleanUp() can never throw an exception. In the above example, if
blah() throws an exception, and then in the
finally block,
cleanUp() throws an exception, that second exception will be thrown and the first exception will be lost forever. If the code that you call in a
finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it bubble out of the
finally block.
Multi-Line Log Messages
Example:
LOG.debug("Using cache policy A"); LOG.debug("Using retry policy B");
Always try to group together all log messages, regardless of the level, into as few calls as possible. So in the example above, the correct code would look like:
LOG.debug("Using cache policy A, using retry policy B");
Using a multi-line log message with multiple calls to
log.debug() may look fine in your test case, but when it shows up in the log file of an app server with 500 threads running in parallel, all spewing information to the same log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code.
Unsupported Operation Returning Null
Example:
public String foo() { // Not supported in this implementation. return null; }
When you're implementing an abstract base class, and you're just providing hooks for subclasses to optionally override, this is fine. However, if this is not the case, you should throw an
UnsupportedOperationExceptioninstead of returning
null. This makes it much more obvious to the caller why things aren't working, instead of her having to figure out why her code is throwing some random
NullPointerException.
Ignoring
InterruptedException
Example:
while (true) { try { Thread.sleep(100000); } catch (InterruptedException e) {} doSomethingCool(); }
InterruptedException is a clue to your code that it should stop whatever it's doing. Some common use cases for a thread getting interrupted are the active transaction timing out, or a thread pool getting shut down. Instead of ignoring the
InterruptedException, your code should do its best to finish up what it's doing, and finish the current thread of execution. So to correct the example above:
while (true) { try { Thread.sleep(100000); } catch (InterruptedException e) { break; } doSomethingCool(); }
Relying on
getCause()
Example:
catch (MyException e) { if (e.getCause() instanceof FooException) { ...
The problem with relying on the result of
getCauseis that it makes your code fragile. It may work fine today, but what happens when the code that you're calling into, or the code that it relies on, changes its underlying implementation, and ends up wrapping the ultimate cause inside of another exception? Now calling
getCause may return you a wrapping exception, and what you really want is the result of
getCause().getCause(). Instead, you should unwrap the causes until you find the ultimate cause of the problem. Apache'scommons-langproject provides
ExceptionUtils.getRootCause()to do this easily.
Conclusion
Good exception handling is a key to building robust, reliable systems. Avoiding the antipatterns that we've outlined here helps you build systems that are maintainable, resilient to change, and that play well with other systems.
Resources
- "Best Practices for Exception Handling"
- "Three Rules for Effective Exception Handling"
- "Handling Errors Using Exceptions" from the Java tutorial
- Antipatternentry on Wikipedia
- Log4j
- Commons Logging
- EJB specifications
|
https://community.oracle.com/docs/DOC-983543
|
CC-MAIN-2017-47
|
refinedweb
| 2,406
| 54.52
|
40. Re: Admob - Google Ads?CowboyBlue Jan 28, 2011 3:48 PM (in response to CowboyBlue)
IUpdate);
}.
41. Re: Admob - Google Ads?CowboyBlue Jan 28, 2011 5:18 PM (in response to CowboyBlue)
one minor issue.
I cannot open the market from an ad. I can open urls but not the market. Hmmmm.
42. Re: Admob - Google Ads?CowboyBlue Jan 28, 2011 5:42 PM (in response to CowboyBlue) ) );
}
}
43. Re: Admob - Google Ads?Joe ... Ward Jan 28, 2011 6:54 PM (in response to CowboyBlue)).
44. Re: Admob - Google Ads?Luoruize001 Jan 30, 2011 4:25 AM (in response to funnyle)...
45. Re: Admob - Google Ads?Tatanium Jan 30, 2011 8:34 AM (in response to funnyle)
Does Adobe even track these forums?
Adobe needs to throw some weight over at Admob and get them to release an official API for A4A (Air 4 Android).
46. Re: Admob - Google Ads?NanoMInd Jan 30, 2011 2:30 PM (in response to Tatanium)
47. Re: Admob - Google Ads?swamp222 Jan 30, 2011 3:10 PM (in response to Luoruize001)
heya!
make sure there's ads available for your "location", I only got a banner once from my location (sweden)
I do more often get more ads when rendering my page @ (germany)
48. Re: Admob - Google Ads?NanoMInd Feb 4, 2011 7:00 AM (in response to funnyle)
This looks nice:
According to a post on the forum there will be support for the PlayBook soon; so this would work with AIR then.
But if Adobe could copy this service that would be even better
49. Re: Admob - Google Ads?llBuck$hotll Feb 4, 2011 7:12 AM (in response to swamp222).
50. Re: Admob - Google Ads?as4more Feb 15, 2011 5:07 PM (in response to funnyle)).
51. Re: Admob - Google Ads?as4more Feb 15, 2011 6:10 PM (in response to as4more).
52. Re: Admob - Google Ads?RobFacks Feb 23, 2011 6:09 PM (in response to funnyle)
Has anyone tried this?
53. Re: Admob - Google Ads?razorskyline Feb 24, 2011 12:52 AM (in response to RobFacks)
Yes, this example is great, I now have two applications in the market both with Admob.
54. Re: Admob - Google Ads?dwightepp Mar 16, 2011 9:47 AM (in response to razorskyline)
Is anyone else having difficulty getting the ads served? The page loads, admob says I
requested an ad, but they're not filling. Thoughts?
55. Re: Admob - Google Ads?p-wing47 Mar 22, 2011 3:05 PM (in response to dwightepp)).
56. Re: Admob - Google Ads?AdmobAndroid.com May 18, 2011 9:32 PM (in response to p-wing47).
57. Re: Admob - Google Ads?12345abcdefghi Jul 10, 2011 12:41 PM (in response to AdmobAndroid.com).
58. Re: Admob - Google Ads?boat5 Jul 10, 2011 2:25 PM (in response to 12345abcdefghi)
it still works for me. i see both admob and smato ads in his app. Sometimes admob does not have an ad to serve to you, is it possible this is what your seeing? Or did you hear there was a click fraud issue?
59. Re: Admob - Google Ads?12345abcdefghi Jul 10, 2011 2:49 PM (in response to boat5)
60. Re: Admob - Google Ads?boat5 Jul 10, 2011 5:55 PM (in response to 12345abcdefghi)...
61. Re: Admob - Google Ads?12345abcdefghi Jul 10, 2011 6:45 PM (in response to boat5)
Thanks again for your info. I wrote to carr. I hope he writes back.
62. Re: Admob - Google Ads?mola2alex Aug 9, 2011 1:45 PM (in response to funnyle)
Adobe, this is a must if you want AS3 to be successful in mobile, especially android.
63. Re: Admob - Google Ads?anthoang Aug 12, 2011 4:27 PM (in response to 12345abcdefghi).
64. Re: Admob - Google Ads?12345abcdefghi Aug 12, 2011 5:05 PM (in response to antho.
65. Re: Admob - Google Ads?vgjhav Aug 22, 2011 9:13 PM (in response to funnyle)
After a lot of trouble (account canned on ADMOB ) and research, I have gotten Ads to work in all my Android Apps. This will work on a lot of AD networks, but most will ban you click fraud. Only one network allows this method and they provide support for it too.
I have over 100 games apps. with this method implemented and working. Here is a link to one of them for you to see how it will look in game. I am using multiple ads in this to force the user to click and make me some money:
Does LeadBolt offer HTML integration for banner ads?
LeadBolt does allow banner ads to be integrated into your app using HTML, rather than using our SDK. To create a HTML banner ad after adding an app to the LeadBolt portal, simply click “Add Ad” and select “App Banner (HTML)” from the drop down box. The HTML snippet can then be added directly into your app’s HTML framework.
So far my eCPM is $6.15
I have created this guide to show my appreciation:
Publisher Code:
STEP I:
Get an Account:
STEP II:
Click on the “APPS” tab and “Create New APP” to create an AD. Remember to change content unlocker to HTML Banner. While in the process.
STEP III:
Get the HTML AD Code and keep it safe. That is all we need from the site. How simple was that?
AD HTML FILE:>
Action Script Code:
STEP I:
Credit: I found this on another site and would like to give credit to the author of pixelpaton.com
The only change you need to make is to enter your website html url where you have placed the AD HTML FILE in the space where I have put : "****ENTER COMPLETE HTML URL HERE****". Where ever you want the AD, place the following code:
// imports
import flash.events.Event;
import flash.events.LocationChangeEvent;
import flash.geom.Rectangle;
import flash.media.StageWebView;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.events.MouseEvent;
// setup variables
var _stageWebView:StageWebView;
var myAdvertURL:String = "****ENTER COMPLETE HTML URL HERE****";
//
{
// check that _stageWebView doersn't exist
if (! _stageWebView) {
_stageWebView = new StageWebView () ;
// set the size of the html 'window'
_stageWebView.viewPort = new Rectangle(0,0, 800, 100);
// add a listener for when the content of the StageWebView changes
_stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGE,onLocationChange);
// start loading the URL;
_stageWebView.loadURL(myAdvertURL);
}
// show the ad by setting it's stage property;
_stageWebView.stage = stage;
}
function toggleAd(event:MouseEvent):void {
trace("toggling advert",_stageWebView);
// check that StageWebView instance exists
if (_stageWebView) {
trace("_stageWebView.stage:"+_stageWebView.stage);
if (_stageWebView.stage == null) {
//show the ad by setting the stage parameter
_stageWebView.stage = stage;
} else {
// hide the ad by nulling the stage parameter
_stageWebView.stage = null;
}
} else {
// ad StageWebView doesn't exist - show create it
}
}
function destroyAd(event:MouseEvent):void {
// check that the instace of StageWebView exists
if (_stageWebView) {
trace("removing advert");
// destroys the ad
_stageWebView.stage = null;
_stageWebView = null;
}
}
function onLocationChange(event:LocationChangeEvent):void {
// check that it's not our ad URL loading
if (_stageWebView.location != myAdvertURL) {
// destroy the ad as the user has kindly clicked on my ad
destroyAd(null);
// Launch a normal browser window with the captured URL;
navigateToURL( new URLRequest( event.location ) );
}
}
// setup button listeners
Hope this works and helps you. If you have questions, let me know. Enjoy.
66. Re: Admob - Google Ads?12345abcdefghi Aug 23, 2011 1:36 PM (in response to vgjhav)
Wow thanks for sharing. I will look into your solution!
67. Re: Admob - Google Ads?mola2alex Aug 24, 2011 5:57 AM (in response to vgjhav)
Thanks for sharing. I will check it out.
68. Re: Admob - Google Ads?mola2alex Aug 24, 2011 7:09 AM (in response to vgjhav)
69. Re: Admob - Google Ads?vgjhav Aug 24, 2011 11:01 AM (in response to mola2alex).
70. Re: Admob - Google Ads?mola2alex Aug 24, 2011 12:10 PM (in response to vgjhav).
71. Re: Admob - Google Ads?JoeCoo7 Aug 25, 2011 9:29 AM (in response to mola2alex).
72. Re: Admob - Google Ads?vgjhav Aug 25, 2011 10:33 AM (in response to JoeCoo7)
That would be awesome buddy... Do share. So you got it working via the
android ad and not smartphone?
73. Re: Admob - Google Ads?vgjhav Aug 25, 2011 8:34 PM (in response to JoeCoo7).
74. Re: Admob - Google Ads?JoeCoo7 Aug 26, 2011 3:44 AM (in response to vgjhav).
75. Re: Admob - Google Ads?vgjhav Aug 26, 2011 4:43 AM (in response to JoeCoo7)
Thanks a ton. Will give it a go tonight or Sunday. Thanks again.
76. Re: Admob - Google Ads?mola2alex Aug 30, 2011 12:26 PM (in response to vgjhav)
Is it possible to put the HTML code into AS3 to be read by the webview or attach the HTML file and referencing it when you publish the app or does it need to be hosted somewhere on the web for this to work?
77. Re: Admob - Google Ads?vgjhav Aug 30, 2011 8:20 PM (in response to mola2alex)
It needs to be hosted. But there are a lot ofgood free hosting companies.
Use any one and you will be good.
The other method never worked for me. So i am still hosting and using that
method.
78. Re: Admob - Google Ads?mola2alex Aug 31, 2011 9:18 AM (in response to vgjhav).
79. Re: Admob - Google Ads?vgjhav Aug 31, 2011 9:37 AM (in response to mola2alex)
Can you share the code too? I have put leadbolt content unlocking on my site
too, getting good conversions. Cant wait for their API to support native
adobe air for android.
Thanks.
|
https://forums.adobe.com/message/3436583
|
CC-MAIN-2018-09
|
refinedweb
| 1,605
| 77.84
|
-1
Hey guys,
I have made a small program called 'Py-mailer' which allows you to login with your Gmail credentials and send text-only messages to anyone. I uploaded it on SourceForge().
The next step I had to take was to make a GUI for it. So, I started with wxPython:
import wx window=wx.App() class pymailer(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,-1,"Pymailer",size=(500,500)) panel=wx.Panel(self,-1) menu=wx.MenuBar() items=wx.Menu() items.Append(201,"Quit") self.Bind(wx.EVT_LEFT_DOWN,self.Quit,id=201) menu.Append(items,"File") self.SetMenuBar(menu) wx.StaticText(panel,-1,"Please enter your Gmail login ID: ",pos=(10,10)) wx.StaticText(panel,-1,"Please enter your Gmail login password:\n(will not be stored)",pos=(10,40)) username=wx.TextCtrl(panel,101,"Login ID",pos=(220,10)) password=wx.TextCtrl(panel,102,"Password",pos=(220,40)) self.Centre() self.Show() def Quit(self,event): self.Close() pymailer() window.MainLoop()
But, on clicking 'Quit' in the 'File' menu, nothing happens! I think it is because in line 29, I have not passed the ID of the event, so how do I pass the ID? Or, is because of some thing else?
Thanks
|
https://www.daniweb.com/programming/software-development/threads/224869/wxpython-events-help
|
CC-MAIN-2017-17
|
refinedweb
| 209
| 53.37
|
Created on 2007-10-10 02:06 by taleinat, last changed 2008-01-14 00:33 by kbk..
Despite your explanation, I don't understand what is being
accomplished here. Delegates are not intended to be callable.
They have methods, e.g. insert, which are callable, and the
insert call is propagated down the chain by calls like
(from ColorDelegator):
def insert(self, index, chars, tags=None):
index = self.index(index)
self.delegate.insert(index, chars, tags)
self.notify_range(index, index + "+%dc" % len(chars))
IMHO it's an incorrect usage of the Delegator mixin to
affect the callable nature of the class to which it's being added.
Also, this __call__ method, if actually used, propagates to the
end of the Delegator chain and calls the function at the end,
(assuming it is a function). Or it will skip non-callable
Delegators and stop at the first callable one.
I doubt this is what was intended, and people trying to understand the code
will be further confused, it seems to me.
Try adding delegator.txt (below) to your Delegator.py and running the
module!?
I understand your argument, but am not convinced. I'll try to explain
how I see this and how I came to this view.
I wished to wrap a specific method (or function) instead of wrapping the
father object with a Delegator and implementing a single method. But I
needed more than simple function wrapping - I wanted a chain of
functions where each wraps the next, and the ability to change the order
of links in this chain. So what I really wanted was a Percolator, but
instead of having it wrap an object and delegate methods, I wanted it to
delegate direct calls.
My first idea was to implement a FunctionDelegator class. But I realized
I would have to implement a FunctionPercolator class, which would be
indentical to the existing Percolator class except that it would inherit
from FunctionDelegator instead of Delegator.
From there I had three choices:
1) create a second pair of delegator/percolator classes which are nearly
identical (much code ducplication)
2) make a Percolator generator function, which accepts a Delegator
class, and returns a Percolator class/object which uses it (possibly
inheriting from it)
3) make Delegator able to delegate direct calls
The third option is obviously the simplest to implement, requiring the
least code without any code duplication.
After some thought, I came to the point-of-view described below, and
realized that the third option is actually what I would expect if I were
thinking about delegators and percolators as transparent proxies.
> Delegates are not intended to be callable.
Why not? IMO, the nice thing about the Delegator class is that you can
use an instance just as if it were the underlying object, transparently.
The major exception from this behavior was that calling a Delegator
never works, even if the underlying object is callable. From this point
of view, my patch makes the Delegator concept complete, while before it
was broken.
>.
You describe method calls and direct calls as though they were
fundamentally different. Therefore you find that delegating both is too
much semantic overloading. However, if one views direct calling of an
object as a special case of calling a method (since functions are also
objects) -- the __call__ method -- then delegating both method calls and
direct calls is The Right Thing.
> Also, this __call__ method, if actually used, propagates to the
> end of the Delegator chain and calls the function at the end,
> (assuming it is a function). Or it will skip non-callable
> Delegators and stop at the first callable one.
True, since this is precisely what Delegators do for any method call --
this is the expected behavior.
>?
Squeezer currently replaces PyShell's write method with a method of its
own. ShellLogger also needs to hook onto the write method, but
ShellLogger's function must be called before Squeezer's method, since
Squeezer can insert a button without calling the underlying write
method. But extensions must replace the write method in their
constructor, and the order of their construction is "random". In other
words, a rudimentary form of constraint enforcement is required, which
can be achieved using a Percolator.
Without the suggested change to Delegator, this can be accomplished by
wrapping EditorWindow with a Percolator, and having extensions insert
Delegators (filters) as appropriate. However, this is a much larger
change to the code -- for example, this breaks type checks, e.g. assert
isinstance(editwin, EditorWindow)). This would also add overhead to
every method call done on EditorWindow, with this overhead growing
linearly with the number of Delegators inserted. I find wrapping
specific methods to be more straightforward and therefore simpler, but
this can be argued.
First, I'm changing my mind about Percolator inheriting from
Delegator. A Percolator acts as a container for Delegators:
it "hasa" (chain) of them. But it fails "isa" Delegator.
It has no use for the Delegator's caching, and chaining
Percolators doesn't make sense. Inheriting from Delegator
just confuses things further, it seems to me.
Delegator is just a mixin implementing a node in the chain.
I do support splitting TkTextPercolator off Percolator.
> 3) make Delegator able to delegate direct calls
Except that the Delegator mixin doesn't know to what function
to delegate the call. Delegating a function call down the nodes
doesn't do anything, except possibly error out if the bottom
object isn't callable, as in delegator.txt.
> IMO, the nice thing about the Delegator class is that you can
> use an instance just as if it were the underlying object, transparently.
> The major exception from this behavior was that calling a Delegator
> never works, even if the underlying object is callable.
But it does work, if the filter that is using the Delegator mixin has
a __call__ method. See delegator2.txt above. Note that the Delegator
__call__ method is removed. You have to override the latter anyway
if you want to run some code in the filter. Do you have some
reason for mixing callable and non-callable filter instances in the
percolator chain?
I can see adding a __call__ method to Percolator, which would call
self.top(). Then each instance in the chain would have a __call__
to appropriate code.
We have two goals: solve your specific requirement of being able to
replace a method with a percolator, and increasing the clarity of the
existing WidgetRedirector/Delegator/Percolator code.
Yes, a Percolator already has semantic overload. Right now, there are
two ways to access the chain:
1. Since the delegate link is exposed, filters can directly call
specific methods further down the chain, e.g. self.delegate.index()
2. The caching and __getattr__() allows a "delegator" to call
unimplemented methods; they will be looked up on the chain. This
allows ColorDelegator to access its Text instance's methods without
having been passed a reference to the instance, as you noted.
Whether this adds or detracts from the clarity of the code is
debatable. Once you understand how it works, it's not a problem,
but it would be for people new to the code. Further, it's fragile,
since the first method with the correct name will be called.
Adding a __call__() method to Delegator doesn't seem to do anything
that can't be accomplished better by adding it to the class
implementing the filter. Why add complexity prematurely?
It seems we're looking at Delegators and Percolators from increasingly
different points of view. Let's back up a little.
I see a Delegator object as a transparent proxy to its "delegate". This
means that attribute access is automatically delegated to the delegate,
unless it is explicitly overridden by the Delegator. That's it.
Some use cases for such a transparent proxy are:
* override only specific attributes/methods of an object
* allow replacement of an object which is referenced in several places
without having to update every reference
(Caching is just an implementation detail, whose only purpose is to
facilitate changing a Delegator's delegate.).
IMO chaining Percolators makes just as much sense as chaining Delegators
-- you're just chaining proxies. How each proxy works internally doesn't
really matter (as long as they work :).
Now, it seems to me that you aren't looking at Delegators and
Peroclators as transparent proxies at all. Specifically, what you wrote
implies that in order to proxy a callable, one should explicitly define
an __call__ method in their Delegator class/instance. But this is
exactly the opposite of the behavior with any other method/attribute,
where I can implicitly have the underlying attribute used by not
defining it in the Delegator. This is Delegator is for!
I'm attaching a Python file which will hopefully show how __call__ is
out of sync with the rest of Delegator's behavior. In its context,
"forwarded" means explicitly defined by a Delegator. "intercepted" means
that except for the interceptor and catcher, the method is not defined
(i.e. by the passers). Please take a moment to run it.
I should note that the situation is similar with other "magic" methods,
e.g. len(). This seems to make Python a bit less dynamic that I would
expect. Aside from implementation considerations such as speed, I'm not
sure I see why this is the way it is, e.g. why dynamically giving a
__call__ attribute to an instance shouldn't make it callable. I'll do
some more searching and reading on this.
Even though, I still think being able to delegate/percolate callables is
important enough to warrant such a change. After all, at the bottom
line, if the underlying object is callable then it will be called, and
if not then an appropriate exception will be raised. Isn't that the
Right Thing?
I'll respond further shortly. In the meantime, please notice that
Delegator3.py works the same whether or not your Delegator.__call__()
method is commented out. That's because you needed to define __call__()
methods in your filters.
We are still suffering from semantic overload. Let's call the instances
which are chained 'filters' and the Delegator mixin machinery 'nodes' for
the purposes of this discussion (because they act much like the nodes in
a traditional Lisp list).
I'm trying to keep this as simple as possible, because it seems we're
tending to over-complicate.
We're discussing two distinct issues:
1) Should Delegator delegate calls to callables
2) Should Percolator inherit from Delegator
Have I missed something?
Regarding the first issue, I do think Delegator should do this, because
I view calling a callable as a special case of calling a method. To
illustrate my point, please take the code in example1.py, run it once
with Delegator as it is, and run it again after adding the __call__
method to Delegator's definition.
Regarding the second issue, I don't think I can put my thoughts better
than I already have:
<quote>.
</quote>
Further response to your 27Oct:
> That's it.
There is more. The Delegator mixin exposes its delegate attribute.
Without that, it would not be possible to pass e.g. insert() down the
chain because (in the case of the Text percolator) insert() is found
in each filter and blocks 'transparent' access.
I agree with your two use cases, but repeat that transparent access is
dangerous in that the class in which the attribute is being looked up
changes for each link on the chain. You could get unexpected results.
IMO you are giving up stability for convenience. "Explicit is better
than implicit."
> (Caching is just an implementation detail, whose only purpose is to
> facilitate changing a Delegator's delegate.)
Don't believe everything you read. While that comment in the code is
true, it's not the whole truth. If 'transparent' access is made to
an attribute further down the chain, that attribute will be actually
cached, i.e. be set as an attribute, in each DelegatorNode. I imagine
this was done for performance reasons. The Delegator.__cache is used to
determine which attributes to delete if a delegate is changed.
I'll defer the Percolator comments until later.
> Now, it seems to me that you aren't looking at Delegators and
> Peroclators as transparent proxies at all.
Not so. That's my 2. in my msg56862 27Oct. But I see filters as
having two modes of operation. In the first, they take an action
like insert() and share it explicitly along a chain of authority.
Each link takes specific action, and passes insert() along.
They also provide transparent access to attributes down the chain, as you
note. But once an attribute is found it will not propagate unless
explicitly passed along, and that requires the self.delegate attribute.
> 1) Should Delegator delegate calls to callables
No, I agree they should. The question is whether it's necessary to add a
__call__() method to the Delegator class. I claim you can do what you want
to do without it. It serves only one purpose that I can see: you want to
delegate to a callable by calling the instance at the top of the chain, and
one of the chain members isn't callable. I don't see a use case for that,
YAGNI.
I'll defer the Percolator discussion for now. There is more to it than just
the inheritance issue.
I found your example1.py to be confusing. Please stop using the word
'delegator', it's too overloaded in this discussion!
I marked up example1.py as example1a.py, changing some names and adding some
I also worked up example2.py which seems to cover the possible combinations
of proxying functions, callables, and methods. It works without adding
__call__() to Delegator. Please check it out, what more do you need?
I'll be away until Sunday, so I can't respond further until then.
Do you have any further comments on this issue?
|
http://bugs.python.org/issue1252
|
crawl-002
|
refinedweb
| 2,327
| 56.35
|
Hello everyone. I am having hard times in dealing with this problem which I've been given. It simply asks me to shift an array K positions without using additional memory. I cannot ask them what they mean by that. No memory, like... not even using a temporary variable for the loop?!
Here is an example:
1 2 3 4 5 6 7 8 shifted 3 times to the right gives:
4 5 6 7 8 1 2 3
Of course, the array is not sorted necesarray, that was just an example.
#include <iostream> using namespace std; void shiftArray(int numbers[], int sizeofArray, int k) { int index; for(index = 0; index < sizeofArray; index++) { if(index >= sizeofArray - k) { numbers[index] = numbers[index % (sizeofArray - index)]; } else { numbers[index] = numbers[index + k]; } } } int main(int argc,char* argv) { int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8}; int k = 3; int sizeofArray = 8; shiftArray(numbers, sizeofArray, k); int i; for(i = 0; i < sizeofArray; i++) { cout << numbers[i] << " "; } cout << endl; return 0; }
This is my code so far. I know I used a temporary variable for the size, but that was because I cannot do it with sizeof...
Also, the problem is that after updating the first sizeofArray - k numbers, the last k numbers will be updated with the replaced values and not with the original ones... can someone please tell me how should I correct it? Or at least give me another way of looking at the problem? Thanks for your time.
|
https://www.daniweb.com/programming/software-development/threads/356693/shifting-arrays-k-positions-without-using-additional-memory
|
CC-MAIN-2018-13
|
refinedweb
| 251
| 59.84
|
2,57 Related Items Preceded by: Highland news (Frostproof, Fla.) Table of Contents Main page 1 page 2 page 3 page 4 Main: Classifieds page 5 page 6 Full Text Frost roof ews Thursday, February 02, 2005 Vol.91 No.33 Council Meet- ing will be held Monday, Feb. 20, at 6 p.m. Frostproof City Hall is located at 111 First Street. For more information call 635- 7855. FREE tax aid at LMML Free Federal Income Tax Assistance and E-file hours for FREE tax assistance Feb. 1 to April 15. Volunteers with the AARP TaxAide program will be at the Latt Maxcy Memorial Library, located on the corner of Wall Street and Magnolia Avenue, to assist in preparing and E-filing 2005 personal Fed- eral Income Tax Returns. Tax- payers should bring picture identification with them as well as Social Security cards for all family members. Please bring a copy of your 2004 Federal Income Tax Return and all nec- essary papers for filing 2005. Art League meeting Feb. 7 The Frostproof Art League's February General Meeting will be at 6:30 on Feb. 7 at 6:30 PM. President Leon jGitlordrl \1i pre:- ' sideover a shortbusiness meet ing. The program \will feature artist and doll maker, Jean Kon- wick of Lake Wales. Jean will be speaking on making porce- lain dolls. Samples of her work are on display in the Frostproof Art Gallery. Project Graduation meeting Feb 13. Project Graduation seeks parent involvement Attention parents of Frost- proof High School Seniors! There will be a ProjectGrad- uation meeting Feb. 13, 6:30 p.m. at the high school TV Pro- duction priority to get inrvok ed in this major event for yourson or daughter. LMML Annual Art Show The'Latt Maxcy Memorial Library will host their Annual Art Show Feb. 1 through Feb 28. ll artists may have 2 origi- nal entries ,2-D). All artwork must be suitable for hanging. All entries will be due by Friday, Jan. 31.Artwork. See Page 2 forinformation about how to Contact the newspaper. newszap.com newsbloginfo Online news & information 8 1 6 5 10 0002 4 Church presents musical The First United Methodist Church of Frostproof has many exciting events planned for Feb- ruary, and the public is invited to all of them. On Friday, Feb. 3 at 7 p.m. in the sanctuary, the Sonshiners Quartet will share the love of Christ through the rich sounds of "Southern Gospel" music that creates an atmosphere for wor- ship! The Sonshiners were founded in 1973 in southern Indiana and give over 120 per- formances each year. They have been involved in over 17 album projects. A love offering will be taken. On Saturday evenings Feb. 4, 11 and 25, the Church will hold a Country Western and Gospel sing featuring "Claude Vance and Friends." Admission is free to this musical worship that takes place in the Fellowship Hall at 7 p.m. The United Methodist Women are hosting a dinner on Saturday evening, Feb. 11 from 5 to 6:30 PM in the fellowship hall. For the price of $7, enjoy a dinner of ham, scalloped potatoes, green beans, applesauce, roll, beverage and dessert. Stay around after dinner to hear country western and gospel band, "Claude Vance and Friends." Dinners will also be available for carryout. If five or more dinners are ordered, deliv- ery will be available. Tickets are available by calling the church office at 635-3107. Beginning on Sunday, Feb. 26, a one-hour Lenten Bible Study, "Living with the Mind of Christ," will be available each Sunday at 9:15 a.m. The series will conclude on Easter Sunday. If interested, contact the church office at 635-3107 to sign up. The cost of the study book is $5.50. The First United Methodist Church of Frostproof holds weekly worship services on Sun- days at 10:30 a.m. at 150 Devane across the street from the Latt Maxcy Memorial Library. Sunday school begins at 9:15 a.m. For additional information, please call the church office at 635- 3107. Local News: Two Postal Clerks retire F roslprooI Iews'Gminoy MIVOIK FP Postal employees honored Mike Fann and Calvin Gavin Jan. 26 with breakfast and gifts. Pictured are former Frostproof Postmaster Garry Jones, Mike Fann, Present Post- master Rick-Benson and-Calvin Gavin. Mike Fann and Calvin Gavin reminisce Postmaster Rick Benson looks on as over old times at the Post Office. Both of Calvin Gavin holds up a T-shirt he received these gentlemen are looking forward to Jan. 26 from fellow employees as a retire- their retirement. ment gift. Fann and Gavin say goodbye By Cindy Monk Mike Fann and Calvin Gavin said goodbye to fellow employ- ees at the Frostproof Post Office on Thursday, Jan. 26,2006. Several former and present Postal employees gathered at the Frostproof Post Office for a farewell breakfast to honor Fann and Gavin for their severalyears of service. Mike Fann \\as employed with the Post Office for over 30 years and Calvin Gavin had over 35 years in. It was a teary eyed goodbye as several of the Postal workers. reminisced about memorable moments they had with their co-workers. Some memories were happy, some sad; Looking back through the years, Calvin and Sherrie Collins shared a story when Sherrie was pregnant and very close to her due date. They went on to say, Sherrie deliberately placed some water on the floor below her, and called Calvin to please come quickly. Sherrie told Calvin her water had broke, call 911. Calvin was so nervous he asked another co-worker for the number to 911. Little pranks and gags would be played every now and then in order to break the monotony. Mike Fann, said one of the Postal duties that stood out in his mind is the Christmas mail- ing for the Ben Hill Griffin Cor- poration this was an annual event. Another big event that Mr. Fann said he remembered was when the Post Office relocated to the present location it took a lot of work but was well worth The Sonshiners Quartet Busy weekend in Frostproof A lot of plans are under way morning with an open air flea for the weekend of Feb. 17 and market to be held at the Wall 18. There will be a myriad of Street City Park beginning at 7 activities for all to enjoy. The a.m. Vendors and residents will weekend will kick off Friday be selling treasures of all types. evening with the arrival of the In conjunction with all of FlI\ heelers association in the other activities Mr. O'Hara's preparation for the "We Drove annual antique car show will through the Grove" annual be occurring. This event will tractor ride. This' event will bringantique cars from around bring antique tractors a bring antique cars from around bring antique tractors and the state to line the streets of other vehicles of interest to e sdtownFrostproof. downtown Frostproof, where downtownFrostproof. they will head, out Saturday To wrap things up, Saturday morning to their destination at evening, the Rotary Club's the Fihv. heelers camp. To... annual Wild.Game Dinner will accompany\ the arriaal of the begin 6 p.m. at the Depot. For Flywheelers an outdoor Friday more information on these evening concert is scheduled to events please contact Mr. be held on Wall Street that will O'Hara at 863-635-9008, and feature local talents. for Wild Game Dinner tickets The fun continues Saturday please call 863-635-2523. Relay for Life plans tourney The Frostproof Relay for Life committee will sponsor their First Annual Bass Tournament Saturday, March 18 on Lake Reedy Lake. Registration fee is $50 per boat with a late registration fee of $10 per boat the day of the tournament. Please make checks payable to: The Ameri- can Cancer Society. Eligibility requirements are as follows. This \\ilI be a team event open to all individuals, 18 yeais of age or older with a paid entry fee. A parent or legal guardian must accompany any one under 18 years of age. A team may consist of one (1) angler per boat or two (2) anglers per boat. This is an amateur event, no See Fishing Page 2 SFCC features area bands The South Florida Commu- nity College Matinee Series con- tinues with an exciting concert with local musicians. Two bands will be featured during the concert which takes place on Tuesday, Jan. 31, at 1:30 p.m., in the SFCC Auditorium, Highlands Campus, Avon Park. The Highlandaires, a 16-piece big band of Florida, includes members who have played with the nationally known big bands during that genre's golden age of the 1930s and 1940s. The other group that will be per- forming is Emanon. Emanon is a local jazz quartet featuring Doug Andrews (piano), Davis Collister (bass), Bill Anderson (drums), and Dave Naylor (trumpet and flugelhorn). The Highlandaires' rendition of "In the Mood," "Tuxedo Junction," "Leapfrog," and "Sentimental Over You" are favorites with their audiences. The SFCC Matinee Series wel- comes back the local big band sound of the Highlandaires for the third time. Emanon is best known for their concert in the park series at Highlands Hammock State Park. The concerts in the park in 2002 quickly expanded to numerous concerts in Central Florida. Performing in various gated communities and retire- ment villages in the Heartland, Emanon has developed a repu- tation for excellence in playing the music of the jazz greats and the great American song book. If you grew up hearing the music of what arguably has been called "the golden age of jazz-popular music," you will recognize most of the classics that Emanon performs. The SFCC Matinee Series season of performances is co- sponsored by Tim and Martile Blackman/Captain D's Seafood and Rick and Jean Moyer. A limited number of tickets are available for this afternoon of music. Tickets range from $11 to $8. To purchase tickets or for information, contact the SFCC Box Office, weekdays, from 11:30 a.m. to 2:30 p.m., at extension 7178, at (863)453- 6661, 465-5300, 773-2252, 494- 7500, or directly at (863)784- 7178. Frostproof News/Cindy Monk FMSHS receives new books Frostproof Middle Senior High School Principal Steven White and English Teacher Linda Baquero visited the Frostproof Rotary Club Jan. 19 to thank them for provid- ing to the school 31 hardback copies of the book "A Land Remembered" by Patrick D. Smith. In November, Mrs. Baquero sent a letter to the Rotary Club, explaining that she taught a unit on this book and that the paperback copies in her classroom were falling apart. She went on to say that the students enjoy "hearing the novel read aloud, but they also cannot wait until it is their turn to read." The Rotary Club completed a grant application, and Wal-Mart partnered with the Rotary in the purchase of the books. Also pictured is Frostproof Rotary Club President Bea Reifeis. ouuIIIILt.U Ut r-rosprouu INews 2 The Frostproof News, Thursday, February 2, 2006 Fishing Continued From Page 1 profession fishermen or guides please. All teams must cull down to their limit of five (5) fish before returning to the official ramp site. The five (5) fish must measure a minimum of fourteen (14) inches. All local and state rules apply. Dead fish presented for weigh-in will result in a four (4) ounce deduction from total weight. If it's the big bass then the reduction shall be assessed against that fish. Only largemouth bass will be scored. Teams presenting fish for weight which are determined to be short (under 14 inches) will be penalized the weight of that fish plus the big fish of the sack. Once We Pledge ... * To operate this newspaper as a public trust To help our community become a better place to live and work. through our dedication to consci- entious journalism. To provide the information citizens need to make Iheir own intelligent decisions about public issues. STo. the fish have been turned in for scoring they become property of the tournament and the team relinquishes all rights to the fish. Late penalty: one pound per minute up to ten (10) minutes then disqualification. Ties: All ties will be broken by 1) big fish; 2) most fish weighed in. In the event of big fish tie the money will be split. Teams must begin from and return to the designated launch site. Send registration and payment to: Mr. Anthony Sackett, 504 Lauterbach St., Frostproof, FL., 33843. For more information please call Tony Sackett at (863) 635-5456. This years American Cancer Society 'Relay for Life' will be held Friday, April 7, and Saturday, April 8 at the Frostproof Middle Senior High School campus. are also willing to provide ten percent. more fireworks if the total cost is paid by March 1, 2006. $5,700,has been committed to by local businesses and residents towards the $10,000 cost. Dona- lions can be made by calling Jimmy Scarborough at 635-2645 or Jim Harmon at 635-2244. Office Coordinator: Cindy Monk Advertising Director: Judy Kasten National Advertising: Joy Parrish Independent Newspapers, Inc. * Joe Smyth, Chairman * Ed Dulin, President - Tom Byrd. Vice President of Newspaper Operations SKatrina Elsken, Executive Editor MEMBER O-- OF: - Florida Press Association For More Information See At Your Service On Page 2 Thrift store has extended hours The Frostproof Care Center Thrift Store is now open from 9 a.m. to 5:30 p.m. on Thursdays. The extended hours are to make shopping more convenient for the working public. The hours for Monday through Wednesday and on Friday continue to be 9 a.m. to 3 p.m. Saturday hours are 9 a.m. to 12:30 p.m. Ralph Waters, executive direc- tor said, "Come and browse through our wide selection of items. Our volunteers have been busy making the store more attractive and organized. The sales from the store are used to fund Care Center programs that aid individuals and families in the Frostproof area." Lions Clubs Annual fertilizer Frostproof Police Department Incident Report Sale February 4 January Week of Jan. 1 through Jan.7 Officers responded to distur- bances on Oak Avenue, Virginia Street, and Overocker Circle. Officers responded to a suspi- cious person in the area of Pep- pertree Apartments. A minor traffic accident occurred on Wall St. Crimes reported Jan. 15 through Jan. 21 A minor traffic accident occurred on County Road 630 at the railroad crossing, a minor traf- fic accident also occurred on State Road 17 at Fifth Street. Someone passed a $100 coun- terfeit bill at Futral's Foodway. Crimes reported Damage to the Frostproof High School Baseball field was report- ed. A skateboard was reported Identity theft by social security stolen from Virginia St. card was reported. Arrests Officer Warren arrested a man for possession of a fraudulent ID card on Fourth Street. Officer Church arrested a man on Lauterbach Street for an out- standing warrant. Jan. 8 through Jan. 14 Someone passed a $20 coun- terfeit bill at Futral's Foodway A minor traffic accident occurred in the parking lot at Frostproof Middle Senior High School. A traffic accident occurred on CR 630 near N. Lake Reedy Blvd. Crimes reported A woman reported the theft of her Credi Caid Arrests Officer Brimlow arrested two men for trespassing in a cultivated field behind Maryland Fried Chicken. Officer Church arrested a man for domestic violence on C Street. Arrests Officer Church arrested a man for domestic violence on Beverly Street. Jan. 22 through Jan. 28 A minor traffic accident occurred in the parking lot of Frostbite, a minor traffic accident occurred in the parking lot, of McDonald's as well. Officers responded to a distur- bance on West Eighth Street. Arrests Officer Church arrested a man for No Valid Drivers License. Officer Davis arrested a man .on at Peppertree Apartments for an outstanding warrant. Officer-Church arrested a woman at Frostproof Villas for an outstanding warrant. Officer Brimlow arrested a man for Felony Habitual Traffic offender. Sergeant Hood arrested a female for shoplifting at Little Dixie #3. The Frostproof Lions Club will hold their annual fertilizer sale Saturday, Feb. 4, from 8:30 a.m. to 4:30 p.m. in front of Futral's Food- way on County Road 630. The cost is $7 for 50-pound bags of 6/6/6 all-purpose fertilizer. Delivery is free inside the city lim- its for a purchase of five bags or more. Purchases may be made by phone at 863-635-2902. Scholarship deadlines approach The Polk Education Founda- tion is trying to make sure word gets out to all Polk County pubic high school seniors and their par- ents about the.opportunities the foundation has available for scholarships to aid students who are graduating this year. The Foundation has contacted all Polk public high school guid- ance counselors, colleges and career lab mangers in an effort to enlighten all Polk County seniors. Time is of the importance with many deadlines approaching. The deadline for applications to be turned into the school is Mon- day, Feb. 13 and the school will in turn send the applications to Polk Education Foundation by Friday, Feb. 17. The Frostproof Relay for Life a survivor registration form. Committee would like to extend a special invitation to all cancer sur- Lowes Distribution Cent vivors, to be honored.guests at once again sponsor the Sur this years' Relay for Life to be held Dinner and all cancel suu at the Frostproof Middle Senior are encouraged to attend High School campus Friday, April. American Cancer Society 7 and Saturday, April 8. If you or donate T-shirts and other someone you know is a cancer sors will have surprises for survivor please contact Sandy yivors attending. Tharnrk ,:ou Sacketl at 863-635-5456 to receive: oui support! The Polk Education Founda- tion gave almost 300 scholarships last year totaling approximately $500,000 and will do the same this year. To view the PEF brochure, application, criteria and awards visit PEF at- fl.net/PEF/Foundation/scholar- ship.htm. Students and parents for more information about scholarship programs available please con- tact your local public high school guidance office. The Mission of Polk County Public Schools is to ensure rigor- ous, relevant learning experi- ences that result in high achieve- ment for our students. J.G.W'EN-TWRTH. ANNUm PU1C-ASE PROOGRAM ouu)-rU IiU~r er will vivors Silver s i. The y will spon- all sur- for all To save time and money by having the news- paper delivered to your home by mail.. n - FrostproofNew*^ , Frostproof News Published by Independent Newspapers. Inc. Serving Frosiprool Since 1915 To Start or Stop A Paper Phone: 177] 353-2424 E-mal: readerservices@newszap corn The Froslproof News is delivered Dy mall to subscribers on Tnursda, and is sold in racks arnd store locations in ine Frostprool area. Call 877-353-2424 to rportn a missel newspaper or poor delivery Tne FrosTproof News USPS No 211-260 Published weekly by Independent Newspapers Inc PO Box 67 Frostproof. FL 338-13 Penodicals Postage Paid at Frostproof. FL Subscription cost is $24 61 per ,ear including tax Second Class positaOe paid at Froslproof Flonda Postmaster Send address change. o the Frostproof News. PO Bo. 67. Froslprool. Florida 33843 Printing Pnnied at Sunshine Pnnlinr a subsidiary of Indeperndern rN ,- car.ers. Phone: 863-465-7300 Enla8: pnniing@cl net Newszap! Online News & Information Gel Ire laIes local ne^s at HIDDEN CITRUS *Gift Shop Florida Souvenirs a Cfe .DEJ tN FROM OUR KITCHEN ""-, hili Bruns\\ick Stew Chili Dogs Cookies Smoothies Pressed Cuban Sandwiches r: :Strawberry Shortcake OPEN DAILY 9-5 SUNDAY-5 CR 630 A., Frostproof 1 Mile E. of U.S. Hwy. 27 Hydroponic U-Pick-We Pick L. In Season Now: Strawberries & Vegetables 635-4302 1-800-334-6720 Denial Experrence. e-mail Info@lakewalesdental.com One Doctor's Lane Lake Wales. FL Dinner planned to .,uOut,. honor Cancer survivors CasllGWentworth, Annuity Purchase Program Chamber seeks donations for firework display joumalistic service, commitment to the ideals of the First Amendment of the U.S Constitution, and support of the community's deliber- ation of public issues. To Reach Us alhdIs: P. O. Box 67. Frostproof, FL 33843 WeOIISB : To Submit News Tne Frostproof News welcomes sub- missions from its readers Opinions. calendar ilems, stones, ideas and photographs are welcome Call (8631 635-2171 to reach our newsroom Items may be mailed, faxed or e- mailed The deadline for all news items is Noon Friday prior to the fol- lowing Thursday's publication E-Mail: froslnews@newszap corn Fax: 863-635-0032 To Place A Display Ad oIhtn 863-763-3134 En 234 The deadline for all advertising is noon Monday for the following Thursdays publication E-Ma okecompo@strato.net To Place A ClassImled Ad afl 817-1i3-22 Iao place a classified advertisement from home. The dead- line for all advertising is noon Monday for the following Tnursday's publication. Fa: 877-354-2424 E-MBa: classads@newszap com Billing Department E-MaI: billteam@newszap.com DOUBLE YOUR INVESTMENT IN ONLY 1 YEAR! Builders Lots Available in the Fastest Growing Areas in Florida Polk County's Oldest & Strongest Bank Founded in 1920 C CitiZENs BANk (863) 635-2244 2 E. Wall Street, Frostproof FDIC NOTICE OF ELECTION An election will be held on April 4, 2006 in the City of Frostproof, Florida to elect a city council member to Seats #4 and #5, each for a three-year term. Electors of the City of Frostproof are eligible to vote in this elec- tion. Qualifying for candidates will begin at noon, February 13, 2006 and end at noon, February 17, 2006. Packets may be picked up after January 31, 2006 at the office of the City Clerk, 111 West First Street, 2nd Floor, Frostproof, Florida. II _ I The Frostproof News, Thursday, February 2, 2006 Polk County Education Briefs PCPS teacher recruitment Polk schools hold meetings to recruit new teachers Polk public schools will hold infor- mationmarked or received electroni- cally during the open enrollment period will be a part of the initial lottery selection for magnet and choice school students. Applica- tions received Jan. 31 through Feb. 17 will be assigned a waiting list number based on the date received. Applications will be available online at- choice, any magnet or choice school or the district administra- tive office in Bartow. For addition- al information, contact the Office of School Choice at (863) 534- 0631. Dates set for FCAT retakes FCAT retakes for students with a certificate of completion from a Florida high school will be given WGD to raffle Canadian fish trip The Frostproof Rotary Club and the Frostproof Rotary Charita- ble Foundation will be holding its 23rd Annual Wild Game Dinner on the evening of Saturday, Feb. 18 at the Depot in Friendship Park in Frostproof. This year's Wild Game Dinner will feature a raffle of a 3-day Canadian fishing trip for two at Budd's Gunisao Lake Lodge. A total of 400 tickets will be avail- able for sale from Frostproof Rotarians for $20 each. Each tick- et gives the purchaser a chance to win this amazing trip! The trip includes overnight lodging in Winnipeg upon arrival, a 500-mile round-trip flight from Winnipeg to the Lodge, comfortable accom- modations at the Lodge, home cooked meals and daily maid service at the Lodge, and world- class fishing with a guide on an Alaskan Lund boat. The trip will take place at a mutually agreed- upon date in the 2006 season. The prize does not include trans- poutaiion to Winnipeg. Gunisao Lake offers some of the finest tro- phy-size Walleye and Northern Church Directory First Baptist Church of Frostproof Daryl Hood-Pastor First Baptist Church of Frost- proof, 96 West B Street is offering a new Celebration Worship Ser- vice on Sunday's, at 8:15 a.m. This service offers a more con- t rn por at style of mnusic while the Celebration Worship at 10:50 a.m. will remain more traditional in nature. Childcare will be avail- Pike fishing in the world. More Master Angler Walleyes (28 inch- es plus) are caught in Gunisao Lake than any other lake in Mani- toba, and pikes ranging from 36 to 40 inches are common! Get your tickets now before they sell out! You need not be present to win! The dinner will be in full swing at 6 p.m. when the gates open! Small tents will be set up around a center social area, each serving its own specialty food item. Guests may wander from tent to tent and sample gator ribs by Gatorama, gator tail, barbecue hog, sausage, elk meatballs, venison filet mignon, venison roast, venison pilaf, tilapia, fried turkey breast, fried cornbread, baked beans, cole slaw, corn on the cob, soft drinks donated by Highlands Coca-Cola, and swamp cabbage! There will be time to enjoy many displays and exhibits, and to purchase raffle tickets for a chance to win one of several guns. Local country western band, "Claude Vance and the Sun- shine Folks," will provide the able for both services. For more information call 863-635-360. entertainment for the evening., Bill Jarrett Ford, Budd's Gunisao Lake Lodge, Cargill Juice N.A., Gatora- ma and Howerton Farms for their donations that will ensure the success of this event that funds educational and charitable proj- ects in the local community. Adult ticket prices are $50 per person, student tickets for ages 13 to 18 are $25 each, and tickets for children ages 6 to 12 are $15 each. No alcohol will be served. For tickets or information, call a Frost- proof Rotarian or Frostproof Rotary Club President Bea Reifeis at (863) 635-2523. First Christian Church of Frostproof Albert Fidler-Evangelist First Christian Church of Frost- proor, 2241 County Road 630 W., Sunday School 9:30 a.m., Wor- ship Service. 10:1b,a.,-i.- Sunday, Evening Worship 6 p.m. Wednes- day Evening Bible Study 6 p.m. For more information call 635- 6700. No I Pler. lo, ur m .. ,ProslI on Monday, Feb. 27 and Tuesday, Feb. 28. The deadline to register for FCAT retakes is Friday, Feb. 17. The reading portion will be given on Feb. 27 and the math portion on February 28. The tests will be given test at any school, regardless of where they received a certifi- cate of completion. Development of SWeb Applications Websites Tailor-made Software Call Today: Logos & Graphic Design 786-419-5555 Ios&rahDei or visit:; A yerticalechnol6gles Check us out Online ALL STEEL BUILDINGS 1.. 25 x 25 x 7 All Steel Garage (2:12 pitch) iGarage Doors, 1 Entry Door, 2 Gable Vents, 4" Concrete Slab (see photo) Installed- $16,995 We Will/ Help You Design A Building To Meet Your Needs - \We Custom Build (WVe are the factory) - Many Sizes A% ailable METAL SYSTEMS LLC - Meets or Exceeds Florida Wind Code 80a-20aa Florida "Stamped" Engineered "w.t0al Drawings (included) SMortgage Highway 30 Year 1% Mortgage! "'. .* -- = :- ., $200,000 at 1% payments only $643.28 $500,000 at 1% payments only $1609.50 L- iiiii nli iii iiiii .i~i_ ^ ___ Ljo- i $300,000 at 1% payments only $964.92 MAu I - 1-888-HIGHWAY NET hiddefl 4 The Frostproof News, Thursday, February 2, 2006 Obituaries Wheelin' Sportsmen Fishing event Evelyn Margaret Dibble Evelyn Margaret Dibble, 57, of Frostproof died Saturday, Jan. 28, 2006 at her resi- dence. born Jan. 15, 1949 in Water Loo, N.Y., and came here from Northfolk, VA., in 1990. She was a homemaker and a member Evelyn of the First Bap- Margaret tist Church of Dibble Frostproof. She was preceded in death by her Husband David Dibble in 2004. Survivors include Daughters: Karyn Ham of Frostproof, Chris- tine Weech of Lake Wales, FL., Brother: Jerry Safranas of W Jor- dan, Utah. Sisters: Judy Dunn of Frostproof, Gail Whirilter of Canandaigua, NY., and 3 Grand- children. Graveside services were held Wednesday, Feb. 01, 2006 at the Silver Hill Cemetery, Frostproof, Florida with Rev. Rick Giles officiat- ing. Marion Nelson Funeral Home of Frostproof, Florida is in charge of local arrangements. Curtis Dale Wineberger Curtis Dale Wineberger, 38, of Watkinsville, Georgia died Sunday, Jan. 22, 2006 in Oglethorpe, Geor- gia. He was born May 29, 1967 in Lakeland, FL. He came to Frost- proof from Athens, Georgia 1 year ago. He was self-employed as a tile setter and was of the Baptist faith. Survivors include his Father; Jerry C. Wineberger of Homosas- sa Springs, FL., Mother and Step-Father: Sandra and Walter Respress of Frostproof. Daughters: Lacy R. Wineberger of Greenville, S.C. and Charity Wineberger of Mooresville, N.C. Son: John Curtis Wineberger of Greenville, S.C. Sisters: Chelene Wineberger and Shelly Turner both of Frostproof. Companion: Shannon Todd of Watkinsville, Georgia. Services were held Saturday, Jan. 28, 2006 at the Bougainvillea Cemetery in Avon Park, Florida with Rev. Darrol Hood officiating. --- ------ - i- --------- li_; Marion Nelson Funeral Home of Frostproof, Florida is in charge of local arrangements. Ruby Christian McFarland Ruby Christian McFarland, 86, of Frostproof died Monday, Jan. 23, 2006 at Spring Lake Nursing Home. She was born Jan. 18, 1920 in Okeechobee, FL., and came here from Lake County, FL., in 1943. She was a homemaker and was affiliated with the Church of God. She was preceded in death by her Husband Clyde Nicholas McFarland in 1991. Survivors include her Daugh- ter; Brenda Gail Meeks of Lake- land, FL., Sons; Thurman Dean McFarland of St. Cloud, FL., Nathan D. McFarland of Frost- proof, FL. 8 Grandchildren, 3 Great-Grandchildren. Graveside services were held Friday, Jan. 27, 2006 at the Silver Hill Cemetery, Frostproof, Florida with Rev. Rex Daniels officiating. Marion Nelson Funeral Home of Frostproof, Florida was in charge of local arrangements. HOMESTEAD EXEMPTION OFFICIAL NOTICE 2006 FLORIDA LAW REQUIRES FILING FOR HOMESTEAD EXEMPTION, DISABILITY, WIDOW, WIDOWER, SENIOR 65 OR OLDER, OR ANY OTHER EXEMPTION MUST DO SO IN PERSON AT YOUR COUNTY PROPERTY APPRAISER'S OFFICE. AGRICULTURAL CLASSIFICATION CAN BE FILED BY MAIL PROVIDING THE CORRESPONDENCE IS RECEIVED BY MARCH 1, 2006. THE STATUTORY FILING DEADLINE IS MARCH 1, 2006 ANYONE WHO HAS MOVED DURING 2005 MUST FILE A NEW HOMESTEAD APPLICATION ON THEIR NEW PROPERTY. TO CHANGE YOUR EXEMPTION IN ANY WAY, YOU MUST FILE A NEW APPLICATION IN PERSON. REQUIREMENTS TO QUALIFY FOR PROPERTY EXEMPTION/CLASSIFICATION $25,000 HOMESTEAD: You must have recorded title to the property and reside thereon as your legal permanent residence on January 1st. Bring evidence of ownership proof of permanent residence. FLORIDA STATUTE 196.012(17) "PERMA- NENT RESIDENCE" means that place where a person has his or her true fixed and permanent home and principal estab- lishment to which, whenever absent, he or she has the intention of returning. A person may have only one permanent res- idence at a time. The following factors will be considered by the Property Appraiser in determining the intent of a person claiming a homestead exemption to establish a permanent:residence in this state: (A) Florida Auto License Registration and Florida Driver's License (B) Voter Registration (C) Social Security Number (D) If employed, current employer's name and address (E) Address shown on the last IRS return (F) If not a U.S. Citizen, submit Permanent Resident Alien Card $500 DISABILITY EXEMPTION: Provide proof of total and permanent disability by one licensed Florida physician, or the Social Security Administration. The statement must indicate that the disability is Total and Permanent. $500 WIDOW'S AND WIDOWER'S EXEMPTION: Must be a legal resident who is a widow and widower on January 1st. Must provide copy of Death Certificate. Divorced persons do not qualify. $500 BLIND DISABILITY: Provide a statement from the Florida Division of Education/Division of Blind Services. $500 VETERANS DISABILITY: Must provide a letter from the Veterans Administration stating that you have a service related disability of at least 10%. SERVICE CONNECTED TOTAL AND PERMANENT-DISABi..IrT' EXEMPTION: Total exemption from Ad Valorem Taxes; applicant must furnish letter from V.A. or U.S. Govenment showing they are total and permanently disabled, the di.iabliht i- service connected and the\ ,were honorable diwhargd- TOTALLY AND PERMANENTLY DISABLED PERSONS: As provided by F.S. 196.101 (Contact your Property Appraiser for details). SENIORS OVER 65 EXEMPTION: As provided by F.S. 196.075(4)(d). (Contact your Property Appraiser for details.) AGRICULTURAL CLASSIFICATION: To qualify land for Agricultural Classification, a return must be filed with the Property Appraiser by March 1st of the tax year. Only lands used for bona fide agricultural purposes shall be classified agricultural. "Bona Fide Agricultural purposes" means good faith commercial agricultural use of land. IF YOU HOLD TITLE TO A MOBILE HOME AND THE LAND ON WHICH IT IS SITUATED, YOU MUST MAKE APPLI- CATION TO THE COUNTRY PROPERTY APPRAISER TO HAVE YOUR MOBILE HOME ASSESSED AS REAL PROPER- TY. THIS APPLICATION REQUIRES'YOU TO PURCHASE A RP DECAL. BRING REGISTRATION OR TITLE TO THE !1 IOB i E HOMK E ND DEED TO YOUR PROPERTY. REPRESENTATIVES OF THE PROPERTY APPRAISER WILL BE IN THE LOCATIONS BELOW TO ASSIST YOU WITH APPLICATIONS FOR HOMESTEAD, DISABILITY, WIDOW/WIDOWER, SENIOR'S 65 OR OLDER EXEMP- TIONS. AND AGRICULTURAL CLASSIFICATION. Muond.a' F.bruarN 6th Tuesday, February 7th Wednesday, February 8th Thursday, February 9th Friday, February 10th Poinciana-Community Center comer of Marigold & Walnut Poinciana Community Center corer of Marigold & Walnut Solivita 395 Village Drive Ballroom A&B Solivita 395 Village Drive Ballroom A&B Davenport City Hall Commission Room comer of Williams Street Lake Wales Public Library 290 Cypress Garden Lane' 10:00 3:30 PM 10:00 3:30 PM 10:00 3:30 PM 10:00 3:30 PM 10:00 11:00 AM 2:00 3:30 PM Courtesy of the National Wild Turkey Federation People with disabilities are invited to enjoy a morning of fishing at the Avon Park Air Force Range with the National Wild Turkey Federation's local chapter and Wheelin' Sports- men program Saturday, Feb. 4. Check-in for the event will begin at 7:30 a.m. at the Out- door Recreation Building on the Avon Park Air Force Range. The fishing portion of the event will start at 8 a.m. and fin- ish around 11 a.m. After a morning of fishing, participants will be served hot- dogs, hamburgers, chips and drinks. Bait and fishing poles will be provided, but early registra- tion is encouraged to ensure enough supplies are on hand for the event. Wheelin' Sportsmen NWTF is dedicated to providing people with disabilities, including hunters, anglers and other out- door enthusiasts with disabili- ties, opportunities to participate in outdoor activities. Visit room/press_releases.php?id= 11 726 for complete press release and photos. Contact: Mike Blanton, NWTF's Wheelin' Sportsmen regional coordinator in Florida, (864) 388 -7931. For more information about the NWTF, contact Jonathan Harling or Brian Dowler at (803) 637-3106. Memorial Tribute Remember a loved one who has departed with a special/iemorials for sample ads and an online order form, or call 1-866-379-6397 toll free. HOM~E Of ThE "ORIG6AAI 0 1 . -it,..... ';".... ^.... .. , : : ,, .- .-.^ ', -,..., . ..n. ,' ....., ...... ._.-.; .r,.s,-..., *'', --.... --, . -- ~~'1x, : -. ,,,: :.'. ,, -,ff" ". .. y;, -'.,. ;-1# z-. Make up to $2500 .. by filling in the space above! Sea IU'y e)So ieOl aluobles iJf" they're $2,500 or less for absolhtelY lP e! No fee, n catch, ito pprobleis! * 4 lines for 2 weeks * Price must be : included in ad f Private parties e." gfi nou.. rcse- ^yeri~sue .-,, -,-.-: -.- -: ---:'--- -" ,-- :-1 use priced i t in less .P!... *Independent Newspapers reserves the right't disqualify any ad. Frostproof News Toll Free 877-353-2424 E-Mail: classad@newszap.com I AUCTIO 772-466-1930 2103 Sunrise Blvd. Ft.Pierce ALL HOUSE & MOBILE HOME REPAIRS Interior a Exterior Painting and Pressure Cleaning NO JOB TOO SMALL! Gary Hicks 863-528-3032 Home: 863-635-7276 I i9 l1.-in4 .C.-Y 100 years combined dental experience LAKE WALES DENTAL Your Loose Dentures Made to Fit 863-676-8536 One Doctors Lane Lake Wales, FL 33853 M.Max Weaver, DDS 863-635-0030 boUntry Music Realty, Inc. (863) 676-2788 Lake Wales, FL Nationwide Advertising "No One Knows The Country Like We Do"* No il., mi [a] -I Mu, [.-IIIletU I [a] 0 Polk County's Oldest & Strongest Bank Founded in 1920 cb CiTiZENS BANk 2. E. Wall Street (863) 635-2244, SiiL estate Your Friendly Hometown Real Estate Agents 635-2593 FDROST R .OFINR IC. A LOCAL COMPANY We specialize in all types of roofing and repair. (863) 696-0646 If you have a roof problem call and get "Certified" today! ****YOU MAY FILE FOR EXEMPTION AT A SITE LISTED ABOVE OR VISIT ONE OF OUR OFFICES NEAREST YOU.**** 255 NORTH WILSON AVENUE, BARTOW 912 EAST PARKER STREET, LAKELAND 3425 LAKE ALFRED ROAD, 3 GILL JONES PLAZA, WINTER HAVEN DAILY 8:30 A.M. TO 5:00 P.M. THROUGH MARCH 1, 2006. MARSHA FAUX, POLK COUNTY PROPERTY APPRAISER call a professional!" Call 863-635-2171 or email us at okecompo@strato.net to place your ad! I I- - e7~ Frostproof News, Thursday, February 2, 2006 ooI ABSOLU .TELY FREEI For any personal items for sale ABSOJLUTELY FREE$ under $2,500 Announcements Merchandise Mobile Homes | Employment i Financial ulag Recreation i Automobiles il~lll -K Services RealEstate PublicNotices F "T 51M k IIIll Submit Your FREE Classified ad today at You Can Reach The World SWith Your Ad! Rules for placing FREE ads! 4 lines for 2 weeks. IB Price must be included in ad. Ad must contain only 1 item. 2 ads per household. SRegular deadlines apply. Must be personal items for sale under $2,500. Announcements Impori nl Irf.: o-rd -"advertisement'. All ads accepted are subject to c^tdit aprodvdl. All ds mus"f', 259+/- acres, 28 tracts. developer's dream, Cook County, GA, Friday, February 10, 10 a.m. Rowell Auctions, Inc. 8A00)323-8388 10% BP, GAL AU-C002594. Shop here first! The classified ads KEY CHAIN w/ 6 keys. found in Taylor Creek Isles, 24th Blvd. on 1/25/06 (863)763-5422 AFRICAN GREY PARROT: Not banded. Grey w/red tail. Vic. St Rd. 70 & Kissimmee River. "Sparkle" Reward. 467-8629 BOXER, Brown w/white mark- ings, Last seen Jan. 26th in LeBelle. (863)673-2953 Re- ward CAT name Alex, Black w/white patch on neck, w/skin condi- tion, Last seen 1/24, near Red Top Dairy (863)261-1153 Lost 2 EMUS at the end of Fernwood Ln down on the B branch 863-843-2495 LOST PEACOCKS assorted colors, last seen on 64th Ave. by Four Seasons, 1/25 (863)610-1964 LOST Ring in Buckhead Ridge area, antique, spoon handle ring, Reward if found (863)447-5263 MISSING: 2% lb. Tea Cup Yor- kie, 7'/2 yrs. old. Needs medi- cation to survive. $1000. Reward. (772)214-3510 BEAGLES- 2, Females, 3yrs old. Indoor/outdoor. Free To Good Home! (863)634-2149 Cur Dog Mix- 2yo, spayed, fe- male, red/white, to good home only, No Hunters. (863)467-6215/634-4102 FREE PIANO AND DR TABLE AND CHAIRS- over 25 yrs old, needs some TLC (863)673-3913 LAB- Male, 2 yrs old, Loves to Hunt! Free To Good Homel (863)634-2149 SEEKING COMPANION: for 46 year old male. No Drugs, No Alcohol. (863)261-7046 Okee- chobee area. Is Stress Ruining Your Life? Read DIANETICS by Ron L. Hubbard Call (813)872-0722 or send $7.99 to Dianetics, 3102 N. Habana Ave., Tam- pa FL 33607. Find it faster. Sell t sooner in tte classified mploent Employment - Full-Time 205 Employment - Medical 210 Employment - Part-Time 215 Employment Wanted. 220 Job Information 225 Job Training 227 Sales 230. EXPERIENCED RV TECHNI- CIAN Wanted! Dealership in the heart of Race Country needs quality, experienced RV Techs. Great Benefits. Pay based on experience.' Hourly shop. Fax Resume Only to (704)455-1439. No phone calls please. Tom Johnson Camping Center. MOVIE EXTRAS, ACTORS & MODELS! Make $75-$250/day. All ages and faces wanted! No exp. Re- quired. FT/PT! (800)714-7564. "NOW HIRING 2006" AVER- AGE POSTAL EMPLOYEE EARNS $57,000/YR Minimum Starting Pay $18.00/hr. Benefits/Paid Training and Vacations No Experience Needed (800)584-1775 Ref #5600 'PLUMBING & HVAC/R Jobs. Experienced PLUMBING or HVAC/R people needed. To apply for HVAC/R Jobs on- line-, PLUMBING Jobs- or fax resume toll-free (866)396-4833. R11.T1 --,--.. Financia Opportunities 305 Money Lenders 310 Tax Preparation 315 ALL CASH CANDY ROUTE Do .you earn $800/day? 30 Ma- chines, Free Candy All for $9,995. (888)629-9968 B02000033. CALL US: We will not be undersold! Stay Home and Enjoy Lifel Work a Little and Get Paid a Full Time Income. I Do and I'll Show You How. (800)311-9365 24 hours JOIN A LOG HOME LEADER Original Old Timer Log Homes. Seeks Representa- tives Great Earning Potential High Quality Products Con- tact Mr. Vester (800)467-3006- merloghomes.com. Professional Vending Route - No Bubble Gum Here! Rea snack, soda, water, juice, fi- nancing available with de- posit. Great equipment. Grea- locations. (877)843-8726 BO#2002-037;- sodavendingroutes.com . Time to clean out the attic, basement and/or garage? Advertise your yard sale in the classified and make Your clean up a breeze IMMEDIATE CASH!!! US Pen- sion Funding pays cash now for 8. years of yout future pension payments. Cal (800)586-1325 for a FREE no-obligation estimate- ing.com. Services aII TI Child Care Needed 410 Child Care Offered415 Instruction 420 Services Offered425 Insurance 430 Medical Services435 ACCIDENT INJURED All Per- sonal Injury *WRONGFUL DEATH *AUTO *MOTORCY- CLE *TRUCK *PREM- ISE/PRODUCT *ANIMAL BITES *SLIP AND FALL *PE- DESTRIAN A-A-A Attorney Referral Service (800)733-5342 24 Hours. DIVORCE$275-$350*COVERS children, etc. Only one sig- nature required! *Excludes govt. fees! Call weekdays (800)462-2000, ext.600. (Sam-7pm) Alta Divorce, LLC. Established 1977. EARN DEGREE online from home. *Medical, *Business, *Paralegal, *Computers, *Criminal Justice. Job Place- ment. Computer provided. Fi- nancial aid if qualify. (866)858-2121- netidewatertech.com. The most important 20 minutes of your day is the time spent reading with your child from birth to age nine.w/heat $1075 (954)309-8659 AIR CONDITIONER 3 -Ton, 10 Ceer 10kw heat strip, $1200 (863)697-0206 AIR CONDITIONER UNIT - Window or wall, works great, $25. Call 772-971-9474. AIR HANDLER for 2 ton AC unit $200 or best offer (863)357-6132 MOBILE HOME UNIT- 4 ton, asking $350,(863)467-0493 WINDOW OR WALL Air condi- tioner unit w/heat 220 volt, good cond. $75 (772)971-9474 CLUB CHAIRS- 2 matching, Red velvet, w/matching pil- lows Exc. cond. Circa early 50's. $100 (863)675-0410 DISHES- 8pc setting, w/sq bread plates, rose pattern, made in England/Sheraton Johnson Bros. $300 (863)634-9620 Okee area FARM-ALL CUB -. Circa 1948. Good shape. $2150 (863)673-9200 MARBLE COFFEE TABLE- W/drawer w/78 turn table, AM/FM radio Circa 50's Works $100.863-675-0410 Antique American Oak dresser, 1800s, excellent condition $550 firm (863)675-4201 HOME ICE MAKER- Kenmore, 50 Ib, just bought, never used, New $1100, asking $800 (863)763-8872 MICROWAVE- PANASONIC, 1300 watts, with turntable $50 (863)467-0493 REFRIGERATOR- GE, Almond, Used but runs great. $35. (863)467-9375 WASHER- Whirlpool, Runs good. $125. (863)763-7034 SCHWINN, 1955- Original condition, $900. (863)467-5756. BUILDING SALE! "Beat Next In :re'se'" 20x2.6 N.O.w .3i40. ?'25.30 $4790. 30x44 $73140 40.,66 $11,490. Fac- tory Direct, 26 Years. Many Others. Ends/accessories optional. Pioneer (800)668-5422. METAL BUILDING FRAME- 24x24, gurts and perlings, $800 (772)342-7304 FENCING: Heavy Duty, New. All parts enough for at least 400 ft. $2500 (863)675-4787 METAL ROOFING SAVE $$$ Buy Direct From Manufactur- er. 20 colors in stock with all Accessories. Quick turn around! Delivery Available Toll Free (888)393-0335. MOBILE HOME STAIRS Fiber glass with rails $250/neg. (863)763-6369 PIPE TRUSSES- 9, For a car- port, 2.5"x14', $270. (863)634-3040 SHINGLES- 9 bundles, 25 yr antique silver, 23 bundles 30 yr antique silver, $453 for all (239)464-1987 COWHIDE RUGS (2) asking $250 for both will sell separate (863)675-3888 after 7pm BABY CRIB- no mattress, Like new Cost $400. sell $100. CRIB MATTRESS- Renais- sance, Never used. $50. or best offer. (863)467-5616 CRIB/DRESSER SET- Child- craft matching set, brand new $600,(863)673-5167 BEER CAN COLLECTION: From 1970's, 199 cans. Good condition. Most are unusual. $50. for all. (863)675-4787 DUKES OF HAZARD '80-Radio Controlled Gen. Lee car. In box. Mint cond in box, 1/24th scale, $45 (856)358-8625 ELVIS RECORD & SOUVENIR COLLECTION: Approx. 44 yrs. old. Rare items. $1000 all or best offer.. 863-824-3358 FOOTBALL & BASEBALL CARDS Racing & Comic. late 80s early 90s Exc. cond. $400 neg. 863)763-8943 HOCKEY CARDS, (100), Wayne Gretzky, insderts incl., great $ value, $25 incl. S&H. (863)674-0564 GATEWAY includes desk & printer. Runs Windows XP $200 or best offer (863)673-1877 Laptop Computer, Windows XP, Microsoft Office, Modem & DSL card. Complete, just $325 (863)843-0158 WEB TV- computer w/2 keybrd, cordless ph & ans mach, $125 (863)902-0257 BAR STOOLS (3) like new, 2 end tables wood/glass, oval dining table All $150 (863)357-0037 Okee BOX SPRING & Mattress, Queen Sealy, excel. cond. $150 (863)763-5422 BR SET 4 pc, mattress & boxspring & computer desk. $300 or will separate. (863)697-8784 /763-0323 BR SUITE- QS bed w/hdbd, chest, Ig dresser & 2 nite ta- bles $400 neg. 1-(270)469-6011 cell OKEE BR SUITE- w/2 end tables with 6 drawers, a tower holding 2 42" mirrors, and more $800 must see (863)610-0577 CAPTAINS BED- Solid wood, 6 drawers underneath. W/mat- tress. Like new. $225. or best offer(863)634-2582 CHINA CABINET Glass front, lighted, old, $200 firm. (863)763-6336. DINING ROOM SET- Table, hutch and 6 chairs, pur- chased at $2000 selling $950 (863)983-5515 DOUBLE BED Mattress and box spring, frame, head board good cond. $75 (863)763-3718 DRESSER 3 drawers, solid wood, $30. (863)634-7712 FUTON- Metal framed $20 (863)763-6346 GLASS TOP TABLE- 3x5, $85 (863)635-3824 Frostproof KING SIZE PILLOWS- 2, 1 King sized Blanket & 2 com- fort. tops $96. (863)763-9135 LA-Z-BOY- green, good condi- tion, $75 or best offer (863)612-1003 NIGHT STANDS- 2, Maple, Ex- cellent conditi-on $20. (863)635-0474 Leave mes- sage RECLINER Blue gray in color $20 (863)763-6346 ROCKING RECLINER- Bur- gundy, Small china cabinet, Very old, Excellent condition, $80. (863)635-0474 ROLL TOP DESK $200 firm. (863)763-6336. SECTIONAL, Black Leather. 2 recliners & hide-a-bed. Good Cond. Seats 8 $850 (863)824-0981 SINGLE BED- With nightstand & dresser, like new $175 (863)635-3824 Frostproof SOFA- 2yrs old, wine colored, with recliners at each end. 2 $300 will sep (863)675-0777 SOFA- French Prov., cream & cherry wood, good cond, $200 or best offer (863)612-1003 SOFA, LS, CHAIR, LA-Z-BOY REC- good condition, take all for $150 ()863)467-7664 af- ter5pm. SWIVEL BAR STOOLS (2) Spindle back. $50 (863)634-5038 TABLE & CHAIRS, 2 Leaf's & Computer Desk $120. Will separate (561)248-7327 TWIN BED- White head board, New mattress & box springs. $50. (863)357-6922 CLUB CAR, '97- Exc. cond., good batt/charger, $1599. (863)697-1350/763-2063. EASY GO Good cond. good battery & charger. $799. (863)697-1350 or (863)763-2063. GOLF CART, '02 Club Car, 48 volt system, top, lights, mir- rors, spinner hub caps. Exc. shape.$2350. (317)902-9827 MacGregor M565, '05, 3pw, $375. (863)528-2884 Mactec Driver, 10.5, $175. (863)528-2884 MAC MODEL 1935 S, Cal 7.65 Long. WW II issue to Italian Police. Semi-auto 4" barrel, Blued. $450. (937)215-0307 SHOT GUN- Remington, semi auto., Sportsman 48, 20 gauge, $365. (863)467-7838 BOW FLEX: Less than 1 year old. Great shape...Like new. $850. (863)697-6652 EXERCYCLE Compact, easy adjustments w/digital read- out Paid $200 sell $65 (863)763-0625 PROFORM ELLIPTICAL TRAINER- ryiDd cadi d tion. $150. (561)248-7327 WOOD BURNING STOVES (2), one uese & one oin crate, $400. (863)763-7727 LAMPS (2) Crystal lamps w/silk shades $40 will separ- ate (863)824-0801 LADIES GOLD ANTIQUE POCKET WATCH- over 100 yrs old, $300 neg. (863)634-9620. Okeechobee PATIO FURNITURE- 7pc set, glass top table, 6 padded chairs, good cond., $100 (863)467-2011 LIFT CHAIR good condition, $350 (863)801-5353 LOWEST PRESCRIPTION PRICES Less than Canada.' Better than MedicareD. Fbsa- max 70mg $16.00, Plavix $41.00, Lipitor 20mg..$37.00/month. Viagra 100mg..$2.75. Global Medi- cines (866)634-0720. POWER WHEEL CHAIR- Bat- tery oper., Joy stick control- ler, Complete, $600. 863-357-7810 For more info WHEEL CHAIR, Heavy Duty. Excellent condition. $650. Firm. (863)675-2596 HOME INTERIOR 27x23 Floral Garden, Wall Picture, Valued at $65 asking $25 863-634-5038 LOG SPLITTER- Electric, Used 20hrs $90. (863)675-3032 MOBILE HOME STEPS- New, fiberglass, 4 steps w/3ft plat- form at top. Alum. rails $400. (863)467-6619 Run your ad STATEWIDE!! For only $450 you can place your 25 word classified ad in over 150 newspapers throughout the state reaching over 5 MILLION readers. Call this newspaper or Ad- vertising Networks of Florida at (866)742-1373. Visit us online at- fieds.com. Display ads also available. SCOOTER Electric, Red, in good cond. W/battery charg- er. Paid $800 asking $400 (863) 610-1363 after 3pm Everything Needed for Home recording Studio & produc- ing a concert $6000 For more info(863)357-2882 ORGAN KIMBALL the enter- tainer model, with seat and music book, like new $189/neg (239)810-3312 PIANO- Upright, antique, very good condition, $800 (863)946-2700. TRUMPET- Gold, Brand new. Sacrifice $150. firm. (863)447-1198 BABY MINI POT BELLY PIGS $50 each. Call Debbie (863)983-7702 BEAGLE PUPPIES- 3 males, CKC reg., born 11/18/05, $400 ea., (863)763-2755 BOSTON TERRIER MALE PUP- $400 (863)946-1279 CANARY'S- 2, With cage, $200. will separate. (863)467-4498 DOG CRATE- Metal, like new, for small to med dog. $35 neg. (561)632-6497 FISH TANK- 10 gal., with pump, filter, plants, rocks, needs fish $25 (863)763-4098 JACK RUSSELL- female, 1 yr old, $100 (863)675-8864 PARROT CAGE- White w/ 24x24x27, playpen on top shelf under cage detachable seed $100. (863)357-0037 PARROT- Double Yellowhead, talks some. $150 (772)597-5387 PUG- Male approx 8 mo. old Has papers, (Pug Lovers On- ly), $500. or best offer. (239)645-9155 Toy White Poodles (2) for sale to right person $1000 (863)612-0147 REVERSE OSMOSIS SYSTEM- Microline, for under sink, ap- Sprox 1 yr old, -$75 (863)763-2692 COMPOUND BOW: "Bear Mag- num". Sights, Scabbard & Case. $175. (502)931-8101 PITCHING MACHINE- Louis- ville Slugger, like new, $50 firm! (863)467-1574 AKAI HOME STEREO SYS- TEM- W/stacking amp, cass, rec player, am/fm radio, 2 spkrs $75 (863)763-2458 TELEVISIONS (2) 1- Sharp 27" Color remote, 1- Curtis Mathis 20" color.$60 will sell sep (863)467-0493 Trussed Antenna, 70 ft in 10ft sections w/ base, mast & hardware $500/neg (863)675-4201 TV- Sylvania, "32 table model, Like new, Used 8 months. $150. (863)357-2424 GENERATOR 10,000 watts, will power a large house, 16hp twin cylinder $1000 (863)763-2349 HONDA GENERATOR 18hp, 8k continuous watt, new never used, $2000 (863)467-5756 PING PONG TABLE 5ftx9ft, w/cover, good cond. $75 (239)657-2114 DVD PLAYERS (2) Apex, 1 single AP500W $15, 1- 3disc AD51313 disc. $30 (863)467-0493 VCR TAPES- 156, $78. (863)763-9135 OLD GUITARS WANTED! Fen- der, Gibson, Gretsch, Martin, D'Angelico, Stromberg, Rick- enbacker, and Mosrite. 1930's thru 1960's. Top cash paid! (800)401-0440; WANTED: FL ART A.E. Backus, J. Hutchinson H. Newton, G. Buckner, E. Buckner, L. Roberts, A. Hair, R A. McClendon, S. Newton, BIG $$ (772)562-5567 Earn some extra cash. Sell your used items in the classified Agriculture FM S 810 Farm Miscllaneous:815 Farm Produce 820 Ofered 825 Form Sup ie a. . Service S Wated 830 Faetillr~ 835 Hoe s 840 Lu.ndicaping BSppig "45 Lawin &i ardien 1 50 Liuoftokk 855 Pooltry/Slw 1ll1M e O Seudolaanta/ . Flowore "., 6 e 5 TRACTOR restored Gilson. 11h/p, 4spd. New tires, tubes, battery & seat. Rebuilt eng. $350 (863)467-6696 APPALOOSA PONY, 14 yrs. old, 13.1 hands, $700 or best offer, delivery available. (239)340-8373 HORSE TRAILER, two, needs a little work, $600. (239)340-8373 Fort Myers area. MARE 17y/o, needs good home, has arthritis in hip but can still be ridden by small child $400 (863)634-2094 MARE- AQHA registered, great for kds/adults. Needs some- one to ride her. $1200/neg (863)634-2094 Jennifer REGISTERED 5y/o Black/White Walker Mare, loves trails, very friendly. $2500 863-843-2495 NEW DUMP LAWN CART- $200 (863)357-5754 PRESSURE WASHER: Camp- bell Hausfield Clean Power 37, Briggs gas eng. 1500 psi/2.0 gpm. $140 (317)902-9827 RIDING LAWN TRACTOR- 2001, 16.5 HP, 42" cut, $300 or best offer (863)763-5137 STRING TRIMMER- Troybilt, heavy duty, on wheel, cuts heavy duty weeds, $300 (863)763-8872 YAZOD Mower for parts $300 (863)673-9200 LLAMAS Young Males and Female, variety of Colors, Very Friendly $475 and up (941)473-9636 NEWSPAR MAKES YOU AMOE INFORMED AND INTERESTING PERSON. 4D -wonderw nwp-p rado n wmaon popilori Eel 6 Frostproof News, Thursday, February 2, 2006 Real Estate Business Places - Sale 1005 Commercial Property Sale 1010 Condos/ Townhouses Sale1015 Farms Sale 1020 Houses Sale 1025 Hunting Property 10 0 Investment Property Sale 1035 Land Sale 1040 Lots Sale 1045 Open House 1050 Out of State Property Sale 1055 Property InspectionlO060 Real Estate Wanted 1065 Resort Property - Sale 1070 Warehouse Space 1075 Waterfront Property 1080 HUNT ELK, Red Stag, White- tail, Buffalo, Wild Boar. Our season: now-3/31/06. Guar- anteed license, $5.00 tro- phy in two days. No- Game/No-Pay policy. Days 314)209-9800; evenings 314)293-0610. ASHEVILLE, NC AREA Peace- ful gated community. In- credible riverfront and mountain view homesites. 1 to 8 acres from the $60s. Custom lodge, hiking trails. 5 miles to natural hot springs. Call (866)292-5762. BEAUTIFUL NORTH CAROLI- NA. WINTER SEASON IS HERE! MUST SEE THE BEAUTIFUL PEACEFUL MOUNTAINS OF WESTERN NC MOUNTAINS. Homes, Cabins, Acreage & Invest- ments. Cherokee Mountain Realty GMAC Real Estate, Murphy- mountainrealty.com Call for Free Brochure (800)841-5868. GOV'T HOMES! $0 DOWN! BANK REPO'S & FORECLO- SURES! NO CREDIT OK! $0 / LOW DOWN! Call for Listings" (800)498-8619. 'Invstmn Invs- Eagle's Nest Estates Ssecluded, private . ranch subdivision : ' offering beautiful vistas of pristine natural habitat. Offered in combinable 40-60ac Tracts for discerning homeowners or weekend nature enthusiasts. Only eleven of these exceptional tracts available. T,= ERoIt 772-468-8306 a8CP1lOIE~tPlBR e. f" OO D COASTAL NC DEEPWATER! Off- season Special- Save Big! 10 acres- $139,900. Beautifully wooded, deep boatable water, long pristine shoreline. Access to ICW, Atlantic, Sounds. Power, phone, perked. Excellent fi- nancing. Call now (800)732-6601x. GEORGIA BLAIRSVILLE IN THE NORTH GEORGIA MOUNTAINS. Land, Homes, Commercial & Investment. "EVERYTHING WE TOUCH TURNS TO SOLD" Jane Baer Realty, (706)745-2261, (800)820-7829- baerrealty.com, jane- baer@alltel.net LAKEFRONT BARGAINS! Wa- terfront Properties from $99,900 Lake Guntersville, Alabama Exclusive Goose Pond Island Premier bass fishing destination ONE DAY ONLY LAND SALE! -Saturday, February 11th- 90 minutes from Atlanta, 1 hour or less from Birming- ham, Huntsville, Chattanoo- ga. Call NOW for early appointment! (888)LAKE- SALE x914.ENNES- SEE (865)717-7775 Char- lotte Branson Agent OR Visit My Website- choicerealestate.com OR. One man's trash is another man's treas- ure. Turn your trash to treasure with an ad in the classified. MURPHY, NORTH CAROLINA AAH COOL SUMMERS MILD WINTERS Affordable Homes & Mountain Cabins Land CALL FOR FREE BROCHURE (877)837-2288 EXIT REAL- S MOUNTAIN VIEW PROP- E R T I E S. NC MOUNTAINS 10.51 acres on mountain top in gated community, view, trees, wa- terfall & large public lake nearby, paved private ac- cess, $119,500 owner (866) 789-8535. NC MOUNTAINS-Log cabin $89,900. Easy to finish cab- in on secluded site. Million $$$ Views Available on 1-7 acre parcels $29,900-$79,900. Free Info Available! (828)256-1004. North Carolina Gated Lake- front Community 1.5 acres plus, 90 miles of shoreline. Never before offered with 20% pre-development dis- counts, 90% financing. Call (800)709-5253 TENNESSEE LAKEFRONT HOMESITES 1 to 6 acres from the $40s. Spectacular lake, mountain and wooded nature sites newly released. Just 1-1/2 hours to Nash- ville. Don't miss out! Call (866)339-4966. TENNESSEE LAKESIDE RE- TREATS New gated commu- nity. Incredible lake & mountain views. 1 to 5 acre building sites from the $40s. Lake access, boat ramp, pri- vate slips (limited). Don't miss out. Call (866)292-5769. Mobile Homes Mobile Home Lots 2005 Mobile Home Parts 2010 Mobile Homes Rent 2015 Mobile Homes Sale 2020 FRANKLIN Park Model $7500 or best offer. (863)357-2979 I CATALINA- '85, 2BR, 1BA Very clean, No hurricane damage. $2500. Firm. You move (863)983-5364 TAYLOR CREEK ISLES- 1989 single wide, 2br, 2ba, water- front, lake access, sewer & city water, $149,000 as is 863)467-4959 or 863)610-1184 Recreation I Boats 3005 Campers/RVs 3010 Jet Skiis 3015 Marine Accessories 3020 Marine Miscellaneous 3025 Motorcycles 3030 Sport Vehicles 'ATVs 3035 -lj~ BASS BOAT 17 ft, 150 hp, troller motor, lots of extras w/ trailer everything you need $1500/neg. (772)559-8558 BASS BOAT, 17'87 Glastream 90 hp Yamaha w/new lower drive. '99 Pro Craft Trailer, Ex- tra's. $3500. (863)763-4495 BASS BOAT: 18' 1987 Ranger 373, 150 hp Mere. XR2, Com- plete Over Haul. New trolling motor. $6000.859-250-5902 BAYLINER CAPRI 1988, 16', 85 hp Force, Stereo & Fish- finder. $1500 or best offer. (863)632-9166 BOAT, TRAILER & MOTOR- 15 HP Johnson, Crest Liner $500 neg. (863)634-4818 FIBER GLASS BOAT 14ft, 15hp Sears Motor, $500/ neg (863)763-6369 FIBERGLASS BOAT- 16' 40hp Mere. w/trailer. Will demon- strate $750. (863)467-4035 JOHN BOAT- 14' alum. flat bottom, 7.5 mercy. w/trailer & trolling motor, 2 seats $1000. (863)634-6862 PIPESTIN '70- 17ft in/out V6, with traile, needs work $300 or best offer (863)467-8496 evenings PONTOON 25ft. w/50hp John- son, looks and runs great $2400/neg in water on canal no trailer (863)634-8343 PONTOON BOAT, '99, 20 ft., 50hp plus trolling motor, very good condition, $8000. (863)357-0028 Powerwinch, model 315, trlr winch for boats to 4,000 Ibs. used very little, $80. (863)946-1829 YAMAHA 8HP '04 2 stroke $1000 (239)225-3282. CAMPER, '76, Skamper, 29', 5th wheel, sleeps 6, $2450 or best offer. (863)675-4578 or 863-673-5655 FORD VAN / CAMPER 1987, Exc. cond. Sips 4. Sink, stove, toilet, shower, etc. Good on gas. $4,750. (863)635-7552 RV, Stationary 14x35' w/8x28' FL room. All furnished. 8x7' work area. Asking $10,000. (863)763-7760 Salem, '95, 25', with hitch, everything works, very clean, exc. cond. $5500. (863)763-7727 Bimini Top for Pontoon 1 inch frame w/cover top and lights 7 ft wide $200 (863)635-9612 BOAT MOTOR- 15hp, John- son, Long shaft, Runs good $400 neg (863)634-4818 YAMAHA 2004, 0/B Motor, 75 hp, 4 stroke. New. In crate. 3 year warranty. $5500. Call (863)634-3248 BMW R1200C '00, 15k mi., bags, windshields, running lights, exc. cond., $8000. (863)824-6799/697-3944 DIRT BIKE 2 stroke, 47cc gas. New, $499 (863)675-0310 DIRT BIKES (2) 49cc, 3 spd trans, 1 running, 1 not. $499 (863)675-0310 YAMAHA '99, 15hp, 4 stroke, long shaft, elec. start, low hrs. $1900. (863)824-6799/697-3944 BOMADIER 660 '98- excellent running condition with trailer $1500 (772)342-7304 Jeep Scrambler, '82, 4" lift, alum. rims, 6 cyl., 35" tires, good cond., fiberglass top, 5500. (863)763-7727 MINI CHOPPER- '04, Electric start, Runs perfect. $250. (863)763-1806 YAMAHA 400 4WD- $2000. or best offer. (863)675-2318 or 673-2108 Caloosa Belle area HOLIDAY RAMBLER TRAVEL TRAILER, '93, 33', new re- frig., a/c etc., good cond., Moving Must Sell. $6000 neg. 866-294-4011 Automobiles Automobiles 4005 Autos Wanted 4010 Classic Care 4015 Commercial Trucks 4020 Construction Equipment 4025 Foreign Cars 4030 Four Wheel Drive 4035 Heavy Duty Trucks 4040 Parts Repairs 4045 Pickup Trucks 4050 Sport Utility 4055 Tractor Trailers 4060 Utility Trailers 4065 Vans 4070 BUICK CENTURY 1981, Clean Interior. Leaks power steer- ing fluid. $750 or best offer. (863)763-5501 FORD ESCORT '95- 2dr, new clutch, excellent condition, $1500. or best offer (863)357-6377/801-1200 HONDA CIVIC '86 In good shape, needs timing belt. Clear title; $300 AS-IS (863)357-3773 LINCOLN TOWN CAR '88, in Jensen Beach, needs work,. runs good, body in mint cond. $2000/neg 772-260-4919 OLDSMOBILE- '91, '98 Elite, Runs good $1900 (863)946-0869 PONTIAC GRAND AM. '00- 82k miles $5800 (863)673-3900 Saturn SL2 '95, 5 Spd, ac, cd player, new clutch, moon roof, runs roof, runs and looks good, $2400 Call (863)824-0561 /447-5171 SEABRING JXI '99 Convert. 70K mi. New top Excel. cond. Blue Book $8300 Asking $7900 863-357-3830 TOYOTA MR2, '88, hard to find, dependable, 5spd, SR, needs compressor for AC $1500 neg. (561)924-2208 MINI SKID STEER: For Rent w/operator. Attachments include rotivator, ditcher, leveler, bucket& 9", 8"&30" auger. $40/hr. $80 minimum. Call Whidden Citrus (863)635-4302 CLUB CAR, '94, green, recon- ditioned, with top, $1595. (863)675-1472 CLUB CAR GAS, '98, recondi- tioned, beige, with top, $2250. (863)675-1472 AUX. FUEL TANK- L shape, for back of PU, black, good cond. $200 (863)673-0648 CAR DOLLY, heavy duty, w/straps & chains, tires in good shape, swivel arm, $400. (863)635-6164 CARBURETOR 750 CFM- Hol- ley, Double pump $100. (863)763- MOTORS & TRANS. (8) 8 cyl. Ford, GMC & Mopar. $2400 will sep. (863)467-1932 or (954)445-0749 TIRES (4) Goodyear Eagle VR50. 225/50R15. Never mounted. $150 (863)357-3773 TOW DOLLY, '03, used very little, cost $1175 new, ask- ing $950 or best offer. (863)697-9704 TOYOTA CRESSIDA '84- good -body, tires, trans motor has rod knocking $50.00 b pull (863)357-0555 Community Events Lake Wales Women's Club update The Women's Club of Lake Wales, Fl. holds its monthly meetings, 2006 from 9 a.m. until 2 p.m. and on Saturday, Feb. 18, from 9 a.m. until 12 noon. A $1 fill a bag, will be on Saturday. Donations will be accepted on Thursday, Feb. 16, 2006 from 9 a.m. until 1 p.m. Pick up of irtms is not available. Training for Camp ROCK counselors The Polk County Leisure Ser- vices Division is offering a free-of charge orientation and training program for teens eligible to be counselors for Camp R.O.C.K. - a summer recreation program. The Junior Counselor Program is a prerequisite for teens to apply for junior counselor posi- tions at one of eight summer campsites. The one-day training program will take place on Mon- day, March 13, from 9 a.m. to 3 p.m. Participates must be between the ages of 13 tol7 and interested in being considered for the Camp R.O.C.K. Junior Counselor position. Beginning Feb. 1; applications are available at the Polk County Leisure Ser- vices Office, located at 515 E. Boulevard St., in Bartow. To attend the training program, each application must be filled ;out, signed by both participant and parent'guardian, and returned by March 1. Following the program, a limited number of teens will be selected for the junior counselor positions. For more information, con- tact Missy Harbin at the Leisure Services Division at 863-534- 4340, or visit the website a. Annual Sweetheart Swing February 11 Come and dance the night away at the Polk County Leisure Services 1940's USO canteen party on Saturday, Feb. 11, from 6 to.10 p.m. at the Polk County Historical Museum, 100 East Main Street,. Bartow., The event will include a swinging jazz band, swing dance lessons, military exhibits, hors d'oevres and door prizes. Attendees are encouraged to dress in 1940's or military cloth- ing. Tickets are available in advance at the Polk County Leisure Services office or the Historical Museum in Bartow. The costs are $12 for a single and $20 for each couple. All proceeds will benefit "Operation USO Care Package." For more information, contact the Leisure Services office at 863-534-4340, or visit our web- site at. 5K Cross Country Race to be held in Homeland Join the Polk County Leisure Services Division on. Saturday, Feb. 4, for the IMC 5k Cross- Country Race at IMC Peace River Park in Homeland. Registration is $25 and will be accepted dur- ing the day of the race. Refresh- ments and T-shirts. (guaranteed to pre-registered participants only) will be provided. Racers. should check-in and register at 7 a.m., and the race will begin at 8 a.m. Awards will be given to the overall male and female win- ners, top masters finisher (male and female), and top three fin- ishers in 5-year age categories (male and female). New this year-a Kids' Fun Run! Entry fee is $10 and-will begin immediately following the .5K. For more information, con- tact the Leisure Services Division at 863-534-4340, or visit the Polk County website at- county.net. Newszap & Newspapers We make it easy to stay up-to-date! Community homepages newszap.com Click anytime for the latest LOCAL NEWS LOAL ADVERTISIN6 LOCAL ORGANIZATIONS! Featuring links to: SAP wire m Weather m Obituaries m Health news Stock quotes Horoscopes TV listings Movie listings Lottery results Food & recipes White Pages Yellow Pages & much more! Newszap! Online News & Information newszap.com Gallery announces event and classes The Frostproof Art League and Gallery will begin working earnestly for the Wearable Art show on March 7. Members will meet each Friday in-February to work on outfits and decorations for the annual show. Tickets for the afternoon and evening shows will be on sale for $10 per person at the Gallery beginning Feb.6. Feb. 8Revise your watercolor with collage is a new workshop being offered Feb. 8 from 9:30 a.m. to 4 p.m. The instructor is Rose Besch from Highlands County. Call for supply list. 'Feb. 11 Hand Lettering with Leon Gifford on Saturday, Feb. 11 is perfect for any one who makes signs or labels. Class time is 10 a.m. to 2 p.m. Free but must sign up prior to class. Feb.18PleinAire Painting with George Arnell is another one-day class. Class will meet at the Art League on Saturday, Feb. 18 at 10 a.m. for brief instructions and then on to the paint site. eb. 25)Drawing and Sketch- ing with confidence by Anne Moore will be taught on Satur- day Feb. 25 from 10 a.m. to3 p.m. This is a perfect class for beginners to the experienced artist. Pat Bowen will be adding a beginners Portrait class. Please call if you are interested so we can advise you of the date and time. Pat continues her Monday evening workshop in acrylics and oils. In March, Pat will be teaching Flowers and Land- scape on Monday mornings. Vicki Alley continues her Famous One-Stroke Painting classes on Tuesday evenings. Call for supply list and to pre- register. She will also be teach- ing a window painting work- shop on Saturday, March 11. Vintage windows from the Old Frostproof High will be painted and then be made available for ate workshop Creative Watercol- sale. Proceeds will be divided or Techniques. Class will be held between the High School Reno- 9 a.m. to4 p.m. This class vations Fund and the Art League. requires a minimum of 8 stu- dents. Looking ahead, we just or more informationcall added a March 18 workshop the Frostproof Art League at.863 with nationally known Water 635 2728 or stop by. It is located Color Arts, Patricia Johnson. She at 12 East Wall St., Frostproof, will teach a one-day intermedi- FL. Do you need Sa loan? "StmaItI l,.fy' by 'ihberly Rusxequity, there's an than $10.000 for amn reason? excellcntchanceyouwillqual- Are you paying more than ify for a loan-usuall)y within 7% interest on any other 24 hours. loans or credit cards? You can find out over the Ifyouarea homeownerand phone-and free of charge-..- answered "yes" to any of if you qualify. Honey Mae these questions, they can Home Loans is licensed by tell you over the phone and the Florida Department of without ohligation if you Financial Services.Open days qualify. a week to serve o High credit card debt? Less- a eek erve y than-perfect credit? Self em- 1-800-700-1242ext 273 Looking for something Unique? Find it in the Classifieds Pages 5-6 [c YYour LOCAL gateway to the Internet CHEVY 70 DUMP TRUCK, '85, $6500 or best offer. Moving Must Sell! 866-294-4011 FORD F-150 XLT 1998- New brakes& tires, Mag rims & no rust, Crew Cab 3dr, Asking $7500/neg (937)215-0307 JEEP CHEROKEE '86- 4x2, 4 cyl., auto, nice body & int.,m needs eng work $450 (863)675-1855 STOCK TRAILER, 30' Goose- neck, 24' inside, 2/6' cov- ered front, good tires, $1850 or best offer. (863)697-9704 TRAILER 4x6, brand new from Tractor Supply. $299 in LaBelle. (239)634-4040. CHEV VAN '85- 15 passenger, $2500 (863)634-5965 CHEVY MINI BUS 1984, Load- er & Transmission in good condition. Asking $2000. (239)823-2851 DODGE RAM '89- 3/4 ton, Good work van, runs great Cold AC!! $1500 (863)234-6040. Econoline Van 1983, Runs, 6cyl, 4.9, Reese Receiver, Hi Top .$600/neg. (863)983-5599 Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2011 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Powered by SobekCM
|
http://ufdc.ufl.edu/UF00028406/00057
|
CC-MAIN-2017-17
|
refinedweb
| 11,941
| 75.81
|
Tuesday, April 04, 2017
Configuring Private DNS Zones and Upstream Nameservers in Kubernetes
Editor’s note: this post is part of a series of in-depth articles on what’s new in Kubernetes 1.6
Many users have existing domain name zones that they would like to integrate into their Kubernetes DNS namespace. For example, hybrid-cloud users may want to resolve their internal “.corp” domain addresses within the cluster. Other users may have a zone populated by a non-Kubernetes service discovery system (like Consul). We’re pleased to announce that, in Kubernetes 1.6, kube-dns adds support for configurable private DNS zones (often called “stub domains”) and external upstream DNS nameservers. In this blog post, we describe how to configure and use this feature.
Default lookup flow
Kubernetes currently supports two DNS policies specified on a per-pod basis using the dnsPolicy flag: “Default” and “ClusterFirst”. If dnsPolicy is not explicitly specified, then “ClusterFirst” is used:
- If dnsPolicy is set to “Default”, then the name resolution configuration is inherited from the node the pods run on. Note: this feature cannot be used in conjunction with dnsPolicy: “Default”.
- If dnsPolicy is set to “ClusterFirst”, then DNS queries will be sent to the kube-dns service. Queries for domains rooted in the configured cluster domain suffix (any address ending in “.cluster.local” in the example above) will be answered by the kube-dns service. All other queries (for example,) will be forwarded to the upstream nameserver inherited from the node..
Customizing the DNS Flow
Beginning in Kubernetes 1.6, cluster administrators can specify custom stub domains and upstream nameservers by providing a ConfigMap for kube-dns. For example, the configuration below inserts a single stub domain and two upstream nameservers. As specified, DNS requests with the “.acme.local” suffix will be forwarded to a DNS listening at 1.2.3.4. Additionally, Google Public DNS will serve upstream queries. See ConfigMap Configuration Notes at the end of this section for a few notes about the data format.
apiVersion: v1 kind: ConfigMap metadata: name: kube-dns namespace: kube-system data: stubDomains: | {“acme.local”: [“1.2.3.4”]} upstreamNameservers: | [“8.8.8.8”, “8.8.4.4”]
The diagram below shows the flow of DNS queries specified in the configuration above. With the dnsPolicy set to “ClusterFirst” a DNS query is first sent to the DNS caching layer in kube-dns. From here, the suffix of the request is examined and then forwarded to the appropriate DNS. In this case, names with the cluster suffix (e.g.; “.cluster.local”) are sent to kube-dns. Names with the stub domain suffix (e.g.; “.acme.local”) will be sent to the configured custom resolver. Finally, requests that do not match any of those suffixes will be forwarded to the upstream DNS.
Below is a table of example domain names and the destination of the queries for those domain names:
ConfigMap Configuration Notes
stubDomains (optional)
- Format: a JSON map using a DNS suffix key (e.g.; “acme.local”) and a value consisting of a JSON array of DNS IPs.
- Note: The target nameserver may itself be a Kubernetes service. For instance, you can run your own copy of dnsmasq to export custom DNS names into the ClusterDNS namespace.
upstreamNameservers (optional)
- Format: a JSON array of DNS IPs.
- Note: If specified, then the values specified replace the nameservers taken by default from the node’s /etc/resolv.conf
- Limits: a maximum of three upstream nameservers can be specified
Example #1: Adding a Consul DNS Stub Domain
In this example, the user has Consul DNS service discovery system they wish to integrate with kube-dns. The consul domain server is located at 10.150.0.1, and all consul names have the suffix “.consul.local”. To configure Kubernetes, the cluster administrator simply creates a ConfigMap object as shown below. Note: in this example, the cluster administrator did not wish to override the node’s upstream nameservers, so they didn’t need to specify the optional upstreamNameservers field.
apiVersion: v1 kind: ConfigMap metadata: name: kube-dns namespace: kube-system data: stubDomains: | {“consul.local”: [“10.150.0.1”]}
Example #2: Replacing the Upstream Nameservers
In this example the cluster administrator wants to explicitly force all non-cluster DNS lookups to go through their own nameserver at 172.16.0.1. Again, this is easy to accomplish; they just need to create a ConfigMap with the upstreamNameservers field specifying the desired nameserver.
``` apiVersion: v1
kind: ConfigMap
metadata:
name: kube-dns
namespace: kube-system
data:
upstreamNameservers: |
[“172.16.0.1”]
Get involved
If you’d like to contribute or simply help provide feedback and drive the roadmap, join our community. Specifically for network related conversations participate though one of these channels:
- Chat with us on the Kubernetes Slack network channel
- Join our Special Interest Group, SIG-Network, which meets on Tuesdays at 14:00 PT
|
https://kubernetes.io/blog/2017/04/configuring-private-dns-zones-upstream-nameservers-kubernetes/
|
CC-MAIN-2018-39
|
refinedweb
| 815
| 55.95
|
Hello,
I am trying to learn WWW::Scripter to scrape some JS intensive pages. I tried evaling the JQuery.js from a page received with $mech->get. Since that didn't work I tried a simple example and this doesn't work either. Maybe JQuery needs a loaded DOM for this to work?
#!/usr/bin/env perl
use warnings;
use strict;
use HTTP::Cookies;
use WWW::Scripter;
my $cookie_jar = HTTP::Cookies->new();
my $mech = WWW::Scripter->new(
agent => 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident
+/5.0',
cookie_jar => $cookie_jar,
);
$mech->get(".
+min.js");
my $jquery = $mech->content;
$mech->use_plugin(
JavaScript =>
engine => 'SpiderMonkey',
);
$mech->eval($jquery);
[download]
I get "c has no properties at WWW::Scripter::Plugin::JavaScript::SpiderMonkey line 165"
Any help greatly appreciated...
To further expand on the comment below by tobyink, the fact that it can't parse JQuery is by no means a limitation of WWW::Scripter, it just means that I was trying to use a great tool for the wrong job.
In my particular case I need a full-blown rendering engine so there is not getting around the use of something like Gecko, whether it's using Xvfb, Crowbar, offscreen or something along those lines. I would definitively try to keep everything within WWW::Mechanize, after all, the final scraping is very effective with the tools provided in that namespace, so probably WWW::Mechanize::Firefox and Xvfb is the way to go. Expect another update when I get one of these working...
jQuery has a lot of stuff that assumes it's running inside a traditional desktop browser. WWW::Scripter emulates that environment pretty well, but still not quite well enough to run jQuery. It might get there eventually, but it's not there yet.
There are plenty of actual desktop browsers (e.g. Konqueror - though I haven't tried its WebKit module) that can't run jQuery fully.
Looked at WWW::Mechanize::Firefox?
Thanks for the thorough explanation... I had the feeling that evaling JQuery might have been probably overkill for what I really need. Yep, I looked at mechanize::firefox but it seems to require firefox running with a GUI. Do you know if there is any way to run firefox without GUI or run the Gecko engine as a library, I mean much like Spidermonkey? Maybe using Xvfb or maybe Firefox itself has the ability to run GUI-less like other GUI-intensive apps?, for example Inkscape which has a console/batch mode (e.g. to convert SVG to PDF).
Not tried this with Firefox, but many years ago I did something along these lines with OpenOffice.org to generate PDF files from various other formats. I used TightVNC Server to create a spare X11 display and ran OpenOffice.org on that.
Maybe JQuery needs a loaded DOM for this to work?
What happens when you try.
|
http://www.perlmonks.org/?node_id=957977
|
CC-MAIN-2016-36
|
refinedweb
| 481
| 75.5
|
I’m flipping between MVC and Silverlight projects when a startling contrast starts to emerge. It’s not the obvious contrast between stateful and stateless. It’s a subtler contrast in design.
If you poke around in a new MVC project, one of the first pieces of code you’ll run across is the code to register the default route. It’s in global.asax.cs, and looks like this:
routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
This snippet relies on some of the recent features added to C# – extension methods and anonymously typed objects. It obviously draws some inspiration from Ruby on Rails, which builds on top of the dynamic, malleable Ruby language.
Compare that code to the code you’ll see when you open up just about any Silverlight control.
Well, you don’t actually see much code because the code is swept underneath a carpet of regions. This happens quite often in Silverlight, and I think it’s because developers are embarrassed to write lines and lines and lines of code to define a single simple property. It’s the elegance of RPG combined with the verbosity of COBOL.
public bool IsDropDownOpen { get { return (bool)GetValue(IsDropDownOpenProperty); } set { SetValue(IsDropDownOpenProperty, value); } } public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register( "IsDropDownOpen", typeof(bool), typeof(Foo), new PropertyMetadata(false, OnIsDropDownOpenPropertyChanged));
I realize IsDropDownOpen isn’t just a simple property. It’s a dependency property, and dependency properties hold many great and magical powers. Data binding in Silverlight (and WPF), for example, is wonderfully feature rich and easy, but it comes with a price. Instead of writing one line of code …
public bool IsDropDownOpen { get; set; }
… we need twelve!
The contrast isn’t in the number of lines of code, however. The contrast is in who the frameworks were designed to serve.
The MVC framework is designed for developers who write code. This fact is obvious in the API design and how the team fights for programmer friendly features like the new HTML encoding block syntax. The MapRoute code we saw earlier is just one example of many. The MVC framework took inspiration from platforms that are popular today because they favor convention over configuration and essence over ceremony. These are fancy terms for keeping things simple and readable.
Silverlight is designed for tooling. Visual Studio, Expression Blend, and other XAML, code, and art editors. I’m not saying we get rid of the tools. We need the tools for the feedback and capabilities they provide when building effects, animations, and irregularly shaped objects. But, it seems the developer’s life gets more difficult with the addition of every feature.
I’d be surprised if another language doesn’t come along to become the de facto standard for the code behind XAML files. A language that is just as friendly to programmers as it is to XAML. A language that makes writing code for System.Windows fun, simple, and readable. Maybe it will look like …
depprop bool IsDropDownOpen { get; set; }
… but smarter people then me can figure out the syntax. I just know there has to be something better.
Could you try using metaprogramming w/ IronRuby to get to your "depprop bool *****" syntax? If you have to have all that CSLA-like noise code to feed the framework, maybe that's the answer to keep from destroying your code readability.
And *I* think the ASP.Net MVC framework has too much noise code for my taste anyway.
However, you're stretching things a little here. You're comparing code in a Silverlight control with an MVC route declaration, which is pretty different. A route declaration is a one-time add to an internal route list, while control code does a lot of other things (UI updates, state maintenance designer support, etc.). A closer comparison would be between the code you actually end up writing more often in both Silverlight and MVC, which is in the ViewModel. Silverlight ViewModels can often just implement INotifyPropertyChanged, which is simpler to handle than DependencyProperties.
The UI controls would be easier to express in a language that has delegation as a first class concept.
INotifyPropertyChanged is something I shouldn't have to write over and over again, either.
On the other hand, I am wondering why they did not use seperate files (like the partial Winforms.Designer files). Maybe the architecture does not allow it ?
What still bugs me is that we do not have a unified pattern for all .net dev (using modelbinders and icommand for example...)
Check out Caliburn, it really cuts down on the repetitive coding involved with XAML
That being said, they really should have had something done for dependency properties. I don't really think that adding a language construct for a framework is necessarily a good thing (e.g. depprop keyword) however I would love a builtin attribute that would accomplish the given task.
[DependencyProperty()]
public bool IsDropDownOpen { get; set; }
|
http://odetocode.com/blogs/scott/archive/2010/01/19/silverlight-and-asp-net-mvc-donrsquot-serve-the-same-master.aspx
|
CC-MAIN-2014-52
|
refinedweb
| 825
| 56.66
|
Opened 5 years ago
Closed 5 years ago
#11264 closed bug (fixed)
Uber Tuber not working in hrev47885 was working before. Possibly Python problem.
Description
Uber Tuber showing error > ImportError: No module named_ctypes. It was working fine before. When run in command line got the following messages: /boot/system/bin> python youtube-dl --max-quality=35 --continue -o Traceback (most recent call last):
File "/boot/system/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"main", fname, loader, pkg_name)
File "/boot/system/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "youtube-dl/main.py", line 15, in <module> File "youtube-dl/youtube_dl/init.py", line 77, in <module> File "youtube-dl/youtube_dl/utils.py", line 7, in <module> File "/boot/system/lib/python2.7/ctypes/init.py", line 10, in <module>
from _ctypes import Union, Structure, Array
ImportError: No module named _ctypes
The ctypes modules is missing from our port of python 2.7. Will release a fixed package soon.
|
https://dev.haiku-os.org/ticket/11264
|
CC-MAIN-2019-30
|
refinedweb
| 166
| 60.51
|
I'm trying to make a shuffler for a blackjack program it's supposed to give me back a random number from a deck of cards each time i call it. But it's also supposed to keep track of cards out of the deck..
I need to make it a function call, but before i do that it's not even working in the first place... it's giving me 51 random crazy numbers..
help please?
#include <iostream> using std::cout; using std::cin; using std::endl; #include <cstdlib> using std::rand; using std::srand; #include <ctime> using std::time; //int random(); int main() {//begin main srand(time(0)); int deck[52]; //int random() //{ for (int i=0; i<51; i++) { int j = rand() % (51 - i) + i + 1; int t = deck[i]; deck[i] = deck[j]; deck[j] = t; //return t; //} cout << t << endl; } //randomize the time //int cardval = random(); system("pause"); return 0; }//end main
|
https://www.daniweb.com/programming/software-development/threads/159174/card-shuffler-program
|
CC-MAIN-2018-43
|
refinedweb
| 157
| 69.25
|
i’m currently learning Ruby. So, while learning about code blocks and
yields i wanted to put my freshly acquired knowledge to the test and
(just to see if i understood correctly) write my own simple each method
for Arrays. so i did:
class Array
def each
for x in self
yield(x)
end
end
end
But running it gives me SystemStackError: stack level too deep. It works
fine when i rename it, so i guess it’s just Ruby not appreciating my
fine work or somehow making sure i don’t introduce flagrant overwrites
to built-in methods??? Anybody feels like enlightening me on how this
works? Thanks.
|
https://www.ruby-forum.com/t/stackerror-stack-level-too-deep/54527
|
CC-MAIN-2018-47
|
refinedweb
| 109
| 67.28
|
Django-Directmessages is a low-level and easy-to-use Django App to manage simple directmessages.
Project description
Django-Directmessages.
Django-Directmessage is thought to be used with APIs or small apps, but can be used for any type of messaging. It featues:
- Sending of private 1-to-1 messages between users.
- Listing unread messages for a given user.
- Read a given message
- Get all conversation partners/contacted users for a given user
- Read a whole conversation between two users.
Requirements
Django >= 1.5 is supported
Installation
- pip install django-directmessages
- add "directmessages" to INSTALLED_APPS and run python manage.py migrate.
Usage
Import the Message Management API on top of your views.py
from directmessages.apps import Inbox
- Send message: Inbox.send_message(from_user, to_user, message)
- List all unread messages: Inbox.get_unread_messages(user)
- Read a message (and mark as read): Inbox.read_message(message)
- Print a message as <user>: <message>: Inbox.read_message_formatted(message)
- Print a list of all conversation partners for a user: Inbox.get_conversations(users)
- Get a conversation between two users: Inbox.get_conversation(user1, user2, _limit_, _reversed_, _mark_read_)
- Limit (Int: optional): Instead of getting the whole conversation, get the first 50 (depends on reversed)
- Reversed (Bool: optional): Usually the ‘limit’-param gives back the first x messages, if you put Reversed to True, limit will give back the x latest messages.
- Mark_Read (Bool: optional): Mark all messages in conversation as read
Signals
You can use the following signals to extend the app for your needs
- message_sent:
- Gets called as soon as a message is sent. Provides the Message object, the sender and the recipient as params.
- message_read:
- Gets called as soon as a message is read: Provides the Message object, the sender and the recipient as params.
Contributing
Bug reports, patches and fixes are always welcome!
To Do
- Add some security functions (e.g checking if user is allowed to read a message)
- Add some custom exceptions (e.g. when no message was found)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/django-directmessages/
|
CC-MAIN-2019-43
|
refinedweb
| 346
| 58.69
|
Tutorials
Forum
Career Development
Articles
Reviews
Jobs
Practice Tests
Projects
Code Converter
Interview Experience
|
New Members
|
IT Companies
|
Peer Appraisal
|
|
Revenue Sharing
|
New Posts
|
Social
|
Forums
»
.NET
»
ASP.NET
»
Text To Speech in ASP.Net And save it into .wav file
Posted Date:
02 Apr 2013
Posted By::
Prasad
Member Level:
Bronze
Member Rank:
6674
Points
: 2
Responses:
2
Text To Speech in ASP.Net And save it into .wav file only in webforms not in winforms
Tweet
Are you looking for a way to convert Text to Speech using ASP.NET ? then read this thread to learn how to convert it
Responses
#710230 Author:
Prasad kulkarni
Member Level:
Diamond
Member Rank:
6
Date: 02/Apr/2013 Rating:
Points
: 3
Microsoft has Speech SDK 5.1. You can download and can use it with asp.net.
check link below
Check following link which gives you more idea about it
Thanks
Koolprasd2003
Editor, DotNetSpider MVM
Microsoft MVP [ASP.NET/IIS]
#710316 Author:
sambath
Member Level:
Silver
Member Rank:
717
Date: 03/Apr/2013 Rating:
Points
: 4
Introduction
Voice over IP (VoIP) VoIP (or Voice over Internet Protocol) refers to voice transmission over the Internet. In other words it refers to telephony over the Internet. Its main advantage against traditional telecommunication is that it is based on the existing technical structure. Due to this fact, a VoIP communication system is far less expensive than a traditional telecommunication system with similar functionality.
VoIP technology uses Session Initiation Protocol (SIP) mainly due to its easy implementation. Since SIP can be implemented in the easiest way it overcomes all other protocols that could be used in VoIP.
Text-to-speech
Text to speech functionality means that the system converts normal (not mathematical or technical) texts into voice. These systems are based on the so called Speech synthesis. These systems structure the voice from the given input text on the basis of sample data and the characteristics of human voice.
Sample programs
This tutorial includes two sample programs in Visual Basic that demonstrate the utilization of text to speech functionality in VoIP. The first sample program is called "TextToSpeechSDK_Sample" (Figure 1). It has a text field and it converts texts entered in this text field into voice. Then you can play the voice and/or save it as a wav file.
The other program is called "SDK_VoicePlayerSample" (Figure 2). It is able to play the previously saved voice during a VoIP call. After it plays the wav file it finishes the call.
TextToSpeechSDK_Sample
It is quite simple to develop an application that is only responsible for converting an input text into voice, especially if you use a recent speech API. In this sample program the tools offered by Microsoft have been used. In this way the source of the program can be made via a few lines. The tool can be found on System.Speech namespace. For conversion only a SpeechSynthesizer object is needed that will make the text to speech conversion.
Figure 1 - Text To Speech SDK Sample
1. Private Sub buttonSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonSave.Click
2. If Not String.IsNullOrEmpty(Me.textBox1.Text) Then
3. Using file As SaveFileDialog = New SaveFileDialog
4. file.Filter = "Wav audio file|*.wav"
5. file.Title = "Save an Wav audio File"
6. If (file.ShowDialog = DialogResult.OK) Then
7. Me.synthetizer.SetOutputToWaveFile(file.FileName, New SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono))
8. Me.synthetizer.Speak(Me.textBox1.Text)
9. Me.synthetizer.SetOutputToDefaultAudioDevice()
10. MessageBox.Show("File saving completed.")
11. End If
12. End Using
13. End If
14. End Sub
The conversion and saving can be performed by the code above. Essentially, the whole program requires only a few lines of code. It can be seen from the source code that a file is opened for writing then the output of the mentioned speech.dll SpeechSynthesizer object is set to this file.
To let the other application process the saved sound I used 800 Mhz sampling frequency and 16 bit rate with mono audio channel. The conversion is made via the Speak method ofSpeechSynthesizer object with the help of a given input text(Me.synthetizer.Speak(Me.textBox1.Text)) that will appear on the oupt, which was set onSpeechSynthesizer.
SDK_VoicePlayerSample
Basically this program is a simplified VoIP SIP softphone (Figure 2). Since this softphone is for demonstration it only has dialing and call initializing functionality. In case of successful call, the application plays the sound, which was saved by the other program, during the phone call and then it ends the call. For making it simple Ozeki VoIP SIP SDK has been used for this softphone. Ozeki VoIP SIP SDK then also can be used for creating a more complex VoIP phone with much more functions even with a few lines of source code.
Figure 2 - SDK Voice Player Sample
Running the program
When the application is started, it automatically tries to register to the SIP PBX based on the given parameters. In case of successful registration, an "online" caption appears on the display that denotes the ready-to-call status of the program. For making a call you only need to dial the phone number and click the call button. Then open the previously recorded wav file. If the wav file can be loaded successfully, the program starts the call towards the dialed party. When the call is established the program plays the sound data to the other party with the help of a timer. After playing the whole sound data the program ends the call and you can start a new call.
Source code
For being simple, the program misses to use any design samples and other conventions. Therefore the full source code can be found in FormSoftphone.cs file that is related to the interface.
By using Ozeki VoIP SIP SDK only a few objects and the handling of their events are needed to create the whole functionality of a complex softphone. The following objects have been used in this program:
1. Private phoneCall As IPhoneCall
2. Private mediaTimer As MediaTimer
3.
4. Private phoneLine As IPhoneLine
5. Private phoneLineInformation As PhoneLineInformation
6. Private softPhone As ISoftPhone
7. Private wavReader As ozWaveFileReader
ISoftphone
IphoneLine. There can be more telephone lines which mean that you can develop a multi line phone. For simplicity this example only uses one telephone line..
MediaTimer
It is a Timer that ensures a more accurate timing than Microsoft .Net Timer.
ozWaveFileReader
It extends the Microsoft.Net Stream type to simplify the reading and processing of Wav audio files. After the program is started, it automatically registers to a previously specified SIP PBX server. This is made via the InitializeSoftPhone() method that is called in the 'Load' event handler of the interface.
1. Private Sub InitializeSoftPhone()
2. Try
3. Me.softPhone = SoftPhoneFactory.CreateSoftPhone("192.168.91.42", 5700, 5760, 5700, Nothing)
4. Me.phoneLine = Me.softPhone.CreatePhoneLine(New SIPAccount(True, "oz891", "oz891", "oz891", "oz891", "192.168.91.212", 5060))
5. AddHandler Me.phoneLine.PhoneLineInformation, New EventHandler(Of VoIPEventArgs(Of PhoneLineInformation))(AddressOf Me.phoneLine_PhoneLineInformation)
6. Me.softPhone.RegisterPhoneLine(Me.phoneLine, Nothing)
7. Me.mediaTimer = New MediaTimer
8. Me.mediaTimer.Period = 20
9. AddHandler Me.mediaTimer.Tick, New EventHandler(AddressOf Me.mediaTimer_Tick)
10. Catch ex As Exception
11. MessageBox.Show(String.Format("You didn't give your local IP adress, so the program won't run properly." & ChrW(10) & " {0}", ex.Message), String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand)
12. End Try
13. End Sub
Where the softphone object has been instanced with the network parameters of the running computer. Please note that if you do not update these parameters (do not modify the IP address) according to your own computer, the program will not be able to register onto the given SIP PBX. The parameters of the object are the follows: IP address of the local computer, the minimum port to be used, the maximum port to be used, the port that is assigned to receive SIP messages.
Create a phoneLine with a SIP account that can be a user account of your corporate SIP PBX or a free SIP provider account. In order to display the status of the created phoneline, subscribe to its 'phoneLine.PhoneLineInformation' event.
Then you only need to register the created 'phoneLine' onto the 'softPhone'. In this example only one telephone line is registered but of course multiple telephone lines can also be registered and handled with Ozeki VoIP SIP SDK. After the phoneline registration was successful the application is ready to load sound data and to call a specified phone number.
Making an outgoing call
Outgoing calls can be made by entering the phone numbers to be called and clicking the 'Call' button.
1. Private Sub buttonPickUp_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button13.Click
2. If (String.IsNullOrWhiteSpace(Me.labelDialingNumber.Text)) Then
3. MessageBox.Show("You haven't given a phone number.")
4. Return
5. End If
6. If ((Me.phoneCall Is Nothing)) Then
7. If ((Me.phoneLineInformation <> phoneLineInformation.RegistrationSucceded) AndAlso (Me.phoneLineInformation <> phoneLineInformation.NoRegNeeded)) Then
8. MessageBox.Show("Phone line state is not valid!")
9. Else
10. Using openFileDialog As OpenFileDialog = New OpenFileDialog
11. openFileDialog.Multiselect = False
12. openFileDialog.Filter = "Wav audio file|*.wav"
13. openFileDialog.Title = "Open a Wav audio File"
14. If (openFileDialog.ShowDialog = DialogResult.OK) Then
15. Me.wavReader = New ozWaveFileReader(openFileDialog.FileName)
16. Me.phoneCall = Me.softPhone.CreateCallObject(Me.phoneLine, Me.labelDialingNumber.Text, Nothing)
17. Me.WireUpCallEvents()
18. Me.phoneCall.Start()
19. End If
20. End Using
21. End If
22. End If
23. End Sub
By clicking the 'Call' button the file loader window appears. In this window you can select the wav audio file that you want to play into a phone call. The call is made via the IPhoneCall object by Ozeki VoIP SIP SDK. In this way you need to create such a call object in the registered phoneline of the softphone.
To make a successful call you need to subscribe to some events (Me.WireUpCallEvents()). With the help of these events the application will receive information about the changes that occur during the call. After subscribing to these events you only need to invite the Start() method on the IPhoneCall object that represents the call. As a result the call starts to be established.
1. Private Sub WireUpCallEvents()
2. AddHandler Me.phoneCall.CallStateChanged, New EventHandler(Of VoIPEventArgs(Of CallState))(AddressOf Me.call_CallStateChanged)
3. AddHandler Me.phoneCall.CallErrorOccured, New EventHandler(Of VoIPEventArgs(Of CallError))(AddressOf Me.call_CallErrorOccured)
4. End Sub
CallStateChanged event is for displaying the changes of the call status. The call statuses can be the follows (Setup, Ring, Incall, Completed, Rejected).
1. Private Sub call_CallStateChanged(ByVal sender As Object, ByVal e As VoIPEventArgs(Of CallState))
2. Me.InvokeGUIThread(Sub()
3. Me.labelCallStatus.Text = e.Item.ToString
4. End Sub)
5. Select Case e.Item
6. Case CallState.InCall
7. Me.mediaTimer.Start()
8. Exit Select
9. Case CallState.Completed
10. Me.mediaTimer.Stop()
11. Me.phoneCall = Nothing
12. Me.InvokeGUIThread(Sub()
13. Me.labelDialingNumber.Text = String.Empty
14. End Sub)
15. Exit Select
16. Case CallState.Cancelled
17. Me.phoneCall = Nothing
18. Exit Select
19. End Select
20. End Sub
In this case only 'Incall', 'Cancelled' and 'Completed' call states are important. After initializing the call, it gets into 'Setup' state. When the called party accepts the call we receive a notification about it via 'CallStateChanged' event that returns the new state in parameters. If the new state is 'InCall' (so the telephone was picked up) the wav audio file starts to be sent to the other party.
Since the participants of VoIP communication send out a defined amount of sound data within a defined time period, I do not send out the whole sound data at once. With the help of a MediaTimer 320 byte of sound data is sent out in every 20ms periods via the 'SendMediaData'method of of the call object:
1. Private Sub mediaTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
2. If (Not Me.wavReader Is Nothing) Then
3. Dim data As Byte() = New Byte(320 - 1) {}
4. If (Me.wavReader.Read(data, 0, 320) = 0) Then
5. Me.phoneCall.HangUp()
6. Else
7. Me.phoneCall.SendMediaData(VoIPMediaType.Audio, data)
8. End If
9. End If
10. End Sub
11.
If the application plays the whole file, it hang-ups the call via the (Me.phoneCall.HangUp())call.
call.CallErrorOccured event notifies about the reasons that prevents the establishment. Such reason is, for example, when the called party is busy, the call was rejected, the called number does not exist or it is unavailable.
Post Reply
This thread is locked for new responses. Please post your comments and questions as a
separate thread
.
If required, refer to the URL of this page in your
new post
.
Tweet
Return to
Discussion Forum
Start new thread
Active Members
Today
Sekhar Babu
(9)
naveensanagase...
(6)
saravanan
(6)
Last 7 Days
Anil Kumar ...
(124)
Asheej T K
(52)
Prasad kulkarn...
(51)
more...
Awards & Gifts
.NET Jobs
.NET Articles
.NET Forums
Articles Rss Feeds
Forum Rss Feeds
Talk to Webmaster Tony John
Online Members
praveen
DHARMENDRA KUMAR
More...
Advertise
|
http://www.dotnetspider.com/forum/324319-Text-To-Speech-in-ASPNet-And-save-it-into-wav-file.aspx
|
CC-MAIN-2014-42
|
refinedweb
| 2,194
| 59.4
|
).
You can see the number of selections in the statusbar, and the minimap is also of great help to see where the other selections are.
This being said, here's a plugin that will deselect anything that is not currently visible:
import sublime, sublimeplugin
class CropVisibleSelectionCommand(sublimeplugin.TextCommand):
def run(self, view, args):
mask1 = sublime.Region(0, view.visibleRegion().begin())
mask2 = sublime.Region(view.visibleRegion().end(), view.size())
view.sel().subtract(mask1)
view.sel().subtract(mask2)
Using view.visibleRegion(), you could create a plugin that warns you about how many selections are currently hidden, or something like that.
... like')
Yeah, I know that you can use the status bar to display messages.
But, to me at least, that doesn't seem intrusive enough.It's always there, and it doesn't grab your attention when it needs you to know something.
I have a vivid imagination of a "message box" that can be display in any view, which pops up for a few seconds and then closes, and which carries important information (something like the Gmail status messages you get when you delete mails, for example).
Then, the editor could help new users by popping up helpful messages whenever they do something that might warrant more explanation.For example, the first time someone does a multi-selection (which is going to be new to most people), the message box can pop up and say "You made a multi-selection. For more info, click here" or something along those lines.
Anyway, that's just a dream of mine for an editor that actually helps the users learn all its awesome features.
I agree: modal alert boxes are too intrusive, so I tend to open/close the console pane all the time, bad habit.
+1 for modeless alerts!
One way this could be solved without the need for alerts is to "throb" all selected regions in the minimap.
Right now, selected regions in the minimap are indicated by a static solid colour, which can be easily overlooked if your colour scheme contains lots of different colours itself. The eye is attracted first to movement, and second to changes in luminosity. So if the selected regions faded gently from (for example) white to grey to white again, seeing all the selections in the document would be very much easier.
Cool idea or no?
Actually yeah, that's a great idea.I'll just add that making the cursor itself (i.e. one selection) blink as well would also be very welcome, since I sometimes have a little trouble finding it on the minimap.
I still think a cool message api is good for really grabbing someone's attention in other cases, though.
Guess there's lots more to do for the next Sublime versions
|
https://forum.sublimetext.com/t/add-a-warning-when-multi-selecting-invisible-text/804/6
|
CC-MAIN-2016-18
|
refinedweb
| 461
| 63.29
|
I am attempting to make a Windows PC Toast notification. Right now I am using a mixture of Swing and JavaFX because I did not find a way to make an undecorated window with FX. I would much prefer to only use JavaFX.
So, how can I make an undecorated window?
Edit: I have discovered that you can create a stage directly with
new Stage(StageStyle.UNDECORATED).
Now all I need to know is how to initialize the toolkit so I can call my
start(Stage stage) method in
MyApplication. (which
extends Application)
I usually call
Application.launch(MyApplication.class, null), however that shields me from the creation of the
Stage and initialization of the
Toolkit.
So how can I do these things to allow me to use
start(new Stage(StageStyle.UNDECORATED)) directly?
I don't get your motivation for preliminary calling the start()-method setting a stage as undecorated, but the following piece of code should do what you want to achieve.
package decorationtest; import javafx.application.Application; import javafx.stage.StageStyle; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; public class DecorationTest extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { primaryStage.initStyle(StageStyle.UNDECORATED); Group root = new Group(); Scene scene = new Scene(root, 100, 100); primaryStage.setScene(scene); primaryStage.show(); } }
|
https://javafxpedia.com/en/knowledge-base/8129207/javafx--undecorated-window
|
CC-MAIN-2020-40
|
refinedweb
| 226
| 52.05
|
Designing Reusable Frameworks!
If you would like to receive an email when updates are made to this post, please register here
RSS
Thank you for just referring to lambda expressions as a shorthand for anonymous delegates. It drove me nuts trying to grasp the concept early on due to all the space dedicated to the origins in calculus (it served to confuse more than inform). In fact, that goes for a lot of these guidelines; I would have saved a bit of time/frustration if these were around a few months ago rather than the long drawn out MSDN articles introducing LINQ. Straight and to the point is great (lamdbas are delegates, LINQ is a bunch of extension methods, the nature of Expression<>.
One thing, though: for us language purists, could you include alternate method call versions of sample code instead of just the language extensions? I find the not-quite-SQL format of the LI part to be more confusing than helpful due to the odd structuring of the SELECTs
Don't seem to be able to comment against that post so I'll post here...
Just wondering whether there should be explicit treatment of extension methods against enumerations in the guidelines. It seems to me that it will be quite common to see something like:
public enum MyEnum {
ValueOne, ValueTwo
}
public static class MyEnumExtensions {
public static string ToHumanReadableString(this MyEnum myEnum) {
//impl
}
According to the guidelines, this is bad because the extensions are in the same namespace as the enumeration. But is it really such a bad thing for enumerations? They're a special case, IMO - these members cannot be added directly to them.
Krzysztof Cwalina savā vietnē ( ) paziņojis
Comments and trackbacks are back on after a futile battle with spam. I'll see how long it
You know that I'm a big fan of framework and library design so also have been a big fan of Framework
[ Nacsa Sándor , 2009. január 19. – február 5.] Ez a Team System változat fejlett eszközrendszert kínál
PingBack from
|
http://blogs.msdn.com/kcwalina/archive/2008/03/12/8178467.aspx
|
crawl-002
|
refinedweb
| 338
| 64.54
|
0
I'm working on a program that reads a file of scores and then outputs the number of scores in certain ranges. I've got it to read the input file (scores.txt) which is set up as follows; 76 89 150 135 200 76 12 100 150 28 178 189 167 200 175 150 87 99 129 149 176 200 87 35 157 189
there are 8 different score ranges and I need to output how many scores are in each range. So far I'm using one range to make sure I figure this thing out. I'm very new to programming. It works if the first number is within the range, but that's as far as it gets. if the first number in the file is not within the range, it outputs nothing. I am totally lost, I'm not sure I'm even going about this the right way. Any ideas?
#include <iostream> #include <fstream> #include <iomanip> using namespace std; const int MAX_CODE_SIZE = 50; void readCode(ifstream& infile, int list[], int& length, bool& lenCodeOk); int main() { int codeArray[MAX_CODE_SIZE]; int codeLength; bool lengthCodeOk; ifstream incode; incode.open("scores.txt"); if (!incode) { cout << "Can't open the input file" << endl; return 1; } readCode (incode, codeArray, codeLength, lengthCodeOk); incode.close(); return 0; } void readCode(ifstream& infile, int list[], int& length, bool& lenCodeOk) { int count; int value; int rangeA; lenCodeOk = true; infile >> length; if (length > MAX_CODE_SIZE) { lenCodeOk = false; return; } rangeA = 0; value = 0; for (count = 0; count < length; count++) infile >> list[count]; { value = list[count]; if (value >= 0 || value <= 24) { rangeA = rangeA + 1; } else { rangeA = rangeA; } } cout << "The number of students with scores 0 - 24 are: " << rangeA << endl; cout << endl; }
|
https://www.daniweb.com/programming/software-development/threads/121565/reading-data-from-a-file-into-an-array
|
CC-MAIN-2017-09
|
refinedweb
| 283
| 72.39
|
Today,I am going to show how to create setup file(.exe) with SQL Database in visual studio 2010.In our previous tutorial I have created a setup file(.exe) without including Database in Setup File.This method is purely different to the previous setup creation method ,But it is very easy .Remember one things ,when you install this setup to your desktop ,first install .NET Framework 4.0 or 4.5 in your machine otherwise it will give error.There are some steps to create setup file with SQL Database, which are given below:
Step 1 : First open your visual studio -->File -->New-->Project-->Select Windows Forms Application -->OK-->and drag and drop Label,TextBox & Button control on the Form from toolbox as shown below:
Note:-
If you are facing problem to Add .mdf file in your solution Explorer then read following links:-
Step 3 : Now Double click on Database.mdf file-->Add New Table as shown below:
Step 4 : Now Enter your table column name-->and press save button as shown below:
Step 5 : Now go left window of your visual studio-->click Data sources (if not available then click Data Button on top-->Click show Data sources)-->Add New Data source --> Select Data Source -->Next-->Select Dataset -->Next-->Choose connection string -->Next
Now continue with Next Button then you will see as shown below-->Next.
Step 6 : Now open Solution Explorer -->Add New Web Form --> drag and drop DataGridView control from toolbox-->and configure it as before.
Step 7 : Now open Solution Explore-->Right Click on Project -->Add New Reference-->.NET --> add Two Namespace as given below-->OK
- System.Configuration
- System.Configuration.install
Step 8 : Now Double Click on Submit and Show Table Data Button and write the following codes as given below.
using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace winsetup { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["newConnectionString"].ConnectionString); con.Open(); String str = "insert into student(Name,mobile,city) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')"; SqlCommand cmd = new SqlCommand(str, con); cmd.ExecuteNonQuery(); con.Close(); label4.Text = "Data has been successfully inserted"; } private void button2_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(); this.Hide(); frm2.Show(); } } }
Step 9 : Now open App.config file from Solution Explorer --> change name and add same code in your connection code as shown below:
Note:- Now i am going to create setup file with SQL Database as shown below .
Step 10 : Now open Solution Explorer -->Right click on the project -->Properties -->click publish Button From left window as shown below:
Step 11 : Now First Create New folder (mysetup) on your Desktop .
Step 12 : Now Click Publishing Folder Location --> Select Your Folder(mysetup) from Desktop as shown below-->click Open.
Step 13 : Now click Prerequisites Button-->Select following options as shown below-->OK.
Step 14 : Now click Options -->Write the required field as shown below-->OK
Step 15 : Now click Publish Wizard.. from bottom --> click Next as shown below.
Step 16 : Now proceed with Next Button --> click Finish .
Step 17 : Now click Publish Now Button from Bottom --> Your setup will be created in your Desktop folder (mysetup).
see it:
Step 18 : Now First install .NET Framework 4.0 or 4.5 in your system,If you are using visual studio 2010 or 2012.After that you can install this setup.It will take few minutes.
Step 19 : Now Double click on setup Icon on the Desktop .You will see.
Step 20 : Now Enter the required field and click Submit Button.You will see.
Step 21 : Now Click Show Table Data Button.You will see.
Step 22 : If you want you can create setup file in visual studio 2012 and visual studio 2013 also.
For More:-
- Ado.Net Application
- How to Build Real Form Filling application in asp.net like IBPS
- Xml Application
- E-Post System Project
- Take Print receipt in Windows Form Application
- oops concepts
- Data Integrity in Sql
- File Handling Real Application
- Overview of C#
- How to use WCF Services in asp.net application
- How to use different connection strings in asp.net
- Operator overloading in c#
- Web Forms controls
-
Application Setup File
Application not formetted well this error occured. please solve it
hi Tej Parikh ! when i have installed this setup on my system then it has not shown any error.i have shown installation on my desktop in above tutorials. pl follow each step very carefully again which is shown as tutorials.first install .net framework 4.0/4.5 in your system.then create setup and install them.it will work..
Can i create a setup file for a website?
if yes please tell me the procedure to build it otherwise what is the other option to do this?
yes, you can create web setup for website also.see it-
hi, nice post but there is a problem that i could find the data in my table offcourse the data is displaying on second form but when i close the application then restart there is no data not even this data is stored in the database. could you please help me.
Thanks in advance
you can improve the setup, before installing the setup check the .net version if its not 4/4.5 then tell user to download it
hi, when i clik the save button their is not showing any connection error but data is not saved in table. plz help me
yes,, correct @Sukant
hi RAMASHANKER !!
we can add the details to table and it is visible in gridview like this,
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["newConnectionString"].ConnectionString);
con.Open();
String str = "insert into student(name,roll,class) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
int a=cmd.ExecuteNonQuery();
SqlDataAdapter ada = new SqlDataAdapter("SELECT *from student", con);
DataTable dt = new DataTable();
ada.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
if (a==1)
label7.Text = "Data has been successfully inserted";
else
label7.Text = "not inserted";
but when i go
server Explorer > show table data
and all values are NULL
:(
Please give me a solution.
cannot we setup a file directly with SQL database ?
Use this code instead of DataTable dt = new DataTable();,otherwise it will show null value.
ada.Fill(dt);
dataGridView1.DataSource = dt;
Dataset ds = new Dataset();
ada.Fill(ds);
dataGridView1.DataSource = ds;
I am facing the same problem. Data is not reflected in database. It shows in the grid view but when we go to server explorer -> show table data the value is not reflected. Plz Help Soon
hi akshay ! first tell me what error is showing....
well, this is what i did
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataSet mydataset;
string sql = null;
sql = "Select id,name,dates from temp";
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter();
da.SelectCommand = cmd;
mydataset = new DataSet();
da.Fill(mydataset, "data");
dataGridView1.DataSource = mydataset;
dataGridView1.DataMember = mydataset.Tables["data"].ToString();
label5.Text = "Data refreshed";
con.Close();
and now i have repeat what Akshay said before "It shows in the grid view but when we go to server explorer -> show table data the value is not reflected"
And see there is no error at all.
hi i want the exact conversion bit for a dot net application, can any you help me
Is this db is always attached with application on various systems? I mean this db will be a local copy whwrever I will install it right?
Ok almost every thing is same in visual studio 2010 and visual studio 2012....
I follow your steps of
"How to create setup file(.exe) with Database in Visual studio 2010"
in visual studio 2012
But when i click on Publish wizard button...and after that when i click on Finish button.it gives me the following error.
Error 1 Cannot publish because a project failed to build
Error 2 Unable to copy file "App.config" to "bin\Debug\app.publish\Application Files\Finding Mac Address of the system_1_0_0_0\Finding Mac Address of the system.exe.config.deploy". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. Finding Mac Address of the system
...please help me what is the problem
This is a problem with Visual Studio that can occur when you have add-ins installed. Instead of using the Publish button in the Publish tab, use Build/Publish from the menu on the top of Visual Studio.
If you use the Publish button, it runs through the add-ins before doing the build (or something like that). If you use Build from the menu instead, it goes straight to msbuild and ignores any add-ins you have installed.
Hope this helps u..
hello sir. I have an error after the publish wizard the error is "Cannot publish because a project failed to build."
Plz help me...
hi chetan, follow each steps carefully,some times it will happened.create new application ,don't use previous application to create the setup.it will definitely work,if any problem then you can contact me through Contact Me form.
hello sir, thanx for reply. I solved the above issue. I have another query.
I want to set the installation path of the my setup file. sir tell me how to do that ? Also i want to know where is database is stored after completion of installation ?
Plz help me sir it's urgent. thnaxx..
Hello sir, Thanx for reply.. i solved the above issue. I have another query.
I want to set the installation path in setup file and also i want to know where is database is storing after the installation how can i take backup of database ?
sir plz help me it's urgent..
Thank you..
hi chetan,first create a folder on Your Desktop or any drive --> give that folder path (i have explained it in above tutorial)-->all database file(sql server) + application will stored in this folder --> when you install it any client machine---> all database is stored on installation path (your drive, where you install it c,d or other) ..
Sir i already do the above process but it is not working. When i m seeing the path of the project it is "C:\Users\hp\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Chetan\setupfile". I want to install the setup in c drive and program files and also the database in that folder..
Thank you.
hi RAMSHANKAR
I want to add framework to my setup file.
means when i click on setup file then first it check that there is framework installed on my machine or not...
nd if it is not installed then first it install that nd then my project will install.......................
plz help me
Hello sir,
I want to make setup file of my windows application ,I am using entity framework model,C#.NET,Winform ,Database I am using is sql server 2008,What is process of making setup file & setup should work anywhere .... ,I am getting JIT debugger error on installing & ruining application.
Please help me I am getting JIT debugger error....
hi suraj ! i have already mentioned 'How to create setup file with sql database' in above tutorial.follow each step and install .net framework 4.0/4.5 before creating the setup file. jit compiler error is coming because you have not create setup file correctly.
I have followed your above Information(Tutorial) for make setup for C# Windows Application which has database in
SQLExpress2008 but following error is occurred when i open that setup application
"Unhandled exception has occurred in your application.
An attempt to attach an auto-named database for file C:\Document and Setting\Rachit-41\LocalSettings\Apps\2.0\YBO9521P.Y3J\db\payrolldatabase.mdf failed.
A database with the same name exists, or specified file cannot be opened.,or it is located on UNC share."
hi Prajakta ! change your database name because one Database.mdf file is exist in your c dive.
change Database.mdf --> mydb.mdf or another name.then it will work.
I hope you can do this...
Sorry Sir But i have changed the database with another name like mydb1.mdf
but it shows also above."
Hi Prajakta ! First read below link .it may be helpful to solve this problem.
read this carefully. first create new application and perform this steps.if it will work.then perform this steps in your original project.
i have changed database name like mydbpay.mdf. but it gives error when i build the program code.
It shows following."
What can i do for this?
i have a problem that i am creating printable application so please tell me how to design winform so that that page data should be show on a4 size paper bottom.....
hi Ankur ! Read below link.It will be helpful for you......
Thank You for this tutorial. It was GREAT!!!
Good Work ...!
Sir When i m seeing the path of the project it is "C:\Users\hp\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Chetan\setupfile". I want to install the setup in c drive and program files and also the database in that folder.. How to backup data from this setup after installation
Pls help me Thank you.
Is there any idea to hide our database files which is stored in C drive....to be safe from unknown user.
Setup is not asking for installation path ???
Please Help !!!
Sir RAMASHANKER VERMA when i insert data into student tbl then object reference not set to an instance of object error is genrate,how to solve it??
hi ,
check your connection string codes whether you are inserting values in same columns which are created in your table or don't change order of your column and data types,see it carefully.this error basically comes due to change order of values or data types in your connection string.
sir its connection string problem,connection method set on form load,when form is run that error is generate object reference not set to an instance of object ,please help
will this exe file work on client machine?which have not sql server
yes , you can install it on other system .
ok thanx sir
Hello sir,
Your tutorial was really helpful and easy to understand so that I was able to create my first setup using DB. Now I am developing a C# windows Application which has a third party Database that is sql server management studio 2008.Will it be possible to create a setup for it in the similar way described above with its database having .dbo extension instead of .mdf? pleas help me.
Hi Sir,
My file.exe created properly.It working fine on my machine but when i am Installing on client machine database module not working
please reply me
I am using an oracle sql database with my website in visual studio 2012. While creating the .exe file..how is the database getting copied to the client's machine? Is it automatically attaching the database along with the .exe file?
how to add installation wizard,agreement,icon in this type of exe???
and why this exe is not displayed in program files??
my app.config code
my App.config file code is as bellow but i am getting error I explain bell
when i publish my application this will showing this error.
To enable 'Download prerequisites from the same location as my application' in the Prerequisites dialog box, you must download file 'DotNetFX45\dotNetFx45_Full_x86_x64.exe' for item 'Microsoft .NET Framework 4.5 (x86 and x64)' to your local machine. For more information, see.
please help me to solve this problem.
Hi Ankit,
Read step 18, first install latest .net framework 4.0 or 4.5 or 4.5.1 on your system, then it will work...
hi ramshanker sir
I check my folder and sqlexpress is not showing in my folder
please help me to rectify the issue
hi ramshankar sir
in my folder that is on desktop sqlexpress2008 is not showing
please help
hi sir
when i trying to install this exe on other machine
getting an sql connection error
i installed .net framework 4.0 on that machine
please help
Can I implement backup and restore in desktop application, that can be work on any desktop machine, please help me
. I develop one Invoice application, but backup and restore not work with local database it find sql server & database
How to attach database in set up file
hello sir ,after creating setup it is working on my pc and if i use other pc where vs and sql server not installed and run this setup it showing Network instance error means service based database not working
hi Manvendra, your sql database is not running on client machine,first install your setup file on client machine after that turn on it from below file..
Is there a way to provide an option to user to just download the setup to user selected folder so that user can later install when we select 'from a website' option while publishing the code..
i want solution for crystal report. whenever i run exe on another system it gives error like failed to open connection
unable to satisfy all prerequisites for WindowsFormApplication2. Setup cannot continue until all system component have been successfully installed
I have an error "Publication not possible due to a failure in generating the project" .
to activate 'Download the required components from
the location of my application 'in the Prerequisites dialog box,
you must download the file ' DotNetFX452 \ NDP452 - KB2901907 -x86 -x64- ENU.exe - Allos ' for
the item ' Microsoft .NET Framework 4.5.2 (x86 and x64) ' on the local computer
Ps: I use visual studio 2015
hello,
I have created setup file and its is created successfully.
But my query is what should i do for database backup?
and how to restore the database backup?
Please suggest me.
Thanks.
Hi, I have a desktop application with C# code in visual studio 2015 IDE connected with MS Access 2007 database. I do not want to publish in web but I want to use this application in several computer those are not connected with LAN. Is it possible?
|
http://www.msdotnet.co.in/2013/07/how-to-create-setup-fileexe-with.html
|
CC-MAIN-2017-26
|
refinedweb
| 3,073
| 67.15
|
Im xorhash, a guest poster, here to talk about my tale going down a trip on the memory lane with QuakeNets service bot Q. If youre not interested in IRC, you can probably skip this one.
As far as I know, QuakeNet’s service bot Q went through these three major codebases:
a. the old Perl Q, b. the first version written in C, and c. Q as part of newserv.
There’s a reason I didn’t have anything to link for (a). That’s because to the best of my knowledge and research, no version has survived these past decades.
As for (b), it seems only the linked version 3.99 from the year 2003 was saved. The CVS repository and thus commit history has been lost.
If anyone has either actual code for the old Perl Q or the CVS repo for the old Q written in C, please reach out to me via `xorhash ++at++ protonmail.com’. I’m most interested in looking through it.
However, not all hope was lost with the old Perl Q. As it turns out, most likely, the old Perl Q was actually based on an off-the-shelf product called “CServe”. What makes me think so?
Let’s take a look at [the QuakeNet Q command listing from1998.
I picked the command “WHOIS” and googled its use “Will calculate a nick!user@host mask for you from the whois information of this nick.” This lead me to a help file for StarLink IRC. At the top, it reads:
CStar3.x User Command Help File **** 09/10/99 Information extracted from CServe Channel Service Version 2.0 and up Copyright (c)1997 by Michael Dabrowski Help Text (c)1997 (c)1997 StarLink-IRC (with permission)
Wait a second, “CServe Channel Service”? I know that from somewhere.
Q!TheQBot@CServe.quakenet.org
So the commands between that help file and the QuakeNet Q command listing match up and so does Q’s host today. Most likely, I’m on the right track with this. What’s left is to track down a copy of CServe.
Note: I’ve been on the old Perl Q for a while and this strategy didn’t useto work. It seems Google newly indexed these pages. For once I can sincerely say: Thank you, Google.
I found that CServe was hosted on these websites:
a. Version 3.0 on, b. Version 3.1 on, c. Version 4.0 on, and d. Version 5.0 and above on.
The only surviving versions are 3.0 and 5.1. CServe got renamed to “CS” starting with 5.0 and was rewritten in C by someone other than the original CServe author, going by the comments in the file header of CS5.1 `src/show_access.c’. CS was actually sold as a commercial product. I wonder how many people bought it.
QuakeNet most likely took a version between 2.0 and 4.0, inclusive, as the basis for the old Perl Q. Which one in particular it was, we may never know. If you have any details, please reach out to me at the e-mail address above.
I can’t make any clever guesses anyway since the only versions that the web archive has are 3.0 and 5.1. The latter is written in C, so it quite obviously can’t be the old Perl Q.
So now that I have CServe 3.0, I wanted to actually see it running.
There are three ways to reasonably accomplish this:
a. port CServe to a modern IRCd’s server-to-server protocol, b. port an old IRCd to a modern platform, c. emulate an old platform and run both IRCd and CServe there.
I chose option (b). Once upon a time, I did option (a) for the old UnderNet X bot. It was a very painful exercise to port a bot that predates the concept of UIDs (or numeric nicks/numnicks as ircu’s P10 server-to-server protocol calls them). There’s nothing tooexciting about doing (c) by just emulating a 486 or so and FreeBSD, just sounds like a boring roundtrip of emulation and network bridging.
Fortunately, the author was a nice person and wrote on the CServe website that version 3.0 requires “ircu2.9.32 and above”.
It seems the ircu2.10 series followed right after ircu2.9.32. While I’m sure there’s some linking backwards compatibility, determining which ircu in the ircu2.10 series still spoke enough P09 to link with CServe sounded like an exercise in boring excruciating pain. Modern-day ircu most certainly no longer speaks P09. Besides, what’s the fun in just doing the manual equivalent of `git bisect’?
So after grabbing ircu2.9.32, I tried to just straightforward compile and run it.
There’s a `Config’ script that’s supposed to be kind of like autoconf `configure’, but I’ve found it extremely non-deterministic. It generates `include/setup.h’. I’ve made a diff for your convenience. It targets Debian stable, and should work with any reasonably modern Linux. There are special `#ifdef’ branches for FreeBSD/NetBSD in the code. This patchset may break for BSDs in general.
Do not touch `Config’, meddle with `include/setup.h’ manually. Remember this is an ancient IRCd, there are actual tunables in `include/config.h’.
The included example configuration file is correct for the most part, but the documentation on U:lines is wrong. U:lines do what modern-day U:lines do, i.e., designate services servers with uber privileges.
U:cserve.mynetwork.example:*:*
Of course, I’m dealing with old code. It wouldn’t be old code if I didn’t have some things that just make me go “Excuse me, but what the fuck?”
aClient *find_match_server(mask) char *mask; { aClient *acptr; if (BadPtr(mask)) return NULL; for (acptr = client, (void)collapse(mask); acptr; acptr = acptr->next) { if (!IsServer(acptr) && !IsMe(acptr)) continue; if (!match(mask, acptr->name)) break; continue; } return acptr; }
See that `continue’ way on the left? What is it doing there? Telling the compiler to loop faster?
So apparently some of this code predates C89. Which means it uses old-style declarations, but that’s okay. It also uses old-style varargs, which is adorable.
The hacks around not even that being thereare adorable, too:
#ifndefUSE_VARARGS /*VARARGS*/ voidsendto_realops(pattern, p1, p2, p3, p4, p5, p6, p7) char*pattern, *p1, *p2, *p3, *p4, *p5, *p6, *p7; { #else voidsendto_realops(pattern, va_alist) char*pattern; va_dcl { va_list vl; #endif Reg1 aClient *cptr; Reg2 int i; char fmt[1024]; Reg3 char *fmt_target; #ifdef USE_VARARGS va_start(vl); #endif (void)sprintf(fmt, ":%s NOTICE ", me.name); fmt_target = &fmt[strlen(fmt)]; for (i = 0; i <= highest_fd; i++) if ((cptr = local[i]) && IsOper(cptr)) { strcpy(fmt_target, cptr->name); strcat(fmt_target, " :*** Notice -- "); strcat(fmt_target, pattern); #ifdef USE_VARARGS vsendto_one(cptr, fmt, vl); #else sendto_one(cptr, fmt, p1, p2, p3, p4, p5, p6, p7); #endif } #ifdef USE_VARARGS va_end(vl); #endif return; }
These functions were declared like this (the example chosen above actually has
no declaration because why not):
/*VARARGS1*/ extern void sendto_ops();
There are `mycmp’ and `myncmp’ for doing RFC1459 casemapping string comparisons. `strcasecmp’ got `#define’d to `mycmp’, but in one case `mycmp’ got `#define’dback to `strcasecmp’. It seemed easier to just remove `mycmp’, replacing it with `strcasecmp’ and forgo RFC1459 casemapping. This is doubly useful because CServe doesn’t actually honor RFC1459 casemapping.
ircu uses PING cookies. I was rather confused when I didn’t get one immediately after sending `NICK’ and `USER’. In fact, it took so long that I thought the IRCd got stuck in a deadloop somewhere. That would’ve been a disaster since the last thing I wanted to do is get up close and personal with the networking stack.
As it turns out, it can’tsend the cookie:
/* * Nasty. Cant allow any other reads from client fd while we're * waiting on the authfd to return a full valid string. Use the * client's input buffer to buffer the authd reply. * Oh. this is needed because an authd reply may come back in more * than 1 read! -avalon */
Nasty indeed.
I lowered `CONNECTTIMEOUT’ to 10 in the diff linked above. This makes the wait noticeably shorter when you aren’t running an identd.
Not that CServe is much better. I have to hand it to Perl, I only needed to undo the triple-`undef’ on line 450 of `cserve.pl’ and it worked with nomodifications. God bless the backwards compatibility of Perl 5.
That said, it has its own interesting ideas of code. This is the main command execution:
foreach $i (keys %commands) { if($com eq $i) { $found = 1; break; } } if($found == 1) { open(COMMAND, "<./include/$com"); @evalstring = <COMMAND>; close(COMMAND); foreach $i (@evalstring) { $evals .= $i; } eval($evals); } else { ¬ice("2No such command 1[4$com1]. /msg $unick SHOWCOMMANDS\n"); }
Yep, it opens, reads into an array, closes and then evals. For every command it recognizes. Of course, this means code hot swapping, but it also means terrible performance with any non-trivial amount of users.
Oh, and all passwords are hashed. But they’re hashed with `crypt()’. And a never-changing salt of ZZ.
up & running
Was it worth it? No, not really. Would I do it again? Absolutely.
You probably do not want to expose this to the outside world. The IRCd code is scary in all the wrong ways.Further Links
Some other things if you’re into ancient IRC stuff:
Continue reading on virtuallyfun.com
|
https://hackerfall.com/story/irc-necromancy
|
CC-MAIN-2019-30
|
refinedweb
| 1,592
| 76.82
|
18th
Python Namespace Packages for TiddlyWeb
In Friday’s TiddlyWeb Dev/Deploy Workshop posting I said that mature plugins need to be packaged so they can be indexed by PyPI and installed via
easy_install and
pip. At base this is relatively straightforward, put some stuff in a directory, make a setup.py, register the package, package up a source distribution, tell PyPI about it.
This is okay if you have a good name for your package, but what about packages, like plugins for TiddlyWeb, which have names which are only meaningful in their use context? You can’t just use the name of the module, otherwise you end up with namespace collisions, trouble finding stuff, and associated beasts of chaos.
Thankfully distutils, setuptools, pip, etc conspire to support a notion called
namespace_packages which can solve this issue. Unfortunately using the feature is not exceptionally well documented. I found getting started a bit frustrating, until I sort of cracked the nut. Here’s some info for reference.
First some prerequisites:
- You need setuptools
- You need a username and password on PyPi.
- Some understanding of how to make a python package distribution. Here’s one tutorial: Use setup.py to Deploy Your Python App with Style.
- Some understanding of Python packages.
That tutorial includes a section about using
namespace_packages under the heading “Multiple Distributions, One (Virtual) Package”. That “Virtual” is key: if you wish to use namespace packages there much be no real distribution which occupies the namespace. In the example of tiddlywebplugins, you can have tiddlywebplugins.static and tiddlywebplugins.utils distributions which are members of the tiddlywebplugins namespace, but you must not have a tiddlywebplugins distribution. If you do the packages which are supposed to occupy the virtual namespace will not be found. The upshot of this is that if you already have a package out there using a name that you want to use as a namespace, you will need to rename the existing package (this is why the old tiddlywebplugins package is now tiddlywebplugins.utils
Packaging a Plugin
So say you have a TiddlyWeb plugin called foobar.py sitting in a directory somewhere. You’ve determined that it is a happy little plugin and the world would benefit if it could be installed easily. You’ve heard of the tiddlywebplugins namespace and you’d like to join the party. Here’s what you do.
- In that directory make a
tiddlywebpluginsdirectory.
- Edit
tiddlywebplugins/__init__.pyto include just this line:
__import__("pkg_resources").declare_namespace(__name__)
- Move foobar.py into the tiddlywebplugins directory.
- Create a
setup.py(in the original directory) that includes at least:
from setuptools import setup, find_packages setup( version = '0.1', namespace_packages = ['tiddlywebplugins'], name = 'tiddlywebplugins.foobar', description = 'A TiddlyWeb plugin for foobaring the fritz.', install_requires = ['setuptools', 'tiddlyweb'], )
- Do not import from the tiddlywebplugins package in setup.py. This will make installs struggle or fail later.
- Learn enough about distribution to register the package and upload it. The links above point to enough documentation to figure that part out. If you can’t be bothered to read that documentation then you shouldn’t be distributing packages. We wouldn’t want you aoling all over PyPi.
- When you want to use your foobar plugin in a TiddlyWeb instance or application refer to it as
tiddlywebplugins.foobar.
|
http://cdent.tumblr.com/post/216241761/python-namespace-packages-for-tiddlyweb
|
crawl-003
|
refinedweb
| 544
| 50.33
|
Nov 07, 2014 03:00 AM|Kevin Shen - MSFT|LINK
Hi topolino,
Based on my understanding ,your message are in string type.
so you can get the string size in your hub, when you are ready to send .
public class MyHub : Hub { public void Send(string userId, string message) { int size = System.Text.ASCIIEncoding.Unicode.GetByteCount(message); Clients.User(userId).send(message); } }
Best Regards,
Kevin Shen.
Nov 10, 2014 09:54 PM|Kevin Shen - MSFT|LINK
Hi toplion,
As far as I know,you can serialize your object ,then get the size code like below:
private int GetObjectSize(object Object) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); byte[] Array; bf.Serialize(ms, Object); Array = ms.ToArray(); return Array.Length; }
Best Regards,
Kevin Shen.
Nov 12, 2014 09:08 PM|Kevin Shen - MSFT|LINK
Hi topolino,
It seems that ther is no evidence prove that signalR can give the message information.
Even when you want to send message to multiple clients,but i think you can try my code above to get the message size in your hub.
Best Regards,
Kevin Shen.
7 replies
Last post Nov 12, 2014 09:08 PM by Kevin Shen - MSFT
|
https://forums.asp.net/t/2017318.aspx?Get+message+size
|
CC-MAIN-2018-05
|
refinedweb
| 196
| 65.62
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.