text
stringlengths 20
1.01M
| url
stringlengths 14
1.25k
| dump
stringlengths 9
15
⌀ | lang
stringclasses 4
values | source
stringclasses 4
values |
|---|---|---|---|---|
import "github.com/golang/go/src/encoding/csv"
Package") // TrailingComma bool // Deprecated: No longer used. //.
Code:.
Code:..
Code:). Updated 2019-09-18. Refresh now. Tools for package owners.
|
https://godoc.org/github.com/golang/go/src/encoding/csv
|
CC-MAIN-2019-51
|
en
|
refinedweb
|
Closing Presentation - The Transformation of Work and the Office
great work guys - interesting to hear more about casablanca and getting close to the metal.
C++ is back
Wow nice. Would love to try it.
Very interesting. What's about using this library for not Azure application? For instance, can I use namespace "http" to write REST service as console desktop application or "http::json" to serialize objects? As far I understand that answer is "Yes".
@maxbeard12: Correct! Azure is not required for consuming REST services.
BTW, We're not monitoring this page actively, so for the future, I suggest Casablanca forums for questions and feedback:
Artur Laksberg,
Casablanca Team
|
https://channel9.msdn.com/Events/TechEd/Australia/2012/AZR331?format=html5
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
problems using Image.open with png file
The following code
from PIL import Image img = Image.open('test.png') img.show()
throws "
IOError: broken data stream when reading image file". Reading the image from the camera roll works flawlessly, though:
import photos img = photos.pick_image() img.show()
The first image prints as
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size 152x152 at 0xDFB438C>
the second one as
<Image.Image image mode=RGBA size 152x152 at 0xDFB460C>
But
PIL.PngImagePlugin.PngImageFileis a subclass of
Image.Imageand things like
img.show()should work in both cases. In fact, nothing seems to work with the first
img.
A quick peruse of google seems to suggest that this might be caused by a
libjpegversion problem.
PS: It used to work with Pythonista 1.3.
This code seems to work quite consistently:
import Image, photos pngFileName = 'test.png' def img_info(img): print(img) print(img.format, img.mode, img.size, img.palette, img.info) img = photos.pick_image() img_info(img) img.save(pngFileName) # write out the image as .png img = Image.open(pngFileName) # read in the image img_info(img) img.show() # This might take a few seconds
Is the image.format of your image really set to 'PNG'?<br />
Can you use the code above to create a new .png file that you can successfully .show()?
Yes,
img.formatis set to 'PNG'.
Your code, however, is a working fine and can be used to create a new .png file that can successfully be dealt with. Kind of weird, though. Why wouldn't it work if saved directly by a dropbox sync?
Thanks for the workaround, ccc.
If you create a gist of the Dropbox code then perhaps others in the Forum can discover why it is not working.
|
https://forum.omz-software.com/topic/440/problems-using-image-open-with-png-file
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Hello, this my first thread and I need some supper fast help I'm on a deadline...
I have applied for a Microsoft program but part of the application process is to complete this assignment...
You are to create a console application that accepts exactly one command-line argument. If it doesn’t receive the argument, the application must display an error message and exit. The application must parse the text input and output the number of times each letter of the alphabet occurs in the text. Case sensitivity is not required.
For example, if the command-line argument is “baaad” the displayed result must be:
There are 3 A's
There are 1 B's
There are 0 C's
There are 1 D's
There are 0 E's
There are 0 F's
etc...
I've gotten this so far...
<html> <head> <script type="text/javascript"> function count_char($str,1) { return ("count_char($str,1); } <?php $ echo(count_chars($str,1)) </script> <body> <form> <input type="text" value="Please enter string" /> <input type="button" value="Click me!" onclick="count_chars($str,1))" /> </form> <p>By clicking the button above the letters in the string will be counted and displayed</p> </body> </html>
But I know for sure I messed something up/left something out because whenever I try to run the code, clicking the button doesn't do anything, Please Help Me!!!
I started learning from w3schools.com but they don't tell you exactly how to assemble the Java Script code I have until 6/25/10 to submit my code to my application overseer.
|
https://www.daniweb.com/programming/web-development/threads/292116/urgent-java-script-help-needed
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Dynamically created Menu is triggered by space key
Hi,
When I have a menu which is created on demand, after first request - it can be triggered by space key press what is completely undesired.
Here is example code:
import QtQuick 2.9 import QtQuick.Controls 2.2 import QtQuick.Window 2.2 ApplicationWindow { visible: true property Menu menu: null Button { text: "get menu" onClicked: { if (!menu) menu = menuComp.createObject(this) menu.open() } } Component { id: menuComp Menu { width: 200; height: 400 MenuItem { text: "action 1" } MenuItem { text: "action 2" } } } }
Do You think it is a bug or a kind of my misusing?
I think it's because the menu gets the keyboard focus when it's created.
Have You any idea how to get rid of this?
I just checked
activeFocusof menu is always
falsewhether menu is visible or not and
focusis
falseby default
The following seems to work:
onClicked: { if (!menu) menu = menuComp.createObject(this) menu.open() menu.focus = false }
@Wieland
Works, but only first time...
When menu is ignored by pressing
ESCor clicking outside, problem comes back, but when menu item is selected menu doesn't react on space key.
Mhh, maybe this?
onClicked: { if (!menu) menu = menuComp.createObject(this) menu.open() focus = false // remove focus from the button on click }
Brilliant!
Thank You!
|
https://forum.qt.io/topic/82081/dynamically-created-menu-is-triggered-by-space-key
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Hey All,
If anyone has a fix for this it would be greatly appreciated, or just let me know if I'm missing something, but I can't seem to get a port open while running on iOS. I've read a lot of reasons for this is that the port is still in-use from a previous session of the application that failed to close the port properly, but that is simply not there case here. To test this, I've tried looping through a variety of different port ranges on application start, and this error occurs on every port attempted...
import flash.net.ServerSocket;
import flash.net.Socket;
...
for (var port:Number = 1000; port <=1020; port++){
var serverSocket:ServerSocket = new ServerSocket();
serverSocket.addEventListener(Event.CONNECT, socketConnectHandler);
serverSocket.bind(port);
serverSocket.listen();
}
it breaks every time on serverSocket.bind(port) with "Error #2002: Operation attempted on invalid socket.";
Any help would be greatly appreciated. Also, I'm using Flash Builder 4.6 compiling to Flex 4.6.0 SDK.
Thanks!
Docs for ServerSocket:. html
Note: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices.
You should trace ServerSocket.isSupported and you'll see it's not supported on iOS devices.
Believe me, I frikin wish they'd support that and SecureSocket.
|
https://forums.adobe.com/thread/997569?tstart=0
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Preface: Part 1 covered the sketch the Arduino will run for this example, and part 2 covered the resources and other people’s code I used to make sure everything works as expected. In part 3 I’m going to go through a small program that does exactly what I want: read serial data from the Arduino. Part 4 is here.
Part 3: Reading
I’ve had a tough time writing this part. One of the hardest lessons I’ve had to learn over the past few years of learning C is that there is never one way to do something, and of the multiple ways to do something there is often never one clear better way to do it.
My Arduino is sending “Hello World” once every second to my PC via a serial connection, and I want to read this and print it out on the PC. Should I write my program to wait until 12 characters are read? Should I wait until one second goes by and write whatever was in the buffer? Should I open the port to be blocking or non-blocking? Canonical or non-canonical?
There is no right answer, so I went with what I could make work in a sensible way. Since my data is always going to be 12 characters long, and it’s always going to come in at once per second, I decided to stick with something similar to Tod Kurt’s example with the exception that instead of looking for the newline character, I’ll use the VMIN control to get exactly 12 (or however many) characters from the serial buffer. IMPORTANT: This means that read() function will block (pause) until all 12 characters are received!
Here’s the program:
#include <stdio.h> #include <stdlib.h> #include <ioctl.h> #include <fcntl.h> #include <termios.h> /* My Arduino is on /dev/ttyACM0 */ char *portname = "/dev/ttyACM" char buf[256]; int main(int argc, char *argv[]) { int fd; /* Open the file descriptor in non-blocking mode */ fd = open(portname, O_RDWR | O_NOCTTY); /* Set up the control structure */ struct termios toptions; /* Get currently set options for the tty */ tcgetattr(fd, &toptions); /* Set custom options */ /* 9600 baud */ cfsetispeed(&toptions, B9600); cfsetospeed(&toptions, B9600); /* 8 bits, no parity, no stop bits */ toptions.c_cflag &= ~PARENB; toptions.c_cflag &= ~CSTOPB; toptions.c_cflag &= ~CSIZE; toptions.c_cflag |= CS8; /* no hardware flow control */ toptions.c_cflag &= ~CRTSCTS; /* enable receiver, ignore status lines */ toptions.c_cflag |= CREAD | CLOCAL; /* disable input/output flow control, disable restart chars */ toptions.c_iflag &= ~(IXON | IXOFF | IXANY); /* disable canonical input, disable echo, disable visually erase chars, disable terminal-generated signals */ toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* disable output processing */ toptions.c_oflag &= ~OPOST; /* wait for 12 characters to come in before read returns */ /* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */ /* CHARACTERS HAVE COME IN! */ toptions.c_cc[VMIN] = 12; /* no minimum time to wait before read returns */ toptions.c_cc[VTIME] = 0; /* commit the options */ tcsetattr(fd, TCSANOW, &toptions); /* Wait for the Arduino to reset */ usleep(1000*1000); /* Flush anything already in the serial buffer */ tcflush(fd, TCIFLUSH); /* read up to 128 bytes from the fd */ int n = read(fd, buf, 128); /* print how many bytes read */ printf("%i bytes got read...\n", n); /* print what's in the buffer */ printf("Buffer contains...\n%s\n", buf); return 0; }
It’s not that interesting to look at. I’ll try to explain it best I can – there are several key things that I’m shaky on that require further experimentation.
First up is declaring the headers, and a few constants, like the port name and the buffer I’ll be reading into. I picked 256 as the buffer size for no particular reason other than it’s bigger than I need.
#include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <fcntl.h> #include <termios.h> /* My Arduino is on /dev/ttyACM0 */ char *portname = "/dev/ttyACM0"; char buf[256];
In main() I declare an integer ‘fd’ to be the file descriptor that open() returns on the next line.
int fd; /* Open the file descriptor in non-blocking mode */ fd = open(portname, O_RDWR | O_NOCTTY);
I mentioned before that some things were still unknown to me. In Tod Kurt’s example he uses open() with one more option – O_NDELAY – which opens the port in non-blocking mode. I had some complications with this, so I removed it and magically my complications went away. Several iterations of this program ago I found that using non-blocking mode meant that read() wouldn’t wait until data was in the buffer to return, but instead of read() returning 0 it was returning -1. This wound up being because my Arduino was busy rebooting (which is does when you open the port) while read() was running. I added some delay and it worked fine, but then I couldn’t reconcile the implications of a non-blocking port and non-canonical input. I’ve been oscillating between thinking I had a grip on it and being completely confused, so I’ll tackle it another day.
Next is setting up the serial communications to our particular way of doing things. Terminal options are held in a termios structure, and it’s typical after declaring the structure (although not entirely necessary, I think) to then set it to the currently set options of the port.
/* Set up the control structure */ struct termios toptions; /* Get currently set options for the tty */ tcgetattr(fd, &toptions);
So now we have the structure toptions set to what currently is set on the tty port. The terminal command stty can show you what a port is set to, so I assume tcgetattr() does something similar and plugs it into the toptions structure.
The next part here is basically the same as Tod Kurt’s example, but it’s all pretty typical – the Unix programming book I’m referencing has something similar in the examples where you want the data coming at you in non-canonical raw mode. The comments explain what each line does. Some flags are grouped together for brevity – they don’t need to be like that (and they COULD all be lumped together).
/* 9600 baud */ cfsetispeed(&toptions, B9600); cfsetospeed(&toptions, B9600); /* 8 bits, no parity, no stop bits */ toptions.c_cflag &= ~PARENB; toptions.c_cflag &= ~CSTOPB; toptions.c_cflag &= ~CSIZE; toptions.c_cflag |= CS8; /* no hardware flow control */ toptions.c_cflag &= ~CRTSCTS; /* enable receiver, ignore status lines */ toptions.c_cflag |= CREAD | CLOCAL; /* disable input/output flow control, disable restart chars */ toptions.c_iflag &= ~(IXON | IXOFF | IXANY); /* disable canonical input, disable echo, disable visually erase chars, disable terminal-generated signals */ toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* disable output processing */ toptions.c_oflag &= ~OPOST;
This was the first time I’d really had to set/unset options using bitwise operators (in a non-tutorial setting). It’s important to remember that it’s there for your convenience, and not meant to annoy. An alternative approach would be to have the termios structure have every individual option exist as a variable set to 0 or 1 in the structure, but for the sake of size and brevity (and because C doesn’t have a true bool type perhaps) it was done such that in the termios structure c_iflag, c_oflag, c_cflag, and c_lflag are all unsigned integers, and each of the 16 bits of the unsigned int represent a different option that can be set. Wikipedia helps explain what the & | and ~ do for us here.
VMIN and VTIME are important in non-canonical processing of serial data. There’s a fantastic explanation of how to best utilize them here, but we can take it in this example to mean that read() will wait for 12 characters to come in before returning.
/* wait for 24 characters to come in before read returns */ toptions.c_cc[VMIN] = 24; /* no minimum time to wait before read returns */ toptions.c_cc[VTIME] = 0;
So at this point the bits are set, but the serial driver doesn’t know it, so call tcsetattr().
/* commit the options */ tcsetattr(fd, TCSANOW, &toptions);
All that setting happens nearly instantly after open() is called. It’s not very obvious, but when open is called a signal is sent via the serial port that the Arduino interprets as “reboot now”. There is a way around it on the Arduino end, but it’s easy enough to simply use usleep() to wait a bit before calling read().
/* Wait for the Arduino to reset */ usleep(1000*1000); /* Flush anything already in the serial buffer */ tcflush(fd, TCIFLUSH); /* read up to 128 bytes from the fd */ int n = read(fd, buf, 128); /* print how many bytes read */ printf("%i bytes got read...\n", n); /* print what's in the buffer */ printf("Buffer contains...\n%s\n", buf);
The last bits of code do the waiting for reboot, flushes what’s still in the serial buffer, reads into the buffer declared (obeying the VMIN rules already defined) and prints out what was received. If VMIN is changed from 12 to 24 you get “Hello World” twice. This makes sense so all is well.
So there is a minimal but functional example of reading serial data from an Arduino. Here are my remaining questions I want to answer someday.
1) Is tcgetattr() really necessary? What if I memset() the structure to 0 and only set what I want?
2) How much of what I set is really necessary? I’m only reading data so should I care about ECHO, ECHOE, or ISIG?
3) Why does Tod’s example work when using a non-blocking port, but mine doesn’t?
4) What’s the point of using a non-blocking port with non-canonical communication?
Some of these questions likely have very complicated answers. I know that there are functions for intelligently knowing when a serial port is ready (which would help with question 3 and 4). Question 1 and 2 simply require experimenting (which requires time).
Part 4 will take longer to come. I want to use what I’ve learned here to do something interesting with serial communication. I have a good project in mind, and I’m shooting for results and a writeup by mid-July. In the meantime I’m going to start learning about socket programming.
EDIT: Part 4 is here.
nice article.
Thank you! I finally managed to get the communication working!
You had the exactly same problems with the communications than I did! 🙂 My take on question 1 is that it’s not needed. I guess it could be system specific, but I have no need to reinstate the previous settings on the device (/dev/ttyACM?) after i’m done (i.e the program terminates). I’m assuming that’s what it is used for.
Your article gave me a great start for writing my own code! However, I was having a problem where I could only receive data from my Arduino after I used a serial port monitor like GNU screen or the monitor that comes with the Arduino IDE. I finally solved this problem by adding cfmakeraw(&toptions) after tcgetattr(fd, &toptions). I’ll admit, I don’t really know what cfmakeraw does, but it seems to work.
cfmakeraw() looks like a sort of helper function that sets some parts of the termios structure.
Take a look here:
and here:
Instead of setting a handful of flags yourself, cfmakeraw() does it for you.
This was very helpful, except from one particular command:
/* wait for 24 characters to come in before read returns */
toptions.c_cc[VMIN] = 12;
If I have understood this correctly, you don’t return the “read” function until 12 characters have been read? If so, this is an cumbersome approach and it got me stuck for hours trying to figure out why I couldn’t read my 7-something-character message from my Arduino. Why not read repeatedly until you reach a end of stream character (I use ‘\n”)? Then your message would be read, regardless of whether it is 10 or 14 characters. Considering you only read 12 characters at a time, why is your buffer 128 bytes?
Sorry if I misunderstood what this function does, but I after a couple of frustrating hours I finally remove that line and now it works as I want. I honestly think you should remove it too, as it will ONLY work for 12-character messages.
I appreciate the feedback. In the paragraphs above the code I explained my reasoning behind setting VMIN to 12 – sorry it caused problems. Using ‘/n’ as a delimiter is (if I recall correctly) when you’d use canonical mode, instead of non-canonical, where you depend on a character limit or time limit (blocking until the limit is met). I almost never use canonical mode day-to-day, so I’m not speaking from authority there.
Woof, it’s been a long time since I’ve look at this. The whole serial communication series is due for an overhaul – I wrote it over three years ago! I’ll edit that part of the code to mention it will block until the set number of characters are met.
Chris,
The code was very helpful for a project I’m working but I’ve run into a problem I was hoping you could help with. I have my VMIN set to 56, so I assume that means I should be able to read in 56 bytes. My arduino loop, shown below, writes “Hello World” to the serial port once every 2 seconds for 30 iterations and then prints “ducks”. I’m planning on using “ducks” as a trigger value; eventually I want the code to search through an input string and trigger on a certain string or sequence of characters. With the carriage return and the newline character “Hello World” equates to 13 bytes. Yet, when I run your code it only reads the data on the port once before closing out the connection and returning me to the command line. Am I doing something wrong? Thanks in advance.
void loop() {
int i = 0;
while (i < 30)
{
Serial.println("Hello World");
delay(2000);
i++;
}
Serial.println("ducks");
}
My output from the code is;
13 bytes got read…
Buffer contains…
Hello World
Chris,
With regard to my post a few minutes ago. I discovered what the problem was; I read through part 4 again and saw the part about your typo regarding “c_iflag to ICANON instead of c_lflag”. As soon as I changed it the code worked correctly. Thanks again.
I’m glad you got it working! I’m going to fix that right now so that it doesn’t throw anyone else off.
I cannot understand the difference between “blocking / non-blocking” vs “Canonical / Non-canonical”. Could you please explain a little about them or put some link for further reading.
The answer to this SO question goes into it a bit:
In short, canonical mode blocks until a whole line is received, non-canonical mode blocks until a minimum amount of characters have been received or a maximum amount of time has elapsed.
Carefull because the code is badly represented..
When you have the tcgetattr(fd, &toptions); it appears as tcsetattr(fd, TCSANOW, &toptions);
And some people they have to put #include (THE SYS/) to include the actual library.
Appart from that is awsome that you took your time to do this walkthrough.
Thanks for the feedback.
A while back this post, and a few other posts with code samples, got really garbled up. The WordPress code formatter is wonky at best. I’ll see about fixing it.
|
https://chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
This action might not be possible to undo. Are you sure you want to continue?
Charm Offensive
Charm
Offensive
How China’s Soft Power
Is Transforming the World
J O S H UA K U R L A N T Z I C K
A New Republic Book
Yale University Press New Haven and London
For Miriam. Nothing is possible without you.
A Caravan book. For more information, visit
This book may not be reproduced, in whole or in part,
including illustrations, in any form (beyond that copying
permitted by Sections Io, and Io8 of the U.S. Copyright Law
and except by reviewers for the public press), without written
permission from the publishers.
Set in Minion type by Integrated Publishing Solutions,
Grand Rapids, Michigan.
Printed in the United States of America by Vail-Ballou Press,
Binghamton, New York.
Library of Congress Cataloging-in-Publication Data
Kurlantzick, Joshua, I,,o–
Charm offensive : how China’s soft power is transforming the
world / Joshua Kurlantzick.
p. cm.
Includes bibliographical references and index.
ISBN ,,8-o-,oo-II,o,-, (cloth : alk. paper)
I. China—Relations—Foreign countries. I. Title.
DS,,,.¡,.K8, :oo,
,o,.¡8Ј:,I—dc:: :oooo,8¡,¡
A catalogue record for this book is available
from the British Library.
The paper in this book meets the guidelines for permanence and
durability of the Committee on Production Guidelines for
Book Longevity of the Council on Library Resources.
Io , 8 , o , ¡ , : I
Contents
Preface vii
Acknowledgments xiii
O N E Courting the World I
T WO Changes on the Home Front I:
T H R E E A Charm Strategy ,,
F O U R The Tools of Culture oI
F I V E The Tools of Business 8:
S I X Mr. Popular Io8
S E V E N Goal Oriented I:,
E I G H T Wielding the Charm I¡8
N I N E America’s Soft Power Goes Soft I,o
T E N What’s Next? I,,
E L E V E N Responding to the Charm Offensive ::o
Notes :¡,
Index :,o
vi Contents
Preface
When I arrived in Bangkok in I,,8, to work first at a local
newspaper and later for international publications, I had not
thought much about China’s influence in Thailand—or in the
world. In fact, I was shocked by how Americanized Bangkok
seemed, and worried that I would find the city not enough of
an exotic experience: as it had been for five decades, the United
States was the primary foreign influence on culture, business,
and politics in Bangkok. Parts of the Thai capital, with their
flashy malls and hip cafés, seemed little different from Chelsea
in New York or Dupont Circle in Washington. Bangkok bill-
boards advertised endless rows of fast food chains, like Swen-
sen’s, that had vanished from most of the United States and
been revived in Thailand.
Overall, America’s popular image was strong—in Thai-
land and nearly everywhere else I traveled in Asia. If I told a
Thai taxi driver I hailed from the United States, he’d praise Bill
Clinton, beloved in Bangkok for both his success with women
and his foreign policies. American politicians and diplomats
received a level of treatment and access in Bangkok offered no
one else, except perhaps Japanese prime ministers. Wealthy
Thai friends constantly asked how to get their children into
American universities, and societies of Thai alumni of the
Johns Hopkins School of Advanced International Studies met
monthly at a Thai-Chinese diner near my house. Thai friends
knew more about American rap and Seinfeld episodes than I
did, and American films and music dominated Bangkok malls.
But while I was living in Bangkok, America’s image began
to suffer, and I noticed China entering the picture. For de-
cades, China had enjoyed a limited relationship with Thai-
land—and almost no relationship with much of the world.
But after Thailand’s economy melted down in the late I,,os,
triggering the Asian financial crisis, the United States initially
did not help bail Thailand out, causing intense resentment
among average Thais and Thai leaders, and forcing people to
look to other powers. By I,,,, when I told cab drivers I came
from America, they would complain that the United States had
ignored the Thais or would refuse even to speak with me. Thai
protesters had started smashing up ,–Elevens and other signs
of American business; after September II and the beginning
of the war in Iraq, America’s public image in Thailand would
bottom out. Polls in other parts of Asia would suggest that
the United States had become more unpopular than crazed
North Korea, that Osama bin Laden was more popular than
George W. Bush.
By early :ooI I had started noticing busloads of Chinese
tourists pulling up to Bangkok hotels and delegations of hun-
dreds of Chinese businesspeople decamping in town to sign
deals. China’s diplomats suddenly were everywhere, fluent in
Thai, opening new consulates and centers for Chinese studies
across the country. Many of my Thai friends now wanted to
learn Chinese, language teachers were opening Chinese schools
throughout the Bangkok business district, and it seemed like
viii Preface
every prominent Thai businessperson wanted to appear on tel-
evision with Chinese officials. China was becoming Thailand’s
most important trading partner.
Yet when I asked Thai officials how China had so quickly
become popular in Thailand, how China was building its rela-
tions to Thailand, few seemed to know anything concrete
about China’s strategy or goals. I could find almost no statis-
tics, reporting, or academic papers about what appeared to be
China’s new charm offensive, or about how average Thais per-
ceived their giant neighbor.
Over the following years, I watched as China repeated its suc-
cesses in Thailand in first its near neighbors in Asia and then
in countries far from China’s borders, like Zambia and Ar-
gentina. Emerging from a shell of defensive diplomacy dating
back decades, China suddenly was engaging with the world,
wooing friends with a subtle, softer approach, and using its
popularity to make gains, even as America’s popularity around
the world was plummeting. In Africa, newly popular China
was winning oil and gas deals; in Latin America, China was
were making inroads against American movies.
Three years ago, I started quizzing policy makers in
Washington about China’s new global influence, its soft power.
I got mostly blank stares in return. Some asked me to brief
them about the topic, and I realized that many policy makers
had missed China’s growing soft power. Used to dealing with
the stiff, unsophisticated Chinese diplomats and officials of
the past, few had anticipated this more nuanced and effective
Chinese diplomacy. No one had any idea about the size of
China’s aid programs, or how China trained its diplomats, or
Preface ix
how people in other countries responded to Chinese cultural
exports—or whether China could use soft power to achieve
any concrete goals.
Even the conservative American policy makers most
skeptical of China, I found, had spent little time examining
soft power. At a major :oo, conference held in Singapore,
Donald Rumsfeld warned that China’s military modernization
threatened countries across Asia, and questioned why China
needed to upgrade its military if not to dominate the region.
Yet though Beijing is rapidly modernizing its armed forces,
China’s army and nascent navy cannot yet match the mighty
American armed forces: the People’s Liberation Army still re-
lies too heavily on conscripts, wastes time studying useless po-
litical doctrine, and spends less than $8o billion per year on its
military, in contrast to America’s more than $¡oo billion an-
nual budget. Still, I found few American defense officials who
had considered how China’s softer forms of influence might
change countries’ views of China—and thus might reshape
US-Chinese competition.
Too often, I found, official Washington, whether focused
on China’s military or stuck remembering China’s old blunt,
gray diplomacy, simply had disregarded the gravity of China’s
growing soft power, or America’s soft power deficit. During a
luncheon I attended in Washington three years ago for the
American ambassador to Thailand, attendees sat through ques-
tions about US software manufacturing in Bangkok, piracy
protection for American firms, and other business issues. Fi-
nally, one person asked about recent unrest in southern Thai-
land, where America closed its consulate years ago—and where
a resurgence of sectarian violence had made the area a hotbed
of extremism. The ambassador mentioned that the United
States was still trying to exert influence in the south and had
x Preface
opened a small “American corner” in southern Thailand,
where Thais could come learn about the United States. “What
happened to the US consulate in Songkhla?” a southern Thai
city, asked someone else in the audience. The ambassador
paused. “It’s the Chinese consulate now,” he said.
This book represents an effort to fill that gap in knowledge
about China’s soft power and increasingly sophisticated diplo-
macy, which will transform international relations. I have
spent the past two years in Asia, Africa, and Latin America, try-
ing on the ground to figure out exactly how China wields its
soft power today—and why it matters, for the United States
and other nations, that China is amassing this influence.
The stakes are high. No one has experience with today’s
China as a global player, or a model for how Beijing will per-
form on the international stage. In a short period of time,
China appears to have created a systematic, coherent soft
power strategy, and a set of soft power tools to implement that
strategy. Through those tools—particularly its public diplo-
macy and its growing aid and trade—it has developed signifi-
cant influence, though it is still in a honeymoon period in
which many nations have not recognized the downsides of
Beijing’s new power.
As China has become a global presence, it has taken steps
to wield its soft influence responsibly, joining multilateral
institutions, supporting peacekeeping, powering economic
growth in Latin America and Africa, and fighting drug and
human trafficking. China even has begun to mediate other na-
tions’ conflicts and apply pressure on dangerous countries, a
step from the recent past, when China avoided any involve-
ment in other states’ domestic politics.
Yet as China has become more powerful it has begun ex-
Preface xi
porting its own domestic problems. Chinese companies’ poor
labor and environmental records and opaque business prac-
tices now are arriving in Zambia and Peru along with Chinese
investment. China’s lack of political openness and its state-
centered model of development are strengthening unstable
authoritarian regimes from Sudan to Burma to Uzbekistan. Its
aid policies are undermining efforts to support better gover-
nance for nations from Angola to Cambodia.
Perhaps most important, China’s soft power could have
a significant impact on American interests. When China dis-
covers that its own interests—in obtaining resources, or in
building ties to certain countries—do not overlap with Amer-
ica’s, it now has the tools to win friends to its side. And as the
United States remains unpopular in many parts of the world,
China finds willing partners. In the worst-case scenario, China
eventually will use soft power to push countries to choose be-
tween closer ties to Washington and closer ties to Beijing.
xii Preface
Acknowledgments
This book could not have been written without the generous
assistance and wise advice of many people. Support for the
book came principally from the Smith Richardson Foundation,
where Allan Song helped shape the idea for the project. The
Carnegie Endowment for International Peace, and especially
Carnegie’s Minxin Pei, Paul Balaran, Doris Grage, Kathleen
Higgs, and George Perkovich, provided vital research support,
oversight, and guidance. The Long-Term Strategy Project also
offered assistance, thanks to the great Samantha Ravich. At the
New Republic, Peter Beinart helped shape the initial draft of the
idea. Readers Josh Glazeroff, Michael Montesano, Jackie New-
myer, Minxin Pei, and Jason Zengerle provided thorough com-
ments on later drafts of the manuscript and related articles.
The Henry Luce Foundation first sent me out to Southeast Asia,
where this all began. At Yale, Keith Condon and Dan Heaton
shepherded the book and provided important insights.
In researching the book, I benefited from assistance across
Southeast Asia, China, Africa, and many other regions. Re-
search assistants George Caparas, Fanny Lioe, Baradan Kup-
pusamy, Soyoung Ho, and Am Kumpera, among others, helped
arrange interviews, fact-checked, and basically made the re-
search happen.
Many scholars shared their insights about China’s diplo-
macy, its impact on developing nations, and US public diplo-
macy. Paul Marks provided essential translations of Cambodian
newspapers and competed a research project for me about
Chinese investment in Vietnam. Henry Yep, Michael Glosny,
and Philip Saunders provided information on China’s aid poli-
cies. Joshua Eisenman helped guide my knowledge of China’s
Africa policies, and Joshua Gordon led me on a fascinating
tour of Mandalay, Burma. Brad Adams, Dan Blumenthal, John
Brandon, Guo Changlin, Richard Cronin, Catharin Dalpino,
Elizabeth Economy, Roland Eng, Roy Godson, Masao Imamura,
Surapong Jayanama, Songpol Kaoputumtip, Walter Lohman,
Joshua Marks, Bronson Percival, Kim Beng Phar, Andy Roth-
man, Eric Teo, Bill Tuffin, and Ruan Zongze all helped expand
my knowledge, as did many, many others.
The support of my family and friends has been critical:
my mother, father, and sister, who have always been my biggest
fans; and the extended Laufer family, my newest fans. And of
course, I cannot do anything without Miriam.
xiv Acknowledgments
I
Courting the World
n October :oo, President George W. Bush arrived in Aus-
tralia for his first visit Down Under, part of a presidential
tour of the Pacific. Bush, who enjoyed a warm relationship
with Australian Prime Minister John Howard and planned
to scarf down some Australian-style barbecue, seemed excited
to be there. For many American presidents, after all, Australia
had served as friendly territory; for more than five decades,
Australia had counted itself among the United States’ closest
friends, and Canberra and Washington had signed a formal
treaty alliance. Australian grunts fought and died alongside
American troops in the jungles of World War II’s Pacific the-
ater. During the Cold War, Washington viewed Australia as one
of the outposts of freedom in a region threatened by commu-
nism, and in Korea and Vietnam, Australian soldiers once
again fought alongside American troops. In the Iraq War, Aus-
tralian troops were serving with the US military, and Howard
repeatedly had refused any opportunities to remove the Aus-
tralian forces from Iraq.
Bush would find the country familiar. In previous de-
cades, as Australia had abandoned some of its traditional ties
to Britain, it had developed closer cultural links to the United
States. Australian entertainers like Nicole Kidman and Heath
Ledger increasingly migrated to the United States for work,
while American film, music, and books came to dominate Aus-
tralian theaters, radio stations, and reading lists. Students from
elite American universities chose Australia as a study-abroad
destination, in part because Australia seemed so familiar.
When Bush landed in Australia, though, his enthusiasm
must have quickly melted. Even before Bush arrived, thou-
sands of demonstrators planned to greet him with protests in
Sydney, Canberra, and other Australian cities against the
White House’s supposedly unilateral foreign policies, includ-
ing its decision to invade Iraq. When Bush touched down, the
demonstrations began, including marches on the American
embassy, where protesters scuffled with police, and mock tri-
als of the American president for his supposed human rights
abuses. Some of the protesters crossed over from anger toward
the American president to broader anti-Americanism, con-
demning US culture and values, and even average Americans
as arrogant and disdainful of the world.
1
Protected by an enormous security cocoon, Bush planned
to address the Australian Parliament. But Bush could barely
get rolling on his speech—in which he planned to tell the story
of how American and Australian World War II troops together
saved Australia from Japanese invasion—before Australian
senators began heckling him. Two senators from Australia’s
Green Party yelled at Bush, screaming that America should fol-
low international law and stop human rights abuses like those
at the US prison compound at Guantánamo Bay. “Respect
Australia. . . . If you respect the world’s laws, the world will
: Courting the World
respect you,” one senator shouted, forcing Bush to halt his
speech and gamely quip, “I love free speech” as police pushed
the senator-hecklers out of the chamber. Bush completed his
speech and left the chamber—where protesters greeted him
with a chorus of boos.
2
Only days later, Australia offered Chinese president Hu
Jintao a vastly different welcome, as the Chinese head of state
became the first Asian leader to address Australia’s Parliament.
While Bush had visited Canberra for less than a day, Hu toured
Australia like a hero. Though China’s human rights abuses,
like its religious repression and arbitrary trials, dwarf Amer-
ica’s supposed crimes, like Guantánamo detentions, fewer
Australians than expected protested against Hu. Even Austra-
lian Tibet campaigners, normally angry about China’s treat-
ment of Tibetans, went out of their way to be polite to Hu. One
Tibet group purchased a full-page advertisement in a leading
Australian newspaper telling Hu, “We welcome you to Aus-
tralia and wish you a successful and pleasant visit.”
3
Few members of Parliament disturbed Hu as he un-
leashed a windy paean to the future of Australian-Chinese ties.
Australia’s business community feted the Chinese president at
one lavish meal after another, where Australian politicians like
Foreign Minister Alexander Downer lauded China, telling au-
diences, “China’s rise is creating new opportunities. . . . China’s
industrial rise is clearly a major boon for the region.”
4
Downer
continued with his fulsome praise, saying, “Australian busi-
nesses need to understand . . . the very great goodwill there is
in China towards Australia.” Before Hu left, the two nations
signed a framework for a future free trade deal.
Australia’s responses to the Bush and Hu visits reflected
shifts in Australian public opinion. Only twenty years ago, Aus-
tralia viewed China as coldly as it greeted American warmly.
Courting the World ,
Australia itself had only begun to allow in waves of Asian im-
migrants, after trying to maintain its European character
under the White Australia policy of immigration. Though
China in the mid-I,8os was opening its economy, many Aus-
tralian opinion leaders and average citizens still viewed Cold
War–era Beijing as a communist threat, a nation that had
sponsored leftist movements in nations around Australia.
Australian politicians won domestic support by claiming that
Australia should ignore Asia, and Australia traded little with
China, still an extremely poor country.
Precisely because Australia has been such a close US ally
and so suspicious of China, the Hu visit and the results of a
poll taken in early :oo, by the Lowy Institute, a respected
Australian research organization, shocked Washington. In the
Lowy survey, barely more than half the Australians polled had
positive feelings about the United States, though 8¡ percent
viewed Japan positively and 8o percent viewed the United
Kingdom positively. Worse, ,, percent of Australians thought
that America’s foreign policies were a potential threat—equiv-
alent to the percentage of Australians worried about the rise of
Islamic fundamentalism. This despite the fact that in :oo: a
massive bomb in Bali, Indonesia, allegedly planted by radical
Islamists killed more than two hundred people, most of them
Australians.
5
In the same Lowy Institute poll, nearly ,o percent
of Australians viewed China positively. Lest anyone think that
was an aberration, another study showed that more than ,o
percent of Australians supported a proposed free trade agree-
ment with China, while only ,¡ percent supported such a pact
with the United States.
The transformation of China’s image in Australia, from pariah
as recently as the I,8os to close friend today, seemed remark-
¡ Courting the World
able. Yet the transformation is hardly unique. Since the middle
of the I,,os, China has started to become an international
power, a nation with global foreign policy ambitions. In fact,
China may become the first nation since the fall of the Soviet
Union that could seriously challenge the United States for con-
trol of the international system.
As Beijing has looked outside its borders, it has altered its
image across much of the globe, from threat to opportunity,
from danger to benefactor. This transformation has allowed
China to suggest to the world that it can be a great power. The
sea change has been most dramatic among developing coun-
tries, the group of nations with lower standards of living than
the United States, Europe, Canada, Japan, and other major in-
dustrial powers, though it is noticeable even in some devel-
oped nations like South Korea and Australia. But it is in the de-
veloping nations where China, itself a developing country, has
made major inroads in transforming its image.
This transformation is due to a range of factors, includ-
ing some beyond Beijing’s control. But it is due largely to
China’s growing soft power, which has emerged as the most
potent weapon in Beijing’s foreign policy arsenal. More than a
decade ago, the Harvard academic Joseph Nye invented a con-
cept he called soft power—a concept that then entered foreign
policy discourse. As Nye explained, “soft power rests on the
ability to shape the preferences of others. . . . It is leading by ex-
ample and attracting others to do what you want.”“If I can get
you to do what I want, then I do not have to use carrots or
sticks to make you do it,” Nye wrote.
6
This attractiveness could
be called a nation’s “brand,” and it can be conveyed through
various means, including a country’s popular and elite culture,
its public diplomacy (government-funded programs intended
to influence public opinion abroad), its businesses’ actions
Courting the World ,
abroad, international perception of its government’s policies,
and the gravitational pull of a nation’s economic strength,
among other factors.
When Nye coined the term soft power, he excluded ele-
ments like investment and trade and formal diplomacy and
aid—elements he considered more concrete carrots and sticks.
“Soft power is not merely the same as influence,” Nye wrote.
“After all, influence can also rest on the hard power of threats
or payments.”Nye focused purely on the attractiveness of a na-
tion’s brand, of its values and ideals and norms.
7
But soft power has changed. In the context of China,
both the Chinese government and many nations influenced by
China enunciate a broader idea of soft power than did Nye. For
the Chinese, soft power means anything outside of the military
and security realm, including not only popular culture and
public diplomacy but also more coercive economic and diplo-
matic levers like aid and investment and participation in mul-
tilateral organizations—Nye’s carrots and sticks. Indeed, Bei-
jing offers the charm of a lion, not of a mouse: it can threaten
other nations with these sticks if they do not help China
achieve its goals, but it can offer sizable carrots if they do.
Soft power can be “high,” directed at elites in a country,
or “low,” aimed at the general public. It can stem from gov-
ernments and nongovernmental actors—businesspeople and
Peace Corps volunteers and pop music stars, as well as politi-
cians and leaders. Nongovernmental actors do not necessarily
operate in concert with the state, and no state can be said to
have a completely coherent foreign policy. In addition, it can
sometimes be difficult to separate elements of soft power and
elements of hard, military or security power. In China’s case, as
we will see, Beijing sometimes uses its soft power to assist in
harder goals.
o Courting the World
Still, a government’s broad strategies can boost its soft
power, and it is possible that an authoritarian government may
be better able to direct coordinated strategies than a demo-
cratic one. Think about how American policies were perceived
abroad and how they made Washington popular across the
world after the Second World War, smoothing the way for
American soft actors to wield unrivaled influence. In the I,¡os,
the United States rebuilt Europe through the Marshall Plan
while simultaneously creating a web of international institu-
tions, like the United Nations, to help create a global order that
could solve conflicts without resorting to world war. These
policies proved highly popular in Europe, and the popularity
of the United States helped American companies, from Coca-
Cola to McDonald’s, colonize the Continent.
Or look at the reverse—American soft power assisted in
the promotion of US policies during the Cold War, when
America’s popular appeal made it easier for leaders in demo-
cratic Western Europe to follow Washington’s lead. In I,,, the
US government created the United States Information Agency
to oversee American public diplomacy, and USIA oversaw a
radio broadcasting effort, Voice of America, which helped
sway foreign opinion, building support for American policies.
During the early years of the Cold War, the US government,
along with private foundations and American universities,
also created programs for Soviet writers, scientists, artists, and
other elites to visit the United States.
8
Many of these visitors,
awed by America’s cultural freedom, returned to the USSR and
became advocates of reform and liberalism efforts promoted
by the United States, efforts that eventually helped bring down
the Soviet Union.
American soft power helped win the Cold War in other
Eastern Bloc states. As Nye writes, the Czech film director Milos
Courting the World ,
Forman says that when Czechoslovakia’s communist gov-
ernment allowed screenings of the US film Twelve Angry Men,
which portrays a negative view of the American judiciary,
Czech intellectuals thought, “If that country can make this
kind of thing . . . that country must have a pride and must have
an inner strength, and must be strong enough and must be
free.”
9
Enthralled by the film, and convinced of America’s
moral strength, many Czechs went on to tacitly support Amer-
ica’s Eastern Bloc policies during the Cold War and then be-
come a leading US ally after the fall of the Berlin Wall.
China now can wield this kind of soft power, and may
use it to remake the world. China’s policies could make it eas-
ier for Chinese actors, from language schools to business-
people to Chinese pop stars, to have an impact on the ground.
And China’s new benign image, in places from Australia to Ar-
gentina, will help Beijing execute its foreign policy more suc-
cessfully.
Since the mid-I,,os, the response to Beijing’s soft power has
been overwhelming. In Thailand, formally a US ally, former
Prime Minister Thaksin Shinawatra announced that China is
one of the two “most important countries for Thailand’s
diplomacy,” and Thailand is negotiating a partnership with
China that could approximate its long alliance with the United
States. Local opinion polls show that more than ,o percent of
Thais now consider China Thailand’s closest friend.
10
Across Southeast Asia, in fact, elites and populaces in
most nations see China as a constructive actor—and, poten-
tially, as the preeminent regional power. Most scholars define
Southeast Asia, a region of some ooo million people, as Burma,
Thailand, Laos, Cambodia, Vietnam, Malaysia, Indonesia, Bru-
nei, Singapore, the Philippines, Indonesia, and the new nation
8 Courting the World
of East Timor. These countries were not part of British India,
which today comprises modern South Asia. Nor, with the ex-
ception of parts of Vietnam, were they part of imperial China,
as Mongolia and parts of modern-day Korea were at times.
11
Still, many Southeast Asian nations share common bor-
ders with China, and nearly all have enjoyed long histories
of trade and diplomatic interaction with China. During the
height of imperial China, the Chinese court sent fifty vessels
per year to trade with Southeast Asia. In some Southeast Asian
states, like modern-day Singapore, this interaction and Chi-
nese migration left an ethnic Chinese majority. In other South-
east Asian states like Malaysia and the Philippines and Indo-
nesia, where the majority of people come from an ethnic
Malay background, the Chinese migrants still constitute a siz-
able minority of the population.
But the response to China’s soft power extends beyond
Southeast Asia. Outside of the United States and Japan, far
fewer world leaders than ten years ago question China’s rise.
Polls show that people in Africa and Latin America now have
more positive feelings toward China than toward the United
States, while ten thousand African professionals will head to
China each year for postgraduate training. A :oo, British
Broadcasting Corporation poll of average people in twenty-
two nations across several continents found nearly all believed
that China plays a more positive role in the world than does
the United States.
12
China also has been able to use soft power to get what it
wants. Nations from Venezuela to Uzbekistan have proven in-
creasingly willing to work with China, whether that means
Venezuelan president Hugo Chávez vowing to reorient his
massive oil industry toward Beijing and away from America,
or Uzbek leader Islam Karimov tossing US forces out of bases
Courting the World ,
in his country. Countries in Asia, Africa, and Latin America
have increasingly cut off even their informal ties to Taiwan,
which Beijing claims is a province of China.
This rise coincides with a sharp decline in America’s soft
power: in a recent poll of twenty-one nations commissioned
by the British Broadcasting Corporation, only one-third of
people polled wanted American values to spread in their na-
tion, a sign of the world’s disdain for the United States. This
decline began in the Clinton I,,os and has spiraled further
downward in the Bush :ooos, as cuts in American public di-
plomacy, scandals in American corporations, new restrictions
on entering the United States, misguided trade policies, a re-
treat from multilateral institutions, and human rights abuses
in Iraq, Guantánamo Bay, and other places have combined to
undermine the allure of America’s ideas, values, and models.
As Andrew Moravcsik, a scholar specializing in European-US
relations, admits, “Not only do others not share America’s self-
regard, they no longer aspire to emulate the country’s social
and economic achievements.”
13
In other words, while once it
seemed like everyone dreamed of being an American, from
Eastern European anticommunists to students in Burma to
liberals in China itself, today that dream may be dying.
It is in Southeast Asia where one can most easily notice Bei-
jing’s new soft power. Beijing first concentrated its charm on
the region, before broadening its efforts to Africa and Latin
America and the Middle East. Such a strategy makes sense.
China’s nearest neighborhood, Southeast Asia boasts nearly
twenty million ethnic Chinese and has long historical, eco-
nomic, and cultural ties to China. For a China still flexing its
strength as an international power, Southeast Asia presents an
opportunity. Perhaps, as a young United States once did in the
Io Courting the World
Western Hemisphere, China could make the region its own—
a Chinese Monroe Doctrine for Southeast Asia would make
Beijing the major influence over regional affairs and reduce US
alliances in the region.
14
Because Southeast Asia is the first region where China
has unleashed its soft power, it also offers a vital window into
how China will act as its influence grows. In some respects,
China’s new assertiveness is only natural. Between AD,oo and
I,oo China often was the most powerful state in the world; at
the beginning of the seventeenth century, China had a bigger
population than all of Europe. Today Beijing is in many re-
spects regaining the central position in foreign affairs it en-
joyed for centuries, and inevitably great powers, whether
China or America or the Soviet Union, exert soft power.
In this book I will trace how China has built its global
soft power, analyze how China uses that power, and consider
how nations are responding to Beijing. I will focus primarily
on China’s wooing of developing nations in Southeast Asia,
Africa, Latin America, and Central Asia, but will occasionally
address how China woos other key nations in Asia, like Aus-
tralia, South Korea, or Russia. I will not, however, directly an-
alyze the US-Chinese relationship, or China’s relationship
with wealthy nations in Europe or the Middle East. I will first
analyze why China has engaged with the world, how changes
within China itself led to a more proactive Chinese foreign
policy, and what China hopes to gain from this engagement.
Then I will examine how China actually achieves its goals, ob-
serving China’s soft power strategies and tools of influence.
Finally, having observed how China sets goals, creates strate-
gies, and utilizes its soft power, I will measure the extent of
Beijing’s success—and failure—in order to learn what it may
mean for the globe.
Courting the World II
II
Changes on
the Home Front
ack in I,¡, Beijing also believed it might wield power
in the world, but not soft power. Triumphing over
both the Japanese invaders and Chiang Kai-shek’s
seemingly superior Nationalist forces, Mao Tse-tung’s
communists thought themselves invincible when they estab-
lished the People’s Republic of China on October I, I,¡,. After
all, the communists had ended the “century of humiliation”
for China that started with the Opium Wars in the I8¡os and
I8oos, when Britain and other European powers had crushed
China’s military and begun a process of national disintegra-
tion that precipitated the end of the Chinese empire.
Mao decided not only to create a revolutionary society at
home but also to foment armed revolution around the world,
helping nations rid themselves of colonial masters and capital-
ist systems. “We must give active support to the national in-
dependence and liberation movements in countries in Asia,
Africa, and Latin America,” the Chairman announced.
1
China
took part in the Bandung Conference, a meeting of newly in-
dependent African and Asian nations in I,,,, and promoted it-
self as a leader of the developing world, a strategy Beijing is re-
asserting today.
Mao quickly put his ideas into practice. He pushed
through one of the most radical revolutions in history, trying
to create a totally communitarian economy and remake a
whole society. The government took control of agriculture,
creating collectives out of small plots and large landholdings;
it banned supposedly feudal traditions, including religious
ceremonies; it restricted travel within China; it created Party
cells to monitor minute details of people’s lives.
With the Great Leap Forward, a late I,,os plan to indus-
trialize the country, Mao tried to make agrarian, rural China a
manufacturing power in just one generation. He encouraged
average citizens to produce steel in backyard factories, em-
barked on massive capital construction projects, and increased
the mass mobilization of peasant groups, supposedly to im-
prove grain production and increase harvests, but also to boost
the Communist Party’s control over the populace.
2
When the Great Leap Forward failed, resulting in mas-
sive famine and damaging Mao’s image, the Chairman re-
sponded with the Cultural Revolution, unleashing Red Guards
against his enemies. This campaign resulted in chaos, with Red
Guards destroying any traditional pillars of society left in
China, from monasteries to schoolhouses to artists’ studios.
Across the world, meanwhile, China tried to support
what Mao called “righteous struggles”—like-minded commu-
nist revolutions that wound up alienating some leaders in
developing nations, who feared being targeted by these leftist
insurgents. In Burma, China bankrolled a communist insur-
gency, offering arms and military instructors to the Burmese
Changes on the Home Front I,
fighters. In Cambodia, China cultivated the Khmer Rouge,
which envisioned an even more radical remaking of their so-
ciety than Mao had considered. In Latin America, China sup-
ported revolutionary movements; in African states, China
trained antigovernment guerillas; in the Middle East, Beijing
funded communist insurgents in Yemen and Oman.
3
These insurgencies created disdain for China and for
ethnic Chinese abroad, and developing nations fought back
against groups supported by Mao. Thailand and Burma, for
example, battled guerrillas who had taken to the jungles of
northern Indochina. By the middle of the I,,os, most of these
communist insurgencies had either fizzled or, as in Cambodia,
succeeded in toppling former regimes. But China’s support for
revolutionary movements had poisoned relations with a gen-
eration of policy makers in the developing world. In response,
many leaders from Asia and Africa and Latin America cut off
relations with China, established alliances with the United
States, created regional organizations that excluded China, like
the Association of Southeast Asian Nations, and tightly moni-
tored and circumscribed the lives of their own ethnic Chinese
minorities. In Indonesia, the government essentially banned
ethnic Chinese from politics, outlawed Chinese literature, and
questioned many ethnic Chinese’s devotion to Indonesia. Even
in Vietnam, a fellow communist nation, China’s backing of the
Cambodian Khmer Rouge, which eventually went to war with
Vietnam, alienated Hanoi from Beijing, leading to a brief bor-
der war between the two in I,,,.
4
Apart from trying to export revolution, China’s other
tools of influence remained weak. Mao’s economic misman-
agement kept China impoverished; as an example of economic
success, China seemed a model few countries would want to
follow. Mao himself knew little about real-world economics,
I¡ Changes on the Home Front
and he refused to listen to confidants who counseled restraint,
like Deng Xiaoping, a pragmatist who wanted to launch eco-
nomic reforms. (For his ideas, Deng was purged as a “capital-
ist roader” during the Cultural Revolution, sent to a tractor
factory in rural Jiangxi Province to perform manual labor.)
The public face Beijing presented to the world was blunt and
gray, just monotone statements from official spokesmen who
understood nothing about the modern media. Older officials,
who’d grown up in the Maoist period—when any deviation
from Party principles could still land you in jail—still domi-
nated the diplomatic corps, and could barely communicate
China’s message, except to selected socialist audiences. “They
had these diplomats who were so stiff they’d just read state-
ments to you,” says one Western diplomat. “If you questioned
anything, they would just repeat what they read, like a robot.”
5
After Mao’s death, Deng returned to power. A savvy po-
litical infighter, Deng carefully cultivated top members of the
Communist Party, then used his backers within the regime to
outmaneuver the Chairman’s appointed heir, Hua Guofeng.
By the early I,8os, Hua conceded that he had lost the support
of the Party, and Deng essentially took control of China, ap-
pointing his reform-minded protégés to top positions. And
since Deng’s restoration, twenty-five years of unparalleled eco-
nomic growth has changed China enormously. The drastic
changes in China itself have set the stage for China to exert soft
power around the world. Within China, the country has wit-
nessed growing economic dynamism, a surge in nationalism, a
new Chinese middle class knowledgeable about the globe, and
a vastly more sophisticated leadership that recognizes the need
for public diplomacy to protect its domestic and international
interests. Combined, all these factors have created pressure for
China’s new international engagement, as more sophisticated
Changes on the Home Front I,
and proud Chinese citizens desire a state that plays a large role
on the world stage.
Deng Xiaoping could claim much of the credit for China’s
changes. A leader within the Communist Party of China since
the I,:os, the pragmatic Deng had seen the excesses and chaos
of the Chairman’s policies firsthand. After Mao’s death, Deng
understood how Maoism had alienated China’s neighbors, cre-
ated instability on China’s borders, and impoverished China
itself. China would need decades to recover, and would require
a peaceful external environment and massive inflows of foreign
investment and technology to become strong. Deng counseled
his proud countrymen, heirs to a Chinese kingdom that once
called itself the center of the world, to bide their time. China
should “keep a low profile and never take the lead” on global
issues, Deng warned—Beijing wasn’t strong enough to expose
itself to a world leadership role.
6
At home Deng launched the Chinese economy on prag-
matic reforms. At the landmark Communist Party plenum in
I,,8, Chinese leaders decided to stop focusing on “revolution-
ary” class warfare, the major task of Mao’s governments, and
instead to try to modernize the economy. Deng opened China
to foreign joint ventures, tasked the government to court for-
eign investment, and created special economic zones like
Shenzhen, in southern China, designed to lure foreign firms by
offering them massive tax concessions. Deng allowed farmers
to again grow crops for profits, and ultimately pushed China
toward dismantling its massive state enterprises. Most impor-
tant, he changed the mindset in China, exhorting his country-
men that “to get rich is glorious,” thereby telling individuals
that entrepreneurship, discouraged for decades, was once
again acceptable, even laudable.
7
Io Changes on the Home Front
As the China scholar David Lampton shows in his land-
mark edited study of post-Mao policy making, in foreign
affairs China under Deng played defense, reacting when
threatened but generally avoiding most global issues. Deng
ended China’s ties to communist insurgencies abroad, which
had drained China’s treasury, and established closer relations
with developing countries like Malaysia that had been targets
of left-wing insurgencies. (Malaysia and China had established
formal diplomatic relations in I,,¡.) He strengthened China’s
growing ties to the United States, now its most important
source of technology. He praised America’s power and acted
the role of a humble student even toward small nations, or-
dering Chinese leaders to “learn from Singapore”about how to
build a modern economy, and sending provincial and national
officials to universities in that tiny city-state. He shunned mul-
tilateral organizations and treaties, and Chinese diplomats at
the United Nations seemed almost invisible, barely comment-
ing on important issues.
8
Deng’s pragmatism resonated with a society recovering
from Mao. The chaos of the Cultural Revolution, when hun-
dreds of thousands of people were purged to the countryside
or killed, and teachers and other intellectuals were terrorized
by waves of ideological Red Guards, had shocked the Chinese
population.
9
Average Chinese had seen power and ideology
wielded by the state bring nothing but misery to average
people; now they remained weary from decades of this inter-
nal turmoil.
Meanwhile, many Chinese intellectuals greatly admired
the United States, which had formed an alliance with Beijing
during the latter half of the Cold War, as China and the Soviet
Union split. To these Chinese intellectuals, no country could
possibly challenge the United States’ influence. A poll taken by
Changes on the Home Front I,
the research organization Horizon Group in I,,, asked Chi-
nese citizens their views of the “most prominent countries in
the world”; one-third ranked the United States most promi-
nent, with only I, percent choosing China. Earlier, in the lib-
eral I,8os, many Chinese academics and students idolized the
US political system and tuned to Voice of America for their
news. One study found that in the I,8os some ,o percent of
Chinese university students trusted Voice of America but ,,
percent distrusted the Chinese media—numbers that would
shift in the I,,os.
10
In fact, throughout the I,8os China’s economic opening
seemed to signal the creation of a cosmopolitan, inquisitive in-
tellectual class committed to China’s eventual democratiza-
tion. Inside the government, officials created a task force com-
prising primarily liberal intellectuals and designed to examine
and push for political reforms. Even senior Party leaders ap-
peared committed to opening up China’s political system. Zhao
Ziyang, one of Deng’s top lieutenants, advocated for elections
in China. As Zhao reportedly told acquaintances, “Give people
more freedom. . . . The people’s demand for democracy is a
trend. We must meet their demand to the fullest extent.”
11
Zhao was not yet in charge, though. The man in charge,
Deng Xiaoping, though he advocated economic reform, did
not share Zhao’s liberal political sentiments. Deng was known
for bluntness, and he made his feelings clear—China could
pursue gradual economic reform without having to rapidly
open the political system. “We cannot abandon our dictator-
ship. We must not accommodate the sentiments of democra-
tization,” Deng told officials.
12
In the climax of that decade, on June ¡, I,8,, this pro-
American bias appeared again, broadcast to the world. Days of
protests against the Beijing regime had culminated in demon-
I8 Changes on the Home Front
strations attended by hundreds of thousands of Chinese in
Tiananmen Square, the central plaza in Beijing located in
front of the Forbidden City, where generations of Chinese em-
perors had ruled over China’s empire. In I,8, young protest-
ers from the Central Academy of Fine Arts carved a “Goddess
of Democracy”—a giant statue resembling the Statue of Lib-
erty—to symbolize their desire for democracy in China. The
protesters stayed until troops and tanks, on the orders of Deng
Xiaoping himself, cleared the historic square by firing auto-
matic weapons into the crowd, killing perhaps two thousand
people.
13
Following June ¡ those warm feelings toward America
cooled. After the crackdown in Tiananmen, the Chinese re-
gime purged Zhao Ziyang from power and placed him under
house arrest for the rest of his life. It tossed other liberals
within the Party into jail. After the crackdown in Tiananmen,
memories of the event were buried under an avalanche of na-
tionalism and growing pragmatism by the Chinese popula-
tion, which essentially seemed to accept their authoritarian
government, at least for the time being. Beijing tightened its
controls over society, alternatively cowing and co-opting elites
to keep them in line, and forcing dissidents into exile. And
after the crackdown in Tiananmen, the appeal of the United
States to average Chinese faded. In :oo, the Horizon Group
polled randomly chosen Chinese citizens again. This time,
nearly ¡o percent picked China as “the most prominent coun-
try in the world.” The United States placed a distant second.
14
In the years after Tiananmen, both the Chinese public and the
Chinese leadership gained vital confidence—confidence that
China had a right to become a global power. More than two de-
cades of post-I,,, breakneck economic growth, during which
Changes on the Home Front I,
China’s trade with other nations grew some eight times faster
than overall world trade, allowed China to build trade sur-
pluses with the world of more than $Ioo billion annually.
China amassed the largest currency reserves on earth and
lifted :oo million people out of poverty, one of the greatest
economic accomplishments in history. China became Asia’s
largest recipient of foreign direct investment, receiving more
than $oo billion in investment in :oo,. By :o:, China should
become the world’s second-largest economy; measured by
purchasing power parity, it already is.
15
China’s growth has defied regional shocks like the Asian
financial crisis of the late I,,os, internal financial problems
like Chinese banks’ morass of nonperforming loans, and end-
less predictions by experts (including myself) of an imminent
downturn in the Chinese economy. In places like vibrant Wen-
zhou, a city in eastern China’s Zhejiang Province packed with
companies that specialize in cigarette lighters, the Chinese pri-
vate sector has created highly skilled and efficient firms, a far
cry from China’s state-owned industrial giants.
16
The impact of this growth can be seen even in the most
remote parts of the country. On a hundred-degree day in Au-
gust of :oo:, vendors and buyers crowded into the open-air
plaza in front of Idh Kah Mosque, a central structure in Kash-
gar, the westernmost city in China, closer to Afghanistan than
to Beijing. Kashgar sits near the border with Muslim Central
Asia, and it is populated by many Uighurs, a Muslim, Turkic
ethnic minority in China. In a Kashgar side alley, an old man
with a thick beard and a white Muslim skullcap sat in front of
a shop, banging an insistent, Arab-sounding rhythm on a hand
drum. Next to him, a younger man with thin stubble kept up a
keening wail, like a snake charmer, on a tiny flute and mouth
:o Changes on the Home Front
pipes. In front of the mosque, olive-skinned men wearing large
cotton mitts pulled naan bread out of a stone oven; kebab sell-
ers molded fresh lamb onto small skewers. Merchants greeted
each other with “salaam alaikum,”and then crowded in close—
prodding and cajoling potential customers.
17
Only two years later, Kashgar looked far different. As
China’s economy boomed, the Chinese government in the late
I,,os developed a plan it called “Develop the West” or “West-
ern Development.” Under this plan, the central government
would build new infrastructure in the western part of the
country and provide financial incentives, like tax exemptions,
to encourage entrepreneurs and investors to migrate to that
poorer region. Between :oo: and :oo¡ Develop the West had
landed in Kashgar. The Chinese government had cleared the
central plaza of merchants, replacing them with new luxury
condo-type buildings, metastasizing construction sites, and a
modern stone plaza. Smooth new highways now connected
Kashgar with the rest of the country, traversing the long, ocher
deserts and deep purple-and-red canyons of Xinjiang. The
highways, and the financial incentives, had attracted new
businesspeople to the city, though Develop the West had not
addressed the overall wealth gap between western and eastern
China. Thousands of these businesspeople had decamped on
Kashgar, where they bunked, three or four to a room, in shabby
long-term hotels.
18
Even the carpet merchants sensed they had to take ad-
vantage of rapid change. Walking around Kashgar one day in
:oo¡, I stumbled into an indoor market. Behind individual
counters, merchants competed for customers, grabbing people
as they walked by and hollering out deals. The old vendors
huddled around a few counters, comparing prices, their arms
Changes on the Home Front :I
around each other’s shoulders. As my eyes focused, I realized
where I was. It was the cell phone market, where the carpet
sellers haggled over mobile phones as aggressively as they’d
once touted thread counts.
Economic growth transformed Chinese society. It trans-
formed even remote backwater cities like Kashgar and allowed
urban Chinese to amass the kind of luxuries they’d once only
heard about. It built up the Chinese academic system, and it
stoked a growing demand for energy to fuel the Chinese econ-
omy, so much so that China, self-sufficient in oil as recently as
I,,,, may have to increase its energy consumption I,o percent
by :o:o to maintain its rate of growth. (Current Chinese Prime
Minister Wen Jiabao recently admitted that shortages of oil
and gas have limited China’s development.) Economic growth
pushed urban Chinese to learn about the world, through the
influx of Chinese Internet news portals. On the Web, they
could watch foreign businesses flocking to China like modern-
day vassals, making any concessions necessary to enter the
Chinese market—even, like Google, tailoring the content of
their sites to please Beijing.
19
They could learn about Chinese
who’d studied and worked in America choosing to come back
to China to work, since the country now offered greater eco-
nomic opportunity.
This powerful growth, technological change, and aca-
demic progress, incessantly highlighted in the state-dominated
Chinese media, fostered a new sense of confidence in China,
particularly among young people who had come of age after
the chaos and disorder of the I,8, Tiananmen crisis. In recent
years, several academics have studied this rebirth of confi-
dence. As Peter Hays Gries, an expert on domestic Chinese
politics, chronicles in a recent study of Chinese nationalism,
:: Changes on the Home Front
the idea that China had become a rising power swept through
the domestic and foreign media, partly replacing images of
China as a weak state preyed upon before I,¡, by foreign pow-
ers and then decimated by Mao’s changes.
20
And like the United
States in the nineteenth century, as a rising power China began
to reconsider the world system it had accepted when it was
weaker.
Young Chinese also began to travel abroad, with the
number of outbound tourists rising from ¡., million in I,,, to
more than ,o million in :oo,. As they traveled, urban Chinese
may have lost some of their awe for America and Europe—one
recent group of editors compiling a Chinese-language collec-
tion of people’s views toward the world noted that other na-
tions were no longer mysterious to average Chinese. The trav-
elers saw that the United States was far from perfect, that it,
too, suffered from poverty and crime and grime that might
weaken the American social fabric. They realized that their
own big cities, like Shanghai, now could match any world cap-
ital for nightlife and culture and technology and economic dy-
namism. In one recent poll only ¡o percent of Chinese had a
favorable impression of the US.
21
Recognizing that communism held little appeal in a na-
tion urging its citizens to get rich as quickly as possible, the post-
Tiananmen leadership, eventually headed by President Jiang
Zemin, needed to offer a substitute ideology to keep the pop-
ulation united. What they came up with, as the China expert
Jasper Becker describes, was a kind of updated nationalism.
This drew upon China’s history of patriotism—nationalism
had played a role in the early-twentienth-century revolutions
that eventually brought Chiang Kai-shek to power.
But the new nationalism did not only look back. It played
on anger about foreign powers’ domination of China in the
Changes on the Home Front :,
nineteenth and twentieth centuries, but it also emphasized
China’s growing strength and its past grievances. Beijing built
enormous new projects, like the Chinese space program, de-
signed to rally public opinion around the state. It launched
mass rallies and rewrote school textbooks to emphasize that
China was gaining strength again; at the same time, the text-
books reminded average Chinese of how foreign powers had
preyed upon China. Beijing’s leaders began stressing that
China must become stronger, to face down external enemies,
even as some top officials worried that the nationalism could
backfire, leading to protests against the government. As Becker
notes, “Jiang and his successors see their country in the midst
of a Darwinian struggle between nations. . . . Jiang has warned
the party faithful, ‘Competition in overall national strength is
becoming increasingly fierce.’”
22
Newspapers like the state-controlled Beijing People’s
Daily and best-selling books touting China’s strength and
questioning the “cultural colonialism” of Western products in
China only reinforced the nationalist mindset. The People’s
Daily sparked nationalism in a sophisticated manner, some-
times featuring Chinese successes abroad and running sup-
posedly neutral commentaries, taken from Middle Eastern pa-
pers and other anti-US news sources, on America’s “failing”
foreign policies around the world. At the same time, the Bei-
jing regime successfully co-opted forces that foreign scholars
had predicted would pry open Chinese society—building fire-
walls, for example, to control the Internet even as some I,o
million Chinese logged onto the Web.
23
By the end of the I,,os some young Chinese urbanites no
longer resembled the idealistic, liberal men and women who
had hopped trains from across China to get to Tiananmen
Square in I,8,. Most were too young to remember the Cultural
:¡ Changes on the Home Front
Revolution, and so were less distrustful than their elders of the
state’s wielding of power and ideology. Unlike their elders,
who’d come to Tiananmen in I,8, furious that they were earn-
ing meager salaries in academia and business even as Party
officials seemed to be rolling in cash, these younger elites were
more comfortable, and often had shunned political science or
history at university in favor of business and computer tech-
nology.
The Party had reached out to these urbanites, essentially
buying them off. As Minxin Pei of the Carnegie Endowment
for International Peace writes in a new study of China’s polit-
ical system, “The Party showers the urban intelligentsia, pro-
fessionals, and private entrepreneurs with economic perks,
professional honors, and political access. . . . Nationwide,
I¡,,ooo designated experts, or about 8 percent of senior pro-
fessionals, received ‘special government stipends,’ or monthly
salary supplements in :oo¡.”
24
What’s more, Pei notes, tens of
thousands of former college professors have been recruited
into the Chinese Communist Party, where leaders have pro-
moted them to senior, and well-paying, government positions.
Party committees in Chinese universities offered house al-
lowances, stipends, and other benefits to promising young stu-
dents who agreed to become Party members.
In essence, young intellectuals, who throughout China’s
history had led reform efforts, had made a pragmatic deal with
their government. The state would deliver growth, and they
would focus on making money. In one study of Chinese stu-
dents, 8, percent ranked the following value statement as most
important: “A modern person should be able to make money.”
In a May :oo, poll of average Chinese citizens taken by the Pew
Global Attitudes Project, more than ,o percent of Chinese said
they were satisfied with current conditions in their nation. By
Changes on the Home Front :,
comparison, even in normally patriotic America, fewer than
¡o percent of people said they were satisfied with national con-
ditions. As one scholar writes, Chinese intellectuals’ “writings
today in academic journals and high-brow magazines are im-
bued with a sense of satisfaction. There are exceptions, of
course, but most intellectuals tend to accept and approve of
the status quo.”
25
In the I,,os several prominent intellectuals even revolted
against the ethos of China’s liberal late I,8os, calling for a
stronger role for the Chinese state; many other liberal intellec-
tuals had fled the country, leaving them incapable of influenc-
ing China’s youth. Young Chinese now wrote nationalistic
books and dominated the chat rooms of China’s most popular
Web bulletin boards, like the Strong Nation forum, where they
competed to attack the government from the right, as soft on
the United States. In the I,8os the Chinese intelligentsia was
opposed to the Chinese Communist Party’s rule, notes Ying
Ma, a specialist on Chinese domestic attitudes. Now, Ma says,
though many Chinese have become “Americanized” by work-
ing for multinational companies, traveling abroad, and ac-
cessing American culture through the Internet, “Chinese in-
creasingly view America today as a bully who . . . attempts to
thwart the rise of their country’s international influence.”
26
This rising nationalism might not have peaked, except
for two disastrous events. In I,,,, relying on an outdated CIA
map, NATO forces accidentally bombed the Chinese embassy
in Belgrade. (The United States apologized for the mistake and
paid restitution.) The bombing killed three Chinese and in-
jured at least fifteen others. To Chinese convinced that their
nation was rising, skeptical of American motives, and stoked
by the Chinese media suggesting that the bombing was delib-
erate, this was a sign. The more nationalist in the population
:o Changes on the Home Front
called for military retaliation against America, and thousands
of young Chinese led boycotts of American products and be-
sieged the US mission in Beijing, trapping the US ambassador
in the compound for four days, and battering the embassy
with rocks and bottles.
27
The Belgrade bombing was followed by the EP-, incident
in early :ooI, when a Chinese F-8 fighter collided with a US
Navy reconnaissance plane finishing a routine mission off the
coast of China. The Chinese plane had been tailing the Amer-
ican craft, and some American officials suggested that the Chi-
nese pilot had flown recklessly close to his US counterpart. In
any event, the collision killed the Chinese pilot, and the Chi-
nese government briefly seized and imprisoned the crew from
the American plane on the island of Hainan. Beijing de-
manded that the United States apologize for the collision, but
America refused to do so.
28
Eventually, Washington and Bei-
jing agreed on a compromise letter of regret that admitted no
guilt, but most Chinese I have met remained convinced that
the Americans were responsible for the Chinese pilot’s death.
The EP-, incident further soured young Chinese on the
United States, no longer the shining model of I,8, but rather
a competitor and potential enemy. Only a tough police re-
sponse, probably mandated by Beijing, kept young Chinese
from demonstrating against the US embassy, as they had done
in I,,,. In one recent major poll of Chinese, twice as many
people in their twenties had a negative view of the United
States as had a positive view.
29
Even Chinese who had previously paid little attention to
foreign affairs suddenly became interested. The Belgrade
bombing and the EP-, incident sparked their interest in for-
eign policy, and made them rethink whether the United States
and China could indeed be “strategic partners,” as President
Changes on the Home Front :,
Clinton once had promised. Constant criticism of China by
US human rights advocates and other pressure groups only
stiffened Chinese views; as Ma notes, no one, whether Ameri-
cans or Chinese, likes to have his country criticized by out-
siders. And so the Belgrade bombing and the EP-, incident
fostered the most significant domestic discussion of China’s
global role in years. Across China’s eastern cities, business-
people, academics, students, and other intellectuals began to
consider whether China should abandon playing defense with
the rest of the world—a debate captured by growing coverage
in the Chinese press suggesting that China should develop a
more aggressive foreign policy.
The September II attacks further exposed China’s na-
tionalist sentiment. “When the planes crashed into the World
Trade Center, I really felt very delighted,” one Chinese student
told Chinese pollsters. “They expected that more places in the
United States would be bombed,” said another Chinese stu-
dent, talking about how he and his friends gathered in a dorm
room after September II to celebrate as Americans leaped
from the burning towers to their death. “The more severely the
United States was bombed, the more excited they would be.”
Though shocking, these feelings were widespread. In a broader
study of post–September II opinion, researchers found that
“most Chinese college students . . . were immediately excited
because the United States, an abhorrent, overbearing, and ar-
bitrary country in their minds, suffered an unprecedented
heavy strike.”
30
Older Chinese liberals, who remembered how a strong
central government fomented the Cultural Revolution, could
hardly understand their nationalist progeny. “Today, my stu-
dents don’t care about political science,” complained one pol-
itics professor at Fudan University in Shanghai, a man who
:8 Changes on the Home Front
had been a young academic during Tiananmen. “They want to
take business, or computer science, or something else that will
get them a good job. . . . They think [the Chinese leadership]
is too weak, and should be harder on the US.”He paused, look-
ing befuddled. “I don’t know how to talk to them.”
31
Just as the Chinese public started to consider a more proactive
foreign policy, China’s leadership, too, was becoming more
confident and more knowledgeable about the world.
Until the mid-I,,os, the generation that had grown up
around Mao—including Deng Xiaoping himself—still dom-
inated China’s inner circle. But this generation passed away in
the I,8os, or was forcibly retired to make way for younger
officials.
This provided an opportunity for Chinese and foreign
scholars of the Beijing regime to assess their replacements.
H. Lyman Miller and Liu Xiaohong produced one of the most
comprehensive assessments. As they found, of the twenty-four
officials who became full or alternate members of the Polit-
buro at the Fifteenth National Congress in September I,,,,
only six had served in the Party leadership before I,,:, and
most were at least ten years younger than the men they’d re-
placed. Many of these new leaders hailed from China’s urbane
eastern provinces, which had benefited the most from eco-
nomic reforms and which were most open to external influ-
ence. In contrast to older leaders, they had completed under-
graduate and even graduate studies. They had studied outside
China, often in Western nations. But these leaders also had
seen Western nations shun China after the Tiananmen crack-
down. As Chinese officials told me, they recognized that Bei-
jing could not rely on the United States but must develop its
relations with its neighbors, with Africa, and with Latin Amer-
Changes on the Home Front :,
ica; it was Argentina’s president, Carlos Menem, who became
the first leader from the Western Hemisphere to visit China
after the Tiananmen crackdown.
32
What’s more, Chinese lead-
ers recognized that, with the end of the Cold War, Russia no
longer threatened China, freeing Beijing to use some of the re-
sources it had spent protecting its northern border on other
efforts, like increasing pressure on Taiwan and building up its
forces across the Taiwan Strait.
From their time in the West, these younger men and
women also had seen how think tanks, career diplomats, aca-
demics, and public opinion helped American officials process
world events and make policy. They began to follow more
closely Chinese public opinion, as the number of voices trying
to make an impact on Chinese policy making was expanding
rapidly. Compared with the past, when scholars and officials
had kept any criticism of foreign policy silent, a growing
number of prominent Chinese intellectuals began to publicly
air policy debates, such as an argument in the I,,os by left-
leaning scholars that the breakup of Chinese state-controlled
enterprises would damage China’s national security. As a re-
sult, leaders like former Premier Zhu Rongji increasingly read
academic papers, watched television shows like Focus that re-
ported on Chinese opinion, and even used the Internet to
gauge public sentiment.
33
These leaders increasingly supported a network of Chi-
nese think tanks like the Chinese Academy of Social Sciences
in Beijing, the China Reform Forum, and the Central Party
School. At these think tanks, Chinese scholars would learn from
Western think tanks and then be called upon to provide sophis-
ticated analysis to the government, upgrading China’s strategic
thinking. As the scholars Evan S. Medeiros and M. Taylor Fravel
note, the Chinese foreign ministry even created an internal
,o Changes on the Home Front
agency focused on long-range thinking, like the State Depart-
ment’s Bureau of Policy Planning.
34
The impact of China’s economic growth trickled down
to midlevel officials as well. Two decades of development has
sharply raised the education level of China’s leaders. As the
former Time foreign editor Joshua Cooper Ramo notes in an
essay called The Beijing Consensus, “There has been a head-
snapping rise in the education level of China’s regional lead-
ers. . . . In I,8: only :o percent of China’s provincial leaders
had attended college. In :oo:, this number was ,8 percent. . . .
Among younger leaders, those ‘fourth generation’ leaders under
,¡, two-thirds hold Masters or PhD degrees.”
35
As a result, today even midlevel Chinese leaders have be-
come vastly more knowledgeable about the outside world and
enjoy far better access to current events. Former State Depart-
ment Deputy Assistant Secretary of State Susan Shirk remem-
bers that in I,,, it was “easier to persuade the North Koreans
to come [to an informal diplomatic meeting] than it was the
Chinese,” since the Chinese were so isolated and distrustful.
Ten years later, one former US diplomat marveled at the Chi-
nese diplomats’ knowledge, telling me, “Chinese officials now
can describe to me in detail the splits within the American
neoconservative movement.”
36
With a more sophisticated knowledge of the world, these
leaders recognized that China must become a greater interna-
tional player. China had pressing great-power needs—needs
for oil, allies, markets, and security, among others. Yet the
United States had built alliances around the world that could
constrain China one day if Washington chose to contain Bei-
jing the way it had tried to contain Moscow and if nations
agreed to join in that effort. America’s relationships in Asia
also could prevent China from eventually regaining control of
Changes on the Home Front ,I
Taiwan. In a study of articles from Chinese-language journals
on international relations, which often reflect government
thinking, the China scholar Biwu Zhang found that many
pieces focused on how America had wooed friends and now
was “capable of establishing regional defense headquarters in
various corners of the world.” To break through this American
containment, and to potentially increase pressure on Taiwan,
Beijing would have to rely on developing nations, which were
more willing to overlook China’s human rights abuses. As
Zhang Xizhen, a professor of international relations at Beijing
University, said, “Threatened and actual economic sanctions
and international political isolation [after Tiananmen] jeop-
ardized our opening up and reform process. [We had] to
strengthen relations with our neighbors and break out of the
Western blockade.”
37
The Chinese leaders also increasingly understood that
as China continued to grow and opened its borders, it could
not avoid the world’s problems, like HIV and drugs seeping
from Southeast Asia into southwest China. Fighting HIV, said
Jiang’s successor, Hu Jintao, would be “a major issue that has a
bearing on the nation’s quality and destiny,”and would require
global cooperation.
38
Chinese officials could not help noticing another important
change. Foreign leaders were beginning to marvel at China’s
economic miracle—as one Afghan vice president recently put
it, “China has made significant [economic] achievements . . .
so we Afghans are looking forward to learn[ing]”—and Bei-
jing began to realize that China has an image it can sell to the
world. At the same time, America’s international image was
slipping. In Chinese publications, Wang Jisi, one of China’s
elite intellectuals, noted that America’s weakness was its soft
,: Changes on the Home Front
power, not its hard power. And after the Iraq War began in
:oo,, the scholar Biwu Zhang found, Chinese authors agreed
that America had suffered “a serious setback in terms of soft
power.”
39
Wang was right. After the end of the Cold War, America
had retreated from the world, consumed with its own eco-
nomic boom, with the Internet, and with American culture
wars. Significant pluralities of Americans opposed US inter-
ventions abroad and called for Washington to cut foreign aid,
and the White House listened. Washington slashed aid and
public diplomacy, long a linchpin of American popularity, and
merged the United States Information Agency, the main pub-
lic. By the end of the I,,os the
appeal of American-style economics, political systems, and
even popular culture had begun to wane.
America’s unpopularity provided an opportunity. When Thai-
land devalued its currency in I,,,, after speculators had at-
tacked the currency because they believed that Thailand’s
strong growth hid major economic weaknesses, the devalua-
tion spiraled into a full-blown financial crisis. As the Thai
economy cratered, Bangkok lurched into a panic. Investors
pulled out of the stock market, and depositors lined up at
banks, causing a run on cash at many branches. When I visited
one branch, employees had locked themselves inside to avoid
being gang-rushed by Thais desperate to withdraw money.
Changes on the Home Front ,,
Construction halted on flashy condominiums launched in
Bangkok’s go-go early I,,os, leaving cranes scattered every-
where like a life-sized Erector Set. Nearly every day it seemed
as if another Thai financial company declared bankruptcy and
the government released another report on unemployment.
Bangkok airport remained crowded: foreign companies flocked
to town to buy Thai assets on the cheap before jetting off to re-
sorts for a round of cheap golf. Bangkok newspapers kept busy
too, reporting stories of former tycoons brought low. One real
estate magnate, Sirivat Voravetvuthikun, had amassed enor-
mous debts. Sirivat lost at least $Io million in assets, and he
could no longer pay his creditors. Desperate, he started selling
sandwiches on Bangkok’s steamy streets to survive.
40
When I drove one day to the prime minister’s official
residence in Bangkok, I found the road blocked by a tent city.
Entire villages from Thailand’s impoverished rural North-
east, hit not only by the financial downturn but also by a
withering drought, had moved themselves to the streets of
Bangkok, where they rebuilt their thatched huts by the prime
minister’s house. They camped there for months—sinewy,
malnourished-looking farmers with creased faces protected
from the sun by straw hats, monks distributing Buddhist amu-
lets and blessings for sick children. As the villagers protested,
one Thai government collapsed and another stepped in.
Handed the keys to the treasury, the newly appointed Thai
finance minister went ashen. “He realized that, basically, there
was nothing there,” remembers one foreign diplomat in close
contact with Thai leaders at the time.
41
The Thais had hope, though. Many believed that, as a
formal US ally, Thailand would soon receive help from Amer-
ica. After all, Washington had bailed out Mexico when the
Mexican economy imploded. Now, inside the National Se-
,¡ Changes on the Home Front
curity Council, Southeast Asia experts pushed for a bailout
package for Thailand.
42
But, at least at first, the NSC advisers
couldn’t get the ear of their bosses. American officials refused
to take the lead and organize a bailout of the Thai finance sys-
tem. The United States even killed the idea of a regional fund
to bail out Asia, anteing up money only as the crisis spread to
South Korea, a larger economy, and threatened the entire
global economy.
When the Thais realized that help wasn’t on the way, the
mood in Bangkok toward America turned sour. Thai officials
blasted American counterparts for their sloth. At the tent city,
I started seeing signs damning the United States, a symbol of
the free-market economics that had brought Thailand low,
and effigies of Bill Clinton, his red, bulbous nose turning
brown as the demonstrators set his cardboard double on fire.
As the United States flubbed its initial crisis response,
China made a symbolic move, publicly refusing to devalue its
currency; if Beijing had devalued, it could have forced further
devaluations of other Asian countries’ currencies. It was a minor
remedy compared with the massive financial bailout eventu-
ally offered by Japan, the United States, and the international
financial institutions like the International Monetary Fund,
which gave Thailand a credit line. But Beijing smartly adver-
tised its decision as standing up for other Asian nations. “The
Chinese Government, with a high sense of responsibility, de-
cided not to devaluate its renminbi in the overall interest of
maintaining stability and development in the region,” said the
Chinese foreign ministry. “It did so under huge pressure and at
a big price. But it contributed considerably to the financial and
economic stability and to the development in Asia.”
43
China’s move seemed to work. “The US response or fail-
ure to respond to the Asian financial crisis in I,,, strength-
Changes on the Home Front ,,
ened China’s standing in the region,” Singaporean ambassador
to Washington Chan Heng Chee said later. Indeed, after the
crisis, Rodolfo Severino, head of the Association of Southeast
Asian Nations, the leading regional political bloc, announced,
“China is really emerging from this smelling good.” Nearly ten
years later, Thai officials still seethed at America’s initial inac-
tion, and even Thai friends snapped at me if I reminded them
that eventually the United States did help Bangkok rebuild its
economy. But when I asked one Thai leader who had come to
Thailand’s rescue during the crisis, he responded immediately.
“China,” he said. “Only China.”
44
Nineteen ninety-seven marked a turning point. For the first
time in decades, China had taken a stance on a major interna-
tional issue and had banked credit as a benign force in global
affairs. In the following years, as the Chinese leadership be-
came richer, worldlier, and more confident, and as it came to
be supported by an increasingly nationalist public, China’s
mandarins reassessed their place in the world. Rather than
playing defense, rather than just reacting to international af-
fairs, they were ready to take the offensive, building a more so-
phisticated and powerful foreign policy.
Chinese leaders and scholars started referring to the
country, in Chinese publications and to Chinese audiences, as
a daguo—a great power—and to suggest that China should
adopt the mentality of a daguo.
45
And by the time Deng’s suc-
cessor, Jiang Zemin, stepped down in :oo:, giving way to the
next generation of leaders, that daguo had created a global
strategy.
,o Changes on the Home Front
III
A Charm Strategy
y the early :ooos China’s charm offensive had begun.
From the top, the Beijing leadership set out its goals.
As Chinese leaders constantly emphasized, China
desires stability and peace with all countries, and es-
pecially those on its borders—frontiers with fourteen nations,
ranging from dynamic Vietnam to tiny Laos to colossal Russia
to backward North Korea. “Safeguarding peace, promoting de-
velopment and enhancing cooperation, which is the common
desire of all peoples, represents the irresistible historical trend,”
China’s Foreign Ministry announced in a white paper.
1
Chinese scholars and officials. At
its core, explained Zheng, a close associate of Chinese Presi-
dent Hu Jintao, Peaceful Rise meant that, unlike past emerging
powers whose new might had caused shock waves across the
world, China would threaten no nation, even as it becomes a
global power. China’s rise “will not come at the cost of any
other country, will not stand in the way of any other country,
nor pose a threat to any other country,” said Prime Minister
Wen Jiabao in a :oo¡ speech that encapsulated the Peaceful
Rise idea.
2
The Chinese leadership created Peaceful Rise as it real-
ized that its hard power remained relatively weak. In the mid-
I,,os, China had tried to use military strength to intimidate
other countries in Asia, by aggressive moves like sending ships
to unoccupied, disputed reefs in the South China Sea. At the
same time, Beijing called on other nations in the region to
abandon their alliances, mostly with the United States, arguing
that these had been made obsolete by the Cold War. This strat-
egy backfired. Countries across the region condemned Bei-
jing’s aggressive behavior and solidified their military links
with the United States, drawing the US armed forces closer
into the region, and closer to China—exactly what Beijing did
not want. Nations like the Philippines, located right in the
South China Sea, started convening National Security Council
meetings just to deal with the possibility of Chinese military
activity. China would then criticize nations like the Philippines
for their response, only engendering more mistrust of Beijing.
Overall, as the regional specialist Denny Roy found in the late
I,,os, China seemed to have no coherent, effective foreign pol-
icy in Asia.
3
Beijing eventually recognized its mistakes: seizing reefs
had turned countries against China, but offering assistance
during the Asian financial crisis had won friends. As Chinese
officials told me, after internal debate, the leadership in Beijing
decided to tone down the military action and instead focus on
,8 A Charm Strategy
building China’s global soft power. In his landmark study of
China’s new engagement of Asia, the scholar David Sham-
baugh, too, suggests that after an internal policy discussion in
Beijing, Chinese leaders decided “to have a peaceful environ-
ment conducive to domestic development” and that “China
needed to be more proactive in shaping its regional environ-
ment.” Furthermore, by focusing on soft power, the former in-
telligence officer Robert G. Sutter notes in his recent book
China’s Rise in Asia: Promises and Perils, Beijing could avoid di-
rectly confronting the United States, the unrivaled global hard
power, while possibly weakening America’s soft power in the
longer term.
4
Wooing, not intimidating, would now be the order of
business. “We should . . . establish a publicity capacity to exert
an influence on world opinion that is as strong as China’s
international standing,” announced Jiang Zemin. Promoting
peace would serve several functions for Beijing. It would allow
China’s economy to continue growing, holding up the regime’s
end of the bargain with the Chinese intelligentsia, and there-
fore forestalling any major national protests. Peace would fos-
ter prosperity, providing opportunities for Chinese companies
looking overseas for outlets for their goods, allowing resources
like oil to flow in and out of China unimpeded, and paving the
way for China to build its own national science and technol-
ogy capabilities, which still relied heavily on imports of foreign
research and technology. “China aims to be one of the front-
runners [in technology] among developing countries around
:oIo . . . and [to be in] the medium level among world giants
in science and technology eleven years later,”noted Bai Chunli,
vice president of the Chinese Academy of Sciences.
5
Peace also would help China portray itself as a benign,
peaceful, and constructive actor in the world. In the West and
A Charm Strategy ,,
in many developing nations, China’s military actions in the
I,,os, and its powerhouse economy, had created a “China
threat” school of thought among many scholars—the idea
that, indeed, a rising China, like rising Japan and Germany in
the early twentieth century, would threaten the world. As the
China scholar David Lampton outlines, policy makers in
many countries responded to this idea of a Beijing threat and
adopted what he calls a strong China paradigm. In Lampton’s
strong China paradigm, policy makers take for granted that
China will increasingly use its strength to wield power abroad,
and they consider how other countries should prepare for po-
tential power rivalry with Beijing.
6
Changing China’s image and undermining the scenario
of a China threat, then, were vital to Beijing—and crucial to
the future of its foreign policy. With this change, Beijing would
diminish fears of China’s future military power, or concerns
that China’s massive economic growth would divert trade and
foreign investment from other nations. Chinese leaders drove
this point home in speech after speech. “It is only through the
road of peaceful development that the progress of the human
race . . . can be achieved,” Hu Jintao said in one such speech.
“History tells us that any attempt by a country to realize its in-
terests through the use or threat of force, or to place its interests
above those of other nations, will get nowhere. Such attempts
are against the tide of history of human development and
against the fundamental interests of people all over the world.”
7
Peace also would allow Beijing to pursue its second goal:
obtaining enough resources to feed its economy. Soon to be-
come the world’s largest consumer of oil, already the major
market for copper, iron ore, aluminum, and platinum, and
desperate for timber, China needs access to critical commodi-
ties. More than ,oo million people may migrate from rural
¡o A Charm Strategy
areas of China to cities and towns by :o:o, only adding to de-
mand. In his major address of :ooo, Wen Jiabao mentioned
energy a whopping twenty-eight times. China faces a “growing
dependence on imports of some important minerals from for-
eign countries,” Wen told his countrymen in another briefing.
As a measure of how important access to resources has become
to Beijing, Prime Minister Wen also has formed an internal
government task force focused on the nation’s energy needs,
and staffed the task force with China’s highest officials.
8
According to Erica Downs, an energy analyst at the
Brookings Institution in Washington who closely follows de-
bate within the Chinese leadership, Beijing believes that it can-
not trust the world markets for long-term supplies of oil, gas,
minerals, and other commodities, since the United States con-
trols the global sea lanes and has long-standing relationships
with key oil suppliers like Saudi Arabia. China has no real
strategic petroleum reserve, and its own domestic oil and gas
production continues to decline, so Chinese leaders, Downs
says, fear that the United States could stop China from obtain-
ing resources if there were a conflict between Washington and
Beijing. To prevent this possibility, China must win the trust of
foreign states that control stakes in oil, gas, and other resources.
In the long run, most energy analysts believe, China wants to
control the entire process of resource extraction, from taking
commodities out of the ground to shipping them back to China.
“If the world oil stocks were exceeded by growth, who would
provide energy to China?” one informal adviser to the Chinese
government mused to reporters, explaining China’s desire for
control. “America would protect its own energy supply.”
9
Smoother international relations would facilitate China’s
third goal: building a ring of allies who share Beijing’s suspi-
cion of nations intervening in other countries’ affairs. In some
A Charm Strategy ¡I
developing nations, like Iran or Burma or Zimbabwe, China
may also seek to help these countries to remain authoritarian
states—states thus more likely to remain close to China.
10
Not all of Beijing’s goals follow from Peaceful Rise,
though. Taiwan is a special case. The Chinese leadership wants
to reduce the international influence of Taiwan, which it con-
siders a province of China. Beijing first enunciated this strat-
egy in I,,¡, when the Chinese leadership declared that it
would “use all economic and diplomatic resources to reward
countries that are willing to isolate Taiwan.” In the I,,os, as
Taiwan became a democracy, the Taiwanese leader Lee Teng-
hui had tried to boost Taiwan’s power through a “Go South”
strategy of boosting Taiwanese investment in Southeast Asia
and upgrading Taiwan’s informal relations with developing
nations around the world.. By winning friends away from Taiwan, China also
could tighten Taiwan’s room to maneuver in international or-
ganizations.
China also wants to demonstrate to the world that it can
be a great power, a daguo, and perhaps ultimately an equal
of the United States. As the scholars Evan S. Medeiros and
M. Taylor Fravel have found, in Chinese journals Chinese
strategists emphasize that China should conduct great-power
relations with other leading nations, like the United States. In-
deed, throughout Chinese-language journals, scholars argue
that China must show the globe it has arrived as a great power.
“By the middle of the :Ist century China will be among the
¡: A Charm Strategy
great powers in the world,” noted Xia Liping, professor at
the Shanghai Institute of International Studies, summing up the
conventional wisdom among Chinese officials. “Although the
United States wants to realize a single-polar world . . . the trend
of multi-polarization”—the rise of other great powers—“will
continue to develop.”
12
As a great power, China might even shift influence away
from the United States, creating its own sphere of influence for
places like Southeast Asia, where China’s power is strongest. In
this sphere, countries would subordinate their interests to
China’s and think twice about supporting the United States
should there be any conflict in the region, and China would
have a final say on important political, economic, and strategic
issues.
By the early :ooos Beijing also had developed the subtle strate-
gies needed to achieve these goals. These strategies were not
entirely responsible for changing global views of China—in-
ternational events, like the declining image of America, came
into play, as did individual countries’ strategic calculations of
how best to respond to China’s charm. But Beijing clearly
has come to employ conscious strategies. In statements and
speeches, Chinese leaders began to enunciate a doctrine of
“win-win” relations, highlighting that Latin American and Af-
rican and Asian and Arab nations might benefit from their
relationships with China even as China benefits from its rela-
tionships with them. In one major address given in :oo,, en-
titled “An Open Mind for Win-Win Cooperation,” Chinese
President Hu told Asian leaders, “Dialogue and consulta-
tion . . . is an important avenue to win-win cooperation. . . .
[China] will only [promote] peace, stability, and prosperity.”
“The aim of Sino-African cooperation is mutual benefit. . . .
A Charm Strategy ¡,
It is particularly conducive for the development of African
countries,” echoed assistant Foreign Minister He Yafei, in a
speech marking Prime Minister Wen’s :ooo tour of Africa.
13
In other words, China would be everyone’s friend; Bei-
jing would listen to the needs and desires of other nations,
supposedly without asking for anything in return; China
would not interfere or meddle. Foreign nations could benefit
because China would not make demands upon other nations’
sovereignty, economic models, governance, or political cul-
ture. China also would not threaten or sanction anyone—
it would reassure other countries that it had no aggressive
desires. “To achieve peaceful development is a sincere hope
and unremitting pursuit of the Chinese people,” Beijing an-
nounced in a landmark policy statement entitled “China’s
Peaceful Development Road,” playing into the broader con-
cept of China’s peaceful rising to power. China will “opt for di-
alogue in resolving disputes[,] step up cooperation in main-
taining security, and bring about lasting peace and stability in
Asia,” Wen Jiabao told an audience of Asian leaders in :oo,.
14
This Chinese doctrine of noninterference, which would
help build a string of allies like Iran and Venezuela, coincides
with an era when, at least since the mid-I,,os, American inter-
ventionists have become more influential in US foreign policy
making—both liberal moralists who argue for humanitarian
intervention and neoconservatives who support intervention
to preemptively halt threats to American security. Conse-
quently, American foreign policy elites increasingly have ques-
tioned the balance Washington should strike between respect-
ing nations’ sovereignty—a traditionally realist foreign policy
position—and pushing for humanitarian action or democra-
tization, whether in Iraq or Ukraine or anywhere else. Going
along with this trend toward greater interventionism, in recent
¡¡ A Charm Strategy
years the United States also has relied more on sanctions as a
weapon, from comprehensive sanctions on new business in
Burma to more targeted restrictions on the export of certain
types of goods to countries like Syria. By comparison, Wen an-
nounced, in one speech, “We believe that people in different
regions in countries . . . have their right and ability to handle
their own issues.”
15
In supposedly trying to be nearly everyone’s friend (Taiwan
and Japan stand as notable exceptions), Beijing was displaying
a type of pragmatism unthinkable to a previous generation of
Chinese leaders. For past leaders, ideology defined relation-
ships, trumping other factors. Now China would deal with any
state it thought necessary to its aims. In the Philippines, China
would ask to mediate between the government and commu-
nist insurgents, so alienating the communists that they started
threatening Chinese businesspeople investing in the Philip-
pines. In Nepal the Chinese government would offer support
to the monarchy, even reportedly sending truckloads of arms
and ammunition, despite the fact that the king was fighting—
and eventually lost to—a Maoist rebel group pursuing the very
military tactics that Chairman Mao himself had pioneered.
16
In Cambodia, I discovered China’s new pragmatism for
myself. In the bowels of the Cambodian Parliament, a low-rise
building crowded with tiny cubbyhole offices, I met Keo Remy,
an outspoken member of the Sam Rainsy Party, a liberal Cam-
bodian party known for its supporters in America and in Tai-
wan. Sitting on a small couch in an office packed with aging
computers and unmatched tables and chairs, Keo Remy looked
the part of a beleaguered opposition politician. A wispy goatee
framed his narrow, sallow, worn face, and he rubbed the bags
under his eyes and cracked his long, thin fingers.
17
A Charm Strategy ¡,
Keo Remy never had it easy. This was January :ooo, and
the head of his party, a mercurial former finance minister
named Sam Rainsy, had fled Cambodia because the prime
minister, the tough and ruthless Hun Sen, had charged him
with defamation. (Rainsy eventually returned to Cambodia
and reconciled with Hun Sen.) Another friend of Keo Remy’s,
an opposition activist, had been arrested for criticizing the
government. Occasionally, Keo Remy stopped our interview to
take calls from well-wishers worried he might be the next one
heading to jail.
For years, Beijing had only complicated Keo Remy’s
troubles. Since I,,, China had become vastly more influential
in Cambodia, as Beijing built close relations with the govern-
ment in Phnom Penh, offered Cambodian sizable new aid
flows, and promoted closer trade links with Cambodia. But
none of this warmth filtered down to Keo Remy. The Chinese
embassy in Phnom Penh had ignored the Sam Rainsy Party,
perhaps because the party criticized China for its suppression
of human rights, and because the shoestring party had little
real power in Phnom Penh. Keo Remy received no invitations
to Chinese embassy functions, and when he ran into Chinese
officials in Phnom Penh, they never spoke to him. When Sam
Rainsy had attended the inauguration of Taiwan’s president,
Chen Shui-bian, Beijing had demanded that Rainsy break off
any future contacts with Chen’s party. When he refused to do
so, the Chinese government announced that it would aggres-
sively monitor Rainsy’s future behavior toward Taiwan.
But in :oo, a deadlocked national election—Hun Sen’s
party failed to get enough seats to form a government—left
Cambodia without a Parliament for more than nine months.
Suddenly, the Sam Rainsy Party seemed like a potential king-
maker, able to create a coalition with other opposition parties
¡o A Charm Strategy
and maybe even form a government, which might put mem-
bers of Parliament like Keo Remy into positions of serious
power. “Then the Chinese ambassador started calling us,” says
Keo Remy with a laugh, even though his party’s liberal mem-
bers still had no love for Beijing. Keo Remy paid several visits
to the Chinese embassy, where Chinese officials explained Bei-
jing’s growing trade with Cambodia and chalked up all the old
friction with his party to misunderstandings. As Keo Remy left
the embassy, he remembers, “They’d invite us to banquet with
them [at the Chinese embassy], they’d drop hints about how
they could aid us.”
In July :oo¡ Cambodia ended nearly a year of political
deadlock, as Hun Sen picked offsome ini-
tiatives. Beginning in the late I,,os China enunciated what it
called a “new security concept,” in which it emphasized that
Beijing and other nations could guarantee their security by
working more closely with multilateral institutions and build-
ing mutual trust with their neighbors. (Elements of the “new
security concept” were later incorporated into Peaceful Rise.)
China soon began putting the new security concept into prac-
tice. These initiatives receive little coverage from a Washington
press corps that focuses on summits, state visits, and other
grand events of international relations, but they are vital to
wooing developing nations. China has ended nearly all of its
border disputes and has signed the Treaty of Amity and Co-
operation, a document that commits the signers to mutual re-
A Charm Strategy ¡,
spect for the sovereignty and equality of the ten countries in
the Association of Southeast Asian Nations. Beijing has com-
mitted to creating a code of conduct on the South China Sea;
it has signed the Southeast Asian Nuclear Weapon Free Zone,
which commits the signers to forgo using, developing, or test-
ing nuclear weapons in Southeast Asia; it has enthusiastically
signed bilateral cooperative agreements and strategic partner-
ships with several Asian states, on a range of economic and
strategic issues. In :oo, China even agreed to work with Viet-
nam and the Philippines on a joint exploration of the disputed
South China Sea. Some of the agreements and partnerships are
no more than vague commitments; others, like China’s strate-
gic partnership with Thailand, are more substantial, and con-
tain specific elements that could eventually lead to more for-
mal alliances.
18
In Latin America and Africa the Chinese government
has used similar initiatives. It has signed as many cooperative
agreements as possible, to boost China’s image as a benign,
nonthreatening actor. These cooperative agreements eventu-
ally could be used as building blocks for more substantial
partnerships. During a trip to Mexico in January :oo,, Vice
President Zeng Qinghong signed seven cooperation accords
on maritime transportation, judicial assistance, and other is-
sues, then signed an agreement with the foreign ministers of
the Andean states to deepen political links. Similarly, on a visit
to Venezuela in :oo,, Zeng signed nineteen such accords on
technology transfer and other topics. In Africa, Beijing helped
establish a Forum on China-Africa Cooperation in :ooo, then
used the forum to create a Program for China-Africa Cooper-
ation in Economic and Social Development, which outlined
plans for closer cooperation on economic, health, develop-
¡8 A Charm Strategy
ment, and diplomatic issues. It also signed more than forty bi-
lateral cooperation agreements with African nations.
19
Beijing seems willing to sign these agreements, leaving
details to be hammered out later. “The Chinese just say, ‘Here,
let’s deal, and we’ll take care of the particulars . . . later,’” said
one Southeast Asian diplomat. In the lawyerly—but demo-
cratic—American political system, this type of sign-first-talk-
later diplomacy would be virtually impossible, anathema to
Congress and American businesses used to scrutinizing every
detail and every sector of a US agreement with a foreign na-
tion. The United States has not signed Southeast Asia’s Treaty
of Amity and Cooperation, and as one congressional official
says, “We need to participate in some of these events, the high-
profile ones, even if we think they’re stupid. The symbolism
matters.”
20
In general, China’s soothing language of noninterven-
tion can provide a sharp contrast with the United States, which
Chinese officials paint as a hegemon unwilling to listen to other
nations’ concerns and slapping sanctions on other countries,
like Burma or North Korea and Cuba. By allying with China,
Beijing suggests, countries can avoid the onerous economic
and political changes demanded by Washington and its West-
ern allies. “The Chinese government has always advocated full
respect for sovereign equality [and] noninterference in the in-
ternal affairs of other countries,”China’s deputy permanent rep-
resentative to the United Nations said at the UN General As-
sembly in :ooI, during a debate about Cuba. “The international
community as a whole has a strong desire for a certain coun-
try to forsake its outdated practice of economic embargo.”
21
This message can be compelling, and not only to leaders
in the ring of authoritarian states China may want to cultivate.
A Charm Strategy ¡,
Elites and populaces in many newly democratic nations, such
as Mexico or Indonesia, often resent US criticism of their
human rights records. When these countries were ruled by au-
thoritarian regimes, US pressure on human rights often res-
onated with local democrats. But today even some committed
Mexican or Indonesian democrats disdain US criticism of
human rights records, which they see as demeaning and blind
to their nations’ progress. In Mexico the government, now led
by a former opposition party, has expressed anger after Amer-
ican officials criticized Mexican police for corruption and use
of torture.
22
Beijing has responded by engaging Mexican offi-
cials in discussion on human rights issues—a discussion prob-
ably designed to portray both China and Mexico as unfair tar-
gets of American criticism.
China’s noninterventionist language also mirrors some
of the ideas enunciated by many developing nations’ own re-
gional organizations, since smaller developing countries often
fear being overpowered by larger states. To take one example,
since its founding four decades ago, the Association of South-
east Asian Nations has always adhered to a code of noninter-
ference in member states’ affairs, a code that fits easily with
China’s message.
23
Beijing also reversed its previous disdain for multilateral
organizations, which older Chinese leaders had seen as con-
straints on China’s power and venues for other nations to crit-
icize China. “Over the past decade . . . China has become a
born-again regional multilateralist,” said Susan Shirk, the for-
mer deputy assistant secretary of state. In part, China may
have realized that by avoiding multilateral organizations in the
past, it had only stoked fears of Beijing, since other countries
had less interaction with Chinese diplomats and few forums to
discuss issues of concern with Chinese leaders. By engaging
,o A Charm Strategy
with multilateral organizations like the Association of South-
east Asian Nations and fostering more interactions between
foreign and Chinese officials, China can reduce fears of Bei-
jing, giving it time to gain more influence without troubling
other countries about its rise.
24
By working with multilateral
organizations, Beijing also can signal to other countries that it
can play by international rules and be a responsible power. It
cannot have hurt that as the United States became less inter-
ested in multilateralism, China’s participation in multilateral
organizations made Beijing look more cooperative by com-
parison.
Again, China backed up its changing strategy with real
initiatives. In Latin America, it joined the Organization of
American States, the most important regional group, as an ob-
server; it observed at the Inter-American Development Bank,
the major international financial institution in Latin America;
and it signed an agreement on closer relations with the Andean
Community. In Africa, China began to provide support to the
African Union and to play a larger role in the African Devel-
opment Bank. In Asia, China joined the Association of South-
east Asian Nations as a dialogue partner, played a growing role
in the Asean Regional Forum, became a major force behind
the first East Asia Summit, and created an Asia Cooperation
Fund to help Chinese government agencies increase their co-
operation with Asean. In fact, according to Asian diplomats,
China has initiated far more joint projects with the Associa-
tion of Southeast Asian Nations than other Asean partners,
like Japan or the United States.
25
While the Bush administration focused its foreign policy strat-
egy before September II on US relations with major powers,
and then after September II on fighting terrorism, China also
A Charm Strategy ,I
began portraying itself as the natural guardian of developing
countries—more natural than the United States. “In :oo:, the
Chinese government looked at its foreign policy and ranked
relations with the US first, and then relations with neighbor-
ing countries second,” says Ruan Zongze, vice president of the
China Institute for International Studies, a prominent Beijing
think tank. “By two years later, China changed the rankings
and ranked relations with neighboring countries first”—re-
flecting its priority on the developing world. Indeed, in the
Chinese Communist Party’s :oo: work report, the most im-
portant record of CCP priorities, the leadership made “be-
coming friends and partners with neighbors”—that is, nearby
developing nations—a top strategic priority.
26
At times, Chinese officials hit the idea of solidarity with
the developing world hard. In an address in Brazil in :oo¡, Hu
Jintao announced that China would always “stay on the side of
the developing countries,” and the following year Hu met with
the leaders of Brazil, India, Mexico, and South Africa in an at-
tempt to build a broader partnership of leading developing
countries, so that they could work together in international or-
ganizations. Lower-ranking officials echo the message. In an
address to the China-Latin America Friendship Association,
National People’s Congress Vice Chairman Cheng Siwei said,
“Both [China and Latin America] belong to the developing
world and have identical or similar views on many issues.”
Cheng also frequently refers to China and Latin America’s
shared histories of imperialism, telling one audience of Latin
Americans, “I think we have very good feelings toward each
other because we both have a history of being invaded by colo-
nialists.”
27
In Asia the story was similar. “It was very clear that at
meetings of the Asia Pacific Economic Cooperation [a group
,: A Charm Strategy
that promotes trade on the Pacific Rim,] that China was look-
ing to be the spokesperson of the Third World countries,” Fed-
erico Macaranas, a Filipino scholar who helped run APEC for
years, told me. “They know if they ally themselves with the
Third World, they can portray themselves as on our side.”
Macaranas was impressed by China’s solicitousness. “Japan
asks talented Filipino scientists to come to Japan and learn,
and the Chinese send their scientists here, to look at the Philip-
pines, to learn from the Philippines,” he says. “If you want to
really have partnership with the Third World, you can go see
[them] on the ground.”
28
China’s strategy also includes focusing on developing na-
tions whose bilateral relationships with other major powers
are faltering. Often, these countries are either authoritarian
states or nations whose leaders display some autocratic traits,
and thus could be sympathetic to Chinese influence; many
also have significant energy resources, though energy is not the
only reason China cultivates them. Beijing has aggressively
courted Hugo Chávez as the Venezuelan leader has stepped up
his confrontation with Washington, repeatedly inviting him
on state visits to China, upgrading trade ties, and supporting
Venezuela’s bid for a seat at the United Nations Security Coun-
cil. Though Chinese officials tried to downplay the Venezue-
lan leader’s anti-US rhetoric, Chávez called China’s moves a
“Great Wall” against US hegemony and touted the two na-
tions’ “strategic alliance,” while proclaiming that Beijing and
Caracas were united in standing up to America.
29
Similarly, when the left-wing populist Evo Morales won
the presidency in Bolivia in :oo, and the United States re-
sponded by quickly proposing cuts in aid to Bolivia, China in-
vited Morales to Beijing for one of his first state visits. Morales
proclaimed China an “ideological ally” and asked China to
A Charm Strategy ,,
help Bolivia develop its reserves of natural gas. In Uzbekistan,
after the Bush administration criticized Tashkent following a
massacre of some four hundred Uzbeks in :oo,, China quickly
expressed “resolute support” for Tashkent, inviting the Uzbek
dictator Islam Karimov for a state visit highlighted by a
twenty-one-gun salute and a treaty on friendship and cooper-
ation. In Sudan, as Western nations isolated the Khartoum
government for its human rights abuses and supposed links to
terrorism, China stepped up its support. While the United
States slapped sanctions on Khartoum, top Chinese politicians
cultivated the Sudanese dictatorship, reportedly speeding up
Chinese megaprojects in Sudan in time for the tenth anniver-
sary of the dictator Omar Bashir’s coup, to bring him more
prestige.
30
Iran is probably the most obvious example of China’s
cultivation of isolated autocrats. Though clearly uncomfort-
able with Iranian President Mahmoud Ahmadinejad’s stri-
dent anti-American and anti-Israeli rhetoric, the Chinese gov-
ernment invited him to address the Shanghai Cooperation
Organization, a leading summit of Chinese, Russian, and Cen-
tral Asian leaders, held in China in June :ooo. There the Iran-
ian president delivered a major address on Chinese state tele-
vision and touted Tehran’s and Beijing’s “identical” views on
world issues. Meanwhile, China has hosted senior advisers to
Supreme Leader Ayatollah Khameini, instructing them in Chi-
nese economic and political management, and has backed
massive investment into Iranian infrastructure by Chinese
firms.
31
But China has not only wooed autocrats. As the United
States threatened to cut off military assistance because Ecuador
would not agree to exempt US soldiers from prosecution at the
,¡ A Charm Strategy
International Criminal Court, China invited Ecuadorian offi-
cials to Beijing and later offered Ecuador pledges of new assis-
tance. In South Korea, a vital US ally, relations between Seoul
and Washington have faltered in recent years over how to
handle North Korea: South Korea, on North Korea’s doorstep,
prefers engagement to the Bush administration’s harder-line
approach. Seeking other partners, Seoul has looked to warmer
ties with Beijing. Although China has never called on Seoul to
choose between Beijing and Washington, it has cultivated
politicians close to President Roh Moo-Hyun and former
President Kim Dae Jung, according to numerous South Ko-
rean officials. Beijing also has launched a comprehensive co-
operative partnership with Seoul and has publicly supported
South Korea’s engagement policy toward the North. Seoul’s
engagement of Pyongyang is in China’s interest, since Beijing
does not want the rapid collapse of the North Korean regime.
32
Even in the Philippines, a former American colony where
cable channels screen American National Basketball Associa-
tion games and US fast food outlets employ bouncers, like chic
bars, to keep out the crowds—“Is T.G.I. Friday’s fine dining in
the US?” one Filipino journalist asked me—China has waded
in as US-Filipino relations grow less steady. After President
Gloria Macapagal-Arroyo pulled Filipino troops out of Iraq in
:oo¡, part of a deal to win the freedom of a Philippine hostage,
the United States cut assistance to Manila. Shortly after, China
invited Macapagal-Arroyo for a state visit, then aggressively
wooed Philippine policy makers, offering greater cooperation
and aid. “My boss came to Los Angeles and he was personally
offended when he was searched down at the airport,” said one
Filipino official charged with escorting a top cabinet member
to the United States. “Then he came to Washington and for
A Charm Strategy ,,
forty-eight hours he didn’t get any answer from the [US gov-
ernment representatives]. That really angered him. . . . Then
when you go to China, they roll out the red carpet.”
33
A major component of China’s appeal to developing nations is
that Beijing portrays China as a potential ideal. In their deal-
ings with other developing nations, Chinese officials suggest
that China has developed a model for social and economic
success, and in speeches to developing-world audiences they
increasingly sell the China model. The former Time foreign
editor Joshua Cooper Ramo calls this model the “Beijing Con-
sensus,” in contrast to the “Washington Consensus” of the
I,,os, which stressed rapid free-market reforms as a path to
prosperity. In the Beijing Consensus, Ramo says, growth
comes from the state directing development to some degree,
avoiding the kind of chaos that comes from rapid economic
opening, and thus allowing a nation to build its economic
strength. Minxin Pei calls China’s model gradualist reform
dictated by authoritarian politics: the Communist Party in-
troduced economic reforms and built economic institutions
slowly, maintaining a large state sector in the economy, and si-
multaneously did whatever was necessary to ensure the Party’s
survival.
34
Whether or not one calls it a Beijing Consensus, China
clearly promotes its socioeconomic model through speeches
overseas, a model of top-down control of development and
poverty reduction in which political reform is sidelined for
economic reform. (In Chinese publications, Chinese govern-
ment-linked think tanks and media have embraced Ramo’s
phrase and have contrasted it with the Washington Consen-
sus.) And this model stands in direct contrast to democratic
liberalism, the economic and political model emphasizing in-
,o A Charm Strategy
dividual rights and civil liberties that has underpinned the so-
cieties of the West, and of its democratic allies in Asia.
35
On the road, Chinese officials do not shy away from ad-
vertising the benefits of China’s socioeconomic model. As
Drew Thompson, a China scholar who has studied Beijing’s
advances toward Africa, found, “The Chinese government has
also actively promoted their own brand of economic develop-
ment and reform model to African countries, encouraging . . .
African governments to fashion their economic systems after
[China’s] own.”
36
China seems to have enjoyed striking success with its an-
tiliberal model—decades of economic success and poverty re-
duction other developing nations can’t help but notice. At the
same time, the Washington Consensus has failed many devel-
oping nations. During the late I,8os and the I,,os, many Af-
rican and Latin American nations opened their economies,
slashed tariffs, and undertook other painful economic reforms,
yet few nations in either Latin America or Africa saw their
economies take off. Even when these poor regions boosted
growth, it seemed to have no measurable impact on employ-
ment, leaving masses of unemployed people willing to try an-
other economic model, and leaders groping for answers as
well. In Africa, for example, the United Nations Commission
on Africa reported that while “Africa’s real Gross Domestic
Product grew by ¡.o per cent in :oo¡ . . . the growth has so far
not been translated to employment creation or poverty reduc-
tion.”
37
This failure of the Washington Consensus opened the
door for nations like Bolivia or Argentina to embrace state-
driven economics once again, even though that state-led model
also had failed in the developing world in the past.
China’s model particularly appeals to rulers in authori-
tarian or semiauthoritarian nations Beijing is cultivating. This
A Charm Strategy ,,
only makes sense. Rapid market reforms like the ones pro-
moted in the Washington Consensus historically also have cre-
ated pressure for political liberalization. With rapid economic
reforms the ruling regime has less time to try to adapt to
change and to figure out ways to co-opt the new business-
people and other economic elites being created by reform.
With the China model, the regime has time to co-opt the
businesspeople and other elites it needs to keep on its side to
remain in power. To someone like the head of the Communist
Party in Vietnam or the president of Uzbekistan, the proof
cannot be ignored: China has liberalized much of its economy,
yet the Communist Party still rules the country.
In small countries, China’s friendship can seem almost over-
whelming in its generosity. China offers the smallest nations
significant respect, in contrast to the supposed American pref-
erence for building bilateral ties with the most important ac-
tors. “Smaller countries like the fact that they are treated as
heads of state when they come to China—so even if they come
from St. Kitts and Nevis, they get great deference in Beijing,
which they might not get in Washington,” says Dan Erikson,
head of a project on China–Latin America relations at the
Inter-American Dialogue, a Washington think tank.
38
China’s focus on small nations receives little attention in
the US policy community or media, a lack of attention Beijing
may prefer. Without any spotlight, it is easy to apply pressure
on smaller countries, getting them in the habit of surrendering
to a larger country’s will. Small gains add up: as anyone who
plays the Chinese classic strategy game Go knows, one way to
beat your enemy is to quietly build relations with small players
until your rival is surrounded.
Countries don’t get much smaller than Laos, a poor
,8 A Charm Strategy
country of six million people, most of whom survive by sub-
sistence farming. In I,,,, after the Vietnam War, which re-
sulted in the Lao communists overrunning the country, Laos
slipped into slumber, a landlocked backwater run. On my first
visit in I,,8, I noticed that several hundred yards from the
airport in Vientiane, the capital, the “highway” turned into a
narrow dirt road. Along the sides of the road, water buffalo
threshed rice and barefoot children rode the backs of wooden
oxcarts. Laos’s small, secretive ruling elite also had been ig-
nored by most of the world. For decades, the United States still
did not grant Laos normal trading relations, though Laos’s
human rights record was no worse than the record of China,
with whom America traded vigorously. American sanctions on
Laos infuriated Lao officials, who didn’t understand why such
a big country like the United States would punish a minnow—
especially since during the Vietnam War, America had dropped
more bombs on Laos than it dropped on Germany and Japan
together during World War II, leaving Laos riddled with un-
exploded ordnance.
In the late I,,os Laos suddenly found another potential
patron—one that didn’t bother with sanctions and, Lao offi-
cials said, seemed to understand what a poor country needed
to survive.
39
Senior Chinese officials started showing up in
Vientiane, dragging Chinese business delegations with them.
Though China had long enjoyed relations with Laos, a sup-
posedly brother communist country, now it was stepping up
its courtship. And Laos’s leadership welcomed the attention.
Around this time, in the fall of :ooo, I was sent to Laos to
cover a story. Knowing that I would be spending several days
in somnolent Vientiane, I called a woman I knew who lived
there and who I hoped might take a romantic interest in me.
We met one night and she suggested an evening sipping cold
A Charm Strategy ,,
beers at one of the quaint stands overlooking the broad Me-
kong River. But we couldn’t find any Mekong stands. Jiang
Zemin had arrived in town, the first state visit by a Chinese
leader to Vientiane. For Jiang, the Lao government spared no
expense, though Laos suffers from African levels of poverty.
Laos was throwing endless banquets in honor of the Chinese
delegation—and tearing down the beer stands to make room
for the parties. A grateful Lao prime minister told Jiang that his
trip was “a historical visit” and that China’s economic growth
“has set a good example for us in constructing and developing
our country.” Jiang responded, playing the developing-country
solidarity card: “All countries in the world, small or large, have
their own merits. Thus, each should learn from others’ strong
points.” Just to make his point clear, Jiang announced, “The
characteristics of our ties can be summed up as mutual trust,
mutual support, equal treatment, non-interference of the
other’s affairs, and sincere cooperation.”
40
The story of Jiang’s visit had a happy ending for my
friend and me. Instead of beers, we migrated to an Italian
restaurant in town and hit it off; three years later we were mar-
ried. It had a happy ending for the Lao government too, if not
always for average Lao people. Soon after, Laos, like other
countries being wooed by China, was hit with China’s whole
toolbox of influence, from aid to trade to promotion of Chi-
nese culture and language. When I returned to Vientiane five
years later, a new delegation of top Chinese officials had ar-
rived in town. This time, Laos did not need to move any stands
or vendors to make way for the Chinese. The Chinese delega-
tion could meet their hosts inside the giant new cultural hall in
downtown Vientiane, paid for by Beijing.
oo A Charm Strategy
IV
The Tools of Culture
s China has built a global strategy, it also has developed
more sophisticated tools of influence, which it de-
ploys across the world. These tools fall into two cat-
egories. First, China utilizes tools of culture and
diplomacy—tools related to Chinese culture and arts and lan-
guage and ethnicity. China’s growing economic might allows
Beijing to deploy these tools, since of course it costs money to
hold cultural summits or send language teachers to other na-
tions. But these tools are not dependent upon trade and in-
vestment.
China’s cultural promotion is part of a broader effort at
public diplomacy. Public diplomacy, according to one accepted
definition, is the cultivation by governments of public opinion
in other nations; by cultivating this public opinion abroad,
states can more effectively pursue their national interests.
Until recently, China either paid no attention to public diplo-
macy or, when it did, made clumsy attempts that bordered on
pure propaganda, like China Radio International, an inter-
national broadcaster with programming that merely repeated
Chinese leaders’ statements. According to a study by the
scholar Rumi Aoyama, since the end of the Cold War, China
has moved away from this pure propaganda toward more nu-
anced public relations, even changing the name of the Party’s
Propaganda Department to the Publicity Department. In the
post–Cold War era, Aoyama found, Chinese public diplomacy
has five main objectives: “Publicizing China’s assertions to the
outside world, forming a desirable image of the state, issuing
rebuttals to distorted overseas reports about China, improving
the international environment surrounding China, and exert-
ing influence on the policy decisions of foreign countries.”
1
Since China announced the idea that peaceful develop-
ment would be the core of its foreign policy, its public diplo-
macy has taken on another objective—selling the idea that
China will not be a threat to other nations, a major undertak-
ing for Beijing. China’s public diplomacy efforts reinforce the
concept of peaceful development, efforts like organizing an
eleven-nation performance tour entitled “Voyage of Chinese
Culture to Africa” and museum exhibits in Malaysia and Sin-
gapore to celebrate the six hundredth anniversary of the voy-
ages of Zheng He, or Cheng Ho, a Chinese admiral who sailed
across Asia, the Middle East, and Africa, encountering but
never conquering other nations. “Zheng He treated other
countries with friendship and respect instead of occupying a
single piece of land, establishing a fortress, or seizing any trea-
sure,” Chinese Vice Minister of Communications Xu Zu-yuan
announced, drawing an implicit contrast with Western colo-
nists of that era. (Zheng He’s voyages, scholars note, did some-
times include violent encounters with locals, and they may
have facilitated a kind of Chinese economic colonialism of
other regions of the world.)
2
Part of this new public diplomacy has been an effort to in-
o: The Tools of Culture
crease cultural exchanges with the developing world. China has
begun hosting overseas scholars, the kind of programming that
the US State Department has long conducted. “China shows its
understanding of Thailand by inviting people from every circle
of Thai society to China—artists, academics,” says one profes-
sor at Bangkok’s Kasetsart University. “The Chinese inviting of
Thai professors to study in China has really grown in the past
four or five years.” Beijing also has created a Chinese version of
the Peace Corps, run by the China Association of Youth Volun-
teers, to send idealistic young Chinese on long-term volunteer
service projects to developing nations like Laos, Ethiopia, and
Burma, where fifteen Chinese volunteers arrived in early :ooo
to work on Burmese agriculture and sports projects.
3
China also has expanded the international reach of its
media. It has upgraded the Chinese newswire Xinhua, created
new overseas editions of the People’s Daily newspaper, estab-
lished a formal briefing system at the Ministry of Foreign Af-
fairs so that journalists can hold modern press conferences,
and expanded and professionalized the international broad-
casting of CCTV, Chinese state television. This expansion in-
cluded hiring Western anchors and making CCTV news look
more polished. Satellite television subscribers in Asia now can
receive a package of Chinese channels, just as Spanish-speak-
ing viewers can watch CCTV’s new Spanish service.
4
Meanwhile, though Xinhua originally fed news back to
Chinese publications—and to the Party—now it is picked up
in newspapers across the developing world and even by Amer-
ican news sites like Google. Since newspapers run it, Xinhua
also gets cited by scholars as a real news source, just like an-
other newswire; when I pick up the paper in Indonesia or Ar-
gentina, I often see stories by Xinhua and wonder whether lo-
cals think the service is any different from Reuters.
The Tools of Culture o,
Yet Xinhua is not Reuters or another private corporation:
it remains run by China’s State Council, essentially an organ of
the government; the Xinhua office even served as the de facto
Chinese embassy in Hong Kong before the handover in I,,,.
Xinhua takes orders from the Party’s Publicity Department,
exhibiting the kind of reverence for government spin that
the White House could only dream about. It cannot produce
evenhanded coverage of topics sensitive to Beijing, like Tai-
wan or Tibet. After the death in :oo, of Zhao Ziyang, the most
reform-minded Chinese leader, who was purged after the Ti-
ananmen riots of I,8,, state media published only a brief obit-
uary, though Zhao had been one of the most important lead-
ers in modern Chinese history. Xinhua’s reporters still receive
training, or indoctrination, sessions heavy in seminars on the
necessary role of the Communist Party. Its journalists also
still provide a kind of intelligence information service for top
Chinese leaders. According to the global watchdog Reporters
Without Borders, “Hand-picked journalists, who are regularly
indoctrinated, produce reports for the Chinese media that give
the official point of view and others—classified ‘internal refer-
ence’ for the country’s leaders. . . . Xinhua remains at the heart
of the censorship and disinformation system established by
the Chinese Communist Party.”
5
The new Chinese public diplomacy also includes setting
up networks of informal summits, either in China or in the
developing world, designed to bring together opinion leaders.
These summits allow China to subtly emphasize its role as a
potential partner for investment and trade and its position as
a leader of the developing world. The larger informal summits
include the China-Caribbean Economic and Trade Coopera-
tion Forum, attended last year by nearly one thousand officials
from China and the Caribbean; the Boao Forum for Asia,
o¡ The Tools of Culture
which brings together Asian businesspeople into a Davos-style
World Economic Forum–like event; and the Asean-China Em-
inent Persons Group, which unites former statesmen and has
produced a comprehensive roadmap for the future of South-
east Asia–China relations. The Chinese government also has
promoted smaller summits, making Beijing a center for meet-
ings of international Chinese-language media and of Chinese
studies associations.
6
As China has upgraded its public diplomacy, like broadcasting
and visitor programs, it also has invested in improving its
diplomatic corps. Over the past fifteen years, Chinese diplo-
mats told me, the Ministry of Foreign Affairs has begun to re-
tire older, more ideological diplomats, replacing them with a
young generation of envoys who speak better English and local
languages. One :oo, study suggested that one-half of the
country’s four thousand diplomats are less than thirty-five
years old. According to another study of China’s relations with
Latin America, since the I,8os Beijing has actively tried to up-
grade the quality of its diplomats in the Western Hemisphere.
It has sent IIo young Chinese officials to a university in Mex-
ico to learn Spanish and deepen their understanding of Latin
America. It has improved the capacity of its own think tanks
focusing on Latin America, ensuring that comprehensive re-
search was available on the Western Hemisphere for Chinese
officials. And China kept its Latin America specialists focused
on Latin America, so that someone like Jiang Yuande, China’s
ambassador to Brazil in :ooo, had already done thirty years of
tours around the Portuguese-speaking world, in countries like
Angola and Cape Verde, before he arrived in Brasilia.
7
China can keep these diplomats in the region because,
unlike the United States, which until recently allowed Foreign
The Tools of Culture o,
Service officers significant leeway to choose postings, the Chi-
nese Ministry of Foreign Affairs can mandate overseas assign-
ments. Chinese diplomats say that the ministry has pushed
envoys to focus on one country and repeatedly return there,
rather than moving from, say, Uzbekistan to Mexico, as an
American diplomat might. Top Chinese diplomats in nations
like Cambodia or Thailand now often have done three or even
four rotations in those countries before rising to the rank of
ambassador, developing extensive contacts in the local busi-
ness and political communities and building language skills to
the point that locals sometimes think they are native speakers.
“China sends the A team here,” says one US diplomat in Thai-
land. “Their ambassador here is really plugged in, and speaks
excellent Thai.” “It used to be that the Chinese officials just
stayed in the embassy, and you never saw them,”says one Asian
diplomat who served in the Philippines. “Now they are so
skilled on the ground they know more than anyone else. If
someone’s wife is having an affair, they know it. If someone is
having problems with their kid, they know it.” By comparison,
a Council on Foreign Relations analysis of Southeast Asia
warned that a “critical shortfall in US regional policy is our
lack of a skilled core of professionals familiar with the lan-
guage, culture, and political-military climates.”
8
Beijing supports its diplomacy through constant visits by
senior Chinese officials to developing nations, and through
nonstop coverage in Xinhua. In a study of China’s new global
foreign policy, National Defense University’s Philip Saunders
found that in :oo: China’s president and premier spent more
than four times as many days abroad as they had in I,,,. In
Asia, a short hop from Beijing but a twenty-hour flight from
Washington, the contrast in face time by senior officials can
be stark. A Singaporean diplomat estimated that China sends
oo The Tools of Culture
nearly three hundred senior-level delegations annually to the
city-state, far outstripping any American efforts; many visits
include the signing of new agreements on trade or investment.
As one US ambassador in Southeast Asia remembers, when
Southeast Asian nations last year decided to create an early
warning system to prevent future tsunamis, the United States
sent a low-level official to the brainstorming group. The Chi-
nese, by contrast, sent a senior cabinet-level official, who
reaped plaudits for Beijing. “It was like God had appeared at a
conference,” the ambassador remembers.
9
Across the developing world, in fact, diplomats con-
stantly complain that they do not see enough of top American
officials, who have focused intensely on the Middle East. South-
east Asian nations raged that Secretary of State Condoleezza
Rice skipped a major annual regional meeting in :oo,. One
White House policy maker bemoaned that she could not per-
suade America’s former trade representative, Rob Portman, to
make even one extended visit to Southeast Asia. In fact, when
I compared visits by top Chinese and American officials—cab-
inet rank in America or the Chinese equivalent—to Thailand
and Cambodia in :oo¡ and :oo,, I found that senior Chinese
officials made at least twice as many visits to Bangkok and
Phnom Penh.
10
Promotion of Chinese-culture and Chinese-language studies
is a major component of this public diplomacy. As Hu You-
qing, a deputy to the National People’s Congress, told the
China Daily, promoting the use of the Chinese language will
contribute to spreading Chinese culture and increasing China’s
global influence.
11
“It can help build up our national strength
and should be taken as a way to develop our country’s soft
power,” Hu said.
The Tools of Culture o,
Around the world, the Chinese government has launched
several measures to increase the teaching of Chinese. Beijing
now funds at least the first year of what it calls Confucius In-
stitutes, Chinese-language and -culture schools created at lead-
ing local universities in countries from Kenya to South Korea
to Uzbekistan to Australia. China plans to open at least one
hundred Confucius Institutes around the world within the
next five years. These Confucius Institutes are reminiscent of
the British Council or the Alliance Française, which have
helped promote British and French cultural brands without
being explicitly linked, in people’s minds, to Whitehall or the
Elysée Palace. (The name Confucius Institute betrays no links
to communism or to the Communist Party, and actually repu-
diates Mao, since the Chairman had tried to wipe out the
teaching of Confucian beliefs.) If local universities that de-
sire China studies beyond the Confucius Institute curriculum
suffer from a lack of resources, they can call upon the Chinese
Ministry of Education to lead intensive short courses for local
Chinese-language teachers, or even to send Chinese teachers
for a period of time. In Cambodia, for instance, the Chinese
government, working with provincial governments in China,
sends hundreds of instructors to Phnom Penh’s Chinese schools,
sparking requests for still more instructors from China. Simi-
larly, in countries like Indonesia, Argentina, Kenya, and Thai-
land, China’s Ministry of Education has begun dispatching
groups of language teachers for one- and two-year stints, which
are normally at least partially funded by the ministry.
12
Beijing also has tried to push instruction in Mandarin
and in Chinese culture in overseas primary schools, partly by
tegrate Chinese into public schools’ curricula, and partly by
o8 The Tools of Culture
helping students in poor nations like Cambodia attend pri-
vate local Chinese-language primary schools. In Thailand the
Chinese Ministry of Education has vowed to help train one
thousand Mandarin teachers per year and offer other Chinese-
language resources. Generally, these private schools receive
some assistance from mainland Chinese governmental and
private sources—the Chinese newspapers in Cambodia are
full of reports of small grants given to Cambodian Chinese-
language schools from mainland Chinese governments and
language associations. Because the Chinese-language schools
in Cambodia receive this outside funding, they can charge less
than many public schools, where impoverished (and some-
times corrupt) Cambodian teachers demand excess payments,
in addition to their salaries, just to teach classes. Cambodian
parents thus view the Chinese-language schools as providing a
finer, less corrupt education, and not surprisingly want to send
their children there.
13
While promoting Chinese studies in other nations, Bei-
jing also has tried to lure more foreign students to China. The
Ministry of Education has done so by advertising Chinese uni-
versities abroad, creating new scholarship programs for stu-
dents from the developing world, loosening visa policies for
foreign students, and increasing spending to lure elite foreign
scholars from the West to teach in China, thereby upgrading
China’s university system. Beijing has focused intensely on
Chinese-born scholars working in the West, creating national
programs named rencai qiang guo (Strengthening the Country
Through Human Talent), charging the Finance Ministry to
make funds available to entice these Chinese-born scholars, or
haigui pai, to return, and pushing select Chinese universities to
use :o percent of their government funding on hiring scholars
The Tools of Culture o,
from abroad.
14
Returnees have been welcomed from the very
top: Hu Jintao himself announced that the returnees would be
“irreplaceable” in China today.
The incentives may be working. In places like Cambodia,
a kind of feeder system has been created. Students who do well
in China-backed primary schools in Cambodia often can ob-
tain assistance from China to continue studies in the People’s
Republic, in either middle school, high school, or university.
(China has opened roughly five hundred of its primary and
middle schools to foreign students.) The Overseas Chinese Af-
fairs Office of the Chinese government has provided scholar-
ships for poor Cambodians to study in China since :ooo; in
Laos, the Chinese government hands out some :,o scholar-
ships per year for students to attend Chinese universities. One
study found that the number of Chinese returning to the
mainland from Hong Kong, to take one example, rose from
seven thousand in I,,, to thirty-five thousand in :oo,, though
China is not yet attracting back the top echelon of Chinese
scholars. Meanwhile, in :ooo China landed one of its univer-
sity MBA programs in the top twenty-five on the Financial
Times’ ranking of the world’s finest business schools, alongside
such luminaries as Wharton and Insead in France.
15
Taiwan and the United States, both of which historically
trained many students from the developing world, unwittingly
have helped China’s efforts to woo foreign students. Between
the I,oos and the I,,os Taipei provided funds for thousands of
ethnic Chinese students from across the world to study Chi-
nese language, culture, and other topics at Taiwanese universi-
ties—a traditional source of Taiwan’s soft power. But the cur-
rent government in Taipei, worried about tight budgets and
Taiwan’s weak economy, has cut subsidies for foreigners to
study in Taiwan. So while generations of older Malaysian Chi-
,o The Tools of Culture
nese received their higher education in Taiwan, built links to
Taiwanese elites, and developed sympathy for Taiwan, today
Malaysian Chinese told me their sons and daughters study in
Beijing University or Fudan University in Shanghai. As a re-
sult, these children know almost nothing about Taiwan.
16
After September II, meanwhile, the United States tight-
ened student visa policies, making it far harder for students
from most developing nations to attend school in America and
for academics to come to the United States to lecture or learn.
Even for foreign students already studying in the United States,
life became harder: in :oo, Washington announced that men
from Muslim countries like Bangladesh, Indonesia, and Jor-
dan residing in the United States would have to register with
American immigration by a specified deadline or face criminal
prosecution. Many foreign students simply left, and no one re-
placed them. In :oo,, for example, the number of Indonesians
studying in America plummeted by more than :o percent.
17
Many of the students heading to China for higher degrees, or
Jakarta or Bangkok, already come from ethnic Chinese back-
grounds. On a hazy Saturday in March :ooo, with thick hu-
midity that verged on actual raindrops, I walked through the
major Chinese cemetery in the Philippine capital of Manila,
set on a high point near the city’s Chinatown, a narrow warren
of stores and tiny alleys, where traditional medicine shops
featuring personal feng shui advisers abut Filipino Chinese
gold merchants and street vendors hiding pirated copies of
Brokeback Mountain and other new Hollywood releases inside
their shirts.
From the cemetery hills I could look out onto Manila’s
endless sprawl of poverty, tin-roofed shacks and “jeepneys,”
The Tools of Culture ,I
the main means of public transport for Filipinos—aging Jap-
anese trucks painted with lurid murals of Christ and pictures
of naked women, and carrying crowds of passengers sardined
into their bays. Although many Southeast Asian nations have
prospered over the past five decades, the Philippines has re-
mained a Latin American–esque economy, with a tiny, wealthy
elite and a vast underclass. Fifteen percent of Filipinos earn less
than a dollar per day, and in Manila tens of thousands of poor
people climb through garbage dumps, scavenging through the
trash to survive. Manila residents have grown so desperate that
thirty thousand of them recently stampeded the gate of a real-
ity television show giving away cash prizes, crushing at least
seventy-nine people to death.
18
Inside the cemetery, though, it’s easy to forget about the
filth and stench and chaos outside. Filipino Chinese have con-
structed elaborate, gated, aboveground tombs of marble and
granite and plaster, some as large as a small home. The tombs
sit next to each other in long rows, with small roads leading
through the tomb city. Inventive families have commissioned
pagoda roofs or detailed metal grilles or gargoyles for their
crypts, or constructed vaults that resemble stark modernist ar-
chitecture, all glass and metal and sharp angles. The most elab-
orate structures contain full sets of modern appliances like tel-
evisions and microwaves, presumably so the dead can enjoy
the latest DVD soap operas and prepackaged food in the next
life. Every few minutes, I see a late model Mercedes or Lexus
pull up to one of the tombs and disburse a large Chinese Fil-
ipino family, the boys in sharp suits, the girls carrying packages
of offerings like fruit and fresh flowers for their dead relatives,
the family drivers in sharp livery wear.
The cemetery reminds me that ethnic Chinese minori-
ties, many originally from the coastal provinces of southeast-
,: The Tools of Culture
ern China, where arable land is scarce and population pressure
intense, have long played an important role in the Philip-
pines—and across the developing world. Even before the
Spanish colonists arrived in the Philippines five hundred years
ago, small-scale Chinese merchants were trading with indige-
nous villages across the Philippine archipelago. Some of these
Chinese merchants stayed, building settlements or integrating
themselves with the local population.
19
For centuries, many nations viewed these ethnic Chinese
arrivals as outsiders, even after they had lived in places like the
Philippines for centuries. And after they left China, the im-
perial Chinese government shunned them, too. Before the
nineteenth century, the Chinese imperial government branded
Chinese émigrés as traitors to the nation—traitors to their
homeland and ancestors. The Ming government issued orders
prohibiting Chinese who emigrated from ever returning to the
country. “I believe that the majority of those who go overseas
are undesirable elements,” the Ming emperor announced.
20
In response, ethnic Chinese outside China often formed
close-knit social and business communities, relying upon in-
formal means of raising capital, sometimes agreeing not to
compete with other ethnic Chinese companies, and often keep-
ing company shareholdings limited to family members, even
as their firms grew into giants. That states targeted Chinese
communities during times of turmoil—as in Indonesia in I,o,,
when fears of communist influence from Maoist China re-
sulted in massacres that targeted Indonesian Chinese and killed
at least half a million people—only tightened the bonds among
ethnic Chinese and led them to avoid ties to mainland China
during the Maoist era.
21
Like the Philippines, Thailand boasts a sizable ethnic
Chinese community, comprising Io to I, percent of the total
The Tools of Culture ,,
population—mostly emigrants from Fujian and Guangdong
provinces in southeastern China. During much of the twenti-
eth century, as China descended into economic backwardness
and Mao’s revolutions alienated the Chinese diaspora, the Chi-
nese in Thailand intermarried with Thais, took Thai names,
and became Thai citizens. They came to dominate Thailand’s
economy, with a small number of Thai-Chinese families con-
trolling Thai manufacturing.
22
The Thai Chinese built conglomerates like Charoen
Pokphand (CP), which started from typically humble origins.
A CP founder, Chia Eksaw, came to Bangkok from China in
I,:I with little more than a signboard, a ledger, and some veg-
etable seeds. He put out his sign and established a small seed
shop in the Thai capital. When his fourth son, Dhanin, took
over the business in I,o¡, he expanded it into a larger feed
shop, and then diversified into farm equipment and other
agricultural products. CP built close relations with important
Thai officials and constantly innovated to improve its feed and
chickens and other products. CP grew and expanded across
the region, eventually becoming the biggest agroindustrial
company in Southeast Asia, headquartered in a high-rise over-
looking Bangkok’s central business district and decorated with
landscape paintings of Chinese mountains and rivers. By the
beginning of this millennium, Dhanin alone controlled per-
sonal assets worth more than $I billion.
23
The company also maintained deep links to China, even
during the Maoist period. When other foreign investors pulled
out of China after the Tiananmen crisis, CP stayed in; it
smoothed its China business through unusual favors like find-
ing Thai elephants to provide to a Chinese tourist site. Eventu-
ally, in the I,,os, CP became the largest foreign investor in
,¡ The Tools of Culture
China, though it probably has since been passed by Western
multinationals.
24
As in Thailand and the Philippines, in Indonesia, Ma-
laysia, Cuba, Peru, Singapore, and many other countries, Chi-
nese diaspora businesspeople have enjoyed similar success.
Magazines have estimated the total wealth of the Chinese dias-
pora at more than $I., trillion; in Indonesia the ethnic Chinese
comprise roughly , percent of the population but reportedly
have controlled as much as 8o percent of the nation’s economy.
The ethnic Chinese tycoon Robert Kuok of Malaysia (esti-
mated net worth $, billion) built the Shangri-La Hotels chain;
the ethnic Chinese tycoon Li Ka-Shing of Hong Kong (esti-
mated net worth $I, billion) amassed a property empire; the
ethnic Chinese tycoon Lucio Tan of the Philippines (estimated
net worth $I., billion) constructed brewing and banking gi-
ants; and the ethnic Chinese tycoon Thaksin Shinawatra (esti-
mated net worth $I., billion), who later became prime minis-
ter of Thailand, used political connections to start a computer
business that he then expanded into a telecommunications
and satellite technology empire.
25
Of course, few diaspora Chinese reached this level of suc-
cess. Most arrived in their new countries poor and stuck to
small business or hard labor; many failed. Chinese came to
Panama more than a century ago as low-wage laborers and
concentrated in small-scale retail shops, creating a tight-knit
community that follows news about Asia in local Mandarin-
language newspapers and Cantonese radio stations. Chinese
businesspeople settled in tiny East Timor decades ago, and
today working-class ethnic Chinese merchants traverse the
country on the back of pickup trucks, peddling clothes and
cheap electronics out of burlap bags. Nearly Ioo,ooo Chinese
The Tools of Culture ,,
were shipped to Peru to work as coolies during the nineteenth
century; many stayed on as laborers or small businesspeople.
26
When Deng Xiaoping opened China’s economy in the late
I,,os, he realized that the People’s Republic could draw upon
this Chinese diaspora for capital. Deng and other top officials
called on overseas Chinese to invest in mainland China and
set up Special Economic Zones in places like Shenzhen, near
Hong Kong, and Xiamen, near Taiwan and Southeast Asia,
which were easily accessible to overseas Chinese capital. (Cha-
roen Pokphand received foreign investment certificate oooI in
the Shenzhen Special Economic Zone.) Beijing passed a range
of laws giving diaspora Chinese preferential treatment over
other foreign investors and created more than fifty industrial
zones specifically for Chinese returning from abroad. Provin-
cial governments in places like Fujian added to these incentives
with their own offers of land, industrial parks, and tax breaks
for diaspora returnees.
27
These policies worked. Between I,,o and :oo: foreign
investors—primarily overseas Chinese—invested nearly $,o
billion in Fujian Province alone, almost , percent of all foreign
direct investment in China during that time period. Overall,
between I,,o and :oo: just five countries—Thailand, Ma-
laysia, Singapore, Indonesia, and the Philippines—invested
roughly $,o billion in China, with most of the capital coming
from diaspora Chinese firms. One study estimates that dias-
pora Chinese, including Chinese from Taiwan and Hong Kong,
account for 8o percent of all foreign investment in mainland
China.
28
In the past ten years, the Chinese government has begun
to view ethnic Chinese as more than merely sources of invest-
ment and technology. Diaspora Chinese have become vital to
,o The Tools of Culture
Beijing’s global charm offensive. In recent years, Beijing has re-
built relations with ethnic Chinese organizations around the
globe—groups ranging from cultural associations to clan or-
ganizations to business chambers—and directly called on these
diaspora Chinese to help boost relations between China and
the developing world.
29
Some rebuilding simply involves recognizing diaspora
Chinese groups’ importance, by hosting meetings like the
World Chinese Entrepreneurs Convention or sending impor-
tant PRC ministers to visit ethnic Chinese abroad. According
to Hong Liu of the National University of Singapore, in :ooI
top officials from Beijing’s Overseas Chinese Affairs Office vis-
ited more than twenty countries to hold meetings with leaders
of diaspora Chinese communities. These meetings inspired di-
aspora Chinese to return to China; the number of Thais visit-
ing China, for example, rose by more than oo percent between
I,,, and :oo,, with most of that visitor traffic coming from
ethnic Chinese Thais. China assists with return trips through
programs like government-run summer camps for diaspora
Chinese children entitled “Travel to China to Find your Roots.”
It supports new Chinese history textbooks designed for di-
aspora schools, produced in Hong Kong and emphasizing
China’s history of guochi, or national humiliation, at the hands
of external powers.
30
Some rebuilding involves cultivating leading ethnic Chi-
nese tycoons in each nation, wooing them to publicly support
Beijing. The tycoons’ influence then trickles down into the
larger ethnic Chinese community; in many cases, they can
push the boards of Chinese chambers of commerce to remove
pro-Taiwan members and develop closer ties to Beijing. In the
Philippines, for example, Chinese officials and business dele-
gations have taken care to woo Lucio Tan, not only one of the
The Tools of Culture ,,
country’s wealthiest men but also a major political player who
was close to former President Joseph Estrada. Tan has installed
businessmen close to him at the head of the powerful Filipino-
Chinese Chambers of Commerce, which has promoted better
relations with China.
31
China has utilized this strategy in other countries with
sizable ethnic Chinese communities. In Panama, for example,
a :oo,ooo-strong ethnic Chinese population relies on Chinese-
language schools, which begin the day with a common anthem
and learn from a standard curriculum. Unlike in Chinese
schools in much of the world, this curriculum has an unusual
component—the Panamanian students learn that Taiwan is a
sovereign nation, near-heresy in most countries. Panama re-
mains one of the few states that maintain diplomatic relations
with Taiwan; Taiwan has given some $:oo million to Pana-
manian schools, which are plastered with posters of Taiwanese
tourist attractions.
32
But Panama may not recognize Taiwan much longer. As
China has become wealthier, and more aggressive diplomati-
cally, it has reached out to Panama’s ethnic Chinese. Whereas
Taiwan traditionally brought important Panamanian Chinese
opinion leaders to Taiwan for higher education, now China
does the same. Whereas Taiwan has long sent Panama cultural
entertainment like troupes of Chinese acrobats, now China
does the same. Whereas Taiwan historically holds lavish na-
tional day celebrations in one of the classiest hotels in Panama
City, now Beijing holds lavish national day celebrations—in
the same hotel.
On one trip to Thailand, I found myself in one of the square,
squat new office buildings that make every area of Bangkok
,8 The Tools of Culture
look the same. A secretary escorted my friend and me into the
offices of Amorn Apithanakoon, chairman of Galaxy, one of
Thailand’s biggest entertainment companies, which sells ar-
cade games, karaoke machines, and anything else you need for
a flashy new nightclub in Asia. Amorn sat in one corner of his
massive office, at a small table, next to a Buddhist monk.
Amorn had plastered the walls of his office with photos of
himself alongside Thailand’s royal family and sculptures made
from jade, a symbol of good fortune in Chinese culture. There
was so much jade in his office that it resembled the lair of some
archvillain gem runner from a B spy movie.
33
I sat down next to the monk, dressed in the traditional
saffron robes and sandals. Amorn had laid three cell phones on
the table. The monk and Amorn took turns fondling a new dig-
ital camera. “This man is good,”the monk said to me in English,
pointing at Amorn, a short older man with sleepy eyes, wearing
a finely tailored suit and dirty running shoes. “He’s a good
man.” Just to make sure I understood, he said it again: “Good
man.” Amorn and the monk returned to speaking in Thai
(which I speak), and I learned that the monk previously had
worked as a policeman, until he decided to switch to the clergy.
Amorn apparently had become one of the monk’s personal pa-
trons. After about twenty minutes of chatting with him, Amorn
finally dispatched the monk, who offered a stream of blessings
as Amorn lowered his head. The Galaxy chairman handed the
monk a wad of cash, and the clergyman left the room.
Like many Thai-Chinese businesspeople, Amorn’s family
hailed from southern China. Galaxy had made Amorn rich,
but he wasn’t content with just the company. Amorn had
founded an organization in Bangkok called Uniting Chinese,
which he said was designed to foster interaction among ethnic
The Tools of Culture ,,
Chinese around the world. Despite chatting with Amorn for
over an hour, I could never tell whether he started the organi-
zation himself or whether someone had pushed him to do it. I
did learn that the organization helped promote trips by Thai
Chinese back to China, as well as to conferences in Bangkok
about diaspora Chinese culture.
But the group also had become a kind of proxy weapon
for Beijing. Twenty years ago, a tycoon like Amorn, or a group
like Uniting Chinese, would not have attracted much attention
from the Chinese embassy in town. But now the Chinese em-
bassy in Bangkok was one of the largest and savviest in the en-
tire Chinese foreign service, and Amorn said diplomats at the
embassy had reached out to his organization. They invited him
to informal strategy sessions and had cultivated close links
with Thai-Chinese business associations that tycoons like
Amorn patronized. After our interview, Amorn rushed to a
meeting at the Thai-Chinese Chamber of Commerce with the
Chinese ambassador.
Whether the embassy in Bangkok had an influence on
Amorn or he came to his views all by himself, Uniting Chinese
proved a useful vehicle for Beijing to woo diaspora Chinese.
When the United States and China got into disputes, like dur-
ing the EP-, incident, Amorn would criticize Washington and
lead anti-US demonstrations in Bangkok. “I had to protest, I
felt too strongly,” he said. Amorn’s organization later wrote ar-
ticles in local papers stressing that Taiwan needed to return to
mainland China, and it helped host conventions of diaspora
Chinese in Bangkok. The conventions supposedly promoted
the “peaceful reunification” of China but mostly served as an
excuse to blast Taipei and demonstrate to diaspora Chinese
that anyone who still supports Taiwan has few allies left among
ethnic Chinese anywhere. At one conference, Amorn called the
8o The Tools of Culture
Taiwanese leader “pathetic” and accused him of “wreaking
chaos.” At the end of the conference, which attracted more
than one thousand people, participants issued a “Bangkok
Declaration” that called on all diaspora Chinese to join to
“strongly oppose any attempts by Taiwan authorities to bring
Taiwan to the brink of ‘independence.’”
34
The Tools of Culture 8I
V
The Tools of Business
or a man who could be arrested at any moment, Harry
Roque Jr. seemed remarkably placid when I met him
in March :ooo. Dressed in a white barong tagalog, the
long, delicately embroidered shirt worn untucked by Fil-
ipino men, he welcomed me into his law office in downtown
Manila, a small room crowded with stacks of books on Philip-
pine constitutional law and photos of his family. “Three days
ago, it was broadcast that I had been arrested,” he said. “Every-
one was calling me, but I was still here.” A laugh boomed out
of his jiggling stomach, and his wide, round face broke into a
grin. Still, he said, though the initial report was wrong, “There’s
a short list of people who have been arrested and longer list—
two hundred people—who could be arrested.”
1
Roque’s offense? Just a few weeks earlier, Philippine pres-
ident Gloria Macapagal-Arroyo had declared a state of na-
tional emergency, similar to martial law, citing an alleged coup
plot against her. In coordination with the state of emergency,
she had created lists of people, including many of her political
enemies, supposedly involved in the plot; these targets could
be arrested for rebellion and sedition at any time. The Philippine
police had raided the offices of the Tribune, a newspaper criti-
cal of the government, and had attempted to arrest at least five
opposition congresspeople. The congresspeople holed up in
the Philippines’ legislative building, a situation akin to Barack
Obama and Nancy Pelosi barricading themselves in the Capitol
while George Bush’s Secret Service tried to starve them out.
2
For several years, Roque, a longtime activist and human
rights lawyer, had auditioned for the list, blasting Macapagal-
Arroyo’s administration for nearly every decision it made. Re-
cently, Roque had embarked upon a crusade against a govern-
ment-backed project called Northrail, an attempt to build a
railway from Caloocan to Malolos on the central Philippine is-
land of Luzon. The Philippines initially had signed a contract
with a Spanish firm to build Northrail. But then, according to
Roque and several Filipino politicians, the Philippine govern-
ment junked that contract and agreed to use Chinese firms,
without any public tender; at the same time, the Chinese gov-
ernment offered more than $¡oo million in assistance for the
project, then an additional $,oo million. “Northrail signified a
shift in policy from China,” which used to keep a low profile in
the Philippines, Roque said. “It’s aggressively pushing its aid
and capital and goods. The Philippines already had a contract
with the Spanish company . . . and just jettisoned this. The
speaker of the [Philippines] legislature negotiated directly with
China for the project, and the Department of Justice never
even gave its clearance for the Northrail.” Along with several
other prominent lawyers, Roque had completed a study of the
Northrail project that concluded that it was improperly man-
aged and financed, and would not be contracted out for com-
petitive bidding.
3
Roque thinks that Beijing understood how to make
The Tools of Business 8,
Northrail happen in one of the world’s most contentious and
corrupt democracies.
4
“The Chinese zeroed in on what local
politicians wanted, which is why in the contract there was a ,o
percent up-front payment in the financing,” Roque says. “You
have to wonder, why this up-front payment? Who was this to
benefit?”
Worried that Northrail had been handled so opaquely,
and concerned that a Chinese contractor hired without com-
petitive bidding might have poor standards of transparency
and corporate governance, Roque had filed a case to challenge
the project as unconstitutional, further angering the Philip-
pine government. He soon got his answer. The government
“hired a Philippine public relations firm to neutralize me in
the media,” he said. Now, he feared arrest—for his Northrail
opposition and for his criticism of the emergency law. And
Roque had not succeeded in stopping the project, though he
did stay out of jail. The Philippines’ Supreme Court tossed out
one of his petitions, and even as he and a group of plaintiffs
filed another suit, the Northrail project marched forward.
5
The size of Chinese aid to Northrail also instantly put
Beijing in the same league as other traditional aid donors to
the Philippines, like Japan and the United States.
6
In fact,
Northrail provided a window into how quickly China has de-
veloped its other set of soft power tools, tools of business. In
addition to cultural tools, these levers of power—trade, in-
vestment, aid, and the appeal of China’s economic model—
make up the second potential weapon in China’s arsenal. In-
deed, over the past decade, Beijing has begun to use aid, trade,
investment, and the allure of China’s economic model, which
combines growth with state control, to charm other nations.
China’s tools of business, in fact, have become powerful enough
that even when people like Harry Roque raise concerns about
8¡ The Tools of Business
Chinese aid and investment, their own governments some-
times shut them up.
As with tools of culture, not everything wrought by tools
of business stems from one grand Chinese strategy. In busi-
ness, even more than in culture, Chinese companies may make
decisions based on corporate rather than national interests,
while companies in other nations are not passive actors—they
aggressively seek Chinese investment and aid. Still, the policies
Beijing has designed have helped its tools of business flourish.
Since I,,, the world has witnessed what happens when you
unleash the entrepreneurial activity of more than one billion
people, most of whom will work for the monetary equivalent
of a Starbucks latte per day, and then combine this with the in-
satiable desire of foreign firms to tap this labor and also to sell
products to the world’s biggest market. As the China business
expert Joe Studwell chronicles in his study The China Dream,
the idea of selling to the Middle Kingdom’s vast population
has been a fantasy of Western companies for centuries—in the
nineteenth century, English tailors rhapsodized that if they
“added an inch of material to every Chinaman’s shirt tail,”
Manchester weavers would be flush forever. Today, this dream
often results in multinationals committing to China invest-
ments without adequate due diligence. According to Studwell,
the British brewing giant Bass tried to peddle high-end im-
ported brews to Chinese consumers used to cheap local beer,
and advertised Bass drafts with dancers dressed in kilts, which
only confused most Chinese. Bass lost millions and shuttered
its factories, so angering its local Chinese staff that managers at
Bass facilities wound up needing bodyguards.
7
Despite multinationals’ misadventures in the People’s
Republic, every major company remains convinced that it
The Tools of Business 8,
must have a China strategy, and many years China attracts the
biggest pool of foreign direct investment of any nation, more
than $,oo billion in total since I,,,. The retailing giant Wal-
Mart alone has an inventory of goods in China worth at least
$I8 billion, the size of Bolivia’s gross domestic product. Since
the early I,8os China has posted average annual growth rates
of more than 8 percent—in a great year the United States
would hit , percent—and in the near future probably will con-
tribute more than :, percent of the growth in the global econ-
omy. China runs record trade surpluses, and it is moving into
value-added industries like automobile manufacturing. The
Chinese automobile companies Chery and Geely have begun
shipping cars abroad, probably a trial run for entering the US
market. China boasts a national savings rate of more than ¡o
percent, compared with the American population’s negative
savings rate in :oo,.
8
This part of the China story is well known, the subject of
bookshelves worth of business tomes and reams of studies by
economists examining China’s path to prosperity. Less under-
stood is what happens now. For some nations, fear of China’s
military power has been replaced by fear of China’s economic
power—of markets being swamped by cheap Chinese goods,
companies ruined by China absorbing investment that would
have gone elsewhere, workers laid off by competition from
China’s massive labor force. Beijing apparently has realized
that, like the United States and Japan before it, it also can uti-
lize its economic heft to minimize these concerns, and even to
boost its appeal in foreign nations, if it portrays its growth in
a certain light, and if other countries can benefit from China’s
consumer power.
In pursuing this goal, China has first tried to demonstrate that
as it grows, it also will become a much larger consumer of
8o The Tools of Business
other nations’ goods, creating “win-win” economics, central to
the idea of China’s rising peacefully. This comes from the top:
though Beijing, like most governments, cannot coordinate all
its policies, in :oo¡ the Chinese government organized an in-
ternal conference on “Economic Diplomacy Toward Develop-
ing Countries,” at which officials planned to increase eco-
nomic cooperation with developing nations.
9
To be sure, China cannot yet match American or Japa-
nese or European investment in the developing world, and some
media accounts overhype Chinese outward investment. In Sin-
gapore, one of the most open and business-friendly economies
on earth—and a state that has encouraged mainland Chinese
companies to enter its market—American companies have in-
vested more than $¡o billion. According to the most recent offi-
cial statistics available, Chinese investments in Singapore have
not yet cracked the $I billion barrier.
10
Instead, Beijing pro-
motes the idea that China eventually will become a major source
of outward investment: China’s appeal to the developing world
rests in part on portraying China’s potential as an investor.
Chinese officials often do so by providing trade and in-
vestment and tourism targets. These targets, for five or ten
years in the future, tend to be enormous and to obscure the
fact that, at present, Chinese direct investment into regions
like Southeast Asia and Latin America still lags far behind in-
vestment from the United States and other wealthy countries
like Japan. “While China has not committed much money to
Cambodia, recent high level visits . . . highlight . . . the prom-
ise of more trade and investment,”notes one cable from the US
embassy in Phnom Penh obtained through the Freedom of In-
formation Act.
11
Indeed, when Chinese President Hu Jintao visited Latin
America in :oo¡, he pledged that China would invest $Ioo bil-
lion in Argentina and Brazil. Since overall net foreign invest-
The Tools of Business 8,
ment in Latin America has dropped from $,o billion in :ooo
to $o8 billion in :oo, (partly because of investors going to
China instead) this Chinese investment could be especially
important to the region, and Hu’s pledges dominated the local
media. When Chinese officials visit Africa, they can highlight
some nine hundred Chinese companies invested in the conti-
nent, and promise more of the same; China has created a fund
worth $, billion to encourage Chinese firms to invest in Africa.
When Hu met Philippine President Gloria Macapagal-Arroyo
in :oo,, he promised more than $I.o billion in new Chinese
investment and aid to Manila; in :oo,, when China hosted
Indonesian Minister of Finance Jusuf Anwar, the Chinese an-
nounced that PRC investment in Indonesia could triple within
five years, to as much as $:o billion.
12
China’s outward investment comes partly from a na-
tional policy, not just from Chinese companies seeking profits
overseas. The Chinese government encourages firms to invest
in strategic industries and select countries. In the late I,,os,
and then again during China’s economic Five Year Plan for
:ooI–:oo,, Beijing created a policy of pushing Chinese com-
panies to invest abroad. Chinese leaders called this policy the
“Go Out” or “Go Global” campaign. “To encourage capable
Chinese companies to go out is an important policy of the
Chinese Government,” Vice Premier Wu Yi told the audience
at an international trade fair in :oo¡.
13
During the late I,,os and early :ooos, China’s Ministry
of Foreign Trade and Economic Cooperation selected some
thirty to fifty top Chinese companies to take the lead in over-
seas investment. As they look to invest overseas, these national
champions enjoy a range of benefits that will help them com-
pete, including low-interest funding from Chinese banks—
banks primarily controlled by the government. In :oo¡, for
88 The Tools of Business
example, according to a report by the consulting group Accen-
ture, one of these Chinese banks provided the Chinese tele-
communications giant Huawei with a $Io billion low-cost loan
to help Huawei internationally.
14
Looking to invest abroad seemed natural: as Accenture
noted, China recognized that it “needs to develop its relation-
ship with the global economy beyond a simple export-driven
model. . . . China’s outward investment has a dual purpose of
building China’s political capital and influence around the
world.”
15
Furthermore, Accenture found, because many Chi-
nese companies gained experience in China, a developing na-
tion itself, “their better understanding of emerging markets
provides a stronger guarantee of success in their initial over-
seas expansion plans.” In other words, with their background
in China’s often lawless business climate, Chinese companies
have the experience to invest in Liberia or Cambodia or many
other countries with little rule of law.
As China’s national outward investment strategy has de-
veloped, provincial governments have announced complemen-
tary programs to encourage Chinese companies to venture into
neighboring countries. The national government sweetens the
pot for Chinese companies with soft loans designed to encour-
age Chinese firms to invest in neighbors like Laos, with centers
for trade promotion providing consultation to Chinese enter-
prises investing in Africa and Southeast Asia, with information
programs for officials in countries like Pakistan on how to at-
tract Chinese investment, and with assistance to business del-
egations that accompany Chinese officials’ trips abroad.
16
On these trips, Chinese leaders often bring along large
mainland business delegations to meet with local business-
people and politicians. Developing-world businesspeople thus
can execute deals directly with Chinese political leaders and
The Tools of Business 8,
heads of Chinese companies without worrying about legisla-
tors back in China holding up completion of the deals, as
might happen in the United States or any other democratic na-
tion. “I went to Beijing with Thai officials and met [Vice Pre-
mier] Wu Yi,” says Vikrom Kromadit, CEO of the Amata Cor-
poration, one of the largest companies in Thailand, which
manages industrial estates east of Bangkok. “She asked me
what kind of companies I’d like in my industrial park, and I
told her, and she sent over twenty companies on my list of
[Chinese] companies I wanted to get.”
17
No American or Eu-
ropean politician could so easily direct a business.
Beijing particularly leans on Chinese companies in the
energy industry to invest abroad. Even more than in other sec-
tors, these energy companies, which do have some autonomy,
remain dominated by the state or at least retain close links to
the Chinese government. In interviews with CLSA Asia Pacific
Markets, a leading research company in China, state-owned
resources firms admitted that Beijing had been pushing them
to invest abroad, though they insisted that their own manage-
ment made the final decisions. Furthermore, as the energy an-
alyst Erica Downs notes, Chinese companies making foreign
investments worth more than $,o million require approval
from the National Development and Reform Commission, the
country’s top planning agency. This suggests that the govern-
ment has some significant degree of oversight, even if it is not
planning each purchase by a Chinese company.
18
In the past five years, Chinese firms indeed have em-
barked upon a frantic shopping spree for commodities, buying
up $I, billion in oil and gas fields and companies worldwide,
and often paying above market price. In Venezuela, China Na-
tional Petroleum Corporation (CNPC) has established a joint
venture with Petroleos de Venezuela, the state oil company of
,o The Tools of Business
a nation whose leader prides himself on opposing US foreign
policy; overall, China has invested roughly $: billion in Vene-
zuela. In Peru an arm of China National Petroleum Corpora-
tion has purchased a stake in Pluspetrol, which has oil fields
along the Ecuadorian border. In Sudan, Chinese firms have be-
come the biggest foreign investors in that nation’s oil industry,
plowing in some $¡ billion. In Nigeria, the state-owned Chi-
nese oil giant CNOOC purchased a $:., billion stake in a
major oil and gas field in the Niger Delta. In Iran, China has
signed a deal to develop one of the country’s major gas fields,
putting China in position to become the largest player in a na-
tion with some of the world’s largest gas reserves. In :oo,
CNPC purchased PetroKazakhstan, one of the biggest oil com-
panies in Central Asia. In Burma, PetroChina signed a deal in
:ooo for o., trillion cubic feet of Burmese natural gas.
19
The
list could go on, well into several pages.
Just as it focuses on strategic industries, the Chinese govern-
ment also pushes investment in strategic nations—countries
on China’s borders and in regions with resources. In the gov-
ernment’s Five Year Plan for :ooI–:oo,, Beijing focused on
three strategic regions of the developing world: Latin America,
North Africa, and Central Asia, all of which have extensive oil
and gas. Prodded by Beijing and by provincial governments,
Chinese firms have poured into Cambodia, Burma, Laos,
Thailand, Central Asia, Pakistan, Vietnam, and Pacific Russia.
China has become the largest source of investment in Cambo-
dia and, anecdotally, in Burma, Laos, Pacific Russia, and Ka-
zakhstan. According to official statistics, in :oo, China’s out-
ward investment rose nearly I,ooo percent, though many of
these investments are merely unfulfilled commitments. With-
in a decade, China could become the biggest investor in all the
The Tools of Business ,I
developing nations on its borders, from Mongolia to Vietnam.
“If the goal of Chinese investment has been not so much to
make money as to win the charm offensive, then victory has
already been delivered,” wrote one US diplomat in Asia, in a
cable obtained through the Freedom of Information Act.
20
Western companies competing with these Chinese firms
realize that they cannot match China’s low labor costs or Chi-
nese firms’ willingness to invest in risky places like Sierra
Leone or Burma. Instead, Western companies compete by ad-
vertising their sophisticated technology and their years of ex-
perience operating abroad, but these advantages may be di-
minishing. “In Indonesia, American companies will say, ‘If you
want US technology, you have to go with us,’” explains Walter
Lohman of the US-Asean Business Council, a trade group in
Washington. “But now, for example with telecommunications,
the Chinese are competitive with the technology.”“I was quite
surprised with the Chinese knowledge of oil fields,” agrees Lin
Che Wei, head of PT Danareksa, an Indonesian state bank that
coordinates investments. They seemed as advanced as Exxon-
Mobil, Wei says.
21
Even if China’s technology lags behind that of American
or Japanese or European competitors, some poorer nations
think that Chinese companies will be more willing to share
what they know, and that Chinese firms, with backgrounds in
the developing world, might be better suited for Africa or Latin
America or Southeast Asia. In Nigeria, where the government
chose the Chinese aerospace giant China Great Wall Industry
Corporation to launch a new Nigerian satellite, one foreign
affairs official told the Financial Times: “Being a developing
country, they understand us better. They are also prepared to
put more on the table. For instance, the western world is never
prepared to transfer technology—but the Chinese do.”
22
,: The Tools of Business
While China cannot yet challenge the United States, Eu-
rope, or Japan as a source of outward investment, it already
can match other major powers as a consumer and as a trading
partner. And China’s consumption is focused on the develop-
ing world: while China imports little from the United States
outside of high-technology products, its imports from the de-
veloping world are worth more than seven times its imports
from the United States.
23
As a result, countries from Asia, Latin
America, Africa, and other regions, hardly passive actors, are
scrambling to take advantage of China’s enormous appetites
for resources, industrial components, and other products, to
play China’s growth for all its worth. Many of these nations,
particularly in Africa, saw their economies blossom in the
I,oos and I,,os, another time of high demand for commodi-
ties, demand that waned in the I,8os. Today China’s demand
offers these nations another shot.
By the end of :ooo, in fact, Southeast Asia’s total trade
with China probably will eclipse its trade with the United
States or Japan. In :oo,, for the first time in decades, the econ-
omies of Asia outside Japan were larger than the economy of
Japan, showing China’s increasing importance to the region.
Over time, as American and Japanese consumption of Asia’s
exports continues to decline, China’s consumption will be-
come even more important to the region’s economies, giving
them the potential to benefit enormously from Chinese growth.
Eventually, China will become the center of trade and eco-
nomic integration in Asia, providing Beijing with the goodwill
that accrues from being the economic locomotive, the engine
that lifts millions of people’s incomes.
24
South Korea, an industrialized economy with close links
to the United States, provides a snapshot of the rapid growth
in trade with China. For centuries, China and Korea disputed
The Tools of Business ,,
parts of Northeast Asia, and in the modern era South Korea
normalized trade relations with China only in I,,:. Yet within
a decade China had passed the United States as South Korea’s
biggest export market, and hundreds of thousands of South
Korean businesspeople were heading to China for trade. Boom-
ing trade was a major reason why Seoul developed what some
Koreans called “China fever,” an interest in all things Chinese,
from Korean students flocking to Chinese universities to some
eight thousand South Korean companies investing in China.
25
Those economic links soon had ramifications for Korea’s po-
litical relationships, from Japan to the United States.
Outside Asia, trade with China is skyrocketing as well. In
sub-Saharan Africa, Chinese-African trade grew by more than
:,o percent between :ooI and :oo,, and China has become the
continent’s third-largest trading partner, behind the United
States and France. Chinese exports to Africa, meanwhile, ap-
peal to a wide section of African consumers, because they tend
to be far cheaper than European or American goods. In Latin
America trade with China has grown from only $:oo million
in I,,, to more than $¡o billion. Mines across Latin America
report that they are working twenty-four hours per day just to
keep up with Chinese demand for commodities; companies
are melting down all the scrap metal they can find to ship to
the People’s Republic. China’s trade with Iran has risen from
virtually nothing fifteen years ago to $Io billion annually. In
Central Asia the numbers are even more impressive. To take
one example, Chinese trade with Uzbekistan, a nation with
high barriers to trade, has grown by I,ooo percent in the past
five years.
26
Since most economists project that China’s economy will
continue to expand between , and Io percent per year, Beijing
can continue its rapid growth in trade. China’s trade volume
,¡ The Tools of Business
with Southeast Asia could reach $I.: trillion within a decade.
In Africa trade with China probably will top $Ioo billion
within the decade, putting China within striking distance of
the United States as the continent’s leading trading partner. In
Latin America, China could be the region’s second-largest
trading partner as soon as :oIo.
Sensitive to fears of China’s economic power, Chinese officials
also try to reassure developing nations by signing free trade
deals and making trade concessions—another economic tool
of soft power. Until the past decade, Beijing actively shunned
bilateral trade agreements, but today China has learned from
its mistakes. In fall :ooI, to the surprise of many Southeast
Asian diplomats who had been unsuccessfully pressuring other
countries to consider a trade deal with the region, Chinese
officials suggested creating a free trade zone between China
and ten Southeast Asian nations, which immediately leap-
frogged China over Japan, traditionally the region’s economic
leader. This Chinese–Southeast Asian agreement, signed in
:oo:, will create the largest trade area in the world. “We were
shocked that the Chinese would come up with a deal,” says one
Southeast Asian diplomat. “The Japanese thought they could
just wait and wait to negotiate with us, and they were totally
unprepared for the Chinese move.” Pressing its charm, China
then offered Southeast Asia an “Early Harvest Package,” which
even before the trade agreement comes into effect will reduce
tariffs on some types of Southeast Asian goods—primarily
agricultural products from poor Asian countries.
27
In the wake of the Southeast Asian–Chinese free trade
announcement, Chinese officials apparently recognized the
kind of goodwill they were earning. Since then, China has
started work on at least sixteen other trade agreements with
The Tools of Business ,,
countries from Chile to New Zealand. In all these deals, Beijing
presents itself as committed to free trade without imposing
any conditions on trade partners related to governance, envi-
ronmental issues, or labor rights, a stance that plays well in
many countries. Beijing also may duplicate the Early Harvest
trade concessions in other developing nations. China has
signed a deal similar to Early Harvest with Pakistan and has
promised African nations easier market access and duty-free
privileges for some categories of goods. In the longer run, Bei-
jing promised in a recent white paper, China would attempt to
negotiate a free trade deal with African regional groupings.
28
The United States, Europe, and Japan, by contrast, have
to deal with more powerful and vocal domestic business inter-
ests, countries. As the United States and Vietnam es-
tablished closer trade relations in the I,,os and early :ooos,
twenty-five years after the end of the Vietnam War, Viet-
namese catfish farmers in the Mekong River Delta, who pre-
viously had sold their catches to Vietnamese state firms for
break-even prices, saw an opportunity. Hundreds of catfish
farmers began exporting to the United States, and by :ooI
Vietnamese catfish exports to America reached $,8 million, a
significant sum for the Vietnamese farmers but a small figure
in the $II billion US market for seafood imports. Still, Ameri-
can catfish farmers, who had seen the Vietnamese capture at
least :o percent of the US market, lodged a complaint with
Washington, charging that the Vietnamese were selling fish
,o The Tools of Business
below cost, or dumping. The Vietnamese argued that they
could sell fish cheaply simply because of low labor costs, but
the US Commerce Department disagreed, imposing steep
tariffs on Vietnamese imports.
29
Vietnamese catfish exports to
the United States plummeted.
Backing up its investment promises and its trade, China has
developed a substantial aid program. From almost nothing in
the mid-I,,os, Chinese aid now can compete with American
aid programs in parts of Southeast Asia, Latin America, and
Africa. Chinese aid tends to be opaque; according to several
sources, China determines its aid policies through informal
meetings of its ambassadors in Beijing, where the envoys es-
sentially bargain over the amounts of assistance.
30
A true understanding of Chinese assistance necessitates
looking beyond traditional definitions of aid, as assistance
provided for economic development. A true understanding
must include soft loans given by Chinese banks with the im-
primatur of Beijing, assistance not explicitly targeted for eco-
nomic development but rather for cultural promotion and
language promotion, in-kind swaps like China’s trade of ar-
mored personnel carriers for dried Thai fruits, or concessional
loans given by China’s state-controlled banks.
31
Already, in
fact, China’s Export-Import Bank has become the largest
source of loans to Africa, surpassing the World Bank.
The Export-Import Bank, for instance, claims that it
makes its own decisions on potential loan recipients without
any interference from the central government. But loans made
to state companies like Huawei are not the only indications of
a connection. Ex-Im Bank officials often travel with Chinese
state-linked companies on business delegations accompanying
Chinese officials, and then offer loans for deals favored by Chi-
The Tools of Business ,,
nese officials. As the Export-Import Bank’s own literature ad-
mits, it sees itself not just as a commercial institution. “The de-
velopment of this business has not only proved effective in
boosting the economic and social development of the recipi-
ent countries but has also improved the friendly economic and
trade cooperation between China and other developing coun-
tries,” the bank says in an annual report.
32
In Asia, China’s aid has exploded, rising from roughly
$:oo million in I,,, to more than $I., billion in :oo¡—even
as the United States cut its aid and Japan, historically one of
the world’s biggest aid donors, shrunk its assistance due to a
decadelong downturn in the Japanese economy. By :oo¡, ac-
cording to a comprehensive analysis by Henry Yep of National
Defense University, China’s aid to the Philippines was four
times as large as American aid to the Philippines, China’s aid
to Laos was three times as great as American aid, and China’s
aid to Indonesia was nearly double US aid. In Burma and
Cambodia, Chinese aid vastly outstripped American aid, while
in Central Asia, China now rivals Russia, the United States, and
Japan in aid projects, such as its $ooo million assistance to
Uzbekistan. In Latin America, Beijing’s aid rose from nothing
ten years ago to at least $,oo million in :oo¡. Between the mid-
I,,os and :oo¡, China’s aid to Africa rose from roughly $Ioo
million to $:., billion. Even in the remote Pacific, Chinese aid
has become a major factor, with Prime Minister Wen Jiabao
recently pledging $,,, million in preferential loans to tiny is-
land nations.
33
Still a developing country, China could overplay its hand,
making promises to other nations that it cannot fulfill. China’s
diplomatic style of signing many agreements during foreign
visits by its top leaders earns it considerable initial goodwill
and positive media coverage. But often the agreements are
,8 The Tools of Business
merely letters of intent. In Latin America and Asia, when offi-
cials from local boards of trade and investment follow up, they
sometimes find that Chinese officials had laid no groundwork
to put these letters into practice. Indeed, after Chinese leaders
make promises of new aid during visits overseas, Beijing some-
times fails to follow through with the cash. Paul Marks, a
China specialist at West Point, has spent years reading Cam-
bodia’s Chinese-language newspapers. The papers are full of
stories hinting that Beijing, or provincial governments, or pri-
vate groups in China, had made offers of aid to Cambodia that
never came through—new schools that had not received their
funding from Chinese sources, unpaid scholarships, Cambo-
dian students who desperately wanted to study Chinese but
had not gotten the money to do so.
34
But while China’s aid overall still does not always match
that of other major powers, and while Beijing sometimes over-
promises, it tries to make the most of the goodwill it receives
from its funds, an approach Chinese scholars call the “maxi-
mini” strategy, of getting the maximum return from the min-
imum outlay. After the Asian tsunami hit in December :oo¡,
China eventually offered $,, million in assistance, one of its
biggest-ever pledges of humanitarian aid, but still far less than
Japan’s assistance or US aid, which approached $I billion. But
because China is a new donor, Beijing seemed to win almost as
much media coverage in Asia for its tsunami relief as did the
United States and Japan. This has become a trend: China gen-
erates goodwill from its assistance partly because countries
have become used to receiving money from Japan and Amer-
ica for decades, and China is a new donor. And China uses its
aid for high-profile projects, like a new parliament building in
Cambodia. “Providing a modern replacement for the current
run-down headquarters of the Cambodian government will
The Tools of Business ,,
remind many in the Cambodian leadership who takes care of
them,” admits one US diplomat in an unclassified cable.
35
The streets of Maputo, capital of the former Portuguese colony
of Mozambique, look little different from those of many other
sub-Saharan African cities. Open sewers overflow with rotting
fruit, beggars and police harass pedestrians for money, and
young mothers wander the streets in dirty rags carrying chil-
dren on their backs. Yet Maputo also seems hopeful. After de-
cades of brutal civil war, Mozambique has enjoyed peace since
the early I,,os, and has built a nascent, if fragile, democracy.
Taking advantage of the peace, Mozambicans have recon-
structed the shattered economy of their capital. Young entre-
preneurs in Maputo clinch deals over thimble-sized cups of
coffee in the city’s new cafés and plates of fresh grilled fish in
the waterfront restaurants and bars lining the capital’s wide
public squares. The business district even has sprouted a small
skyline of office towers.
In February :oo, I arrived in Mozambique. Walking amid
the pink and green Mediterranean-style buildings of Maputo’s
oceanfront, signs of its Portuguese colonial heritage, I noticed
one structure that stood out—an enormous, blocky building
with an Asian pagoda roof nothing like the surrounding ar-
chitecture. It was the Ministry of Foreign Affairs—built with
Chinese aid, which is why it wound up looking like a giant slab
of concrete topped with a pagoda.
In recent years China has become a major donor to
Mozambique, not only constructing buildings, which China
has been doing abroad since the I,oos, but also offering many
other types of aid. Beijing has paid for an investment and
trade-promotion center in Maputo, offered the country debt
reduction, and promised significant other economic assis-
Ioo The Tools of Business
tance, like more than $: billion offered in May :ooo by China’s
Export-Import Bank to help Mozambique rebuild its power
infrastructure, ruined by the long civil war.
36
Perhaps unsur-
prisingly, Mozambique now regards China as one of its most
important allies outside of Africa.
Maputo shows how China’s aid has not only grown
but also become more sophisticated. In the past, many
scholars associated China’s aid with giant white-elephant
projects, like large buildings and ministries and similar struc-
tures. Since the late I,,os, though, Beijing has developed
comprehensive aid programs beyond funding buildings, so
that projects like Maputo’s Ministry of Foreign Affairs come
along with other initiatives, like debt reduction and economic
assistance and training programs for professionals from the
developing world. In fact, Beijing will train some ten thou-
sand African professionals annually; China already trains
some three thousand professionals from the developing world
each year, in programs organized by the Chinese Ministry of
Commerce.
37
As in Mozambique, around the world China also has
more closely linked assistance to discrete policy goals, includ-
ing mitigating concerns about China’s economic rise, develop-
ing poorer parts of China, and increasing China’s influence in
places where other major powers, like the United States and
Japan, seem to be losing influence. In Mozambique this means
funding the trade-promotion center, which could help Chi-
nese companies investing in Maputo. In Thailand it means
Beijing using its aid to purchase surplus Thai agriculture, a
way of conciliating Thai farmers worried about the impact of
a looming Asean-China free trade agreement. Along the Me-
kong River in Southeast Asia, it means major new road-devel-
opment projects that will link Southeast Asia to Yunnan, an
The Tools of Business IoI
impoverished province of southwestern China central to the
Chinese government plan to boost the economies of western
China.
38
This aid helps Chinese companies, too—the roads will
open routes to ocean ports for Yunnanese farmers and traders.
Around the world, when Beijing scouts potential new infra-
structure projects, this infrastructure construction winds up
benefiting Chinese construction companies. Work on a $I.8
billion dam in Merowe, Sudan, for example, backed by export
credits from China Export-Import Bank, will be farmed out to
Chinese firms. Chinese companies can rely upon low-interest
loans from Chinese banks and can bring cheap Chinese labor
to implement the projects.
39
In fact, Chinese aid also often comes tied to commit-
ments to provide contracts to Chinese construction firms—a
strategy similar to unpopular Japanese assistance programs in
the past. In Angola, for example, ,o percent of Chinese-funded
projects were reserved for Chinese companies.
China also has used its aid to cultivate important politi-
cal actors. Beijing is building an informal kind of visitor pro-
gram, creating opportunities for opinion leaders from the de-
veloping world to be wooed in China, including potential
future heads of state like Cuba’s Raúl Castro or young Viet-
namese and Thai officials. Opinion leaders are brought to
China for conferences, trips to study China’s economic model,
and contact with the Communist Party, which has aggressively
built contacts with parties in the developing world—by :oo,,
the Chinese Communist Party had established official rela-
tions with thirty-nine political parties in Southeast Asia alone.
In Cambodia, where Chinese aid will build a new prime min-
ister’s office and the Beijing Diplomacy Institute trains Cam-
bodian officials from the ministries of tourism, foreign affairs,
Io: The Tools of Business
industry, and agriculture, several politicians say that the Chi-
nese government also has directly provided funds to parties
like the ruling party and its coalition partner.
40
Some visitor programs may look little different from the
kind of junketing for which Congress has long been notorious.
“I look around the Parliament, and I see everyone I know tak-
ing trips to China,” says the prominent Thai senator Kraisak
Choonhavan. “If you’re a Thai MP, it’s the easiest thing in the
world to get a trip to China for conferences or other events.”
41
In Laos, where Chinese aid built the capital’s main drag
and funded hospitals in Luang Prabang, the second city, Chi-
nese junkets have proven even more popular. Some impover-
ished Lao officials—most take second jobs to supplement their
meager government wages—receive sizable per diems when
they travel to China for trainings on governance, environ-
mental policies, counternarcotics strategy, and other issues, or
when they attend China-sponsored seminars in Vientiane.
42
“Now our staff go to China as much as they can,” says a top
official in Laos’s foreign ministry. “We have no money, and this
is the only training we can get.” Before I leave his office, he
touches my arm and asks, “Do you think you have any books
you could ship us?”
As China has become an international investor and world
trader, the Chinese government has not only lifted restrictions
on migration within China but also made it vastly easier for
Chinese to leave the country for business and tourism. As Bei-
jing relaxes immigration restrictions and encourages outward
investment, Chinese businesspeople, traders, and workers leave
China en masse. The fact that China has begun to protect some
of its nationals abroad—in April :ooo, the Chinese govern-
ment airlifted more than three hundred people who had been
The Tools of Business Io,
attacked by rioters in the Solomon Islands, a Pacific nation,
during a wave of anti-Chinese violence—also encourages Chi-
nese businesspeople and laborers to feel comfortable moving
abroad. One study of Chinese workers in Africa found that the
number of Chinese registered in Sudan had tripled since the
late I,,os, to roughly :¡,ooo in :oo¡, and the trade organiza-
tion of Chinese labor contractors believes that the number of
Chinese workers heading abroad is rising by nearly :o percent
per year; some will overstay their visa and never come home.
Barry Sautman of Hong Kong University of Science and Tech-
nology found that one database of Chinese in Africa showed
I,,,ooo Chinese residents on the continent in :oo:, a number
he believes out of date and vastly understated. In Nigeria
alone, for example, Sautman found only :,ooo Chinese resi-
dents in :ooI, but he estimated that some ,o,ooo Chinese had
migrated to Nigeria by :oo,, and that South Africa had as
many as ,oo,ooo Chinese migrants.
43
Since many of the Chi-
nese migrants live more modestly than Western expatriates,
they tend to earn the respect of local Africans—though in the
long run, if the Chinese traders replace African businesses they
may create resentment.
Asia has witnessed the largest number of Chinese mi-
grants. In Thailand I:o,ooo Chinese migrants who entered the
country in :oo, reportedly did not return home. In Cambodia,
China has become the number one source of visitor arrivals,
but Cambodia does not rank highly on Chinese tourists’ itin-
eraries, suggesting that most of these visitors are business-
people, including many who do not return home.
44
These new migrants are transforming the demographic
makeup of China’s border regions, like northern Southeast
Asia, a wide swath of land from northern Burma to northern
Vietnam. In these porous border areas, recent migrants from
Io¡ The Tools of Business
China now dominate towns like Mandalay in Burma or Chi-
ang Saen in northern Thailand or Luang Namtha in northern
Laos. At a new glass-and-steel mall in Mandalay featuring al-
most exclusively Chinese products, Chinese teenage girls wan-
der the floors in small groups. Outside the mall, wives of Chi-
nese businessmen have opened hair salons, Chinese-style
coffee shops, and stands selling fashion accessories; in one cof-
fee shop, Burmese boys study Chinese-language books. The
girls are part of the wave of :oo,ooo Chinese tourists and mi-
grants who have come to Burma in recent years, mostly
businesspeople from southwestern China and their families,
along with laborers in town to work on infrastructure projects
outside Mandalay funded by Chinese assistance. China’s influ-
ence has become so prevalent in Mandalay, in fact, that locals
call the town a “Chinese city,” and some quietly resent the pos-
sibility that Chinese migrants dominate business in town.
Similarly, around Luang Namtha, recent migrants now
run local markets and establish large agricultural estates, since
Laos offers the kind of open land that is becoming almost im-
possible to find in China. “The Lao government is concerned
about the Chinese influence in northern Laos, and they’ll try
to get people to go back to China,” says one Western diplomat
in Vientiane, Laos’s capital. “But they don’t have the resources
to look for people.” As a cable from the US embassy in Vien-
tiane admitted, “the expanding Chinese presence in northern
Laos . . . is nothing short of an economic offensive.”
45
This new migration of Chinese traders and laborers has
had another effect. It has created a zone on China’s borders in
which Chinese currency is traded freely, despite the fact that it
is not officially convertible. In Burma, Mongolia, Laos, Cam-
bodia, and Vietnam, businesspeople use the renminbi as a de
facto reserve currency, sometimes instead of the US dollar.
46
In
The Tools of Business Io,
northern Laos, migrant Chinese truckers and laborers now
stop at the makeshift new bars and nightclubs lining the road-
ways, often just wooden shacks with tin roofs and signs in Chi-
nese characters—though they all take renminbi. Inside, Lao
and Chinese girls stand packed into one corner of the bars
until the men pick them out, negotiate a price, and take them
to grubby local short-time hotels or trailers for quick sex.
The lifting of restrictions on tourism from China also
has allowed more Chinese to take their first vacations overseas.
According to the World Tourism Organization, some Ioo mil-
lion Chinese will be traveling abroad by :o:o, making China
eventually the world’s largest source of tourists. Today, South-
east Asia is the destination of choice for one-third of all out-
bound Chinese tourists. It will soon become the most impor-
tant tourism market for Thailand, Singapore, Vietnam, and
other Asian nations, and even more important in an era of ter-
rorism, when Americans have grown increasingly fearful of
travel abroad. Thailand alone hopes to receive four million
Chinese tourists per year by the end of the decade.
47
Many first-time mainland Chinese tourists, like the Jap-
anese and Taiwanese before them, travel on short group tours.
But as China becomes richer, average Chinese are breaking
away from these group tours. They are traveling on their own
on extended trips, spending like people from developed na-
tions, and impressing citizens of host countries with their
wealth and sophistication and taste. “The Billion Boomer
generation—young, career-driven [Chinese] consumers—are
spreading their wings,” notes a report on Chinese tourism by
the research group CLSA Asia Pacific Markets. “Luxury goods
and cosmetics are the most sought after items” by these rich
Chinese tourists, CLSA notes. In Hong Kong, mainland Chi-
nese travelers now spend more per day than their Japanese
Ioo The Tools of Business
counterparts; in Thailand, Chinese travelers already stay for as
many days as Japanese tourists. Even in Paris, boutiques have
added Mandarin-speaking staff to their coterie of English and
Japanese assistants.
48
The new migrants flocking out of China, the growth of Chi-
nese business, the interest in studying Chinese, the Chinese aid
projects, the influx of modern Chinese urban culture—in
some places, like Mandalay, Burma, all these elements of soft
power are coming together. China’s soft power indeed has
proven successful in many cities like Mandalay, allowing China
in some cases to supplant the United States as the major exter-
nal cultural and economic influence. But whether China can
continue to enjoy this success without fostering more resent-
ment in Burma—and elsewhere—is a far different question.
The Tools of Business Io,
VI
Mr. Popular
riving through the streets of Dili, the waterfront
capital of the new nation of East Timor, I passed
building after building littered with burned de-
bris. The coastal road outside of Dili resembled an
Iberian resort, with rose-and-white homes overlooking beach
soccer games and waterfront palms, and Portuguese dance
music blaring from car speakers. But the music concealed ob-
vious pain. Rows of house frames lined the tarmac, mere skele-
tons of former dwellings, some still bearing char marks. For
centuries, East Timor had been a sleepy outpost of Portugal’s
empire, and even when the Dutch surrendered the rest of the
surrounding archipelago to create independent Indonesia, Lis-
bon maintained control of East Timor. But in I,,,, after Por-
tugal granted East Timor its independence, Indonesia imme-
diately invaded the territory (with the tacit consent of the
United States and Australia), launching one of the most brutal
occupations in history before Jakarta allowed a referendum in
I,,,. After East Timor voted for independence in that referen-
dum, the Indonesian military delivered a final blow, burning
down much of East Timor, a swath of violence that forced
more than ¡oo,ooo people from their homes, most of which
were destroyed.
1
During the Indonesian period, thousands of East Timor-
ese fled into exile or escaped into Timor’s mountains to wage
a guerrilla battle against Jakarta’s troops for an independent
and democratic nation of their own. Their quixotic battle at-
tracted global attention, partly because of Timor’s tiny size—
its entire population was less than I., million people, yet it was
battling giant Indonesia, with the world’s fourth-largest popu-
lation.
2
Honoring their struggle, in I,,o the Nobel committee
awarded the Peace Prize to the Timorese leaders José Ramos
Horta and Bishop Carlos Filipe Ximenes Belo.
When East Timor became an independent nation in :oo:,
after three years of UN administration, these former exiles and
guerrillas became the leaders of their new country. In his bare,
windowless office inside the East Timorese government com-
plex—an Iberian-looking structure with a white frontage and
long, shuttered windows—I met João de Câmara, director of
the government division for multilateral affairs. When In-
donesia invaded East Timor in I,,,, de Câmara had fled into
the hills to serve in the guerrilla resistance. Arrested four years
later, he wound up in Jakarta, where the Indonesian govern-
ment released him so that he could study law. “But then I was
arrested in law school, and put back in jail,” he says. “I was
there in jail with Xanana Gusmão,” the leader of the Timorese
guerrillas. All told, de Câmara spent nearly two decades in
Jakarta, either in jail or closely monitored by the Indonesian
security forces.
3
Where did fighters for freedom like de Câmara turn
once they controlled their own destiny? To China. After Timor
voted for independence in the I,,, referendum and was put
Mr. Popular Io,
on the path to nationhood under UN trusteeship, Chinese
officials quickly cultivated the Timorese who would be leading
the new country; some left-leaning Timorese had ties to China
going back to the I,,os. Although in the past China had op-
posed virtually any UN-led intervention abroad, now Beijing
deployed police as part of the UN mission to reconstruct East
Timor. Beijing heavily advertised its peacekeeping, though its
actual troop commitment to Timor paled next to those of
other countries.
4
China became one of the major donors in Dili, though
Beijing does not actively coordinate its efforts with other
major aid givers like Australia and the United States. Besides
funding the construction of East Timor’s foreign ministry,
China paid for the Timor government to open a new embassy
in Beijing and sponsored trainings for the biggest party in
Timor. Meanwhile, a wave of Chinese migrants from the main-
land have arrived in Dili, some encouraged by Chinese gov-
ernment policies that offer minimal assistance to come to
Timor, others persuaded by word of mouth that Timor could
be a business opportunity.
5
China’s ambassadors in Dili, Portuguese speakers able to
communicate with Timor’s Portuguese-speaking leadership,
became some of the most active diplomats. More important,
the savvy Timorese leadership saw in Beijing an opportunity to
use China for its own ends, allowing Timor to avoid becoming
dependent on either of its two giant neighbors, Indonesia or
Australia. With their Portuguese skills, Chinese diplomats
gained close access to Mari Alkatiri, independent Timor’s first
prime minister, who had spent the Indonesian years in exile in
Portuguese-speaking Angola and Mozambique. Chinese offi-
cials could deliver an appealing message, emphasizing both na-
tions’ history of socialism—many Timorese leaders had begun
IIo Mr. Popular
their guerrilla careers as Marxists. China’s domestic economic
success helped as well, as did a vow never to bully small nations
like East Timor.
6
Rewarding China’s diligence (and acting on Timor’s need
to find a friend outside Australia and Indonesia), Dili quickly
established diplomatic relations with Beijing—in fact, China
was the first country with which independent Timor estab-
lished diplomatic relations. Foreign Minister Ramos Horta an-
nounced that China would be Timor’s “closest possible ally,”
though Ramos Horta later said he had meant only that China
and Timor should develop the closest possible relationship.
Since then, the Timorese government has given Chinese com-
panies permission to conduct seismic studies in Timor, put-
ting these firms in position to play a role in extracting the
resources of the oil- and gas-rich Timor Sea, which divides
Timor and Australia, and which contains deposits that may be
worth more than $,o billion.
7
Though some former independence fighters seem con-
cerned about Timor cozying up to China, Beijing appeared
genuinely popular in Dili among average Timorese. Across the
half-island, people praised China’s influence, and many young
Timorese tried to find ways to study Chinese in private classes.
Educated middle-class Timorese who knew anything about
the PRC knew that China had once been poor, like Timor, but
somehow had become fabulously wealthy.
In East Timor, China’s charm offensive is beginning to show
results. Beijing has used a blend of pragmatic diplomacy, in-
creased aid, and an implicit comparison between China and
other major powers to woo elites and average people. Timor,
like many countries, has seen China rising and has decided
that it must make the most of this opportunity. But is China’s
Mr. Popular III
charm working in other parts of the globe? Is Beijing truly be-
coming more popular, more of a model, more persuasive,
more appealing? Have other nations resolved to make the most
of China’s newfound assertiveness?
Having traced China’s goals for its influence, its strategies
for building influence, and the tools it uses to cultivate that
charm, it is possible to judge how successful Beijing has been
in wooing the world. The clearest type of evidence is explicit
evidence—evidence that directly demonstrates whether China’s
charm offensive is gaining ground.
Polls and opinion surveys offer one explicit measure of
China’s success. In :oo, the US embassy in Bangkok commis-
sioned a study of Thai perceptions of other nations. This poll
revealed that a majority of Thais believed that China would
soon become their most important external influence and clos-
est economic partner–a “development that few [Thais] perceive
in threatening terms,” the study reported. (Seven years ago, the
study found, only I: percent of Thais thought that China would
wield the most influence in East Asia.) Eighty-three percent of
Thais polled had a favorable opinion of China.
8
Other studies concur. The comprehensive :oo, BBC poll
of twenty-two nations, including developing countries like the
Philippines, found that ¡8 percent of people thought China’s
role in the world was mainly positive. Thirty percent saw
China’s role as negative. “It is quite remarkable that, with its
growing economic power, China is viewed as so benign, espe-
cially by its Asian neighbors that it could threaten or seek to
dominate,” noted Steven Kull, director of the organization that
conducted the poll for the BBC. A follow-up poll released in
February :ooo revealed positive public opinion toward China
and deteriorating public opinion toward the United States in
II: Mr. Popular
important developing nations, from Indonesia (oo percent
positive for China) to Nigeria (o8 percent positive) to Kenya
(,, percent). Another study just of Latin America found that
there was “ample support in Latin American public opinion,
Argentina and Mexico partially excepted, for China’s new role
in world affairs.”
9
Anecdotal research suggests the same, though polls and
anecdotes are not conclusive evidence, and need to be consid-
ered warily. In interviews with opinion leaders across Asia out-
side of Japan, I have found far less concern about China’s
growing influence than I heard during the late I,,os. Of course,
this is partly because many Asians realize that China is grow-
ing powerful and that they cannot ignore China’s influence. It
is easy, however, to stumble across people furious over Ameri-
can policy, like the elderly Indonesian businessman who grilled
me for thirty minutes about why America had allowed him to
come lecture to business groups in the United States but
barred his wife, a seventy-something woman, from accompa-
nying him on the trip.
10
Eventually, China’s warm image may recede. One reason
why the United States evokes such negative feelings in some
countries is that many foreigners now feel they know the
United States intimately. In places like Latin America, coun-
tries have two hundreds years of experience with the United
States acting like a great power; even in Asia the United States
has projected its power at least since the Second World War.
Leaders and average citizens know America well, and in places
like Latin America, some have come to associate the United
States with interventions that backfired, causing economic and
political misery. The fact that the international media focus on
the United States further exposes America’s faults to the world,
Mr. Popular II,
like the Hurricane Katrina debacle or the controversy over the
:ooo presidential election. “The image of the United States as
a promised land—distant, exotic, and glamorous—has faded
in the onslaught of familiarity with U.S. products, the media-
portrayed image of America, and the vast numbers of people
who have traveled there,” notes a leading US business journal.
And as American culture becomes so ubiquitous overseas, its
exoticism and the excitement it inspires diminish, thereby
undermining the glamour of the United States as a model
of affluence and innovation. In post–World War II Europe,
writes the German scholar Josef Joffe, “save for the tourists and
soldiers, America was not a reality but a distant myth, as por-
trayed in soft brushstrokes on TV by series like Lassie and Fa-
ther Knows Best.” Today, Joffe notes, “the entire world watches,
wears, drinks, eats, listens, and dances American.”
11
By contrast, for countries outside of Asia, China remains
something of a blank slate. After I,,, China retreated from the
world and did not attempt to exert power across the globe, so
a generation of African and Latin American policy makers had
little experience with a powerful China. Though the interna-
tional media cover China, it does not attract the kind of close
attention that the United States draws. As a result, some opin-
ion leaders can believe that China, unlike other major powers,
will impose no conditions on other countries or pressure other
nations to do what Beijing wants. They can believe that China’s
rise will truly be an uncomplicated “win-win,” an opportunity
but not a threat.
That honeymoon period will end. As China becomes
more powerful, the world media will focus more intensely on
the People’s Republic. Some of China’s own dirty laundry, like
rising socioeconomic inequality or Beijing’s crackdown on
II¡ Mr. Popular
Muslims in the western province of Xinjiang, will be beamed
around the world. And as China becomes more powerful,
other nations also will begin to see beyond its benign face to a
more complicated, and sometimes negative, reality. Already, in
one example, the South Korean media have highlighted state-
ments by Chinese academics that seem to suggest that parts of
ancient Korean kingdoms were actually not independent but
rather subordinate to Chinese dynasties.
12
Still, for now China is enjoying the honeymoon. China
has gained popularity even in countries whose recent relations
with Beijing had proved disastrous. In Cambodia the Maoist
Khmer Rouge regime killed as many as two million Cambodi-
ans between I,,, and I,,,. In one part of Phnom Penh, the
Khmer Rouge turned Tuol Sleng, an old high school, into a
laboratory of humankind’s worst impulses, chaining prisoners
to beds to stretch their limbs, applying shocks to their genitals,
burning them with hot metal rods, or hanging them from
hooks in the ceilings. (Signs posted at Tuol Sleng informed
prisoners not to scream or commit other breaches of deco-
rum.) China served as the Khmer Rouge’s major foreign pa-
tron, sending it more than fifteen thousand military advisers.
Beijing knew what was going on: former Chinese Vice Premier
Geng Biao admitted that he suspected the Khmer Rouge was
persecuting its opponents and putting them to death.
13
In the decade after the fall of the Khmer Rouge, Cambo-
dia had no relations with China, and even when the two na-
tions restored ties, the relationship remained cool for a time.
Cables obtained through the Freedom of Information Act
from the US embassy in Phnom Penh suggest that China also
pressured the Cambodian government not to create a tribunal
to try former Khmer Rouge leaders. But today, opinion leaders
Mr. Popular II,
across Cambodia look to China as a partner and model of de-
velopment.
14
China’s appeal is reflected in another explicit sign of success.
Chinese-language and -cultural studies have skyrocketed in
popularity in the developing world, as average people come to
see learning Chinese as vital to business and as providing a
kind of popular cachet, the way English long has. In Argentina,
the number of people studying Chinese reportedly tripled in
:oo,, and the new Mandarin program at the University of
Buenos Aires enrolled more than a thousand students in just
two years of operation. In Malaysia average daily readership of
Sin Chew Daily, the largest Chinese-language newspaper, grew
from 8¡,,ooo in I,,, to I.I million in :oo¡, despite a global
downturn in newspaper reading. Financial analysts believe Sin
Chew’s readership will continue to expand as more Malaysians
study Chinese and become interested in news about China.
Thailand has announced that every public school in the coun-
try should teach Mandarin, attendance at Laos’s main Chinese-
language school has more than doubled in the past five years,
the demand for Chinese in Indonesia has become so great that
the country faces a shortage of some Ioo,ooo Chinese-language
instructors, and in Cambodia one Chinese-language elemen-
tary school alone boasts more than Io,ooo students.
15
Though not a developing country, South Korea also
reflects this trend. For centuries, Korea has enjoyed close links
to China. Though history can divide the two nations, espe-
cially in debates over which parts of modern-day Korea and
China historically belonged to each country, the shared her-
itage also unites them. As China has become South Korea’s
biggest trading partner, and growing numbers of Koreans visit
China for holiday or business, private Chinese-language schools
IIo Mr. Popular
have blossomed in Seoul and other cities. Some Ioo,ooo South
Korean high school and university students now study Chinese,
roughly oo percent more than studied the language five years
ago, and Chinese-language books and films sell well in Seoul,
even as Korean soap operas and movies are hits in China. Chi-
nese has begun to challenge English as the second language of
choice in South Korean cities. Indeed, as the number of people
studying Chinese grows, more Chinese companies expand
abroad, and Chinese becomes the language most used on the In-
ternet, Chinese may become a global second language, the way
English is now—the language people want to learn after they
master their own tongue. South Korea now sends more than
I,,ooo students per year to China, a figure equal to the total
number of Koreans who studied in the United States between
I,,, and I,,,, the height of US–South Korean relations.
16
Some elite Chinese universities have begun to challenge
Western schools as destinations of choice for higher educa-
tion, especially as China’s provision of university scholarships
has begun to be noticed in developing countries. Between :oo:
and :oo¡ the number of Cambodian students in China grew
by nearly :o percent, the number of Indonesians rose nearly ,o
percent, and the number of Vietnamese rose nearly ,o per-
cent—even though the Vietnamese government, still suspi-
cious of historic enemy China, has restrictions on the study of
Chinese in Vietnam. Overall, the number of Southeast Asians
who obtained visas to study in China nearly doubled between
:oo: and :oo¡, and more than I,ooo African students now
study at Chinese universities, many on Chinese government
scholarships. “For a few years ahead, it will still be the United
States as number one, but soon it will be China,” one Thai stu-
dent told the New York Times, explaining why he chose to
study Chinese rather than English.
17
Mr. Popular II,
In total, the number of foreign students enrolling in
China has been increasing by :o percent per year. By :oo8, the
Chinese Ministry of Education estimates, China’s universities
will enroll more than I:o,ooo foreign students, compared with
some 8,ooo twenty years ago. Some of these foreign students
come from government backgrounds, as other countries en-
courage their diplomats and officials to learn Chinese. Singa-
pore, for example, has launched a government effort to send as
many top students on scholarships to China as to the United
States. “As the Singapore government bolsters the number of
scholarships to go to China for its brightest minds, it’s going
to become more prestigious for Ministry of Foreign Affairs
people to have studied in China,” says Eric Teo Chu Cheow, a
former Singaporean diplomat. “Singapore will develop a cadre
of diplomats with ties to China, just like we already have ones
close to the US.” Singapore proved visionary. In :oo, China
trained nearly I,,oo people from Io, countries, primarily gov-
ernment bureaucrats and officials, in public management and
technology.
18
Desire for learning the Chinese language often sparks a
greater interest in Chinese culture. “Chinese culture belongs
not only to the Chinese but also to the whole world,” Hu Jin-
tao announced in :oo,—revealing a conviction that other
countries desire his culture, just as American leaders have al-
ways evinced. “It looks like being Chinese is cool,” the pub-
lisher Kitti Jinsiriwanich told the Wall Street Journal, explain-
ing his decision to produce a glossy new magazine about
ethnic Chinese life in Bangkok and ethnic Chinese pop stars
and rappers. His magazine had proven so popular, in fact, that
high-rent advertisers like Nokia had tracked him down in his
tiny office to hawk their wares. In other developing nations,
publishers are launching similar efforts, which portray a glam-
II8 Mr. Popular
orous Chinese lifestyle similar to what you might see in Vanity
Fair’s depictions of the United States—a far cry from the drab
peasant clothes of the Maoist era, or even from the wrenching
poverty of rural China today.
19
Meanwhile, interviews with artists across Southeast Asia
suggest that many would be as interested today in training in
China as in Japan or Europe or the United States, though they
recognize that the Chinese government still imposes serious
limits on artistic freedom. China has developed an art scene
centered in places like Dashanzi, an art-oriented area of east-
ern Beijing where painters have gutted Maoist-era military
equipment factories to put galleries and cafes inside the build-
ings’ shells. A surprising recent report by UNESCO, the United
Nations Educational, Scientific, and Cultural Organization,
revealed that China has become the world’s second-largest ex-
porter of visual arts. China’s scene is beginning to be recog-
nized by collectors—the Beijing Art Fair now attracts nearly
one hundred galleries from around the world, and one collec-
tor recently paid nearly $I million at a Sotheby’s auction for a
painting by the Chinese contemporary artist Zhang Xiaogang,
a high-water mark for modern Chinese art.
20
Not content to
let Sotheby’s control the market, Christie’s has tried to muscle
into contemporary Chinese painting, holding its first-ever
auction of modern Chinese art in :oo,.
As mainland China has developed an impressive literary
scene, meanwhile, translators have been buying up Chinese
works. In Vietnam, despite long-standing tensions with China,
the Ministry of Culture’s Publishing Department reports that
novels by Chinese writers account for roughly half of all the
foreign literary books translated in the country. Chinese-lan-
guage television, music, and film are gaining wider audiences,
too. Chinese-themed films have been sweeping cinemas in
Mr. Popular II,
Southeast Asia, so much so that the Philippines holds its own
Chinese film festival. Chinese-themed films have won top
prizes at the Manila Film Festival and attracted the interest of
Hollywood studios, which are searching for joint-venture op-
portunities in China. Several Chinese movies have even begun
to make waves internationally, like Sanxia Haoren, or Still Life,
which won the Golden Lion for best film at the Venice Inter-
national Film Festival in :ooo. And across Asia, Chinese televi-
sion serials have staked out viewerships alongside longer-es-
tablished Korean and Hong Kong soaps, while Chinese pop
singers, classical music stars, and film actors have become
major figures in South Korea, part of a first wave of Chinese
stars abroad—even as Korean stars, too, have become popular
across Asia.
21
In some developing nations, meanwhile, the print and
broadcast media have become decidedly more positive toward
China. In Thailand an analysis of elite English and vernacular
media suggests that a decade ago many publications voiced
concerns about China’s economic power, human rights abuses,
and designs on regions of Southeast Asia, but today it is nearly
impossible to find any columnist or writer consistently critical
of Beijing. Similarly, in Indonesia the media have been uncrit-
ical of China. This despite the fact that pan-Islamic issues
dominate Indonesian newspapers’ opinion pages, and Beijing’s
crackdown on Chinese Muslims in its western province of
Xinjiang includes, according to Human Rights Watch, thou-
sands of arbitrary detentions for “illegal religious activity.”
Yet Xinjiang rarely merits even a mention in the Jakarta Post,
Tempo, or other top Indonesian publications.
22
Partly, this reflects tough Chinese control of foreign news
outlets, which limits coverage of Xinjiang and other problems
in China. Partly, it reflects Washington’s unpopularity: because
I:o Mr. Popular
the United States is still vastly more powerful on the world
stage than China, American abuses of Muslims at Guantá-
namo Bay or Abu Ghraib make better-selling stories in the
media than China’s abuses. And partly, it may reflect success by
Chinese diplomats in other countries in using their influence
to prevent local reporters from writing stories that reflect
badly on Beijing.
Elites in some developing nations also seem to have em-
braced China’s growing soft power—they see in it opportu-
nity for their companies and political parties. Across the de-
veloping world, mainland Chinese businesspeople and policy
makers now are given the type of welcome and access once re-
served for Americans or Japanese or Europeans. “Even Chinese
diplomats well below the ambassadorial level, like the cultural
and commercial attachés, get treated like royalty here,” says
one Malaysian scholar. When Hu Jintao arrived in Thailand in
:oo,, the Thais welcomed him with a state banquet at the royal
family’s palace, a rare honor. When Hu stopped in Brazil in
:oo¡, Brazilian President Luiz Inácio Lula da Silva upgraded
bilateral trade ties and decided to send Brazilian advisers to
Beijing to study Chinese economics. “We want a partnership
that integrates our economies and serves as a paradigm for
South-South cooperation,” Lula cooed.
23
In the chaos of Indonesia’s financial meltdown in I,,8, many
journalists focused on the implications of the crisis for Su-
harto, the sleepy-eyed dictator who had ruled Indonesia for
three decades, maneuvering among his country’s power bases
like a masterful puppeteer. With Indonesia’s currency free-
falling, Suharto had approved fiscal austerity measures pro-
posed by the International Monetary Fund. Austerity bit into
average Indonesians’ pocketbooks, and squatter camps of the
Mr. Popular I:I
newly poor spread across Jakarta. Students and democracy ac-
tivists held open protests against the faltering government, un-
thinkable only five years before. By March I,,8 Suharto
seemed exhausted and ready to leave—which he did in May,
handing power to his vice president, B. J. Habibie.
24
With the spotlight on Suharto, many reporters missed an
ominous trend. Though Suharto’s government had imposed
restrictions on the Chinese Indonesian minority, making it
difficult for them to obtain financing from state banks and In-
donesian citizenship, there had been no large-scale anti–ethnic
Chinese violence in Indonesia for thirty years, partly because
Suharto’s authoritarian regime limited open protest. But in
January I,,8, as Suharto’s grip on power loosened, Muslim
leaders across the archipelago began demonizing the country’s
Chinese minority, telling young Muslims to “take back the
wealth that is rightfully [yours],” as one academic studying the
violence recorded. Religious leaders, army officers, and police
further whipped up crowds of unemployed young men with
anti-Chinese slurs and unsubstantiated reports that Chinese
merchants were gouging customers on cooking oil and other
staples. By February mobs had begun attacking Chinese-
owned shops in the Javanese city of Pamanukan, screaming
“Kill the Chinese” and “Chinese out”; some rioters ripped jew-
elry from the necks and arms of ethnic Chinese women in the
streets.
25
Violence spiraled. In February a meeting in the Al-Azhar
mosque in Jakarta featured speakers calling on Indonesians to
fight “traitors” in the country who were stealing the nation’s
wealth, leaving little doubt who they considered traitors. Mobs
focused on ethnic Chinese–owned businesses like shopping
malls and gold stores, and men on motorcycles led some of the
rioters to selected Chinese-owned shops, where they locked
I:: Mr. Popular
the proprietors inside and burned the buildings to the ground.
Perhaps as many as seventy thousand Chinese Indonesians
fled the country, and many more escaped Jakarta for quieter
parts of the archipelago, like Bali.
26
At the time, the Chinese government did almost nothing
to stop the rioting in Indonesia. During the Maoist period in
the mid-I,oos, when some Indonesian rioters had targeted
Chinese Indonesians, Beijing had stepped in, offering refuge for
ethnic Chinese fleeing the archipelago. Similarly, when ethnic
Chinese refugees fled Vietnam in I,8o, China sent ships to help
them. But in I,,8 Beijing said nothing for months about the In-
donesian riots. More than two months after some of the worst
violence, a Chinese foreign ministry spokesman belatedly an-
nounced, “China is concerned and sympathetic with the suffer-
ing experienced by the Indonesians of Chinese origin,”but Bei-
jing did not apply any pressure on Jakarta to protect Chinese
Indonesians.
27
This callous approach alienated some diaspora
Chinese, but, as interviews with Chinese officials suggest, it was
part of a strategy by Beijing to assure its neighbors that it would
not intervene in their affairs. The strategy worked: it made it
possible for Indonesian leaders to genuinely believe Beijing was
becoming more pragmatic and noninterventionist.
When one looks down from A. B. Susanto’s penthouse office
today, a view stretching over the elevated, manicured highways
of Jakarta’s financial district, it is hard to imagine that the
chaos of I,,8 took place less than a decade ago. Ushered into
the office, I sit on a leather couch in one end of the sprawling
room at Susanto’s business strategy firm, the Jakarta Consult-
ing Group, which counts among its clients many of Indonesia’s
most prominent companies. Susanto, who just returned from
a lecture tour in Australia, had furnished his office, the size of
Mr. Popular I:,
two hotel suites, with large portraits of himself mounted on
artists’ easels and a coffee table covered in business books he
had written. He settles his pudgy frame onto the couch oppo-
site me, pulls off his gold cufflinks, and rolls up the sleeves of
his crisp peach shirt.
28
A. B. Susanto had long been a prominent Indonesian
Chinese member of the Jakarta business community, but de-
spite his wealth, until recent years he never became involved in
politics. In the past five years, though, he began to sense a shift
in views of Chinese Indonesians. After the riots in I,,8, ten-
sions calmed in Indonesia, and the country made the transi-
tion to democracy and developed closer ties to China itself,
mitigating any (irrational) fear that Beijing would try to use
Indonesian Chinese as a fifth column to undermine the In-
donesian government.
“The population in Indonesia definitely has become
more tolerant of ethnic Chinese—of ethnic Chinese politi-
cians,” says Susanto. In this new era of tolerance, several polit-
ical parties wooed Susanto to run for Parliament in the :oo¡
Indonesian elections. He chose the National Awakening Party,
and ran in :oo¡, one of at least thirty Indonesian Chinese run-
ning for Parliament in that election.
Though he did not win, Susanto was staying in politics.
29
In fact, he now felt completely comfortable in the political
game, and was waiting for barons to come to him. “I’ve been
asked to run for other offices, including vice mayor of Jakarta,”
Susanto said, though for now he had turned down all comers.
“We can really exert our presence—we [ethnic Chinese] are
not afraid to share some of our ideas anymore.”
Analyzing the position of ethnic Chinese in the diaspora—
men and women like A. B. Susanto—offers another explicit
I:¡ Mr. Popular
way to measure China’s charm. Beijing has actively cultivated
the diaspora, and sometimes has tried to use them as links
between the developing world and China. And the ethnic
Chinese’s position, in society and politics, has been radically
transformed in the past ten years. Diaspora Chinese, even
powerful businessmen like Susanto, once avoided politics for
fear of being tied to China’s policies and negative image, and
then being targeted by the majority in their nations.
But today diaspora Chinese increasingly advertise their
Chinese heritage, like Americans living abroad in the I,,os and
I,oos, a time when the United States’ image in much of the
world was much more positive, and advertising your American
background might help woo business partners or persuade
local politicians to side with you. Of course, many in the dias-
pora have little connection to mainland China, and many do
not even speak Chinese; in this way, they are vastly different
from Americans overseas, who obviously remained US citizens.
Still, even if the diaspora Chinese actually have little in-
teraction with China, in many countries perceptions of China
reflect upon perceptions of diaspora Chinese. In many cases
the diaspora’s identity now has taken on a positive connota-
tion because China is no longer seen as a threat, and because,
rightly or wrongly, some non-Chinese view ethnic Chinese as
potential links to China.
In Indonesia, ethnic Chinese’s fortunes have benefited
from warming relations with Beijing, as well as from the
democratization of Indonesian politics and society, which
opened people’s eyes to the history of Indonesia’s discrimina-
tion. Over the past five years, Chinese Indonesians like A. B.
Susanto have become even more integrated into Indonesian
society. They now celebrate Chinese New Year, outlawed under
Suharto, and visit China for vacations. Banned by Suharto
Mr. Popular I:,
from creating political organizations, Chinese Indonesians
today have founded ethnic associations and self-help groups
that assisted ethnic Chinese victims of the :oo¡ tsunami.
Along with Susanto and the thirty parliamentary candidates,
more than one hundred Indonesian Chinese ran for regional
legislatures in :oo¡. Perhaps the greatest sign that Indone-
sians are more willing to accept their Chinese minority? A Chi-
nese Indonesian nearly won the Indonesian version of Ameri-
can Idol.
30
Other developing nations have witnessed similar shifts in
public opinion toward diaspora Chinese. Shortly after coming
to office in :ooI, former Thai Prime Minister Thaksin Shi-
nawatra paid a visit to China. Bringing with him a delegation
of Thai business and political elites, Thaksin arrived in Beijing
before continuing on to Meizhou, the area of Guangdong
province that Thaksin’s ancestors had left for Thailand. The
prime minister’s visit befuddled the farmers in Meizhou, who
probably remembered Thaksin’s relatives about as well as any-
one in Poland would remember the Kurlantzick family, which
emigrated to America a century ago. But the Meizhou resi-
dents played along in the spirit of goodwill, staging a lion
dance and chatting with the prime minister in Hakka, a dialect
spoken in southern China.
31
Returning to Thailand, Thaksin emphasized his ethnic
Chinese background and touted his ability to bridge relations
between Bangkok and Beijing. Playing up his heritage, Thak-
sin led some of the largest delegations to the Boao Forum,
China’s World Economic Forum–like summit, and ultimately
pushed for a closer Thailand-China strategic partnership. Bei-
jing responded, providing funding for the Sirindhorn Center,
a new Chinese-language and cultural facility located at Mae
Fah Luang University in northern Thailand, and signing an
I:o Mr. Popular
agreement promising to increase bilateral trade between the
two nations to $,o billion by :oIo. Today other prominent
Thai politicians tout their Chinese background, partly because
they believe it will open doors to China, and partly because it
seems popular with a public that views Beijing as cool, rich,
and attractive. “Every time we sit down with the Chinese [offi-
cials], all the Thai are always tracing their ancestry,” says Krai-
sak, the Thai senator.
32
Meanwhile, few Thais accuse local Thai companies with
close links to Beijing of favoring the People’s Republic, even as
some Thai firms and Thai leaders receive criticism for their al-
liances with Western companies or Western countries. When
Thailand tried to negotiate a free trade deal with the United
States in :ooo, more than ten thousand protesters greeted the
negotiating team during their meetings in Chiang Mai, a city
in northern Thailand. Demonstrators fought with police and
burned the Thai negotiator Nit Pibulsongkram in effigy, com-
plaining that he was too American, because he had formerly
been the Thai ambassador to the United States and had family
links to America.
33
Contrast this with average Thais’ response to news about
Charoen Pokphand, the agricultural giant that was the first
foreign investor in China. CP, I learned, is quietly building
warehouses across Bangkok to import Chinese goods; some of
those Chinese agricultural imports probably will displace Thai
farmers. CP’s chief reportedly examined prospective hires’ fa-
cial features to see whether they have ethnic Chinese ancestry.
CP has advised the Thai government on its relations with
China, and reportedly even helped the Chinese government
with its overseas lobbying efforts.
34
But China is now seen as Thailand’s close friend, a friend-
ship facilitated by China’s diplomacy, aid, and cultivation of
Mr. Popular I:,
diaspora Chinese in Thailand, and because Thailand sees the
benefits of latching onto China’s rising economic star. So few
Thais lash out against Thailand’s trade negotiations with China,
or Thai companies that benefit from close relations with Bei-
jing. The Thai media rarely criticize CP for being “too Chi-
nese.” When I asked many Thai opinion leaders whether they
were concerned that CP might benefit at the expense of Thai
farmers, most seem befuddled at the question. Not a single one
said yes.
I:8 Mr. Popular
VII
Goal Oriented
hese are the early days of China’s charm offensive,
which can make it difficult to draw hard and fast
conclusions, but there are other ways, beyond what we
saw in the last chapter, to measure Beijing’s successes
and failures. Results of opinion studies, interest in Chinese
culture and language, respect for Chinese officials, and treat-
ment of diaspora Chinese are explicit, relatively obvious signs
of China’s charm success. It is also possible to look at implicit
signs of China’s success—by recalling China’s goals, and then
examining whether it is achieving its goals.
China has hardly enjoyed unchecked success in achieving
its goals, and it still faces many significant obstacles. Since
China’s soft power also contains coercive elements, it can be
hard to tell how much China is pulling other nations and how
much it is pushing. Nor has Beijing consistently used its power
to compel other nations to take actions not already in their
own self-interest; other countries may use aspects of Chinese
soft power to their own benefit.
Still, by examining China’s goals, we can infer that China
has enjoyed some success wielding soft power. China’s goals
include maintaining peace and stability on its borders, por-
traying itself to other nations as a benign and constructive
actor, possibly becoming a model of development to other na-
tions, obtaining resources needed to power the Chinese econ-
omy, isolating Taiwan, and demonstrating the possibility that
it can eventually become a great power—one day even an
equal of the United States.
Beijing has built peaceful relations with most of its
neighbors, creating the kind of stability China long has de-
sired. As China has become more popular, leaders across Asia
could not rally domestic political support by persisting in dis-
putes with Beijing. Beijing has settled most of its border issues,
which previously threatened its peaceful relations.
1
China also has begun to convince developing nations
that it can be a constructive player in global affairs. To be sure,
Asian nations like Vietnam clearly still harbor fears that China
seeks to dominate the region; countries like Vietnam build ties
with other Asian nations, and with the United States, to coun-
terbalance Beijing. China’s neighbors have some reason to
worry: the history of interactions between China and the rest
of Asia stretches back millennia, and gives little reassurance to
other Asian countries. As the historians John King Fairbank
and Merle Goldman write, historically China viewed the na-
tions of Southeast Asia as inferior vassal states. China carried
out a foreign policy in which it sought to dominate these
countries without militarily controlling them; other Asian
countries offered the Chinese court lavish gifts, probably to
keep Beijing from invading.
2
These memories have not vanished, from the minds of
either Chinese leaders or their neighbors. As Chinese foreign
I,o Goal Oriented
policy specialists recently told the former intelligence officer
Robert Sutter, secret Chinese Communist Party documents con-
sistently refer to a goal of having China be the leader in Asia.
3
Still, other nations are balancing less against China than
in the past. Only a decade ago, after China’s military staked a
claim to the South China Sea, fearful Southeast Asian nations
united to condemn Beijing’s actions. Today, the Southeast
Asian nation closest to the disputed sea, the Philippines, has
established closer military ties with China—a decision, Philip-
pine politicians agree, it can make only because the Philippine
public has grow more enthusiastic about China’s influence.
Indeed, a Pentagon-sponsored report obtained through the
Freedom of Information Act noted, “Philippine officials and
scholars generally have a very positive view of China.”They are
not alone. As a panel of Asian experts convened by the Na-
tional Bureau of Asian Research, America’s leading Asia re-
search group, concluded, “Southeast Asian states generally
perceive China’s rise as more of [an] opportunity.” “The ma-
jority of Asian states currently view China as more benign than
malign, and are accommodating themselves to China’s rise,”
agrees George Washington University’s David Shambaugh, in
one of his most recent studies of Asian reactions to China.
4
This appeal could boost Beijing’s influence, just as Amer-
ican popularity after the Second World War allowed leaders
from a range of nations to ally with the United States, since ap-
pearing close to America helped them in their domestic polit-
ical environments. In democratic nations like the Philippines
or Thailand, China’s appeal today allows leaders in the region
the political space to move closer to China, since public senti-
ment supports warming relations. In Thailand, for example,
former Prime Minister Thaksin Shinawatra’s aides believed
that their boss’s touting of ties to China helped him win votes
Goal Oriented I,I
among businesspeople and other elite sections of society.
5
In
less democratic nations, like Venezuela, where a small circle of
leaders makes decisions, China’s appeal to those elites may serve
the same function, allowing them to build consensus on warm-
ing relations with Beijing.
In South Korea, meanwhile, some government officials
told former intelligence officer Sutter that they were concerned
about how popular China was becoming among South Korean
legislators and the general public. One internal poll of incom-
ing South Korean legislators, they warned, showed that o, per-
cent viewed China as the most important nation for Seoul.
Though these officials wanted to make relations with the
United States the top priority of Seoul’s foreign policy, they
said that “they faced a difficult challenge in achieving these
tasks in the face of widespread South Korean public opinion,
and the opinion of recently elected legislators, that gave China
the top priority in South Korean foreign policy and took a dim
view of the United States.”
6
Many of these leaders already display greater comfort
working with China. In the run-up to the December :oo, East
Asia Summit, a pan-Asian forum on economic and regional
political issues, semiauthoritarian Malaysia consulted closely
with China on EAS policy making, reflecting the warmth be-
tween the Malaysian and Chinese governments.
7
Some Asian
countries eventually may consider upgrading their strategic
partnerships with Beijing to formal alliances. Again, if they
have more comfort working with Beijing, it is because China
has become less threatening, and more popular, with elites and
with the general public.
Some of this warmth clearly comes from other countries’
fear of getting on Beijing’s bad side—they have no choice but
to deal with China’s rising strength. “This government sees
I,: Goal Oriented
China as the power that will engage Asia and dominate the
destiny of Asia,” leading Thai commentator Kavi Chongkitta-
vorn told the Washington Post. Similarly, Cambodian Prime
Minister Hun Sen in I,88 wrote, “China is the root of all that
is evil in Cambodia,” remembering that Beijing had supported
the murderous Khmer Rouge in the I,,os. In :oo, as China
poured in aid to Cambodia, Hun Sen announced that Phnom
Penh’s relations with Beijing were “entering into the best stage
in history.” “The People’s Republic of China has achieved this
amazing volte-face through a patient and economical applica-
tion of military and development assistance, loans, invest-
ment, and the cultivation of the Sino-Khmer community,” ad-
mitted a classified cable sent by former US Ambassador to
Cambodia Charles A. Ray. Similarly, partly because of China’s
dominance of trade with Thailand, a Thai foreign ministry
official, Sihasak Phuangketkeow, was careful to tell the Wash-
ington Post that Thailand’s relationship with the United States
was “not more special than relations with China.”
8
Some countries now appear comfortable enough with China’s
rise that they do view it as a model of development. In places
like Vietnam or Iran, where regimes are attempting to main-
tain control while growing the economy, policy makers seem
convinced that if they learn from China, they can duplicate
China’s success in promoting development while forestalling
political liberalization. In Vietnam younger policy makers
have adopted what they call a “Chinese model”of slowly open-
ing the economy while retaining control of the political sys-
tem. Across the border, policy makers in Laos see China as a
source of inspiration. “We see that the economy of China has
grown, and we think that there are lessons for Laos’s economy
from China—the building up of socialism while also having
Goal Oriented I,,
sustained economic growth,” said one China specialist at Laos’s
foreign ministry.
9
Iran and Syria provide even clearer examples of the appeal
of the China model. In Syria, the leadership has openly touted
its desire to move toward a Chinese model of development. In
Iran conservatives from the office of Supreme Leader Ayatollah
Khameini have traveled to China to study the Chinese develop-
ment model, and the applicability of the China model to Iran
became a major topic of debate in the :oo, Iranian elections.
10
In Latin America and Africa, the China model of state-
directed growth and poverty reduction holds appeal as well.
China successfully advertises its model of development as a
contrast to the neoliberal, free-market Washington Consen-
sus, which failed many developing nations. In a poll taken in
:oo:, after a decade of weak growth in the region, a mere ,,
percent of Latin Americans said that the state should allow the
private sector to control economic activity, showing the level
of frustration with free-market economics and its supporters
in the West. Another study showed that support for democracy
was declining sharply, with more than ,o percent of Latin
Americans agreeing with the statement “I wouldn’t mind if a
nondemocratic government came to power if it could solve
economic problems”—a sentiment that could prove amenable
to China’s model of economic liberalization combined with
political control.
11
Perhaps unsurprisingly, then, Brazilian
President Lula has sent teams of advisers to Beijing to learn
from China, while Raúl Castro has traveled to China on nu-
merous occasions, spending long periods learning at the side
of China’s former Premier Zhu Rongji. According to the Cuba
expert William Ratliff, Raúl invited one of Zhu’s top advisers
back to Cuba, where he gave lectures to hundreds of top Cuban
officials and executives.
I,¡ Goal Oriented
Similarly, in Africa many opinion leaders tout the Chi-
nese model as a solution to the continent’s long history of un-
derdevelopment. According to Barry Sautman, the specialist
on China-Africa relations at Hong Kong University of Science
and Technology, one leading Nigerian writer has argued that
“China has not allowed any . . . World Bank to impose on it
some neoliberal package of reforms. . . . Their strategy has not
been a neoliberal overdose of deregulation, cutting social ex-
penditure, privatizing everything under the sun, and jettison-
ing the public good. They have not branded subsidy a dirty
word.” Even the head of the African Development Bank an-
nounced, “We can learn from [the Chinese] how . . . to move
from low to middle income status.”
12
Even democracies that historically have placed commu-
nal rights above a Western emphasis on individual liberties can
find things to admire in China’s model. I Wibowo, a specialist
on Chinese studies in Indonesia, which is still struggling to re-
cover from the Asian financial crisis, says, “Indonesians might
not know much about China, but they know that China has
been successful in making their economy grow, [and] they see
China as a model”—a place where some individual sacrifices
have created prosperity. “There’s great admiration of China,”
agrees Dewi Fortuna Anwar, former assistant minister for for-
eign affairs in the Indonesian government. “Indonesians look
at China and see a situation Indonesians would like to emu-
late.” Next door in Malaysia, “China’s model of government
mobilizing society for economic gain, while keeping down
tension—this is attractive here,” says Gavin Khoo, a research
fellow at the Asian Center for Media Studies, a Malaysian think
tank. “There is little emphasis on individual rights and free-
doms here, even among average people.”
13
The Chinese vision of diplomacy, in which countries
Goal Oriented I,,
rarely intervene in each other’s affairs, also appeals to elites and
populaces in some democracies—particularly in freer nations
like India and Thailand and Brazil and Mexico, which face se-
rious rights problems at home. India, for example, has earned
criticism from American policy makers for its crackdown in
Kashmir, as has Thailand for its brutal battle against a Muslim
insurgency in its deep south. Indeed, many of these countries,
like Thailand, chafe at American criticism of their human
rights records. “China doesn’t lecture . . . on democracy, human
rights, or deregulation,” argues Frank Ching, a leading Hong
Kong–based commentator on China. “As a result, [countries
are] wooed more successfully by China.”
14
The appeal of the China model, of course, depends on
China’s continuing to post astounding growth rates. Any slip-
page would cost it dearly in soft power; in the old Soviet
Union, when sympathetic foreign visitors actually came to the
USSR and saw how poorly its economy was performing, they
often became far less enthusiastic about the potential spread of
the Soviet model around the world. China clearly faces obsta-
cles to long-term growth. China’s banking sector remains rid-
dled by nonperforming loans and shady deals with state-linked
enterprises—several state recapitalizations of the banking sec-
tor have failed. Only three years ago, one of China’s largest
financial institutions, China Construction Bank, was insol-
vent, and while the Chinese government estimates that its
banking sector faces roughly $I,o billion in bad loans, most
Western analysts believe the true number is far higher. Mean-
while, China faces an income divide between its prosperous
eastern half, which has attracted most of the foreign invest-
ment and has cities like Shanghai that rival New York, and the
interior, rural areas, which look more like Africa, with farmers
struggling to eke out any income and living in simple huts
I,o Goal Oriented
without modern amenities. “The income gap . . . has exceeded
reasonable trends,” the Chinese news wire Xinhua admitted in
:oo,. Rising income inequality has sparked waves of protest in
China: even China’s public security minister admitted that
there were some eighty-seven thousand “mass incidents” in
China in :oo,, up from fifty-eight thousand in :oo,.
15
In poorer countries like Laos, Cambodia, Kazakhstan, North
Korea, and even the Russian far east, the appeal of China’s
model, of life in China, is more than an abstract idea: people
want to get to China itself. This isn’t a new concept for Amer-
icans or Europeans, who expect to see millions of foreigners
coming to the United States or the European Union to make a
better life for themselves and their families. Mexicans and
Central Americans look to the United States as an example of
a successful, wealthy neighbor and a place to make money;
Moldovans and Ukrainians now see the European Union the
same way.
This is how many Laotians and Burmese and Cambodi-
ans and North Koreans see China today—as a promised land,
even though China’s per capita gross domestic product, out-
side of a few rich eastern cities, remains low compared to the
United States or the European Union. In Africa, Latin Amer-
ica, and parts of Asia, many people already perceive China as
a wealthy nation, because they hear about China’s economic
progress and see Chinese business delegations jetting into
town to buy up their resources, and because they know far
more about wealthier Chinese cities like Shanghai than they
do about poor interior areas of China.
Just as Central Americans want to get to the rich United
States, some of these people want to get to China. In Burma
laborers tell of developing plans to sneak across the porous
Goal Oriented I,,
border at night and then stay in China permanently. In far
western China, Kazakh, Pakistani, and Uzbek traders flock to
the bustling Chinese markets, and then often stay on, trying
to blend into western China’s ethnically diverse society. In
Laos, Laotian women search for Chinese husbands, whom
they believe might take them back to China. To Laotians,
“China kind of symbolizes modernity—they move to Jing-
hong [a city in southwestern China] and they can go to shop-
ping malls, live a modern life,” says Antonella Diana, an an-
thropologist at Australian National University specializing in
Laotian perceptions of China. “Lao citizens want to strategi-
cally get married to Chinese [even though this does not guar-
antee Chinese citizenship] because it’s a way to enhance your
living standards,” she says. “They view China as . . . a ticket
out of their lives.”
16
As we have already seen, Beijing’s state-linked companies are
amassing stakes in numerous foreign oil and gas fields, though
they are far from matching the holdings of major Western
companies like ExxonMobil. Still, China’s skillful resource
diplomacy has allowed Beijing to diversify its base of oil and
gas suppliers. In I,,, China obtained more than half its crude
oil from just two nations, Indonesia and Oman. By :oo, Bei-
jing obtained Io.8 percent of its oil from Saudi Arabia, I,.8 per-
cent from Iran, Io., percent from Oman, and smaller percent-
ages from other nations.
17
Foreign leaders now sometimes sell resources to China
because dealing with Beijing is less politically dangerous than
selling to Western firms. If they sell resources to American
companies, leaders find themselves vulnerable to accusations
by political opponents of being too pro-American. As one sur-
vey of the Middle East by Mamoun Fandy, then of Rice Uni-
I,8 Goal Oriented
versity, discovered, Arabs “find in Beijing a counterweight” to
American power.
18
In contrast with several years ago, when Beijing could
only pick off small oil fields in second-tier countries, China has
built inroads with the most important suppliers, like Saudi
Arabia. In January :ooo Riyadh and Beijing signed a landmark
deal expanding oil-sector cooperation between the two na-
tions. China National Petroleum Corporation, one of China’s
major oil companies, has rapidly set up offices in Saudi Arabia,
and the Saudi government also is considering creating a strate-
gic reserve of Saudi Arabian oil in China, which Beijing might
be able to rely on the way Washington relies upon America’s
strategic reserve. Trade between the two countries is rising by
more than ,o percent per year, and Saudi businesspeople and
officials have been impressed that Chinese diplomats take the
time to learn their language. “Their Arabic is fluent. They don’t
even talk slang,” one Saudi businessman marveled about his
Chinese hosts.
19
Though some energy analysts believe that China may
have overpaid for resources, the price of a barrel of oil has
more than doubled since I,,,, and global reserves of cheaply
obtainable black gold are decreasing, as major fields in coun-
tries like Saudi Arabia reach maturity.
20
Though China’s declared policy is noninterference, and though
many nations have found that China does not make as many
demands as the United States, Beijing has begun to get what it
wants from its foreign relations. In fact, China has skillfully
used soft power to influence nations to act according to Bei-
jing’s wishes.
In a dramatic shift, China has subtly begun to dominate
the internal dynamics of regional organizations in Asia. These
Goal Oriented I,,
groups have begun to shape their decision making to accom-
modate Beijing, making choices they know will please China.
Take the most prominent example. The Association of
Southeast Asian Nations, the most important regional group,
is of course supposed to take its interests into account first,
making decisions based on Southeast Asia’s needs. But several
Southeast Asian countries, like Burma, Cambodia, and larger
and wealthier Thailand, have developed such close ties to
China that they often seem to be considering Beijing’s interests
while they are making decisions in Asean.
Indeed, Southeast Asian diplomats say that in the past
three years, consensus at Asean meetings often is delayed as
member nations analyze how Beijing will react to any decision.
“A lot of Asean countries clearly take into consideration what
the Chinese think—and info quietly gets leaked back to Bei-
jing about who’s on their side,”says one senior Southeast Asian
diplomat. “Asean nations are trying to figure out what China
wants ahead of time.”
21
China also has begun leveraging its influence with indi-
vidual nations. In Zambia, where China is one of the largest
investors in the local copper industry and one of the biggest
sources of aid, the Chinese ambassador in :ooo warned that
Beijing might cut off diplomatic ties if voters picked an oppo-
sition candidate known for protesting China’s poor labor poli-
cies and threatening to evict Chinese companies from the
country. The ambassador’s comments, which sent shock waves
through the local media, marked the first time in the post-Mao
period that China had overtly tried to influence an African
election.
22
The effort may have been a success: the opposition
leader lost the presidential election.
In Cambodia, too, China uses its soft power to force
Phnom Penh to take actions it might not otherwise choose.
I¡o Goal Oriented
China has become the most important foreign influence and
aid donor in Cambodia, and Cambodian Prime Minister Hun
Sen shuttles to and from Beijing constantly. Yet by :ooo it also
was clear that China’s decision to dam upper portions of the
Mekong River, which runs down through Southeast Asia,
could have a disastrous impact on Cambodia. In some parts of
the river, water levels had fallen so low that the Mekong had
turned into flat plains. China had refused to join the Mekong
River Commission, the main organization monitoring the
river, and continued blasting and damming its sections of the
waterway. China even commissioned an environmental im-
pact assessment of its dams that was the ecological equivalent
of a drive-by shooting—a one-day trip in which scientists saw
virtually nothing. “Hun Sen knows what China is doing,” said
one Cambodian scientist. Like the prime minister, the scientist
was convinced Chinese dams on the upper part of the Mekong
River were drying up Cambodia’s Tonle Sap, the biggest fresh-
water lake in Southeast Asia, which is fed by the Mekong and
provides the major protein source in Cambodia.
23
Still, said one senior Cambodian environmental official,
every time Cambodians complain privately to the Chinese about
the Mekong River, a Chinese delegation visits countries in
Southeast Asia, offers promises of aid, emphasizes how popu-
lar China has become, and makes promises to uphold envi-
ronmental standards. “They know Asian leaders can go back to
their people and say, ‘We have this commitment from China,’”
he says—it will appear that these leaders are building relations
with China, which average people support. And Beijing’s aid
goes far in poor nations like Cambodia. As a result, the official
said, Hun Sen had publicly declared that Chinese dams would
pose “no problems” and instructed his diplomats not to make
any complaints about the Mekong.
24
Goal Oriented I¡I
As China becomes more aggressive, however, it could
squander its own gains. “The Chinese diplomats I’ve dealt with
have become increasingly sure and proud of their status, and
disdainful of Southeast Asian nations,” says one Singaporean
diplomat. As the Chinese diplomats abandon their style of ap-
pearing to listen to every nation’s concerns, he says, they will
lose some of their appeal. In Singapore, one of the Southeast
Asian nations more skeptical of China’s charm offensive,
China’s growing diplomatic assertiveness has suggested to
some Singaporean officials that China’s charm is merely a fa-
cade, one reason why Singapore has boosted defense coopera-
tion with the United States in recent years. Similarly, says
James Wong, a leading Malaysian commentator, “The Chinese
angered many Asians by so openly confronting Japan at the
East Asia Summit,” where China’s delegation refused to meet
Japan’s delegation and Beijing pressured other attendees to
disregard any proposals backed by Tokyo.
25
Beijing also flexes its muscles to isolate Taiwan. Countries are
dropping Taiwan partly because they desire closer relations with
Beijing and partly because they fear offending China. Either
way, for many nations cutting ties to Taiwan now makes sense—
it hurts very little but pleases China enormously. In Latin Amer-
ica, where Taiwan retains nearly half of its formal allies in the
world, China’s economic success, aid, and broader popularity
have in recent years swayed Dominica and Grenada to switch
recognition to Beijing, while Guatemala has opened commercial
relations with China, often the first step toward recognition.
Latin American nations have prevented Taiwan from obtain-
ing observer status at the Organization of American States, the
region’s most important international grouping.
26
Matters could get worse for Taipei. If Panama switched
I¡: Goal Oriented
recognition to Beijing, other Central American nations prob-
ably would follow, since Panama is the most important nation
in Central America still recognizing Taiwan. In :oo¡, during
Panama’s presidential election, one leading candidate an-
nounced that if elected he would open ties to Beijing. Though
he lost, his position cannot have reassured Taipei, and several
prominent Latin America scholars believe that within a de-
cade Taiwan will retain no formal allies in Central or South
America.
27
In Africa, another region where countries still recognize
Taiwan, the die seems cast as well. The Central African Repub-
lic and South Africa switched recognition to Beijing in the
I,,os. In :oo, Liberia switched to China, and in late :oo,
China won over Senegal, one of the most important democ-
racies in Africa, even though Taiwanese President Chen Shui-
bian had taken a personal tour through Senegal touting the
importance of new democracies sticking together. In :ooo
Chad cut diplomatic ties to Taiwan. “We are losing the people
sympathetic to us,” admits Joanne Chang, formerly one of Tai-
wan’s top representatives in Washington.
28
Governments are slashing even their informal links to
Taiwan. In the I,,os leaders from many developing countries
that officially recognized Beijing hosted Taiwanese leaders for
quiet meetings and traveled to Taipei for informal visits, as for-
mer Malaysian Prime Minister Mahathir Mohamad and for-
mer Singaporean Prime Minister Goh Chok Tong did in I,,,.
They also allowed Taiwan to open informal embassies abroad,
normally known as Taipei Economic and Cultural Offices.
Cambodia was one of the first to push the Taiwanese out. In
I,,8 Cambodian Prime Minister Hun Sen announced that he
did not want a Taiwanese informal embassy in Phnom Penh,
depriving Taipei of this important forum. Other Asian coun-
Goal Oriented I¡,
tries halted the informal diplomacy routine. In :oo:, after Bei-
jing publicly exposed a visit by Taiwanese Vice President An-
nette Lu to Bali, the Indonesian Foreign Ministry announced
it knew nothing of her visit—surely a lie—and refused to let
her come to Jakarta, where she probably had planned some
informal meetings with the government. Shortly after the
Jakarta incident, the Philippine government announced that it
would refuse any visit by Taiwan’s president. The following
year, after China blasted Lee Hsien Loong, then Singapore’s
deputy prime minister, for making an informal visit to Taipei,
Malaysia announced it would bar any ministers from trips to
Taiwan.
29
Chinese diaspora organizations have become wary of
Taiwan as well, and the allure of Taiwan has faded. Over the
past decade, Taiwanese companies have relocated large chunks
of their factories abroad to China: by the period between :oo:
and :oo¡, nearly half of Taiwan’s entire outward investment
went to China.
30
At the same time, Taiwan’s opposition group,
the Democratic Progressive Party, grew in strength and ulti-
mately defeated the long-ruling Kuomintang in the presiden-
tial election of :ooo, putting itself in power for the first time.
These changes may have helped Taiwanese businesses
and benefited Taiwanese democracy, but they damaged Tai-
wan’s precarious soft power. Taiwan’s investments in other
parts of the developing world plummeted as Taiwanese firms
moved to China. Meanwhile, the Kuomintang had spent
decades building up links to ethnic Chinese organizations
around the world and to leading politicians—women and
men like the Philippines’ former President Fidel Ramos,
whose father had been Philippine ambassador to Taiwan and
who himself had built close relations with the Kuomintang
leadership.
31
I¡¡ Goal Oriented
After nearly two decades in opposition, the Democratic
Progressive Party came to power with weak ties to foreign
leaders and to the ethnic Chinese diaspora. Still, the DPP
quickly cashiered many of the Kuomintang-era diplomats,
costing Taiwan years of experience and strong links to dias-
pora Chinese organizations.
32
Taiwan has paid a price. Diaspora Chinese organizations
have started holding international meetings specifically to de-
nounce Taiwan, like the :oo¡ get-together in Bangkok, where
some one thousand ethnic Chinese held a two-day meeting
entitled “Global Overseas Chinese Congregation of Anti-Tai-
wan Independence.” Obviously aware of the vast potential of
trade with China, they are making decisions in their best in-
terest. The Chinese Chamber of Commerce in Panama has
moved closer to the PRC, pushing for the Panamanian gov-
ernment to switch diplomatic ties and formally recognize Bei-
jing. When Chen Shui-bian has visited Panama, other dias-
pora Chinese groups like the China Council for Peaceful
Reunification have announced that they did not welcome his
visit. In the Philippines, Ellen Palanca, a China expert at Ata-
neo de Manila University, closely monitors these trends. “The
Filipino-Chinese business community historically was very
pro-Taiwan, but in the past five years they’ve started to become
more pro-PRC,” says Palanca. Like many Filipino analysts, she
believes that the influence of pro-Beijing Filipino-Chinese ty-
coon Lucio Tan has swayed the diaspora Chinese community.
33
Countries have proven willing to isolate other perceived
enemies of China—again, both because they desire warmer
relations with Beijing and because they fear cooler relations.
At the request of Beijing, Cambodia in :oo: barred the Dalai
Lama from attending a Buddhism conference. Later, the South
Korean government essentially refused the Dalai Lama a visa.
Goal Oriented I¡,
Similarly, China seems to have persuaded other countries to
crack down on the Falun Gong, the spiritual movement that
frightened Beijing in the late I,,os by holding coordinated na-
tionwide demonstrations, some of the largest in China since
the I,8, Tiananmen movement. Soon after, Chinese security
services arrested thousands of supposed Falun Gong mem-
bers, sending them to labor camps and sometimes executing
them. China then targeted the group’s actions overseas. In :ooI
the Thai government, under pressure from Beijing, forced
Falun Gong to cancel an international meeting in Bangkok.
Explaining Thailand’s actions, the country’s police minister
bluntly told reporters, “We want to keep good relations with
China.” Thailand established a precedent, and in the following
years, Indonesia prohibited marches by Falun Gong support-
ers and sentenced Falun Gong activists to jail, and Malaysia
filed charges against Falun Gong adherents.
34
The ultimate test of a country’s influence is its ability to create
a string of friends around the world; great powers build rela-
tionships spanning continents. China has begun creating an
alternative pole to Western democracies in international or-
ganizations and global diplomacy. On Iran, on North Korea,
and on many other issues, the United Nations Security Coun-
cil now faces a long-term serious divide among its five perma-
nent members. China, along with Russia, can increasingly as-
semble a bloc that can stop US, British, and French action
against oil and gas producers, like Sudan or Burma, or simply
halt action against authoritarian states, like Belarus and North
Korea, even if those countries do not possess petroleum.
China has assembled these coalitions to protect itself as
well. In :oo¡ the United States sponsored a resolution at the
United Nations Commission on Human Rights, the global
I¡o Goal Oriented
body’s main rights watchdog, prodding China toward greater
openness and respect for human rights. China proposed a mo-
tion urging “no action”on the Americans’ idea—a motion cal-
culated to prevent a potentially embarrassing debate and vote
on China’s rights record. The no-action resolution passed,
with the support of twenty-seven nations. Half of those coun-
tries were from Africa, including Sudan, Eritrea, and Zim-
babwe. Many had benefited from aid and targeted investment
from China, and few wanted to see any human rights resolu-
tions levied against Beijing.
35
China had set a precedent: it now
had enough allies that it could beat back any future challenge
at the Commission on Human Rights.
Goal Oriented I¡,
VIII
Wielding the Charm
ong La, a village in northeastern Burma, lies
more than three hundred miles from the nearest
city, has no air links with the world, and sits in
one of the poorest, most mountainous regions
of one of the poorest nations in the world. Towns near Mong
La lack electricity, paved roads, running water. In these towns’
simple huts of thatch and wood, naked, hungry-looking chil-
dren squat in the dirt, fighting over scraps of food.
1
An unlikely place for an Asian version of Las Vegas. But
in the late I,,os, that is exactly what Mong La became. Fueled
by investments from the United Wa State Army—a nearly
twenty thousand–strong militia group operating in northeast-
ern Burma, situated in a region of Burma with few laws—
Mong La proved an ideal spot for casino gambling. Beginning
in I,,8 businesspeople with links to the UWSA, allegedly along
with the Burmese government, constructed garish casinos in
the one-lane frontier town, complete with Vegas-style neon
billboards, tons of fake marble, and croupiers in tuxedos. The
formal attire worked in the casinos, but the dealers seemed
strangely out of place when they left the gaming palaces to
walk Mong La’s narrow dirt streets.
2
The casino tycoons brought in Vegas-style entertainment,
too—with a twist. Casinos built up Mong La dance revues and
staffed them with “ladyboys” imported from Thailand, known
as katoeys in Thai—either transvestites or, more commonly,
transsexuals who had undergone sex-change operations at one
of the Bangkok hospitals. The ladyboys played all the dance
roles and then posed afterward for photos with patrons. For a
few bucks, gamblers could shoot photos of themselves fond-
ling the dancers’ surgically altered body parts.
3
On any weekend night in the late I,,os, more than a
thousand visitors from China streamed into Mong La, getting
little trouble from either the Burmese or the Chinese customs
authorities. By one estimate, Mong La received as many as
,,o,ooo Chinese tourists a year. In town, where Mercedes taxis
ferried gamblers from one Mong La hotspot to the next, the
Chinese visitors could spend more than $I:,ooo each at some
of the city’s more exclusive tables. After an evening of gam-
bling, Chinese punters would hit one of the large karaoke
halls, where they could sing Chinese, Thai, Korean, or English
songs, hook up with platinum blond Eastern European prosti-
tutes, or drink hundreds of dollars worth of imported Scotch,
before retiring to the lavish hotels that had appeared almost
overnight in town.
4
According to one estimate, the Mong La casinos grossed
as much as $, billion in revenues between I,,8 and :oo¡. (By
comparison, Burma’s entire annual gross domestic product has
been estimated at $,., billion.)
5
Some of that money helped
build Mong La’s services and infrastructure: the city offered a
better electric grid than Burma’s decrepit capital, Rangoon.
Even better, Mong La created jobs for many local villagers.
Wielding the Charm I¡,
But much of the Mong La casino profits were plowed
back into corrosive activities. One cut undoubtedly went to the
Burmese military junta, which the international monitoring
group Freedom House ranks as one of the world’s worst re-
gimes. Since the Burmese junta reportedly spends less than
one-half of one percent on health care, but devotes some ¡o
percent of the budget to its military, it is unlikely that much of
the regime’s casino money ever helped average Burmese.
6
One cut undoubtedly went to the UWSA itself, a drug-
running private army the US State Department has called the
world’s “most heavily armed narco-traffickers.” The money
probably helped the UWSA flood amphetamines and heroin
into neighboring countries like Thailand, Laos, and China.
(The Golden Triangle region of Burma and Laos is the world’s
second-largest source of opium poppies, the precursor to her-
oin.) The drugs created an epidemic of amphetamine users in
Thailand, where as many as two million Thais used the drugs,
, percent of the entire population. The heroin seeped into
southwestern China, which soon faced an epidemic in border
cities like Ruili, where junkies shot up openly on city streets,
and needle sharing and prostitution led to rising HIV rates.
7
As Mong La was prospering, China was becoming vastly
more influential in Burma. After the United States imposed
sanctions on Burma in I,,, and :oo,, American companies
avoided the country, and China became Burma’s major source
of investment and aid.
8
Chinese businesspeople flowed into
northern Burma, and Beijing received Burma’s leaders on lav-
ish state visits, even as Europe and the United States banned
top Burmese leaders.
In the fall of :oo, China started to use that influence to
do some good in Burma. Worried about the flow of drugs out
of northeastern Burma, and angry that Chinese officials were
I,o Wielding the Charm
blowing state money at overseas casinos, including in Mong
La, the Chinese government’s attitude toward Mong La and
other casinos on China’s borders changed. Beijing restricted
visas for travel to Mong La, forbade Chinese to stay overnight
in the one-time casino capital, and even massed troops on the
Burmese border. China instituted tough measures on travel by
senior cadres to casinos in other countries, like North Korea,
where one Chinese official reportedly had lost more than
$,oo,ooo in state funds and other monies. One Chinese media
outlet reported that because of the crackdown, “Io, overseas
casinos in counties surrounding Yunnan, Guangxi, Heilong-
jiang, Jilin and other provinces and autonomous regions had
been shut down.” At the same time, China cracked down on
drugs entering from Burma, prodding the Burmese govern-
ment to fight narcotics within its borders and stepping up en-
forcement cooperation.
9
Cooperation produced results—Chinese police started
seizing heroin along the border. By the spring of :ooo Mong La
no longer resembled a frontier Vegas. Most casinos had closed
their doors and boarded up their windows, though some were
launching online gambling operations to survive. No one sang
in the karaoke halls; no one slept in the hotels. No one shopped
in the stores full of fake brand name clothes. Even the dancers
had gone home to Thailand, though an occasional solitary ka-
toey still wandered the empty streets.
10
Mong La, along with the Chinese government’s response,
reveals one side of Beijing’s growing influence in the world.
China could use its growing power to promote positive change,
like fighting narcotics in Burma and cooperating with its
neighbors to stop drug trafficking and the spread of HIV.
But only a few hundred miles from Mong La, China has
Wielding the Charm I,I
used its influence in a vastly different way. Chinese companies,
including many with close government links, have decimated
Burma’s northern forests, which are supposedly protected from
logging, and which have been called “very possibly the most
biodiverse, rich temperate area on earth.”
11
With soaring demand for housing in China’s cities, and
with China’s own forest cover depleted or protected, China’s
builders needed new sources of lumber. In Kachin State, the far
north of Burma, the Chinese companies found a solution. Be-
tween I,8¡ and :oo,, according to one report, the number of
Chinese logging companies operating near Kachin State rose
from four to more than one hundred. Investigators for the
watchdog group Global Witness reported seeing “vast quanti-
ties of timber” stockpiled in towns along the China-Burma
border. Nearly all that felled timber probably was illegally cut.
12
China itself has some of the world’s weakest environmen-
tal controls, and Beijing has repressed green activist groups,
fearing they could spark broader protests against the govern-
ment; in October :oo,, China arrested members of Chinese
activist group Green Watch. Given this background, Beijing
and Chinese provincial governments seemed unlikely to inter-
vene in the deforestation of its neighbor, though China offi-
cially had signed international bans on illegal logging. “By tak-
ing action [to fight deforestation], the government of the PRC
can demonstrate that it takes its responsibility as a regional
and global power seriously, and provide leadership for other
timber importing countries,” Global Witness argued. But
China did nothing of the sort. Chinese officials seemed to en-
courage the illegal timber trade, with local leaders allegedly en-
couraging the cross-border cutting.
13
By :oo,, Global Witness reported, “large tracts of forest
adjacent to the China-Burma border have been almost entirely
I,: Wielding the Charm
logged out,” mainly by Chinese companies. Its estimate sug-
gests that ,8 percent of Burma’s exports of felled timber to
China come from illegal sources, such as supposedly protected
forests. Global Witness further reported that revenue from the
timber trade was funding low-intensity local conflicts inside
Burma.
14
Burma is not unique. Global Witness believes that half
of China’s total felled timber imports—wood from not only
Burma but also many other nations, including Indonesia—
come from illegal sources. Overall, between I,,, and :oo,,
China’s imports of forest products more than tripled in vol-
ume, with illegal wood accounting for much of that.
15
Today China is a rising power whose role in the world’s future
remains unclear. Beijing could wield its soft power responsi-
bly. As one analysis by the US National Intelligence Council
suggests, in the coming years China may “remain an authori-
tarian state . . . but respect the rules of the order, work within
the existing framework [of international institutions] and seek
to change it by peaceful and legitimate means.”American lead-
ers unsurprisingly urge China to go in this direction. “China
has a responsibility to strengthen the international system that
has enabled its success,” said former Deputy Secretary of State
Robert Zoellick, a longtime Asia hand, in a major policy ad-
dress in September :oo,. China should “recognize that the in-
ternational system sustains their peaceful prosperity,” Zoellick
added.
16
Some Chinese officials seem to agree with Zoellick. After
all, Beijing argues that it wants only peace and harmony in the
world; the Chinese government’s :oo, white paper on foreign
policy claims, “To achieve peaceful development is a sincere
hope and unremitting pursuit of the Chinese people.” As Fu
Wielding the Charm I,,
Ying, the former Chinese ambassador to the Philippines and
current envoy to Australia, notes, “Throughout history, the rise
of most of the world’s large countries was inevitably the result
of bullying, weakening, and exploiting other countries.” China,
Fu Ying argues, will be different. Or as one Chinese diplomat
told me, if China is truly going to become a world leader, it will
have to use its soft power to serve the global good, and it must
use the United Nations and regional groups to solve serious
problems.
17
Yet as China’s soft power grows, its influence also could
prove disastrous in other countries—an obstacle overseas to
environmental protection, to better labor policies, to corporate
governance. Whichever way it goes, of course, in a more inter-
linked and globalized world, where countries can utilize much
faster tools of communication, China’s influence will spread
faster than that of other rising powers, like the United States,
Germany, and Japan, did during the early twentieth century.
China could essentially wind up exporting its own do-
mestic weaknesses. Before China became a major player on the
world stage, its internal policies were a potential nightmare for
people in Shenzhen or Guangzhou or Shenyang. Today Chi-
nese policies could be a nightmare for people in São Paolo or
Guatemala City or Surabaya.
Consider China’s labor policies. Most Chinese compa-
nies still do not treat their employees well at home, and devel-
oping countries have few of the tools necessary to enforce
labor rules on powerful multinationals, whether from Amer-
ica or China. Chinese companies have no experience dealing
with independent unions, since the All China Federation of
Trade Unions, an organization controlled by the Communist
Party, runs all unions in the country, and the government
sometimes jails people who try to start independent unions.
I,¡ Wielding the Charm
Most Chinese corporations do not know how to interact with
nongovernmental organizations, activists, shareholder groups,
and other groups overseas. Many Chinese heavy industries,
such as coal mining, have horrible safety and environmental
records. Being a coal miner in China must rank among the
world’s most dangerous occupations; thousands of Chinese
miners die in accidents each year, often because their employ-
ers did not purchase even minimal safety equipment.
18
There are clear positive signs of how China will use its soft
power. Beijing seems ready to embrace multilateral institu-
tions. In the past decade, besides enthusiastically joining re-
gional groups and creating its own multilateral initiatives, Bei-
jing has sent Chinese peacekeepers or police under the UN flag
to desperate places like Haiti and Liberia and East Timor. In
Liberia, China has contributed some six hundred men to the
UN mission, and today China has more troops participating in
UN peacekeeping missions than any other permanent mem-
ber of the Security Council.
19
China also has begun to mediate other nations’ disputes—
a task of responsible great powers. This is a significant change
from China’s recent past, and can scarcely be overstated. If Bei-
jing is to begin playing a role as a mediator of conflict, joining
with the United States in solving many problems, it could dra-
matically transform power dynamics in Asia and elsewhere.
In some cases, China has proven a proactive mediator.
On most days, the street outside the Thai embassy in Phnom
Penh, Cambodia’s capital, fills early with pedicab drivers shut-
tling old women to market and Thai diplomats greeting local
businessmen with modest bows. But one winter day in :oo,, a
far different crowd gathered outside the Thai mission. For cen-
turies, Thailand and Cambodia have bickered over their bor-
Wielding the Charm I,,
ders, their ancient history of wars and incursions, and their
modern-day politics.
In January :oo, Cambodian newspapers misquoted a
Thai television pop star as calling Cambodians “worms” and
questioning whether Angkor Wat, Cambodia’s gargantuan an-
cient temple complex, should be returned to Thailand, which
controlled the temple at several points in history. Stoked by the
report, and by Cambodian politicians’ anti-Thai comments,
mobs attacked Thai-owned businesses across Phnom Penh,
causing millions of dollars worth of damage and forcing many
Thai citizens to evacuate the city on Thai military aircraft.
20
Hundreds of young Cambodian men ran toward the
Thai embassy, where they smashed through the mission’s glass
doors. Inside, they pulled down pictures of Thailand’s beloved
king, Bhumibol Adulyadej, and stomped on his face. Thai-
land’s ambassador scrambled out the back of the embassy,
hopped over the guard wall, and ran down to the river, where
he escaped the rioters, James Bond style, in a speedboat. Noth-
ing angers a Thai more than an insult to the country’s mon-
arch, who has led Thailand through fifty years of political tur-
bulence. When the Philadelphia City Paper, a local free weekly,
once ran a throwaway advertisement for a local bar portraying
the Thai king as a hip-hop star, the Thai deputy consul in
America warned that the ad could disrupt US-Thai relations,
and Thais from Bangkok deluged the paper’s offices with
angry phone calls and thousands of emails.
21
Not surprisingly, images of Cambodians stomping and
burning the Thai king’s picture infuriated Thailand’s popula-
tion. In response, Thailand moved an aircraft carrier near the
Cambodian border and threatened to send commandos into
its neighbor’s territory. A border war seemed possible. “Cam-
bodia must burn,” one Bangkokian told Time magazine. “This
I,o Wielding the Charm
is the worst incident in international relations between Thai-
land and Cambodia,” Thailand’s prime minister announced.
22
Both countries needed someone to broker their feud, and
Cambodia has poor relations with the United States. So the
two sides turned to Beijing. After the Chinese ambassador in
Phnom Penh issued a statement asking Cambodia and Thai-
land to cool down, Chinese Vice Foreign Minister Wang Yi
called in the Thai and Cambodian representatives in Beijing
and helped them lay out their grievances. In private, several
diplomats told me, the Chinese minister warned the neigh-
bors to normalize relations as soon as possible, or risk anger-
ing China—something neither Cambodia nor Thailand wanted
to do, since both are increasingly reliant on trade and aid from
China. Chastened, the two sides began to patch up their rela-
tionship, with Cambodia’s own king, Norodom Sihanouk, send-
ing a personal apology to the Thai monarch. By March :oo,,
Thailand and Cambodia had reopened their customs posts,
and their relationship had normalized.
23
China has started mediating even more important disputes. In
October :oo:, after a decade of supposedly cooperating with in-
ternational efforts to monitor its nuclear program, North Korea
admitted that it had been secretly enriching uranium. Soon
after, a top North Korean official, Li Gun, took US Assistant
Secretary of State Jim Kelly aside at a meeting in Beijing. Li Gun
nonchalantly informed him that the North, one of the most
closed and unpredictable countries in the world, possessed
nukes and might be willing to sell them to other nations.
24
With few levers to pressure North Korea, and no access to
high levels of dictator Kim Jong Il’s isolated regime, the United
States and North Korea’s Asian neighbors turned to China,
Pyongyang’s longtime ally and major provider of aid, food,
Wielding the Charm I,,
and energy. Beijing pushed North Korea and the United States
to hold bilateral talks. Later China volunteered to host six-way
talks on the North Korean nuclear program involving Beijing,
Moscow, Pyongyang, Seoul, Washington, and Tokyo. The for-
mer US envoy to North Korea, Charles Pritchard, admitted
that without China’s help, there would have been no six-way
talks at all. And when the North Koreans balked at coming to
the table, Chinese officials engaged in rounds of shuttle diplo-
macy to bring them in and also handed North Korea increased
aid. At the same time, top Chinese officials invited Kim to
booming southern China in order to study China’s economic
reforms, potential models for remaking North Korea’s Stalin-
ist economy. To support reform, China stepped up training for
key North Korean bureaucrats, teaching them about modern
economic management.
25
After several rounds of discussions, when North Korea
declared that it would withdraw from the six-party talks, Bei-
jing openly expressed anger with the North. To put more pres-
sure on North Korea, Beijing reportedly shut off an oil pipeline
to Pyongyang for three days in :oo,, then cracked down on
North Korea’s banking in the Chinese territory of Macau.
26
Again, China simultaneously offered new disbursements of aid
to North Korea, and when North Korea tested a nuclear wea-
pon, China agreed to the major step of imposing sanctions on
Pyongyang, temporarily cut off oil exports to North Korea,
and sent a high-level delegation to Pyongyang to try to defuse
the crisis, bringing the North back to the bargaining table.
Beijing wasn’t shy about taking credit for its diplomacy.
“With respect to the nuclear issue on the Korean Peninsula,
China has worked tirelessly with the other relevant parties, and
succeeded in convening and hosting” the talks, noted the :oo,
government white paper on Chinese foreign policy. Even some
I,8 Wielding the Charm
impartial observers agreed. “I think we should really focus on
the positive aspects of [the six-party talks], including the ab-
solutely rightful role of China,” said Aleksandr Ilitchev, a Rus-
sian UN expert on North Korea.
27
Getting Pyongyang to the table helped China’s appeal
with other countries, too. Since the talks began, South Korean
President Roh Mun-Hyun, a former human rights lawyer who
has led Seoul toward Beijing’s orbit, consistently has looked to
China for cues on how to handle North Korea.
28
Asian news
outlets, meanwhile, typically portrayed China as a rational
actor mediating between two angry, unbalanced nations led by
madmen—North Korea and the United States.
Besides mediating disputes, China has utilized its charm in
other positive ways. Over the past five years, as China has de-
veloped a serious heroin problem in parts of the country, it has
worked not only with Burma but also with many other nations
in battling drugs. According to America’s Drug Enforcement
Administration, Chinese authorities “clearly understand the
threat posed by drug trafficking.” Beijing has signed several
UN drug conventions, hosted major multinational meetings
in China on drug control, and started training Asian prosecu-
tors on combating transnational crime like drug trafficking.
Working with Asian neighbors and with the United States, the
Chinese authorities in :oo, busted one of the biggest drug syn-
dicates, an organization known as “I:,.”
29
Beijing also has taken a proactive stance on fighting
trafficking in human beings. “The Chinese authorities . . . have
become relatively progressive on issues of human trafficking,”
says Heather Peters, an expert on trafficking who has worked
for several UN agencies. Peters says the Chinese government
has supported her efforts to teach women in Chinese border
Wielding the Charm I,,
regions about HIV and other sexually transmitted diseases.
Beijing also has put pressure on China’s neighbors to partici-
pate in these educational programs. In :oo¡ China created a
joint effort with Vietnam to fight human trafficking along
their common border—an effort that included educational
campaigns and stepped-up law enforcement.
30
Meanwhile, after facing international criticism in :oo,
for initially covering up the outbreak of SARS disease in China,
an outbreak that soon spread across the world, the Chinese
government has begun using its influence to promote cooper-
ation in fighting dangerous diseases. As avian flu became the
latest potential pandemic to emerge from Asia, Beijing re-
sponded. China vowed to help other countries develop bird flu
early warning systems and to work with international organi-
zations to strengthen quarantines. Later, in January :ooo, China
hosted a global donors’ conference on fighting avian flu.
31
China’s growing soft power also is having some economic
benefits. China’s enormous consumption of resources offers
an opportunity to developing countries, and they are trying to
make the most of China’s needs for oil, gas, minerals, and
other commodities. China now drives trade in Asia, a role the
United States and Japan historically filled, and China’s com-
modity demands are allowing Latin American and African na-
tions to run trade surpluses and potentially use the money to
build stronger social and educational institutions. These sur-
pluses forestall the kind of debt that once crippled many de-
veloping world economies. They have another benefit, too—
feeding China’s economy creates jobs, reducing the kind of
social unrest that in many Latin American countries has driven
migrants north toward the United States.
Even countries facing intense competitive pressure from
Ioo Wielding the Charm
China understand this opportunity. Though Mexico’s indus-
tries compete directly with China’s, a comprehensive opinion
survey taken in :oo¡ shows that few Mexicans worry about
China—“the development of China as a world power rank[s]
at the bottom of the list of threats that Mexicans consider crit-
ical.” Malaysia has run trade deficits with China, but a study
of Malaysian businesspeople found that “in spite of the pur-
ported threats of free trade from China, the majority of the
private sector respondents views China positively.” While Ma-
laysia’s previous prime minister warned, “China is an eco-
nomic threat for Southeast Asia,” the current Malaysian leader,
Abdullah Badawi, an advocate of the China–Southeast Asia
free trade deal, asserted that “Malaysia does not feel threatened
by the emergence of China as an economic powerhouse.”
32
Yet China’s exports also may threaten developing na-
tions’ industries. China’s exports overlap by more than ,o per-
cent with those of countries like Thailand and the Philippines,
foreign investment in developing regions like Latin America
that compete with China fell by half in the early :ooos, and na-
tions like Laos import eight times as much as they export to
China. Since joining the World Trade Organization in :ooI,
China has displaced Mexico as the second-largest exporter
to the United States; nearly ::,,ooo workers in Mexican ma-
quiladoras, factories near the US border, may be endangered
by competition from Chinese manufacturing. One study of
Thailand-China economic relations found that Thailand al-
ready runs a trade deficit with China of more than $I billion
annually, and Vietnam’s Ministry of Trade warns that the
country’s trade deficit with China will soon top $: billion.
33
In the long run, developing nations may become less san-
guine about trade with China if leaders perceive Beijing as an
unfair competitor, due to China’s labor practices, dumping, un-
Wielding the Charm IoI
dervaluation of its currency, and state support for certain in-
dustries. China’s labor costs in producing clothing, to take one
example, are roughly one-half Mexican labor costs.
34
Many of
China’s overseas investments are made by state-owned compa-
nies, which do not necessarily have to prove their profitability
to shareholders. And though cheap Chinese goods are wel-
comed by some poor consumers in the developing world, who
cannot always afford Western products, Chinese companies
have been accused of dumping low-quality, sometimes pirated
goods on markets across Africa, Latin America, and Southeast
Asia, taking a loss at first in order to win market share.
Some foreign leaders are beginning to respond. In Octo-
ber :oo, Brazil’s foreign minister told reporters that Brazil has
not reaped the new investment from China it had expected
when it granted Beijing market economy status, and Argentine
leaders expressed frustration that imports from China were
growing at more than three times the rate of exports to China.
In response, Argentina’s government imposed new nontariff
barriers on categories of Chinese imports. In fact, though the
international financial press has highlighted European Union
and US actions against Chinese exports, nearly two-thirds of
trade investigations against China in :oo, actually were initi-
ated by developing countries. Brazil alone has imposed at least
twenty antidumping clauses and safeguards against categories
of Chinese exports. In Ecuador the government has passed
laws to limit Chinese investment, and potential competition
from China was a reason why Central American nations signed
a :oo, free trade agreement with the United States, since they
believed that it might entice some garment companies to keep
production in the hemisphere rather than switching to China.
35
Similar complaints have begun to surface in Asia and
Africa. Though China has promised that trade would be a win-
win proposition, like other major powers it also has tried to
Io: Wielding the Charm
protect its own population from some of the negative effects of
slashing trade barriers. Even as Chinese agricultural products
flood into Thailand, Thai farmers have faced difficulty selling
their products to China, encountering high value-added taxes
and other obstacles. “Breaking into China’s market is not as
easy as some might think,” admitted one Thai academic study-
ing Thailand-China trade relations. Across northern Thailand,
farmers now question whether it was wise to sign a free trade
deal with Beijing, and farmers, textile companies, and small
manufacturers in Vietnam, Cambodia, Malaysia, and Indone-
sia express the same fears of trade with China.
36
This difficulty of trading with China, and the suspicion
that China is acting rapaciously, may be seeping into local per-
ceptions of Beijing. In Nigeria militants in the Niger Delta
have warned Chinese investors that they will be “treated as
thieves” robbing Nigerians of their valuable oil resources—a
charge the militants previously laid against Western compa-
nies. In the Nigerian commercial capital of Lagos, police have
begun expelling recent Chinese migrants from local markets
because Nigerians complained that Chinese goods are under-
cutting local products. In Zambia the populist politician Mi-
chael Sata has rallied support among the poor by claiming that
Chinese imports are undercutting Zambian products, while
Zambian companies cannot export any finished goods to
China. “Chinese investment has not added any value to the
people of Zambia,” Sata declared. Responding to his rhetoric,
Zambians have targeted Chinese shops in Lusaka, the capital.
37
China’s growing soft power also could lead it to export its envi-
ronmental problems. Within China, environmental protection
is almost nonexistent, and despite a government campaign for
more sustainable development, most officials, focused on keep-
ing up growth rates, care little about the ecological conse-
Wielding the Charm Io,
quences of construction and industrialization. As the China
environmental expert Elizabeth Economy has revealed, Bei-
jing has demonstrated little commitment to river and water-
shed preservation within China, destroying the Yangtze River
and other major waterways. Two-thirds of Chinese cities fail
World Health Organization standards for air quality, by far the
worst rate of any large country. Several cities rank among the
highest rates of airborne carbon monoxide in the world.
38
This environmental recklessness spreads across borders
as China’s global influence grows. Ten years ago, China’s envi-
ronmental mismanagement was a problem for a citizen of pol-
luted Lanzhou city or someone living along the Yangtze; today
it is a threat to citizens in Burma or someone living along the
Amazon. Besides the logging of its neighbors, China may fund
a massive Burmese dam that could proceed without adequate
environmental studies, and China’s Export-Import Bank re-
portedly declines to sign environmental guidelines commonly
adopted by credit providers from Western countries. In north-
ern Laos, according to a consultant with the Asian Develop-
ment Bank, a major aid donor, Chinese firms tasked to build
part of the country’s new highway simply refused to produce
any environmental impact assessment. “The Chinese just went
ahead and did their part of the road, without any assessment,”
said the consultant, who worked on the highway, “They would
just never talk to me.”
39
China also has ignored fears about the impact of Chinese
dams on the Mekong River—Beijing has silenced critics, and
continued building dams and blasting parts of the river. While
China stalls, scientists estimate that fish catches in part of the
river have fallen by half; the giant Mekong catfish, a monstrous
creature that can top six hundred pounds, soon may become
extinct. Whole stretches of the Mekong, which must support a
Io¡ Wielding the Charm
growing human population that could double within thirty
years, are becoming too dry for farming.
40
In its aid, infrastructure building, and business deals,
China also demonstrates little respect for transparency and
other aspects of good governance. In other words, how Chi-
nese companies act at home reflects how they may act over-
seas. In Cambodia local activists accuse both the Cambodian
government and Wuzhishan LS, a Chinese state–linked firm,
of forcing hundreds of villagers off their land in a Cambodian
province called Mondulkiri, and replacing them with large-
scale agriculture. Critics contend that Wuzhishan then sprayed
the area, which includes ancestral burial areas, with dangerous
herbicides. “The government and the company have disre-
garded the well-being, culture, and livelihoods of the . . . in-
digenous people who make up more than half the population
of the province,” announced the United Nations’ special repre-
sentative for human rights in Cambodia.
41
Wuzhishan’s behavior so infuriated locals that despite
the Cambodian government’s usual rough treatment of dem-
onstrators, villagers took to the roads in Mondulkiri to protest.
Five hundred villagers tried to march to the local capital to pe-
tition the governor, while another pack of six hundred launched
a demonstration. Local police officers fired water cannons into
the crowd, knocking several women unconscious. One group
of Mondulkiri ethnic minority protesters even seized Wu-
zhishan’s trucks and blockaded roads with old tree branches,
backing off only after Cambodian police armed with AK-¡,s
threatened to jail them.
42
More generally, the state-led business model China suggests to
the developing world could undermine the rule of law in
Africa or Latin America or poorer countries in Asia. To be sure,
Wielding the Charm Io,
American or European or Japanese companies also sometimes
abdicate corporate responsibility, cook their books, or hand
out bribes. And some Chinese companies operate transpar-
ently at home and abroad, install quality management, and
practice corporate responsibility. China’s true private sector,
that group of companies without ties to the state, boasts sev-
eral high-quality multinationals that operate with real over-
sight and modern corporate boards.
But for the most part, Western and Japanese firms are
private companies separate from their governments. These
companies have some degree of accountability to their share-
holders and boards, offer the public information about their
environmental and labor practices, and can be sanctioned,
whether by America’s Foreign Corrupt Practices Act or similar
legislation in other countries, by the media, or by democrati-
cally elected legislatures. When Enron collapsed in a mountain
of supposed fraud, American prosecutors indicted its cor-
porate leadership, and the US Congress passed tougher laws
on corporate accounting policies. When the US oil company
Unocal allegedly contributed to forced labor in a pipeline in
Burma, Burmese villagers affected by the oil project sued Uno-
cal in an American court and won a settlement from the com-
pany estimated at more than $,o million.
43
Chinese firms generally do not operate under the same
burdens of oversight. As Minxin Pei of the Carnegie Endow-
ment has found, the Chinese state and state-linked companies
still account for nearly ¡o percent of China’s Gross Domestic
Product, control more than ,o percent of industrial assets, and
dominate more than oo percent of the financial sector. Chinese
firms with state links often display poor corporate governance,
including a lack of transparency. China’s own official news
agency revealed in :oo¡ that some four thousand corrupt offi-
Ioo Wielding the Charm
cials had fled the country, carrying with them $,o billion in
state money.
44
Chinese courts and prosecutors rarely apply the
kind of scrutiny to Chinese firms that the United States did to
Enron; according to Pei, one study of twelve thousand Chi-
nese, across several provinces, found that people perceived
China’s judiciary to be one of the five most corrupt public in-
stitutions in the country.
Yet at least Beijing has to play by some rules. Constrained
by its need to demonstrate rule of law in order to maintain
China’s attractiveness to investors, Beijing has managed to
prosecute the most egregious white-collar criminals in China,
like senior officials at the Bank of China accused of stealing
nearly half a billion dollars.
45
Driven by the need to keep the
population placated through consistent economic growth, and
unable to repress all interest groups in such a large and diverse
country, Chinese officials have used the state-dominated
model of development to do considerable good. Though cor-
ruption ravages Chinese officialdom, the central government
and provincial governments have used enough of the state’s
wealth to pull hundreds of millions of people out of poverty.
In the poorest parts of Africa, Asia, and Latin America—
where the rule of law often simply doesn’t exist, the media are
far less sophisticated than Chinese financial publications, eco-
nomic policy makers are not insulated from politics, and lead-
ers have no problem stealing all, rather than part, of the state’s
wealth—the state-dominated China model of development
could be an invitation to disaster. In parts of Africa, Asia, and
Latin America, the China model could be an entrée for already
rapacious governments to act even worse. In Indonesia, for ex-
ample, one reason why Chinese companies have success win-
ning deals, admits an oil executive, is that the Chinese compa-
nies basically bribe whomever they need to pay. This behavior
Wielding the Charm Io,
only adds to graft in one of Asia’s most corrupt nations—an-
gering local good-governance activists, who then blame China
for their problems.
46
The small Peruvian town of San Juan de Marcona, an old port
on the Pacific long since bypassed by larger harbors, offers a
window into some of the problems that occur as China exports
labor and environmental policies to poor nations. In I,,:–
I,,,, Shougang International Trade and Engineering, a Chinese
state steel company, purchased Hierro de Peru, a state-run iron
mine near San Juan de Marcona, for roughly $II8 million. At
first, residents of San Juan de Marcona, a town of thirteen
thousand people, welcomed the Chinese company’s invest-
ment, sure that it would revitalize the dismal economy in the
town, some two hundred miles away from the capital, Lima.
The Chinese company promised to invest $I,o million in the
mine to modernize its facilities.
47
The locals’ delight soon faded. Even as Shougang’s profits
rose due to strong prices on the international market for met-
als, the company did little to improve the mine or its safety fa-
cilities, spending only $,, million. The mineworkers in San Juan
de Marcona began to complain. They complained about seri-
ous environmental problems, like Shougang’s alleged dumping
of chemical waste in the nearby ocean, killing the fish around
town that provided a source of protein. They complained about
lax safety standards, charging that the mine lacked safety har-
nesses and workers suffered many accidental electrocutions.
They complained about their dismal pay. “Shougang has turned
us into slaves,” one local told a reporter, complaining that her
husband worked fifteen hours per day at the mine for roughly
fourteen US dollars, less than half the average miner’s salary
in Peru.
48
Io8 Wielding the Charm
The Peruvian government began to investigate. Peru’s
Labor Ministry recorded I,o accidents, including two fatal
ones, at the mine in one year alone. Peru’s government slapped
a $I¡ million fine on Shougang for failing to spend the money
to improve the mine. The company paid the fine, but its man-
agers still didn’t improve working conditions, probably be-
cause paying fines seemed cheaper than spending money to
upgrade. Shougang had no background experience of dealing
with protests or unions, and the Peruvian government would
not take more steps to punish the company. “There is a culture
problem,” Peru’s minister of mines told Reuters. “The Chinese
managers see their way of doing things as discipline, while the
workers see it differently.”
49
Eventually, the relationship between the miners and the
company deteriorated so badly that the employees could not
control themselves. Starting in :ooI the miners began going on
strike nearly every year; at some points, more than one thou-
sand strikers demonstrated at one time. In :oo¡, a year when
Shougang’s parent earned a record profit of $I,o million, the
strikers blocked local roads accessing the mine, asking for a
raise of eighty-five cents per day and better safety conditions.
Some angry locals reportedly covered the town’s walls in anti-
Chinese graffiti and threatened the mine’s management.
50
The
following year, strikers again walked out of work, this time
complaining that the company, which is supposedly respon-
sible for providing water to the town, paid for only four hours
of water per day.
The miners’ activism got them nothing. When their labor
unions protested too much, Shougang simply fired them. To
fix their problem, the company brought in imported laborers
from China to replace them, a common practice among Chi-
nese companies investing overseas. Or it hired temporary Pe-
Wielding the Charm Io,
ruvian workers, whom it employed without offering them any
benefits at all.
51
Exporting China’s own poor standards on labor issues, the en-
vironment, and corporate governance could foster blowback
against Beijing in many other countries: in one ranking of
eighty nations’ adherence to corporate responsibility, China
placed sixty-sixth, below other developing economies like
India.
52
The Chinese government probably realizes this, one
reason why China recently has hosted high-profile meetings
on issues like corporate responsibility, such as the United Na-
tions Global Compact Summit in Shanghai in November :oo,.
Foreign opinion leaders and the general public realize
that China could export its domestic problems, a recognition
that could limit China’s soft appeal. Local workers have pro-
tested Chinese firms’ labor policies not only in Peru but also in
South Africa, the Pacific Islands, and Zambia, where one miner
told reporters that his Chinese managers “make me work seven
days a week [and] pay me $,o a month.” In South Africa trade
unions have warned the government that it must control Chi-
nese investment, and trade union leaders tore off their T-shirts
during a meeting when they discovered that the shirts had
been manufactured in China, thus potentially in factories with
minimal labor standards.
53
Foreign populations also recognize Chinese firms’ low
safety standards. In Zambia, where a Chinese firm runs the
Chambishi copper mine, and where locals had been overjoyed
that the company had revitalized Chambishi’s decrepit infra-
structure, forty-nine miners died in an accident in April :oo,.
Soon after, the dead miners’ families complained that they
had received no compensation at all, and Chambishi’s Chinese
managers stayed away from the men’s funerals for fear of being
I,o Wielding the Charm
attacked. “The Chinese don’t put safety concerns . . . as that
important,” one professor at the University of Zambia told the
Chicago Tribune.
54
Though China’s demand for resources is powering some
African and Asian and Latin American economies, local opin-
ion leaders also recognize the potential environmental conse-
quences, like the deforestation of Southeast Asian nations like
Indonesia and Burma, and African nations like Gabon. In
Thailand, Laos, and Cambodia, activists and some politicians
have aggressively campaigned against China’s damming of the
upper portions of the Mekong River, while Filipino activists
have launched a campaign against China’s poor environmen-
tal standards in mines it has purchased in the Philippines. In
Brazil, nongovernmental organizations like Amazon Watch
warn that Chinese investments could damage Amazonian in-
digenous groups and their native environments.
55
Even as China’s corporate governance could undermine labor
and environmental standards in other countries, China’s aid
policies could undermine efforts by Western governments
and international financial institutions to demand better gov-
ernance and environmental regulation from aid recipients.
Led by the World Bank, international development special-
ists have moved toward an aid model that distinguishes be-
tween governments that fight corruption and those that do
not. This model tries to impose some transparency, so that
aid benefits a wider spectrum of people in the developing
world. America’s Millennium Challenge Corporation, which
offers aid to countries that “rule justly, invest in their people,
and encourage economic freedom,” offers one example of this
trend. The World Bank’s anticorruption strategy, a priority of
new bank President Paul Wolfowitz, offers another example
Wielding the Charm I,I
of this trend of setting more stringent conditions before grant-
ing aid.
56
Committed to this new, tough aid model, in late :oo¡ the
World Bank threatened to suspend hundreds of millions of
dollars worth of assistance to Cambodia because of Phnom
Penh’s allegedly rampant corruption and its crackdown on
civil liberties. The United Nations’ special representative in
Phnom Penh warned of an “increasingly autocratic form of
government and growing concentration of power in the hands
of the prime minister.”
57
Five or ten years ago, Cambodia would have had to com-
ply with the World Bank and the donors’ demands. Not now.
“Western governments would like to use their assistance to
[Cambodian Prime Minister] Hun Sen to put pressure on Hun
Sen, so he turns to the Chinese,” said Sokhem Pech, a leading
Cambodian academic. Beijing then rewards Hun Sen. On a visit
to Cambodia in April :ooo Chinese Premier Wen Jiabao prom-
ised Phnom Penh $ooo million worth of loans and grants.
Meanwhile, the World Bank did not cut Cambodia off, per-
haps because it feared that it would then have no influence in
the country. Foreign diplomats in Cambodia say that Western
donors now feel they have no choice but to continue assisting
the Cambodian government in order to maintain some lever-
age over Phnom Penh’s human rights record and political fu-
ture. Similarly, in neighboring Laos, after the World Bank con-
sidered withholding support from a new dam project called
Nam Theun : because it could potentially destroy the local en-
vironment, China made it clear that it would help finance the
dam instead. Worried that China’s backing could result in an
environmental disaster, the bank agreed to support the dam.
58
Africa, the biggest recipient of foreign assistance, has become
perhaps the most glaring example of the potentially corrosive
I,: Wielding the Charm
consequences of Chinese aid. After Western donors withdrew
aid from the autocratic government of the Central African Re-
public in :oo, following a coup, China stepped in, providing
key assistance to the regime.
59
As a result, the Central African
regime has been able to tighten its rule.
Eventually, this Chinese assistance could lead average cit-
izens in Africa, and in other regions, to question whether Bei-
jing really is a power that does not interfere in nations’ affairs.
After all, if China uses its influence to support elites in coun-
tries like the Central African Republic or Cambodia, to the
detriment of average people, it is very clearly interfering.
Beijing’s assistance has proven even more critical in the
southwest African nation of Angola, where China’s demand
for resources, foreign aid, and commitment to noninterference
all come together. During three decades of civil war, a tiny elite
in Luanda, Angola’s capital, siphoned off revenues from the
country’s oil deposits, the second-largest in Africa. The elites
holed up in Luanda’s seaside mansions, ringed with barbed
wire and protected by private security companies, and they
used the oil money to fund the ongoing conflict and line their
own pockets. Meanwhile, most of Angola’s twelve million citi-
zens lived in dire poverty, earning less than two dollars a day
and surviving in shacks made from tin and old bricks and scrap
metal, built on top of each other across Luanda’s shantytown
sprawl. One corruption watchdog, Global Witness, reported
that one-third of Angola’s state revenue goes missing, essen-
tially meaning that it has been siphoned off. An Angolan news-
paper found in :oo, that the nation’s president, José Eduardo
dos Santos, had somehow become Angola’s richest man.
60
In :oo: Angola’s government and the rebels finally laid
down their arms, paving the way for free, competitive elections
in the future. Peace also offered an opportunity for foreign aid
organizations to get back into the country and help rebuild the
Wielding the Charm I,,
shattered social services and decrepit oil infrastructure. To en-
sure that Angola used aid money wisely, the International Mon-
etary Fund tried to force the government to agree to provisions
that would slash graft and improve economic management.
61
Angolan government ministers at first seemed receptive
to loans linked to intensive, on-the-ground monitoring by
IMF staff designed to ensure that the aid and oil money actu-
ally got plowed into social programs. Angola even promised
to join Britain’s Extractive Industries Transparency Initiative
(EITI), a program designed to monitor how resource wealth
gets spent. By the beginning of :oo, IMF officials had reason
to believe that they stood on the verge of a financing agree-
ment with the country.
62
At the last moment, the Angolan government broke off
talks with the IMF. China had stepped in, offering Angola loans
and credits for reconstruction that may be worth as much as
$o billion. The Chinese money came with no conditions for
accountability—only an agreement to use Chinese firms for
the reconstruction—and no demands like the EITI program.
63
For the Angolan leaders, though perhaps not for average
Angolans, China’s policies jibe with their own disdain at West-
erners trying to tell them what to do. (One reporter for the
Financial Times remembered an executive at Angola’s state-
owned oil company ranting at him after the journalist asked
a question about transparency.)
64
International corruption
watchdogs warn that the Chinese assistance, given with no
conditions, will allow the Angolan government to revert to its
old habits, skimming the petroleum cream for itself. Already
Angola has backed off its EITI commitment and postponed
a mission by the World Bank designed to teach the country
about transparency.
Some of the Chinese cash may even go directly to the
I,¡ Wielding the Charm
government, funding progovernment propaganda in advance
of the national election—and offering a sign to other African
leaders of what they can get by joining up with Beijing. “The
African [leaders] are very welcoming of the Chinese,”the South
African economic analyst Dianna Games told reporters. “They
feel it’s easy money. In Angola in particular, the Chinese don’t
ask many questions.”
65
Wielding the Charm I,,
IX
America’s Soft Power
Goes Soft
ven as China has wooed the world, America has alien-
ated many of its oldest friends. Australia, where legis-
lators jeer President Bush, is but one example. In the
:oo, BBC poll of twenty-two nations, not only did
¡8 percent of people believe that China’s role in the world was
mainly positive, only ,8 percent thought the United States had
a positive influence on the world, about the same number as
for Russia, a near-authoritarian regime run by a dour former
KGB man. The follow-up BBC poll in :ooo displayed similar
results. In some of these nations, Osama bin Laden enjoyed
higher favorability ratings than the United States—a trend
that led former US Ambassador to the United Nations Richard
Holbrooke to wonder, “How can a man in a cave outcommu-
nicate the world’s leading communications society?”
1
Although China’s soft power rise does not depend on an
American soft power decline, plummeting American appeal
could contribute to China’s growing appeal. But before we ex-
amine, in the next chapter, how China’s appeal can affect the
United States, we must understand why and how America’s
brand has been tarnished. The tarnishing began in the I,,os,
after the United States had vanquished the Soviet Union in the
Cold War and seemed at the peak of its power. The trend be-
came worse after :ooI—so bad that dislike for American pol-
icy has often mutated into hatred of American culture, people,
and companies, and, sometimes, American values themselves.
After the fall of the Berlin Wall, America seemed to have no
competitor for global soft power. Representative democracy
and free-market capitalism were now spreading throughout
the world, and leaders of newly democratic countries looked
to the United States for cues on how to build their political sys-
tems. President Bill Clinton, the symbol of US-style democ-
racy, was welcomed overseas like a rock star, as on a trip to
former enemy Vietnam, where the president waded through
crowds of jubilant Vietnamese as if he were the pope.
2
America’s rivals couldn’t keep up. The former Soviet
Union was preoccupied with itself—disintegrating into chaos
and discovering capitalism and democracy, all at the same
time. China remained weak and, in the wake of the Tiananmen
crackdown, had become a pariah in much of the world. The
European Union struggled to unite with the former commu-
nist Eastern European nations. Though Japan had built itself
into an economic colossus, Japanese culture, outside of its
business models, had little impact on the wider world. (Today,
with Japan in economic decline, its culture actually has be-
come more popular internationally.)
Meanwhile, American companies’ dominance in infor-
mation technology powered the US economy and placed US
businesses at the leading edge of the I,,os Internet revolution
America’s Soft Power Goes Soft I,,
and of the process of international integration that came to
be called globalization. American music, film, and television
dominated local markets in nations ranging from India to In-
donesia. English was becoming the universal language of bus-
iness, and companies around the globe copied American man-
agement style, shareholder capitalism, and other corporate
practices.
But with the Cold War won, Americans seemed to look
inward, as if tired of the world’s burdens. For nearly a decade,
America turned to its own problems, debated its own culture,
and feasted on its own scandals, highlighted by the Clinton
impeachment trial. “Since World War II, America has accumu-
lated huge, huge reservoirs of goodwill all over the world,” said
Kishore Mahbubani, Singapore’s former ambassador to the
United Nations and one of the world’s most respected foreign
policy thinkers. In part, Mahbubani believes, America built
this goodwill by serving as a beacon of morality and democ-
racy. In part, it built this goodwill by leading in the creation of
institutions during the Cold War, like the United Nations, de-
signed to integrate the United States with the globe and to cre-
ate a multilateral order in trade, aid, and diplomacy. “But, un-
fortunately, at the end of the Cold War, when there was a
massive opportunity for America to take advantage of these
reservoirs of goodwill to build a better world, America did the
opposite thing: it walked away from the world,” Mahbubani
continued.
3
The numbers do not lie. Throughout the I,,os the White
House and Congress slashed programs that had bound Amer-
ica to the world. Washington hacked up the Foreign Service
and stopped paying America’s share in international institu-
tions like the United Nations. Several blue ribbon studies re-
vealed that the US government cut funding for foreign affairs
I,8 America’s Soft Power Goes Soft
programs from more than $, billion in I,,¡ to $,.o¡ billion in
:ooo. Because of this, from I,,¡ to I,,, the State Department
could replace only ,, percent of the staff it lost through retire-
ment, resignation, and death. According to one report, these
cuts resulted in “decrepit facilities” at US embassies that put
American diplomacy “near a state of crisis.”
4
Washington eviscerated US public diplomacy, the gov-
ernment-funded programs designed to influence public opin-
ion abroad. State Department international exchange pro-
grams had introduced future foreign leaders like Afghanistan’s
Hamid Karzai to the United States. Libraries and American
Centers operated by the United States Information Agency
(USIA) had offered foreigners a window into American soci-
ety. US government–sponsored tours by artists and musicians
had brought jazz, Pop art, and many other American trends to
foreign audiences. Now Washington was destroying those suc-
cess stories. “We cut out a lot of what we do well,” admitted
Lloyd Neighbors, a former public affairs officer at many Amer-
ican embassies. “We wound up closing our United States Infor-
mation Service libraries.” Indeed, State Department funding
for educational and cultural exchange programs declined every
year between I,,, and :oo:. By the late I,,os the United States
Information Agency, once the main outlet of public diplo-
macy, had roughly half as much staff as it had in the I,oos.
5
American leaders also turned away from Washington’s
commitment to multilateralism. The United States failed to
ratify the Kyoto Protocol or the International Criminal Court,
and President Clinton did not expend much political capital
trying to push for their ratification. This was an initial sign
that the United States would no longer support the multilat-
eral institutions it had helped create after the Second World
War. At the same time, the Clinton administration refused to
America’s Soft Power Goes Soft I,,
intervene in the genocide in Rwanda, further undermining
Washington’s credibility as a moral actor. That the world’s sole
remaining superpower would not lift a finger to help in times
of great crisis, even as it slapped sanctions on nations like
Burma and Pakistan, created a legacy of resentment. America
had put itself in the worst possible position, appearing de-
manding of other nations but unwilling to provide the world
with help or moral leadership.
Worse, as democracy swept through the world, the
United States did not embrace many of the actors newly em-
and Africa made the transition to democracy, conservative
elites, many of whom had studied in the United States, could
no longer dominate politics. Long-suppressed popular move-
ments, from indigenous groups in Latin America to religious
parties in Turkey, came to the fore, gaining power at the ballot
box. The United States could have worked to gain the trust of
these new actors. It could have leveraged the fact that Amer-
ica’s democracy promotion had helped empower them. In-
stead, Washington chose to continue dealing primarily with
elites in most developing nations, who tended to be more con-
servative, even repressive.
Later, during the Bush administration, this ignorance of
how democratization had changed other nations’ relations
with America would come back to haunt the White House.
Democracies like Chile and Turkey would prove accountable
to their own people—people who did not want to support the
war in Iraq and other White House objectives.
This retreat from the globe seemed to enjoy popular support
among the American public. Numerous studies showed de-
clining interest among Americans in global events and foreign
I8o America’s Soft Power Goes Soft
aid: polls taken in I,,, and I,,, revealed that just one out of
eight Americans thought that the United States should be the
globe’s single leader. Despite the fact that much of the United
Nations’ peacekeeping force is staffed with soldiers from low-
income countries, in a poll of Americans taken in I,,, by the
Program on International Policy Attitudes (PIPA), the major-
ity of respondents were convinced that America offered more
than its fair share of troops to United Nations peacekeeping.
6
During the Clinton years, the White House did pay close
attention to one element of foreign policy—international eco-
nomics. Clinton seemed personally fascinated by economic
globalization, and his top economic policy makers, like Trea-
sury Secretaries Robert Rubin and Larry Summers, were at-
tuned to international business, finance, and trade. But Amer-
ican intransigence on many free trade initiatives fostered ill
will abroad. American business leaders and politicians seemed
to ignore fears that, because of globalization, US film and
media and consumer products would overwhelm local indus-
tries. The free market–oriented, neoliberal economic model
promoted by the United States and by Washington-based in-
ternational financial institutions failed to deliver strong growth
to many poor nations. “The I,,os turned into a period of se-
vere disappointment as free markets led to rampant corrup-
tion and unfulfilled expectations in Latin America,” argues
Cynthia Watson, an expert on Latin America at the National
War College.
7
Across the world, as America’s cultural and corporate
power grew unchallenged, many average citizens began to see
globalization essentially as Americanization. If they saw it this
way, they often viewed American-led globalization as a threat
to their societies and national identities—one reason why the
antiglobalization activist José Bové became an overnight ce-
America’s Soft Power Goes Soft I8I
lebrity in I,,, by smashing up a McDonald’s franchise in the
French town of Millau. Of course, even as they worshiped
Bové, the French remained among the world’s biggest con-
sumers of Ray Kroc’s products—the kind of schizophrenia
and desire for American products and culture that could even-
tually allow the United States to rebuild its global soft power.
8
Some foreigners also linked globalization with unwel-
come elements of the United States’ social model, including
laissez-faire capitalism. This fear of adopting American-style
socioeconomic models grew as ever fewer foreigners perceived
the United States as a meritocracy—perceptions sparked by
Americans’ late-I,,os worship of the stock market and Inter-
net start-ups at a time when much of the developing world was
facing financial crises.
9
These perceptions would only grow
stronger in the :ooos. Foreigners first witnessed revelations of
American executives living plutocratic existences while aver-
age American workers’ incomes stagnated, then, in :oo,, saw
the savage poverty revealed by Hurricane Katrina.
By the end of the I,,os nations also had other models to
look toward—other models of successful development. Dur-
ing the Cold War, the United States had held itself up in con-
trast to the Soviet Union, whose totalitarian system and stag-
nant economic development made America look more efficient
and successful. With the Soviet Union gone, the “American
Dream” was matched up against other models, like China and
the European Union, not against the villainous USSR.
As the I,,os came to a close, then, the United States had
squandered many of its Cold War gains, though it remained
more popular than it is today. Too many foreigners no longer
noticed US foreign aid: one study of Moroccans showed that
“older focus group members recalled US food aid and libraries
in their youth, but they said no one sees US aid now.”
10
The
I8: America’s Soft Power Goes Soft
fear of American-led globalization exploded, resulting in vio-
lent anti-US and antiglobalization protests at meetings of the
International Monetary Fund, the World Trade Organization,
and the World Bank in places like Quebec City, Genoa, and
even in the United States—in Seattle in I,,,.
Since :ooI America has turned this resentment against the
United States into outright anger. Shifting from the neoisola-
tionism of the I,,os, the White House has become intensely
engaged with the world. But in the process, it has alienated
many former friends and sparked worries about Washington’s
excessive involvement in other nations’ affairs.
To start with, tough security measures launched in the
wake of September II made it harder for foreigners to obtain
American student, work, and tourist visas, or to apply for po-
litical asylum in the United States. No one doubts that Amer-
ica had to bolster security after September II. But tighter secu-
rity was bound to alienate foreigners. The cost of applying for
a US visit visa quintupled between I,,8 and :oo¡, and new se-
curity restrictions slowed reviews of visa applications. Not sur-
prisingly, the State Department’s refusal rates for all forms of
visas rose between :ooo and :oo,.
11
The security measures were understandable, but the
White House made significant mistakes in public diplomacy.
Under an increasingly partisan board of governors, the Bush
administration prodded Voice of America, long the flagship of
US broadcasting abroad, to become less impartial. Manage-
ment demoted Voice of America’s news director, a move some
at VoA suspect was punishment for the director’s refusal to air
positive coverage of the war in Iraq. This demotion threatened
VoA’s image as an impartial news broadcaster. Meanwhile, the
administration’s new broadcasting efforts, like Radio Sawa, a
America’s Soft Power Goes Soft I8,
pop music station aimed at average people in the Middle East,
failed to have much impact on Middle Easterners’ opinions of
America, because they shied away from serious news. “Radio
Sawa has failed to present America to its audience,” argued a
draft report by the State Department’s inspector general ob-
tained by the Washington Post.
12
More broadly, the administration did not develop an ef-
fective public diplomacy strategy, even more important in an
age when globalization can instantly spread rumor and anti-
American sentiment around the world, and when tight secu-
rity measures at American embassies overseas make it even
harder for US diplomats to meet foreigners and promote
America’s appeal. When I visited the US embassy in Jakarta,
where the mission indeed faces a serious terrorist threat, I
passed through rings of barbed wire, barriers, and numerous
security checks to meet my contact, who had had to preclear
me for entry the day before.
Ultimately, though most American diplomats joined the
Foreign Service to meet people in other countries, security
measures will only put them at an increasing disadvantage
compared with diplomats from countries that do not feel as
threatened by terrorism. The war on terrorism also stretches
the US Foreign Service, since it must staff large missions in
Iraq, Afghanistan, and other hotspots in the war on terror. “It
didn’t help that the US didn’t have an ambassador in Australia
for eighteen months [between :oo¡ and :ooo], even while the
Chinese were making inroads,” said Allan Gyngell, a former
senior policy adviser to the Australian prime minister.
13
There was no shortage of warnings: every think tank and
advocacy group in Washington seems to be issuing reports on
how to improve America’s image abroad. Reported the Gov-
ernment Accountability Office, the US government watchdog,
I8¡ America’s Soft Power Goes Soft
“Public diplomacy efforts generally lacked important strategic
communication elements. . . . These elements include having
core messages, segmented target audiences, [and] detailed stra-
tegies and tactics.”
14
The White House realized that it needed one figure to
command public diplomacy. But by :ooo the Bush adminis-
tration already had picked its third public diplomacy czar, the
White House confidante Karen Hughes. The first two public
diplomacy czars, the advertising executive Charlotte Beers and
the longtime diplomat Margaret Tutwiler, quit after short ten-
ures. Once in place, Hughes embarked on “listening tours,”
primarily in the Muslim world, in which she preached about
America but did strikingly little listening. When confronted
with difficult situations amid skeptical foreigners, Hughes just
resorted to platitudes, informing a Turkish audience, “I am a
mom, and I love kids. I love all kids.”
15
To its credit, at least the Bush administration has tried to
revive the Foreign Service and foreign aid. The White House
has developed an innovative new program for delivering aid
to well-governed poor nations, the Millennium Challenge
Corporation. Though the first MCC head appointed by the
administration, Paul Applegarth, was criticized for his poor
management, the MCC at least demonstrated to developing
nations that America was back in the aid game. Meanwhile,
Secretary of State Condoleezza Rice decided upon an ambi-
tious restructuring of the US Foreign Service. Under the re-
alignment, Rice would shift some one hundred Foreign Ser-
vice officers away from overstaffed but comfortable posts in
Western Europe and place them in important, if less comfort-
able, developing countries. She also vowed to reopen many
one-person Foreign Service missions in important outposts of
the developing world, like Alexandria, Egypt, and Medan, a
America’s Soft Power Goes Soft I8,
provincial city in Indonesia. Just having one US diplomat on
the ground in these places could prove vital for extending the
American government’s presence.
16
Washington’s near-exclusive focus on terrorism in the
years after September II only adds to alienation overseas. In
a small number of foreign countries seriously threatened by
terrorism, such as Israel and Singapore, this focus on terror
makes sense. But in many countries where terrorism is not a
threat, an almost exclusive focus on counterterrorism by the
world’s biggest power, which should be able to focus on many
issues at once, seems unwise. At meetings of the Asia Pacific
Economic Cooperation (APEC) group in Chile in :oo¡ (APEC
includes several Latin American nations), President Bush fo-
cused on counterterrorism cooperation and weapons of mass
destruction. Yet most APEC nations, like Chile, have only lim-
ited interest in terrorism issues, and APEC originally was sup-
posed to just discuss issues of economics and business. So the
president’s focus at these APEC events, and at many other
summits, befuddled some foreign opinion leaders. As the Ma-
laysian lawyer and columnist Karim Raslan told the New York
Times, Washington’s “obsession” with terrorism had become
irrelevant to average people in Asia. “We’ve all got to live, we’ve
all got to make money,” Raslan told the Times. “The Chinese
want to make money, and so do we.”
17
Meanwhile, the White House and Congress ignored eco-
nomic globalization, an ignorance symbolized by tin-eared
treasury secretaries and congresspeople transforming the war
on terror into economic demagoguery, for example, by at-
tempting to block a Dubai company from operating six US
ports, though there was no evidence this would compromise
security. When Chile’s neighbor, Argentina—held up as an
example of neoliberal economics during the I,,os—melted
I8o America’s Soft Power Goes Soft
down into an economic crisis in :ooI and :oo:, the Bush ad-
ministration did not respond. Instead, the White House poured
scorn on the Argentines. “They have been off and on in trouble
for seventy years or more,” Treasury Secretary Paul O’Neill re-
marked about Argentina. “Nobody forced them to be what
they are.”
18
On a one hundred–degree day in Phnom Penh in January
:ooo, I saw firsthand how the US government’s lack of inter-
est in economic globalization and its focus on terrorism was
costing America friends. Outside one of the offices of Cam-
bodia’s Ministry of Commerce, I met Mean Sophea, a squat
middle-aged man with small eyes and a broad forehead. It
was a weekend, but he had been rushing from meeting to
meeting, and now he dabbed his slick forehead with a mound
of paper napkins.
19
Mean was in charge of trade preferences in the Cambo-
dian Ministry of Commerce, which meant that he was one of
the people responsible for studying how tiny Cambodia could
compete in the global economy. He had few resources at his
disposal; he kept all statistics on Cambodia’s textile exports on
a laptop computer. When I asked for information about Cam-
bodia’s economy, I didn’t need to make a formal request: he
simply called up files from his hard drive and burned me a CD
of the government’s economic data.
From outside the building, Mean led me up a narrow
staircase that stank of old fruit and into a small office that re-
minded me of every other bureaucrat’s office I had ever seen in
the developing world. The only decoration was a garish, faux-
Impressionist painting of Angkor Wat, Cambodia’s famous
twelfth-century temple complex. A small fan shuddered and
sputtered. Mean’s assistant kicked the fan. The fan stopped
America’s Soft Power Goes Soft I8,
moving at all. Sweat dripped offmy forehead onto the linoleum-
covered floor.
In I,,, Cambodia had signed a unique trade agreement
with the United States, the first to link duty-free access to
American markets with labor standards in factories overseas.
Under the deal Cambodia and the International Labor Organi-
zation together would certify that the workers in Cambodian
garment factories received fair pay and decent labor condi-
tions. The better these conditions became, the more Cambo-
dia would be entitled to export garments duty free to the
United States. In theory, the better these conditions became,
the more Western companies would be interested in importing
from Cambodia, since they would receive preference in selling
Cambodian goods to America and could advertise to Ameri-
can consumers that they had not used sweatshop labor.
20
This agreement worked—at least at first. Cambodia’s gar-
ment industry gained jobs, won foreign investment, and culti-
vated major buyers like Nike. According to the Asian business
expert Sheridan Prasso, the agreement led to large increases in
foreign companies’ purchase of Cambodian garments, and in
:oo, garments accounted for ,, percent of Cambodia’s ex-
ports and earned one-third of the country’s entire gross do-
mestic product. While the United States had purchased $I mil-
lion in Cambodian textiles in I,,o, it bought $I.I billion in
:oo,, making America the biggest market for Cambodian
goods. The garment industry fed Cambodian families and
built Cambodians houses back in their hometowns. By the
early :ooos, :, percent of Cambodia’s population depended in
some way on garment workers’ wages.
21
But in January :oo,, according to a World Trade Organi-
zation decision, the world eliminated quotas for garment im-
ports—quotas like the duty-free access to America enjoyed by
I88 America’s Soft Power Goes Soft
Cambodian goods. After January :oo, Cambodia would face
the same duties as bigger rivals like Indonesia and China, which
have many more workers, lower wages, and worse labor condi-
tions.
22
Since the Clinton administration had pushed Cambodia
to sign the I,,, agreement, Mean and other Cambodian trade
officials thought that the White House now should help Cam-
bodia’s garment makers survive by continuing to give them
preferential access to America’s markets. “We need US help. We
need quota-free access for garments, or our garment makers
will die,” Mean pleaded with me. “We must have help.”
Mean’s pleas didn’t get him anywhere. Washington had
developed a closer relationship with Phnom Penh in recent
years, but the cooperation centered on counterterrorism. The
Cambodian government started cooperating in :oo,, arresting
alleged members of the Al Qaeda offshoot Jemaah Islamiah.
The United States then helped Cambodia participate in a
multinational counterterrorism exercise. But counterterror-
ism assistance should not have been the extent of the relation-
ship. Several savvy American politicians, like former Arizona
Congressman Jim Kolbe, had realized how the United States
could build greater goodwill in poor nations. Kolbe had pro-
posed the Tariff Relief Assistance for Developing Economies
Act. This bill would have given Cambodia and thirteen other
poor nations duty-free access to the United States.
23
But the
bill didn’t go anywhere. Perhaps in the run-up to :ooo mid-
term congressional elections, American legislators didn’t want
to alienate the United States’ own tiny, and shrinking, textile
sector, which still had some lobbying clout.
In the first three months of :oo,, after the elimination of
garment quotas, Cambodia’s garment factories suffered, and
some closed.
24
Looking for help, Mean had turned to China,
America’s Soft Power Goes Soft I8,
which had been cultivating the Cambodian cabinet for nearly
a decade. Mean personally feared that Cambodia might be over-
whelmed by Chinese imports—China’s giant textile sector
competed directly with Cambodian garments. Still, on the ad-
vice of one of his superiors, he had taken a study trip to the
booming southern Chinese city of Guangzhou, where Chinese
officials told him that they would soothe Cambodia’s pain by
considering lifting tariffs on certain Cambodian exports. The
Chinese loaded him with reports about efficiencies attained in
China’s garment factories, and he rolled some of these man-
agement buzzwords off his tongue, trying the phrases out as if
they were new toys—“supply chain,” “labor-management re-
lations.”
Mean smiled briefly, then frowned again. “But how can
we sell garments to China? China itself produces garments
much cheaper than we do.”His voice rose and he stood up, and
then sat down again. “They use cheap labor, even forced labor,”
he said. “I don’t know. I don’t know what to do.”
Worse than the White House’s indifference toward economics,
the excesses of the war on terror, like abuses at Guantánamo
Bay, undermined the attractiveness of American values, since
that attractiveness rested in part on perceptions of the United
States as a humane and lawful actor—as compared with, say,
China. These excesses also undermined American attempts to
promote democracy and human rights abroad, since repres-
sive nations could always turn the spotlight back on the White
House’s own unattractive policies. “The treatment of prison-
ers at Guantánamo and in Iraq, and US policies in other cor-
ners of the Muslim world . . . have all undercut US moral
standing in the region,” reported one panel of Asia experts.
25
China’s annual report on America’s human rights record
I,o America’s Soft Power Goes Soft
captured how America had lost some of its ability to criticize.
For years Beijing has been producing this document to rebut
American criticism of Chinese abuses. In the past China used
the report to make mild complaints about problems like in-
come disparity in America. But now Beijing had more than
enough ammunition. “In :oo¡ the atrocity of US troops abus-
ing Iraqi POWs exposed the dark side of human rights per-
formance of the United States,” noted China’s :oo, report.
“The scandal shocked . . . humanity and was condemned by
the international community.”
26
The White House also eviscerated multinational institu-
tions, from the Kyoto Protocol to the Comprehensive Test Ban
Treaty on nuclear weapons. The Bush White House reportedly
even opposed a United Nations treaty to promote cultural
diversity, which has strong support around the world, partic-
ularly in nations proud of their local film and music indus-
tries. To take one of the saddest examples, as the New York
Times reported, Washington considered cutting off aid to im-
poverished nations like Niger—a relatively pro-US Muslim
country in Africa that has suffered repeated famines—if they
supported the International Criminal Court, which the White
House opposed. By comparison, the United Kingdom’s gov-
ernment, which also went to war in Iraq, continues to back
international institutions ranging from Kyoto to the Interna-
tional Criminal Court. The United Kingdom’s global image
has remained strong.
27
A freer international media now magnified Washington’s
mistakes. Satellite television stations like Al Jazeera, which tend
to be skeptical of the United States, have spread through for-
merly media-poor regions of the world. These globalized media
have made the White House’s actions—for good or ill—in-
stantly accessible to people around the globe. In one study of
America’s Soft Power Goes Soft I,I
Moroccans’, Egyptians’, and Indonesians’ views about Amer-
ica, no one in the focus group had a positive thing to say about
the US president, and the authors reported that “among edu-
cated, otherwise polite young women, reactions to the men-
tion of America included ‘Go to Hell’ and ‘I hope God will de-
stroy them.’”
28
Some Moroccans, Egyptians, and Indonesians
even compared President Bush to Satan.
American policy today is as unpopular as at any point in the
United States’ modern history. Some anti-Americanism has
become so strident it is almost comical. In one recent poll of
South Korea, a country the United States continues to help
defend against nuclear-armed North Korea, roughly half of
young South Koreans surveyed said that their nation should
support North Korea if Pyongyang and Washington were to go
to war.
29
Only II.o percent thought that South Korea should
back America in a North Korea–United States conflict.
Evidence of American unpopularity is both wide, as sug-
gested by broader polls, and narrow, as revealed by specific
weaknesses in American appeal. The Council of Graduate
Schools, an organization of American universities, found that
the number of international graduate school applications to
US universities fell :8 percent between :oo, and :oo¡, its first
decline in more than thirty years. Applications dropped , per-
cent further between :oo¡ and :oo,. France now receives more
applications for asylum than does the United States.
30
What is more important, unlike previous periods of un-
popular American policy, when people in many countries dis-
tinguished between their dislike for US foreign policies and
their personal respect for American people, American values,
American culture, and American companies, today these dis-
tinctions are disappearing. In the early I,8os many countries
I,: America’s Soft Power Goes Soft
criticized Washington’s decisions to increase rhetorical pres-
sure on the Soviet Union and to deploy new nuclear missiles in
Europe, but American culture, companies, and people re-
mained popular. A I,8, Gallup poll revealed that many Euro-
peans disdained President Ronald Reagan’s policies but ap-
proved of the American way of life.
31
That has begun to change. In a :oo: poll of forty-three
nations, majorities of people in thirty-four of the countries
were unhappy with the growing influence of America—not
just American policy—on their nation. In another study, large
percentages of respondents in eighteen nations had a declining
view of American people between :oo: and :oo,.
32
Foreigners also seem to be losing interest in America’s
core values—like the idea of America as a land of opportunity,
an idea that vanishes if foreigners believe that the United States
is no longer a meritocracy. In a :oo, Pew study of people from
sixteen countries, in which respondents were asked, “Suppose
a young man who wanted to leave this country asked you to
recommend where to go to lead a good life—what country
would you recommend?” most of those polled placed other
nations above America as choices for emigration. US compa-
nies took a hit, too. Even in relatively pro-American countries
in Western Europe, recent studies suggest that some consum-
ers avoid American brands, and a study by Anholt-GMI, an or-
ganization that ranks the “brands” of nations, found that re-
spondents from a range of nations ranked the United States
only eleventh overall in terms of its cultural, political, popular,
and business attractiveness.
33
This unpopularity matters. Even without China on the scene,
America’s declining popularity decreases Washington’s soft
power, and potentially makes the United States more likely to
America’s Soft Power Goes Soft I,,
resort to force rather than persuasion to meet American ob-
jectives. One recent bipartisan report on American diplomacy
concluded as much, warning that if the “downward spiral [in
diplomacy] is not reversed, the prospect of relying on military
force to protect US national interests will increase.”
34
In just the past four years, the impact of American un-
popularity has become clear. With America so unloved, and
with American leaders having failed to understand how de-
mocratization in Africa, Latin America, and Asia had changed
international relations, the United States was unprepared for
the run-up to the war in Iraq. At the time, many leaders of de-
mocracies felt that they could not support the US-led war in
Iraq, for fear of the popular backlash against them if they
joined the coalition. So Chile, Mexico, and Turkey did not sup-
port the US intervention. Similarly, even though Indonesia
clearly faces a serious domestic terrorism problem—a problem
highlighted by the :oo: Bali bombing—Indonesian leaders for
years refused to publicly support the US-led war on terror or
to openly cooperate with Washington on counterterrorism.
35
These countries’ decisions had serious consequences.
Unlike in the past, when the United States could twist arms
among these countries’ leaderships and get what it wanted,
now Mexican and Chilean and Turkish leaders had to be ac-
countable to their electorates. Without the votes of Mexico,
Chile, and others, the United States failed to get the United
Nations Security Council to endorse war against Iraq, a deci-
sion that made the conflict look illegitimate in the eyes of
many nations, and ultimately made it difficult for Washing-
ton to persuade countries to contribute to Iraq’s reconstruc-
tion. Because Turkey refused to provide a base for the inva-
sion, there was no initial US troop presence in northern Iraq,
giving Kurdish militias rein to push Sunnis and Shia out of
I,¡ America’s Soft Power Goes Soft
their homes and setting the stage for deadly interethnic con-
flict in northern Iraq.
36
In Indonesia, the government’s refusal to cooperate with
American counterterrorism efforts deprived Jakarta of intelli-
gence, and allowed terrorist groups to proliferate, taking ad-
vantage of Indonesia’s weak rule of law to establish themselves
across the archipelago. FBI agents working in Indonesia com-
plained about a lack of cooperation from local authorities, and
then–Indonesian President Megawati Sukarnoputri failed to
appoint a national counterterrorism coordinator. Eventually,
Indonesia’s policies rebounded against it, and against the
United States. A string of post-Bali bombs in Indonesia further
scared off tourists and investors and targeted American com-
panies like the JW Marriott Hotel in Jakarta, where a :oo, at-
tack killed twelve people.
37
By the end of :ooo, more than three years after the invasion of
Iraq, the White House still had not succeeded in restoring
America’s popularity, even in longtime allies like Turkey. The
isolationism of the I,,os had set the stage for America’s de-
clining soft power, undercutting America’s ties to the world.
While the United States reengaged with the world in the :ooos,
the style of its reengagement—unilateral action, bellicose
rhetoric, public diplomacy that seemed all style and no sub-
stance—only further alienated many countries. As Karen
Hughes was setting off for her first listening tour, a congres-
sional panel pulled no punches, capturing all of these trends in
American declining appeal. The panel reported, “America’s
image and reputation abroad could hardly be worse.”
38
Of course, America still possesses numerous strengths,
including core values and ideals that remain attractive to many
foreigners. America could draw upon these strengths to stage
America’s Soft Power Goes Soft I,,
a comeback, to potentially combat China’s influence, and win
back the world; in some countries, like Indonesia, the United
States has already come back from the depths of its unpopu-
larity. But until America uses those inherent strengths, Beijing
will be able to wield its soft power to push back against Amer-
ican power and, potentially, to threaten American interests.
I,o America’s Soft Power Goes Soft
X
What’s Next?
n June I¡, :ooI, China, Russia, Kazakhstan, Kyr-
gyzstan, Tajikistan, and Uzbekistan founded the
Shanghai Cooperation Organization, or SCO, an
organization focused on Central Asia. At the found-
ing summit, the members declared that the SCO would be de-
voted to enhancing regional economic, cultural, and security
cooperation. As the Chinese foreign ministry put it, in a ram-
bling statement, the SCO would “strengthen mutual trust and
good-neighborliness and friendship among member states,
developing their effective cooperation in political affairs, the
economy and trade, science and technology, culture, education,
energy, transportation, environmental protection and other
fields.”
1
The rest of the world paid little attention to SCO’s
founding; most American officials dismissed it as a useless
talk shop. As the Central Asia scholar Greg Austin wrote, “The
Shanghai Cooperation Organization has been ridiculed in
many Western commentaries . . . for its apparent lack of focus
and lack of achievements.”But between :ooI and :oo,, Central
Asia went from an obscure region of Muslim-majority “’Stans”
to one of the world’s most vital regions. As diminishing global
oil reserves and growing energy demands pushed up world oil
prices, the resource-rich Central Asian states—Kazakhstan
alone produces more than one million barrels of oil per day—
became, comparatively, even resource-richer.
2
After Septem-
ber II, the region’s land borders with Afghanistan, and its old
Soviet bases, placed it in the center of the fight against Al
Qaeda. US Secretary of Defense Donald Rumsfeld suddenly
had to bone up on his Uzbek. Foreign reporters descended on
cities like Tashkent and Dushanbe to cover the battle for Cen-
tral Asian oil and the links between Central Asian radicals and
Al Qaeda members holed up in Afghanistan and Pakistan.
After September II, sta-
tioned next door, and its paranoia only grew after democratic
revolutions in the former Soviet states of Georgia and Kyrgyz-
stan. Combined with the democratic revolutions, American
troops stationed in Japan and South Korea, and American de-
fense relationships with Singapore, Mongolia, the Philippines,
and Thailand, having US soldiers in Central Asia made some
Chinese strategists feel surrounded. “As the war on terrorism
continues in Afghanistan, [the] US military presence in Cen-
tral Asia has become a reality. However, the United States will
never be satisfied with this reality,” wrote the Chinese com-
mentator Gao Fuqui. “The entrance of the United States into
I,8 What’s Next?
Central Asia serves as a springboard from which to contain the
rise of China.”
3
China had been cultivating Central Asia before the world
discovered the region. Beginning in the mid-I,,os, Chinese of-
ficials like then-Premier Li Peng courted Central Asia’s leaders,
promoting Chinese investment and trying to boost trade
through proposed border free trade zones. Supporting China’s
charm offensive, the Chinese government invested in public
diplomacy in Central Asia and increased its aid programs. Bei-
jing established a Confucius Institute for Chinese-language
and -cultural studies in Uzbekistan. It created programs to
train Central Asian officials and politicians, and promised the
’Stans that Beijing would fund a $I., billion highway linking
China to Central Asia.
4
Once the SCO was formed, China could use the multi-
lateral organization for leverage as well, to present itself as a
natural leader of the region, or at least a regional coleader with
Russia. China would be the friend who would not interfere in
domestic politics, even as American officials touched down in
Central Asia to make demands for basing rights. Chinese in-
vestment also received local media coverage, which molded
perceptions of China. At the same time, America’s image plum-
meted—in one Pew poll, a majority of people in Uzbekistan
did not want American ideas and customs spreading to their
country.
5
China’s appeal seemed to be working in Central Asia. Just
as important, China’s rise offered the Central Asian nations
leverage to pursue their own national self-interests—with
China becoming a major player in the region, countries that
resented growing US influence now had another power to turn
to. By :oo, China was ready to use its subtle influence in Cen-
tral Asia to support the region in taking a clearer stand against
What’s Next? I,,
America. Before the :oo, SCO meeting, China quietly offered
increased aid to Central Asian nations. After the Uzbek gov-
ernment cracked down on opposition in :oo,—a crackdown
that culminated in the massacre of more than four hundred
people in the city of Andijan—and American officials criti-
cized the Uzbek regime, China quickly backed the Uzbek poli-
cies, hosting Uzbek leader Islam Karimov for a state visit to
Beijing, where China feted him with a twenty-one-gun salute.
6
In July :oo,, at the Shanghai Cooperation Organization
summit, SCO countries warned against any countries—clearly
meaning America—“monopolizing or dominating interna-
tional affairs” and demanded that Washington provide a time-
line for withdrawing American forces from SCO member
countries. Soon Uzbekistan rescinded America’s basing rights.
Now Washington was paying attention to the Shanghai Co-
operation Organization. General Richard B. Myers, chairman
of America’s Joint Chiefs of Staff, resorted to tossing a kettle-
calls-the-pot-black charge at Moscow and Beijing: “It looks
to me like two very large countries were trying to bully some
smaller countries” in Central Asia, Myers told reporters.
“China’s interest in building relations with Central Asia is not
startling given its long history in the region, but the agility and
creativity it has exercised in doing so has taken many by sur-
prise,” admitted Bates Gill and Matthew Oresman, China spe-
cialists at the Center for Strategic and International Studies, a
Washington think tank.
7
The story of the Shanghai Cooperation Organization
teaches several lessons—lessons about China’s growing global
influence, and potentially about the future of China’s relations
with the United States. In a short period of time, and under the
US radar, China amassed significant soft power in Central Asia
through aid, formal diplomacy, public diplomacy, investment,
:oo What’s Next?
and other tools. Even as China’s role in Central Asia expanded,
the region became far more important to both China and
America. Central Asia became critical to America for its energy
reserves and its role in the war on terrorism. Meanwhile, Cen-
tral Asia became crucial to China for its resources, its support
for China in international organizations, its trade potential,
and its geostrategic position.
In some respects, Chinese and American interests coin-
cide in Central Asia—and around the world. Many of China’s
interests, as we have seen, are only natural—peace, access to
resources, friends, and allies. China’s soft power often has
benefited the United States. In Central Asia, Beijing has helped
prod the Central Asian governments to round up suspected
terrorists, promoted regional economic cooperation, and be-
come a growing market for Central Asian goods, potentially
reducing economic instability. But sometimes China’s inter-
ests conflict with American interests, including America’s own
alliances, need for energy, and commitment to democratiza-
tion. When China discovers that its interests do not overlap
with America’s, it now has the tools to build allegiances to Bei-
jing—and it can find countries looking for a great power to
balance their relations with America. In the worst-case sce-
nario, China might use its soft power to subtly prod countries
to choose between itself and the United States.
As China becomes more powerful, it has begun to face inter-
national pressure, as an important nation, to use its soft
power more responsibly. In one sign of growing engagement
with the United Nations, Beijing recently sent some one
thousand peacekeepers to southern Lebanon after the Israel-
Hezbollah war. Beijing’s Foreign Ministry has created a new
department for external security affairs, to handle larger
What’s Next? :oI
peacekeeping duties and other tasks like protecting Chinese
citizens abroad.
8
Despite its unconditional aid to countries like Angola,
China also is thinking about working with other aid donors so
that its assistance does not undermine World Bank or IMF
programs supporting good governance. In some respects,
China’s aid fills gaps—China constructs roads and bridges
across Africa and Latin America, where most major donors
abandoned funding infrastructure decades ago, and it often
produces infrastructure far more cheaply than contractors
working for Western aid organizations. China may make its
aid programs more transparent and sophisticated. In crises like
the Asian tsunami, China has coordinated with other donors.
On other occasions, in Cambodia and East Timor, Chinese offi-
cials were invited to meetings of all major donors, and began
attending, showing their interest in working with other coun-
tries. Beijing also has quietly told aid specialists that it wants to
build a Chinese version of the United States Agency for Inter-
national Development (USAID), a permanent aid bureaucracy.
9
Building a Chinese USAID would make Chinese aid more ac-
countable, since it would create an independent organization
full of aid specialists rather than relying on the Chinese Min-
istry of Commerce—which simply links assistance to China’s
immediate political and economic needs—to disburse aid.
Beijing also may be warming to the idea that Chinese
support for authoritarian regimes can create instability—in-
stability that, in the long run, doesn’t benefit China itself. In
Burma the junta’s backward, erratic rule has not only created
the drug and HIV crises that threaten China but also endan-
gered local Chinese businessmen, who never know when the
political situation will turn violent or whom they must pay off
to keep operating.
:o: What’s Next?
Fearful of Burma’s instability, Chinese officials have not
only cracked down on gambling and drugs in the China-
Burma frontier but also pushed for political reform inside
Burma. According to several Burma watchers, Chinese officials
have held quiet meetings with activist organizations battling
the Burmese government, bringing these opposition figures to
China for talks. During the most recent visit of Burma’s prime
minister to China, Chinese officials pushed Burma to improve
its dialogue with opposition groups, with Wen Jiabao calling
for “reconciliation” in Burma. “China is increasingly circum-
spect in its defense of Burma,” one diplomat told the Burma
analyst Larry Jagan. Even more surprising, Beijing has allowed
Burma’s human rights crisis to be placed on the agenda of the
UN Security Council, a momentous decision for a country
skeptical of allowing the United Nations to meddle in other
nations’ affairs.
10
The Burma example may become representative—China
may increasingly use its soft power to promote stability in places
where the United States has little influence. Having China,
along with the United States, prodding these countries means
that leaders in places like Burma or North Korea cannot write
off the pressure as merely an American initiative. China is es-
pecially likely to use its influence when Beijing fears that insta-
bility in another nation could spill over into China, either by
spreading drugs and disease (Burma), or by causing massive
refugee flows (North Korea), or by exacerbating terrorism
(Central Asia)—and when those countries do not possess sig-
nificant amounts of oil, gas, or other resources.
China’s soft power can help the United States in other
ways. As we have seen, by providing a new, growing market for
developing nations’ commodities, China has allowed African,
Asian, and Latin American countries to amass large positive
What’s Next? :o,
balances of trade (at least for now), pay off some of their debts,
and reduce potential financial instability. Even Chinese com-
petition with Latin American and Asian exports could have a
positive impact, tangentially benefiting the United States. In
Latin America, competition with China is leading nations to
address their own obstacles to economic competitiveness, for
fear of losing foreign direct investment to China. These are
problems often cited by US firms operating in Latin America
as obstacles to better business. In Africa growing Chinese com-
petition is providing a similar wake-up call, especially in more
developed economies like South Africa or Kenya. Similarly, the
China–Southeast Asia free trade agreement has forced the re-
gion’s leaders, who have many of their own bilateral griev-
ances, to think of Southeast Asia as a unified economic bloc,
and to move faster on a free trade agreement linking ten coun-
tries in Southeast Asia. Again, lower trade barriers within
Southeast Asia would benefit American multinationals—com-
panies like Ford that have developed regionwide supply chains
in which they make some parts in Thailand and other parts in
the Philippines, then ship completed automobiles to dealers in
Indonesia.
11
Some Asian leaders believe that China’s soft power will have its
greatest impact not on the United States but on Japan. Japan,
which also focuses on cultivating influence in Asia, certainly
has found itself on its back foot. During its own period of
stunning economic growth, from the end of the Second World
War until the early I,,os, Japan failed to cultivate soft power.
Japanese companies did invest heavily in Asia, helping nations
like Thailand grow from making toys and shoes to building
computers and personal digital assistants. Japan lavished aid
on the developing world as well. During the I,,os and early
:o¡ What’s Next?
:ooos, Indonesia, Japan’s largest aid recipient, often received
nearly $I billion in assistance from Tokyo each year.
12
But Tokyo seemed to believe that this cash alone would
win friends. Though aid and investment helped to improve
Japan’s image, during its economic boom Japan never became
an object of cultural interest, a draw for emigrants, or a model
of development. With only a small diaspora in the developing
world, Japan could not undertake the kind of outreach to
overseas Japanese that China can with diaspora Chinese. And
Tokyo, chastened by shame over its World War II history, was
loath to advertise Japan with high-profile public diplomacy.
“We don’t need to do the kind of official visits to show what
we’re spending in aid in a country,”one Japanese diplomat told
me.
13
The Japanese foreign ministry did not heavily advertise
its aid programs, or hold out Japan as a model, or take the lead
on regional trade agreements.
Without unsubtle advertising, however, average people
in other nations often do not know where the donated vac-
cines for their children or the new road for their town came
from. Too often, Tokyo does not even try to leverage the fact
that it is a democracy to appeal to average people in the devel-
oping world, making it hard for Japan to differentiate itself
from China. After the Burmese government refused in spring
:ooo to release opposition leader Aung San Suu Kyi from
house arrest, every democracy on the UN Security Council
wanted to put more pressure on the Burmese regime. Alone
among free nations, Japan argued that the United Nations
should do nothing.
14
As a result, Japan did not build as much goodwill among
leaders or average citizens as one might have expected, given
the size of its aid and investment. Few opinion leaders in a
place like the Philippines had genuinely warm feelings toward
What’s Next? :o,
Tokyo; even fewer had lived or studied in Japan. During the
I,8os and the early I,,os, as China remained weak and Japan’s
economy boomed, these mistakes did not matter much. And
of course, Japan did not directly compete with America’s soft
influence, since Tokyo and Washington were close allies. But
when Japan’s economy sank into decadelong stagnation in the
I,,os, and China began to exert influence and subtly prod
other nations to pay less attention to Japanese leadership,
Japan’s past missteps grew in importance.
By the late I,,os and early :ooos a combination of fac-
tors further undermined Japan’s soft power. As the United
States became more unpopular, Japan, a close American ally,
suffered by association. With no room for flab in their over-
seas operations, Japanese companies shifted investments away
from other parts of the developing world and toward China.
Worried about popular anger within Japan over Tokyo’s lav-
ishing money abroad while the domestic economy tanked, the
Japanese government slashed foreign aid: in its :oo, budget
Japan’s Finance Ministry cut overseas development assistance
for the sixth straight year. Meanwhile, the conservative Japa-
nese leader Junichiro Koizumi, prime minister between :ooI
and :ooo, alienated other nations in Asia by visiting the Ya-
sukuni Shrine, a controversial Tokyo memorial that commem-
orates more than two million Japanese war dead but also ex-
plicitly honors fourteen veterans convicted of class A war
crimes by a post–World War II court. Next to the controversial
shrine stands a museum that downplays Japan’s behavior in
the war, like its massacre of some ,oo,ooo Chinese civilians in
Nanjing.
15
China skillfully played on this anger, condemning Koi-
zumi’s visits and using Yasukuni against Japan in public set-
tings. (China’s spotlighting of the Yasukuni situation, of course,
:oo What’s Next?
helps the Communist Party at home, by directing potential
popular anger toward Japan and away from the Beijing gov-
ernment.) As Japan has pushed in recent years for a permanent
spot at the UN Security Council, one of Tokyo’s most impor-
tant goals, China has repeatedly brought up the Yasukuni vis-
its to remind the world of Japan’s wartime aggression and to
persuade Asian nations not to support a permanent Japanese
seat. During a summit in South Korea held in :oo,, China’s
foreign minister, Li Zhaoxing, wondered, “What would Euro-
pean people think if German leaders were to visit [shrines] re-
lated to Hitler and Nazis?”
16
By the early :ooos Japan was hemorrhaging influence in
the developing world. “In the I,8os, the US ambassador would
be lucky to see [Malaysian Prime Minister] Mahathir Mo-
hamad and the Japanese ambassador was there three times a
week—not anymore,” says one American policy maker. In-
deed, when China proposed a free trade deal in :ooI with ten
Southeast Asian nations, Japan appeared caught off guard.
Suddenly China, not Japan, was driving trade talks in Asia, and
many Asian opinion leaders perceived Tokyo as lagging and
out of touch. When nations in Asia and Africa that had been
major recipients of Japanese aid refused to back Tokyo’s bid for
a UN Security Council seat, the message came home: the
Japanese foreign ministry realized how badly it had slipped.
Japan belatedly acceded to Southeast Asia’s Treaty of Amity
and Cooperation, but because China had signed on first, Japan
received little press coverage for this decision. Japan came up
with a framework for a free trade agreement with Southeast
Asia but did not take discussions very far, partly because
Japan’s farmers resisted opening markets.
17
Opinion leaders across Asia already believe that China’s
charm eventually will overwhelm Japan’s fading influence, es-
What’s Next? :o,
pecially as Japan’s population ages and its investments abroad
decline. “The Chinese are just moving much faster than the
Japanese,” said Ajit Singh, the former secretary general of
Asean. “The Japanese are mired in bureaucracy and now
they’re always looking over their shoulder” at China. Even
American policy makers sympathetic to Tokyo admit as much.
“It’s amazing how much influence Japan has lost,” marveled
one senior American policy maker.
18
But China’s growing soft power will threaten the United States
as well: the emergence of China’s soft power is already having
a strategic impact on US foreign policy. China could wield its
influence in a growing clash over resources. Like China, the
United States needs continued access to oil and gas, since esti-
mates suggest that America could be importing nearly ,o per-
cent of its oil in two decades, up from just over ,o percent
today. Oil and gas do not trade on a completely free market,
tend to be controlled by state-linked companies—and may be
running out. Stores of easily accessible petroleum, like the
fields in Saudi Arabia, could be dwindling. Colin Campbell,
the former chief geologist for Amoco, argues that :ooo may
have been the peak production year for oil, after which re-
serves and production will hit a long downward slope.
19
With
oil becoming scarcer, Latin American and West African and
Asian oil remain among the cheapest for the United States, and
the easiest for American companies to refine and use.
The United States cannot afford to lose access to these re-
serves to any potential competitor. As we saw in Chapter ,,
China has enjoyed success in winning access to oil and gas, and
Beijing views energy as a zero-sum game. “For China’s leaders,
energy security clearly is too important to be left to the mar-
kets,” argues the Asia energy specialist Mikkal Herberg, who
:o8 What’s Next?
believes competing US and Chinese demands for energy will
eventually lead to a clash over resources. “The Chinese are
seeking to achieve assured sources of supply in Latin America
through a strategy that focuses on securing the entire supply
chain in critical industries,” believes R. Evan Ellis, a Latin
America specialist.
20
“This strategy of ‘vertical integration’
involves using strategic purchases and investments to ensure
an acceptable amount of leverage over . . . all elements of the
supply chain.”
In Venezuela, for one, China not only promises new in-
vestment and aid but also provides Hugo Chávez with a po-
tential alternative consumer to the United States, which has
endured frosty relations with Caracas. For now, Venezuela,
home to the largest oil reserves outside of the Middle East, re-
mains reliant on shipping its oil to the United States, and
China has resisted suggesting that it will lead Caracas to shift
its oil industry toward Beijing. But Venezuela eventually may
wean itself off of American markets. Chávez has announced
plans to double oil exports to China, and Venezuela is building
its shipping fleet, making an investment in long-term growth
in exports to the People’s Republic.
21
Beijing does not want Chávez to openly tout his China
connections—in :oo, China’s ambassador in Venezuela point-
edly told reporters that “the natural markets for Venezuelan oil
are North and South America.” But though China has been
cautious about directly threatening American access to oil, as
Beijing’s energy needs skyrocket, it could find itself with little
choice other than to compete with the United States. Already,
the Chinese state-linked oil company Sinopec has expressed
interest in upgrading a pipeline from Venezuela that would
run through Panama and to the Pacific, orienting Venezuela
toward China, and Chinese companies have helped Venezuela
What’s Next? :o,
become less dependent on American technology in other in-
dustries, including telecommunications.
22
Any major shift in Venezuelan oil shipments could badly
damage America’s economy. Caracas sends some I., million
barrels of oil a day to the United States, making it America’s
fourth-largest supplier of crude. According to Michelle Billig,
a former analyst at the US Department of Energy, in June :oo¡,
after a strike in Venezuela decreased the country’s oil produc-
tion, Venezuela’s shipments to America crashed. “Over the next
three months,” Billig says, “the [Venezuelan] crisis kept some
:oo million barrels of oil and gasoline from the world market,”
forcing the price of a barrel of oil to a twenty-one-year high.
23
If Venezuela shifted to sending more oil to China, it
could set a model for its neighbors as well. As with Venezuela,
China’s socialist history, and its long-standing outreach to
populist groups in the developing world, offers Chinese lead-
ers residual bona fides in dealing with leftist leaders in nations
like Bolivia or Ecuador. If Latin countries run by populist lead-
ers see that Venezuela shifts to supplying China and does not
suffer economically, other leaders, like Bolivia’s Evo Morales,
would recognize that they too could use relations with China
to reduce America’s dominance in the Western Hemisphere
without damaging their own economies.
Getting deep into Latin American oil also could draw the
Chinese military into the region, which would clearly chal-
lenge American power. This scenario lies in the future, but in a
:oo¡ white paper explaining its defense planning, Beijing, in a
departure from past strategy, accepted the idea that the Chi-
nese military could become engaged in power projection
abroad to protect economic interests and secure strategic as-
sets.
24
If this idea of power projection becomes a central com-
ponent of Chinese military strategy, and if China comes to see
:Io What’s Next?
its assets in Latin America—resources and ports, access to
pipelines—as vital, the People’s Liberation Army may seek
closer relationships with many Latin American militaries.
A similar situation could unfold in Nigeria, the fifth-
biggest supplier of oil to America, which like Venezuela has a
political elite sensitive to the idea that it is selling the country’s
resources to rich Western nations. This is a criticism leveled at
the Nigerian government by opposition groups and armed
radicals operating in the Niger Delta, which pumps two mil-
lion barrels of oil per day yet remains one of the poorest parts
of the country. Beijing has enjoyed initial success in Nigeria,
leveraging the idea that China, as a nonmeddling, developing
nation, could be a better partner than Western states; China
has won some $¡ billion worth of preferential Nigerian explo-
ration rights. If Beijing builds on its initial success in Nigeria,
once again China will come into direct conflict with America’s
need for vital resources.
China might be able to apply the type of appeal it uses in
Venezuela and Nigeria to producers in the Middle East, who
also see in China a potential alternative consumer. As the en-
ergy analyst Erica Downs writes, Chinese scholars now argue
that Beijing could utilize “opposition to American hegemony”
to improve relations with leaders in the Middle East. By part-
nering with China, these regimes would reduce domestic crit-
icisms that they are too pro-American. Saudi officials have
begun speaking openly about potentially cutting off oil to the
United States—presumably if America’s image in the Muslim
world declines so much that Riyadh cannot afford an alliance
with Washington.
25
America’s demand for oil, when combined with a reduc-
tion in exports from Venezuela or Nigeria, could have even
more dangerous consequences. Facing a world in which oil
What’s Next? :II
producers now have another large consumer, the United States
has abandoned some of its own commitment to promoting
democracy, for fear of alienating autocratic oil states. After de-
livering a speech in May :ooo in which he blasted President
Vladimir Putin for destroying Russian democracy, Vice Presi-
dent Richard Cheney jetted off to Kazakhstan, a dictatorship
whose oil production could nearly triple by :oI,, and where
the United States wants the Kazakhs to build a pipeline that
would bypass Russia. In Kazakhstan, Cheney “expressed [his]
admiration” for the country’s “economic and political devel-
opment.” Soon after, the administration invited Kazakh leader
Nursultan Nazarbayev to visit the White House, though the
State Department’s own report on human rights in Kazakh-
stan put it simply: “The government’s human rights record re-
mained poor.”
26
Meanwhile, Secretary of State Condoleezza Rice hosted
Teodoro Obiang Nguema Mbasogo, who has ruled Equatorial
Guinea with an iron grip since a coup in I,,,. Obiang also ap-
pears extraordinarily corrupt—as documented by the jour-
nalist Peter Maass, Obiang is accused of depositing at least $I,
million into accounts at the shady Riggs Bank in Washington.
As the two leaders together met the press, Obiang seemed un-
comfortable—at home, he could toss pesky reporters in jail—
but Rice held his hand. “You are a good friend,” Rice cooed.
27
China’s soft power also could help it push countries to decide
between Washington and Beijing. Already, partly due to China’s
improving image, which makes other countries comfortable
with closer ties to Beijing, nations in Asia, as well as in parts of
Africa and Latin America, are using Beijing as a hedge against
American power. China could take advantage of these changes.
As these shifts are occurring, right now Beijing has supported
:I: What’s Next?
only nations, like Uzbekistan, looking to break away from
closer ties to the United States, but in the future it could more
aggressively push countries to make those decisions.
China is already trying to draw upon its charm to push
back against American power in Asia. Even as it publicly accepts
America’s presence in the region, Beijing has helped initiate
multilateral forums, like the East Asia Summit, that exclude
the United States. Similarly, Dennis Blair, then commander of
American forces in the Pacific, proposed in :ooI that Asia cre-
ate what he called “security communities” in which the United
States would increase its defense cooperation with Asian na-
tions to create a kind of informal regional security organiza-
tion. But many Asian nations vetoed the idea, in part because
China quietly applied pressure on them to reject it.
28
In the Philippines, defense officials told me that China is
pushing for much closer military relations, the kind of strong
defense ties the Philippines enjoys with America now. If Bei-
jing were to develop this close cooperation with Manila, the
Philippines’ cooperation with the United States would almost
certainly decline, since it would be difficult for Manila to have
close security ties with both powers. “The Chinese would like
joint military exercises [with us], huge defense assistance,” says
one Philippine official.
29
Five years ago, Philippine defense
planners would have balked at this idea. But as China becomes
more popular in the Philippines, he says, this is no longer out
of the question, because the Philippine public could be sold on
close defense ties with Beijing. “China-Philippines defense co-
operation can be expanded,”he said. “My gut feeling is that the
Philippine public would support this.”
In the future, China could prod countries like the Philip-
pines or Thailand, which are already using China as a hedge,
to downgrade their close relations with the United States, or
What’s Next? :I,
could push countries like Singapore to stop providing basing
rights for America. It could pressure countries not to intervene
if the United States and China were to go to war over Taiwan,
as it has done with Singapore, protesting angrily and threaten-
ing to impose economic sanctions when Singaporean Deputy
Prime Minister Lee Hsien Loong visited Taiwan. China’s pro-
tests obtained results: Lee later promised that Singapore would
not support Taiwan in a war, if Taiwan provoked the conflict
by making moves toward independence, as China often ac-
cuses it of doing.
30
China might even drive a wedge between America and its clos-
est allies. For fifty years, Australia has been bound to the United
States through the ANZUS treaty, which states that any armed
attack on a country covered in the treaty would endanger all
the countries, compelling them to come to the besieged na-
tion’s assistance.
But as we have seen, Australians no longer feel so warmly
toward America, an alienation captured in the :oo, poll by
Australian research organization the Lowy Institute, in which
only half the Australians surveyed had positive feelings about
the United States. At the same time, China has aggressively
wooed Australia, sending its finest diplomats, building up cul-
tural exchanges, offering a strategic partnership, and aggres-
sively promoting the importance of China’s demand for natu-
ral resources to the Australian economy. China has become
Australia’s second-largest trading partner, behind Japan, and
Australian mining companies like BHP Billiton have posted
record profits—in February :ooo BHP Billiton announced the
highest half-year profit in Australian history. Australia’s close
commercial relationship has received major coverage in the
Australian media, making China seem more benign.
31
:I¡ What’s Next?
As in Central Asia, China’s soft power has begun to help
it gain harder objectives in Australia. With Chinese consump-
tion becoming crucial to the Australian economy, and China
itself becoming vastly more popular, Australian politicians
have started to back away from ANZUS. At a press conference
held in Beijing in August :oo¡, Australian Foreign Minister
Alexander Downer told reporters, “The ANZUS obligations
could be invoked only in the event of a direct attack on the
United States or Australia.” Downer continued, with his com-
ments clearly suggesting that Australia would not help the
United States fight a war with China over Taiwan. “Some other
activity elsewhere in the world . . . doesn’t invoke it.” A sur-
prised US State Department issued a sharp rebuke and sent six
cables to Canberra to ask the Australians for an immediate ex-
planation of Downer’s comments, and Australian leaders pub-
licly repudiated Downer.
32
China has tried to build on this potential Australian-US
divide. In March :oo, a top Chinese Foreign Ministry official
suggested that Canberra “relook” at the ANZUS treaty and
reinterpret it so that Australia would not be compelled to help
defend Taiwan. “We all know Taiwan is part of China, and we
do not want to see in any way the Taiwan issue become one of
the elements that will be taken up by bilateral military al-
liances,” he warned. Just to make sure there was no misunder-
standing, he added: “If there were any move by Australia and
the US in terms of that alliance that is detrimental to peace and
stability in Asia, then [Australia] has to be very careful.”
33
Iran. Uzkbekistan. Sudan. What do all these countries have in
common? Freedom House ranks all of them as “not free,” its
lowest possible rating.
34
Governments in all of these places
show little respect for human rights. And China courts all of
What’s Next? :I,
them, selling its model of controlled development and assist-
ing them to build the same model.
This is the most dangerous part of China’s soft power—
the most dangerous to the world, and, potentially, to American
influence. Despite its smooth highways and flashy shopping
malls and reams of Starbucks, China remains an authoritarian
country, a Leninist regime if no longer a Marxist one. Despite
promises of reform, under Hu Jintao China actually has proven
less tolerant of domestic civil society than under Jiang Zemin.
“Plans by some officials to ease regulations and give more
room to civil society, including grassroots groups, appear to
have been shelved,”says Human Rights Watch in its annual re-
port on human rights in the PRC. Despite media coverage sug-
gesting that Chinese officials are allowing more popular pro-
tests, the US State Department recently reported, “There was a
trend [in China] towards increased harassment, detention,
and imprisonment by government and security authorities of
those perceived as threatening to government authority.”
35
Though China may be backsliding on reform, American
leaders and foreign policy elites in other free societies have em-
braced the idea of promoting democracy. When the Berlin
Wall fell, America was led by George H. W. Bush, a traditional
realist wary of interfering in other nations’ affairs, except in
cases of overwhelming American security interests. Since the
end of the Cold War, the elder Bush’s brand of realism has all
but perished, even in the wake of the disastrous Iraq war. The
idea that rich nations should use their power both to intervene
in humanitarian disasters and to reform autocracies has mi-
grated from the creed of a select few American thinkers once
perceived as naïve idealists to the core of the United States’ na-
tional security strategy. As Western leaders witnessed—and
often ignored—genocides in the I,,os, nations realized that
:Io What’s Next?
they had to intervene in catastrophes like those in the Balkans
and Rwanda; otherwise, these mass killings would happen
again, and dangerous leaders in the developing world would
lose any respect for the threat of foreign power. As the post–
Cold War era’s failed states bred civil conflict and havens for
terror like Afghanistan, world leaders recognized that devel-
oped countries could not isolate themselves from the unrest of
the developing world.
Just ten years after George H. W. Bush left office, Amer-
ica’s National Security Strategy announced, “The events of
September II, :ooI taught us that weak states, like Afghanistan,
can pose as great a danger to our national interests as strong
states.” To defeat terror, the National Security Strategy prom-
ised, America would “actively work to bring the hope of de-
mocracy . . . to every corner of the world.” Many liberals, too,
agreed that helping create strong civil societies and democratic
systems in the developing world is not just a good in itself—it
is the key to security, to combating instability and terror. Sub-
scribers to this belief included foreign leaders like Britain’s
Tony Blair and Germany’s Joschka Fischer and members of
both major parties in the United States. Even John Kerry, who
during the :oo¡ presidential campaign heaped criticism on the
White House for its mismanagement of the Iraq War, bought
into the idea of using American power to promote democrati-
zation. “Kerry and his foreign policy advisors are not doves,”
the writer Paul Starobin noted in a :oo¡ profile of the Demo-
cratic candidate. “They are liberal war hawks who would be
unafraid to use American power to promote their values.”
36
Academics provided rigor to these theories. In one prom-
inent study, Harvard professor Alberto Abadie found that na-
tions with the highest levels of political freedom had relative
few incidents of terrorism. Another study, by the economists
What’s Next? :I,
Alan B. Krueger and Jitka Maleckova, demonstrated a link be-
tween terrorism and the lack of civil liberties within societies.
37
Beijing’s support for authoritarian regimes, stemming
from its vow of noninterference, runs exactly contrary to this
American foreign policy. Though their interests sometimes
overlap, fundamentally the United States and China do not
agree on how diplomacy and international affairs should be
conducted. And though Beijing can be persuaded to support
better governance in places, like Burma, with limited resources
and such horrendous regimes that they breed instability in
China, it is much harder to persuade China to act against ter-
rible governments with oil, like Sudan, or whose policies have
no direct impact on China itself, like Zimbabwe. In the future,
China’s ability to support its friends will only grow stronger as
China builds its global soft power.
In the spring of :oo, once-prosperous Zimbabwe, which be-
cause of government mismanagement now boasts the world’s
worst inflation, held a dismal election. As election day drew
near in Harare, Zimbabwe’s capital, President Robert Mu-
gabe’s goons detained hundreds of activists and opposition
politicians. On election day, when thousands of opposition
voters claimed that they had been physically prevented from
going to the polls, Mugabe unsurprisingly won a smashing vic-
tory, then announced that he could remain in power until he
was one hundred. (He was eighty-one at the time.) The US
embassy in Zimbabwe announced that its election monitoring
had uncovered “several patterns of irregularities that raised
concerns about the freeness and fairness of the process.”
38
After the election, Mugabe further consolidated his
power, launching what the Zimbabwean government called
“Operation Drive Out Trash.” As part of this campaign, the
:I8 What’s Next?
state evicted from their homes hundreds of thousands of
urban poor, who tended to be opposition supporters, then
forced the poor people to burn down their own houses.
39
During the sham elections, no major international power
would endorse the Zimbabwe vote—except China. Beijing
didn’t just endorse the election; it may have actively helped
Mugabe win. During the run-up to the election, China offered
planeloads of T-shirts to Mugabe backers, sent the Zimbabwean
government jamming devices to be used against independent
radio stations, and provided Zimbabwe with riot-control gear.
“Providing African countries with aid without any political
strings within our ability is an important part of China’s pol-
icy toward Africa,” Hu Jintao confirmed in a speech.
40
China’s assistance went along with Mugabe’s broader
“Look East”policy of cultivating Beijing, under which the gov-
ernment helps students at Zimbabwe’s public universities learn
Chinese, and Zimbabwean officials tout China’s economic
model as a solution for their nation’s financial woes. Beijing re-
sponded by promoting a trade deal with impoverished Zim-
babwe and sending economic advisers to Harare. China even
hosted Mugabe for a state visit, where one of China’s leading
universities honored the Zimbabwean leader, who had alien-
ated his entire region, for his “brilliant contribution” to global
relations.
41
Mugabe appeared ecstatic over his good fortune. “The
Chinese are our good friends, you see,”he told one interviewer,
barely able to contain a smile. At a rally held on Zimbabwe’s in-
dependence day at a stadium in Harare, Mugabe declared, “We
have turned east, where the sun rises, and given our back to the
West.” Many in the crowd, forced to attend the rally, did not
agree, but Mugabe paid them no mind, warning that state se-
curity forces would “descend mercilessly” on anyone who
What’s Next? :I,
questioned him.
42
As he spoke, Chinese fighter planes looped
over the stadium, which had been built for Zimbabwe by China.
Few Western nations have tried to pressure Beijing to back off
of its support for Mugabe. On Iran, however, a much more
dangerous actor, Europe and the United States have tried to
persuade China to work with them. But Iran is a major source
of oil for China, providing some I¡ percent of Beijing’s im-
ports, and unlike Burma or North Korea, which sit on China’s
borders, domestic events in Iran do not directly affect China.
Since the election of hard-line president Mahmoud Ah-
madinejad in May :oo,, Iran has become more unstable and
threatening. Under Ahmadinejad, the Iranian government has
cracked down on writers and even bloggers, purged Iran’s civil
service of its most moderate members, and called for Israel
to be “wiped off the map.” At the same time, Ahmadinejad
has become more aggressive in touting Iran’s nuclear pro-
gram, which many Western experts believe is designed to
build weapons; Ahmadinejad prevented inspectors from vis-
iting suspected Iranian nuclear sites, called Iran’s nuclear pro-
gram “irreversible,” and oversaw new tests of Iranian missiles.
Ahmadinejad even presided over a bizarre event on Iranian
state television, in which the president celebrated Iran’s nu-
clear ambitions by speaking in front of men dressed in tradi-
tional Iranian costumes, who danced around a silver box Ah-
madinejad claimed held enriched uranium.
43
With Iran defiant, the Bush administration, along with
Britain and France, pushed for a UN Security Council resolu-
tion that would require Iran to stop its uranium enrichment or
face such potential consequences as multinational sanctions.
But the Chinese Foreign Ministry stood fast. Although Beijing
expressed concern about Iran’s nuclear ambitions, China op-
posed any efforts by the Council to censure Iran. The Beijing
::o What’s Next?
People’s Daily newspaper announced, “The real intention be-
hind the US fueling the Iran issue is . . . to pave the way for
regime change in that country.” At the same time, China ex-
panded its oil interests in Iran, tying itself closely with Tehran
by proposing a $Ioo billion deal to develop a new Iranian oil
field. Although China later quietly applied pressure on Tehran,
working behind the scenes to come up with a nuclear com-
promise, it still refused to accept any intervention in Iran’s do-
mestic affairs.
44
Even in cases of genocide, China seems willing to choose
noninterference when the crisis does not threaten its immedi-
ate interests. By the fall of :oo, veteran Africa watchers had
begun warning of impending disaster in the western Sudanese
region of Darfur. Local villagers told foreign aid workers that
the Arab janjaweed, militias reportedly backed by the Sudan-
ese government, were attacking black tribes. The janjaweed,
they said, were trying to wipe out entire tribes, destroying their
towns, possessions, and even their tools.
45
Over the next year, janjaweed attacks escalated. The
World Health Organization reported that as many as ten thou-
sand people were perishing per month in Darfur. United Na-
tions monitors sent to the region in April :oo¡ came back with
tales of massacres, gang rapes, and worse. By September :oo¡,
then–Secretary of State Colin Powell told the Senate Foreign
Relations Committee, “We concluded—I concluded that gen-
ocide has been committed in Darfur.”
46
In response to the cri-
sis, the UN Security Council passed a resolution in September
:oo¡ condemning the killing.
China, the major consumer of Sudan’s oil and most im-
portant foreign partner, did not budge. (China National Petro-
leum Corporation owns ¡o percent of Sudan’s oil consortium.)
Beijing allegedly did nothing to stop its state-linked oil compa-
nies from removing populations of average Sudanese to replace
What’s Next? ::I
them with oil installations. It worked at the United Nations
to water down condemnations of the Sudanese government.
China’s UN ambassador, Wang Guangya, pushed the United
Nations to change a resolution from calling for “further action”
against Sudan’s government to considering “taking additional
measures.” Beijing then threatened to veto any subsequent res-
olutions that imposed sanctions on the Sudanese leadership. As
China’s Deputy Foreign Minister Zhou Wenzhong said, “Busi-
ness is business. We try to separate politics from business. Sec-
ondly, I think the internal situation in the Sudan is an internal
affair, and we are not in a position to impose upon them.”
47
Over the following years, the situation deteriorated fur-
ther. Sudanese soldiers blocked access to some of the Darfurian
refugee camps, ensuring that even larger numbers of people
would die. Human Rights Watch estimated that at least two
million Darfurians had been driven from their homes.
48
Casu-
alty counts skyrocketed, and the crisis spilled into other coun-
tries, destabilizing neighboring Chad. By the spring of :ooo,
the Sudan expert Eric Reeves estimated that more than ¡,o,ooo
people had died in Darfur, and nearly ,o percent of the black
villages in Darfur had been ruined. Reeves further concluded
that communities would never rebuild, since the janjaweed
had murdered an entire generation of Darfurian men.
Still China did not budge. On a visit to the United States
in April :ooo, Hu Jintao offered no concessions on China’s
support for Sudan. Chinese foreign ministry officials repeat-
edly emphasized that they opposed any economic sanctions on
Sudan, no matter how grave that regime’s offenses.
Citizens of authoritarian regimes like Zimbabwe or Sudan are
not the only ones who suffer from China’s influence; China’s
support for dictators damages American interests. For years,
::: What’s Next?
the United States and its allies had tried to pressure Mugabe to
loosen his control of the political system, and Zimbabwe was
proving one of the world’s major tests of whether the United
States and its democratic allies could actually help transform
other societies. Western countries had slapped sanctions on
Zimbabwe, and the Commonwealth of Nations, the associa-
tion of former British colonies, had suspended Zimbabwe
from the group. But with China’s support, Mugabe could ig-
nore Western pressure.
In August :oo, Mugabe said as much. In a televised
speech, he ruled out any talks between himself and the politi-
cal opposition—talks favored by many foreign powers, in-
cluding neighboring South Africa. “I am aware there are shrill
calls from many quarters,” the Zimbabwean leader said. But,
he said, Harare would not bow to pressure, since “our Look
East policies are beginning to assume a concrete form. . .
transform[ing] our economy in a fundamental way.”
49
In other countries, too, China’s backing of dictators
makes Washington look weak and reduces pressure on unsta-
ble, rogue actors like Sudan or Venezuela or Iran. In Sudan,
China’s decisions not only condemned tens of thousands of
Darfurians to death but also helped demonstrate to the world
that the United States, the world’s biggest power, could not
stop genocide. (To be sure, some critics have argued that the
Bush administration did not press hard enough for tougher
UN action against Sudan, but it tried far harder than China.)
In Chávez’s case, China’s backing actually helps boost his re-
gional profile. This adds prestige Chávez can use to convince
other leaders in Latin America, like his fellow populist Bolivian
President Evo Morales, to follow Chávez’s autocratic policies.
In Iran, China (aided by Russia, which has significant in-
terests in Iran) also serves as the major impediment to further
What’s Next? ::,
pressure, and to keeping nuclear weapons out of the hands of
the Iranian regime. China is effectively prolonging the Iranian
nuclear stalemate, making it more likely that Tehran will ac-
quire nuclear weapons and reducing pressure on a dangerous
actor. In this way, Beijing again weakens Washington’s global
influence, since the United States talks tough but the world
sees that it does not have the appeal to persuade enough na-
tions to support its pressure on Iran.
In the long run, however, China’s relations with countries like
Sudan could come back to haunt Beijing. If countries like
Sudan or Zimbabwe ever made the transition to freer govern-
ments, China could face a sizable backlash for its past support
of authoritarian rulers, just as the United States now faces left-
leaning governments in Latin America resentful of past US
backing for conservative Latin dictators. This is one reason,
perhaps, why Chinese officials have begun cultivating contacts
with opposition activists in countries like Burma. “Don’t you
think that if Burma became a democracy all the leaders might
remember who helped keep them in jail before?” asked one
Burma activist. “There could be an immediate popular back-
lash against all the Chinese businesses and officials in Burma.”
50
Locals angry over China’s propping up bad governments
already have attacked Chinese businesspeople in the Pacific Is-
lands, Venezuela, Burma, and elsewhere. If the killing in Sudan
continues, and if China is perceived as doing nothing to help
solve the Darfur crisis while taking out vast quantities of Su-
danese oil, protesters eventually might wind up directing vio-
lence at the thousands of Chinese who have come to Sudan to
set up businesses or work in the oil industry.
Even China’s old comrades have turned against Beijing.
In the Philippines, the New People’s Army, a communist in-
::¡ What’s Next?
surgent group, once based its rhetoric on Mao’s teachings and
exempted Chinese businesspeople from its attacks. In the
I,oos and early I,,os Beijing even provided support for the
NPA. But China cut off its aid to the NPA long ago, and now
NPA soldiers threaten Chinese companies coming to the Phil-
ippines as well. The NPA views them as no different from other
firms—as equally guilty of “stealing” the Philippines’ re-
sources.
51
What’s Next? ::,
XI
Responding to
the Charm Offensive
n a short period of time, Beijing has proven that it can
shift its foreign policy quickly and woo the world, often fo-
cusing on countries America has alienated. China has dras-
tically changed its image in many parts of the world from
dangerous to benign. It may already be the preeminent power
in parts of Asia, and it could develop China-centered spheres
of influence in other parts of the globe, like Central Asia or
Africa. Even longtime American allies like Australia have
moved closer to Beijing.
But these changes do not mean that China’s soft power
yet approaches America’s, or that the United States will not re-
main the essential power in world affairs. They do not mean
that the United States will never recover its lost appeal. As
Joseph Nye notes, the United States recovered from a similar
decline in its international soft power in the wake of the Viet-
nam War, partly by reemphasizing American values that ap-
peal to the world.
1
The United States still enjoys several crucial advantages over
China. America remains the world’s unchallenged military
power. Military power does not necessarily ensure soft influ-
ence—North Korea retains a massive army but few people are
listening to North Korean music. But military power, if used
correctly, can complement soft power. Military power can be
deployed for humanitarian missions that then improve a na-
tion’s popularity, like American relief efforts after the :oo¡
Pacific tsunami. The tsunami demonstrated that only the
United States has a sufficiently sophisticated military to move
aid overnight. And the tsunami response, combined with ag-
gressive American public diplomacy that highlighted the re-
lief effort, clearly altered opinions of the United States, even
among some of the most anti-American groups. In Indonesia
you did not have to look hard to find strident anti-American
sentiment before the tsunami hit: after the September II at-
tacks, Indonesian Vice President Hamzah Haz declared that
the terrorist attacks might “cleanse the sins of the United
States.” After seeing American marines delivering relief to the
shattered province of Aceh, one of the most devoutly Muslim
parts of Indonesia, many Indonesians changed their minds.
A survey of Indonesians taken in January :ooo found that un-
favorable views of America had dropped from ¡8 percent
in :oo¡ to I, percent. “There has been an incredibly deep
emotional connection between America and Indonesia since
the tsunami,” Indonesian President Susilo Bambang Yudho-
yono told the audience during a dinner in :oo,. “When the
USS Lincoln and the USNS Mercy ended their humanitarian
mission in Aceh and Nias [another part of Indonesia], they
Responding to the Charm Offensive ::,
left behind thankful patients, tearful friends, and a grateful
nation.”
2
Military power also can help defend allies and friends,
thereby improving popular and elite opinion. Only the United
States has the blue-water navy, basing agreements around the
world, and rapid reaction forces to come to the aid of any friend
threatened by conflict. Elites in most foreign countries, includ-
ing China, recognize this, and understand that it will be decades
before Beijing has the potential to perform a similar role. The
:oo, study of Thailand commissioned by the US embassy,
which revealed growing warmth toward China, also showed that
“The US has always been the prime choice as a security partner.”
Even elites in countries that fought recent wars with the United
States understand that only America can act as the global po-
liceman. “Vietnam sees the US as the only superpower that can
really influence major events, and so Vietnam must deal with
the US,” said one official from Hanoi’s Institute of International
Relations, the Vietnamese government’s think tank.
3
The United States also remains the world’s preeminent
economic power. For all its staggering growth, China remains
a developing country, with a gross domestic product per capita
of less than $,,ooo, calculated using purchasing power parity.
America’s GDP per capita, by comparison, now tops $¡o,ooo.
At least for now, American investment dominates foreign di-
rect investment in developing countries. The United States’
dynamic economy and relatively open door to immigration
allow US companies to remain world leaders in technology.
This technology reflects back on America as a land of innova-
tion—even in global polls where respondents do not support
American policy, majorities usually express admiration for
American science and technology.
4
Although Chinese-language studies and Chinese culture
::8 Responding to the Charm Offensive
have become more popular, they remain no match for Ameri-
can popular culture. The United States stands as the biggest
source of film, television, popular music, and fiction and non-
fiction books. Average people across the developing world still
prefer to send their sons and daughters to universities in the
United States, which they consider the best schools in the
world. In a :ooo ranking of the world’s top universities con-
ducted by Shanghai’s Jiao Tong University, which examined
quality of education, quality of faculty, and research output,
American schools took eight of the top nine places.
5
Most important, the United States still offers a political
and social model, a set of values, which can appeal to average
people around the world. China’s values—noninterference,
respect for other nations’ internal affairs, economic gradual-
ism directed by the state—can enjoy appeal. But China’s val-
ues appeal only to specific groups: elites in authoritarian na-
tions; average people in countries like Venezuela or Iran that
equate the American model with the failing Washington Con-
sensus or American interventionism; populaces in states will-
ing to trade away some degree of political freedom for Chi-
nese-style growth rates. China cannot offer average people a
comprehensive, inspiring vision of how to build a free, rights-
oriented political system and economy, a vision that remains
popular in many parts of the world. In studies of Asian popu-
lations taken by the East Asia Barometer, a comprehensive
project examining opinion in nine countries, majorities in
every nation said that they desired democracy rather than any
other type of political system. “If America does live up to its
values, it will find states in Asia who can and will cooperate,”
notes Simon Tay, a leading Singaporean commentator.
6
Even in less free regions of the world, studies show the
same trend. In Pew polls taken in :oo,, more than 8o percent
Responding to the Charm Offensive ::,
of people in Muslim nations like Morocco, Jordan, and Leb-
anon believed that Western-style democracy could work in
their countries. They clearly desired American-style demo-
cratic freedoms, including freedom of the press, multiparty
systems, and freedom of expression.
7
China also may not be able to build its soft power indefinitely.
As we have seen, greater familiarity with China will expose
many countries to the People’s Republic’s flaws. China’s prom-
ises of aid and investment could take years to materialize, yet
Beijing has created heightened expectations about its potential
as a donor and investor in many countries. China’s exporta-
tion of labor, environmental, and governance problems alien-
ates average people in Asia, Latin America, and Africa. China’s
support for autocratic rulers in countries like Zimbabwe and
Sudan angers civil society leaders and opposition politicians. If
Beijing seems to be dropping its preference for noninterfer-
ence and “win-win” relations, it will spark fears in countries
like Vietnam already suspicious of China. It also could re-
inforce the idea that despite Beijing’s rhetoric of cooperation,
when it comes to core interests, China, like any great power,
will think of itself first. The Mekong River offers.
8
China could further alienate other nations if it seems to
be using multilateral institutions as a cover, without jettison-
ing Beijing’s own more aggressive, even military aims. Despite
:,o Responding to the Charm Offensive
signing a deal with the Philippines and Vietnam for joint ex-
ploration of the disputed South China Sea, Beijing has not re-
tracted its claim to large swaths of the water. Any Chinese
decision that appears arrogant or targeted toward Chinese domi-
nation of the region will cause a backlash. Even as officials in
Vietnam signed the joint exploration deal, they privately warned
that they still could not trust their Chinese counterparts
enough to share the most important data with Beijing.
Similarly, if China drops its rhetoric of “win-win” rela-
tionships and makes more aggressive, unilateral demands, it
could provoke a backlash in Asia, which is relying on multilat-
eral institutions to restrain China from regional dominance.
Some Chinese officials have begun to act more assertively. In
:oo, one former Chinese ambassador to Singapore warned
that Beijing would no longer bow to other nations; as she told
a business forum, Singaporeans had to lose their “air of supe-
riority” if they wanted to continue dealing with China.
9
China’s trade relations, too, ultimately could limit its soft
power. If China builds the kind of trade surpluses with the de-
veloping world that it enjoys with the United States, it could
stoke local resentment. Eventually, Beijing could wind up
looking little different $,., billion in electronics to China and
import more than $o billion worth. In Malaysia one study of
Responding to the Charm Offensive :,I
local manufacturing found that the country is rapidly losing
its ability to compete with China in manufactured goods. “To
compensate for the decline,” the study concluded, “Malaysia is
turning towards resource-based exports [like] oil, petroleum
products, liquefied natural gas, and wood-based products
[that] are top exports to China.”
10
Beijing also may fail in its efforts to persuade diaspora
Chinese to return. After years of Chinese officials traveling
across the world wooing ethnic Chinese organizations, many
diaspora Chinese are shocked by the welcome they get when
they finally travel to the People’s Republic. In Malaysia, In-
donesia, Thailand, and many other countries, local ethnic Chi-
nese businesspeople constantly complain about China. Many
of these diaspora Chinese made investments in China ex-
pecting some kind of preferential treatment on the mainland.
When their Chinese business partners squeezed them, or
mainland Chinese looked down on them because they did not
speak Mandarin, some found that being in China just empha-
sized how little they had in common with people in Beijing or
Shanghai. “Ethnic Chinese in Indonesia go back to China and
find they don’t like China,” said Ong Hok Ham, an Indonesian
Chinese historian. “They are disappointed in how different
they are from the Chinese.” Conversely, mainland Chinese do
not necessarily see the diaspora Chinese as brothers and sis-
ters..”
11
:,: Responding to the Charm Offensive
Even diaspora Chinese companies with the closest links
to China sometimes can feel alienated. Charoen Pokphand, the
Thai conglomerate that invested so much time over the years
cultivating Chinese leaders, found in the mid-I,,os that Bei-
jing had denied it valuable telecommunications concessions.
Most famously, in the early I,,os China allowed Singaporean
companies to build an enormous industrial park in the eastern
Chinese city of Suzhou. Lee Kuan Yew, the founder of modern
Singapore, took a personal interest in the industrial park. De-
spite this high-level support, the Singaporeans still came away
angry. They complained that their Chinese partners backed a
rival industrial park. They alleged that their partners were pil-
ing up wasteful spending, resulting in tens of millions in losses.
Finally, the Singaporeans just gave up, selling majority owner-
ship in the park to mainland Chinese developers.
12
When these countries have concerns about China, the obvious
place for them to turn is the United States, the other great
power. Asian nations are always “playing the US off of the Chi-
nese—dangling what the Chinese will offer in order to get the
US more interested in them,” one senior American policy
maker told me.
13
Washington should be prepared to simulta-
neously leverage Beijing’s charm on issues of interest to both
the United States and China, like preventing disruptions in
global energy supplies, while rebuilding America’s soft power
so that the United States has the ability to confront China on is-
sues where American and Chinese interests diverge. To accom-
plish this, America first has to understand Chinese soft power.
The United States needs to comprehend exactly how
China exerts influence. In part, this can be accomplished
through efforts like Congress’s U.S.-China Engagement Act,
Responding to the Charm Offensive :,,
which would create more American missions in China. invest-
ment, China’s public diplomacy, Chinese leaders’ visits.
As anyone who has worked for a large organization
knows, if your boss tells you to do five tasks, you will try to
finish all five. But if your boss hires you to do only one job, like
studying China’s charm offensive, you will be more likely to
produce great work, since you have no subsidiary responsibil-
ities. After all, Chinese embassies closely monitor US relations
with each nation, even as Chinese diplomats cooperate with
their American peers on topics of mutual concern. Surely, the
world’s greatest power should be able to figure out what China
is doing while also dealing with Chinese diplomats on issues
both Washington and Beijing care about, such as drugs, HIV,
and nuclear weapons proliferation.
With a better understanding of China’s soft power, Wash-
ington can more systematically set clear limits—for itself, for
China, and for other nations—and establish where it believes
China’s soft power possibly threatens American interests. As
we have seen, these US interests include other nations’ territo-
rial integrity; support for the United States in case of a conflict
in regions like Southeast Asia; control of sea lanes and water-
ways; access to resources; formal alliances with foreign na-
tions; and, perhaps most important, the promotion of democ-
ratization and good governance.
To protect these interests, the United States must focus
:,¡ Responding to the Charm Offensive
on rebuilding its soft power. Otherwise, it will face even more
situations where citizens of democratic nations put pressure
on their leaders not to cooperate with the United States. In-
deed, unlike during the Cold War, as the world has become
more democratic, America’s core interest—its national secu-
rity—increasingly relies on wooing foreign publics.
Rebuilding soft power will require a multifaceted initiative. It
will require a clear, concrete national public diplomacy strat-
egy. This strategy would begin by defining the role of the US
public diplomacy czar. If the president names an internation-
ally famous figure, rather than someone like Karen Hughes—
say, a revered figure like Colin Powell or Bill Clinton—the czar
could then reach out not only to elites abroad but also to larger
segments of foreign populations.
The czar will have to rebuild the public diplomacy appa-
ratus, which still has not recovered from cuts in the I,,os,
though there are encouraging signs, like congressional support
for increases in cultural exchanges. Congress and the adminis-
tration will have to reconsider past cuts in core public diplo-
macy tools like Voice of America, or American Centers offer-
ing library facilities and cultural programming in foreign
countries. The United States also will have to rethink its visa
processing and other new security measures, which have alien-
ated so many foreign travelers. The State Department has
taken some steps to address the obstacles to foreign visitors,
like trying to expedite visa applications.
15
Some public diplomacy efforts could be targeted at cer-
tain ethnic groups, the way China has tried to woo diaspora
Chinese. Why not entice Latin American opinion leaders who
already have relatives in the United States? Why not reach out
Responding to the Charm Offensive :,,
to Lao and Vietnamese and Cambodian businesspeople who
already have connections to Lao Americans or Vietnamese
Americans, so that businesspeople in these countries have
more contact with their American counterparts?
The United States also will have to protect its image of
fair reporting by government-funded radio and television out-
lets like Voice of America. It is unbiased, stellar reporting that
has earned the British Broadcasting Corporation trust—trust
that reflects back upon the United Kingdom. The United States
also could support independent and indigenous media orga-
nizations in foreign countries—for example, by helping train
local reporters. Such support, to be effective, would have to
mean turning the other cheek if those very media groups
sometimes criticize America.
16
Renewed public diplomacy also will require Washington
to promote its specific policies, and to listen to locals for advice
on what kinds of aid to provide. Department of Defense docu-
ments reveal that Pentagon contractors who visited Southeast
Asia in :oo, repeatedly found a perception that “US policy and
assistance programs are mainly focused on counterterrorism
rather than social and economic development”—even though
local leaders preferred assistance for economic development.
But when the United States does use its aid to address local
concerns, it can change minds. One study of public percep-
tions of America in two important developing nations, Mo-
rocco and Indonesia, found that when locals learned about
specific, concrete US assistance programs, they were more likely
to view America positively. By contrast, promoting broader
images of the United States, like a poorly conceived post–
September II public diplomacy initiative to portray America
as a land of tolerance toward Muslims, has little effect.
17
Changing the nature of aid, so that it is more relevant to
:,o Responding to the Charm Offensive
recipient nations, will help the United States win back soft
power, too. It will reduce the causes of anger at America—as
when students dropping out of Indonesia’s impoverished pub-
lic schools wind up in more radical private Islamic schools. It
will address concerns that America cares only about security
and counterterrorism. It will reflect American strengths, like
the United States’ skill in combating disease and in providing
food and clean water: in :oo¡, the United States signed an
agreement with Indonesia to provide more than $¡,o million
in aid for nutrition, education in Indonesian public schools,
and other necessities. US policy makers also have started to
recognize that more American assistance needs to go toward
local organizations in countries, rather than US aid groups or
businesses.
18
This helps distinguish American assistance from
Chinese aid linked to jobs for Chinese firms.
Supporting public diplomacy, the United States will need to
rethink its formal diplomacy—how its diplomats operate on
the ground, and how its top leaders interact with leaders and
populaces abroad. Some of these changes should steal ideas
from China. China has pushed its diplomats to return to one
country for multiple tours of duty and to learn local languages.
Unlike China, the US Foreign Service cannot force its employ-
ees to go to any country, but the State Department could more
aggressively encourage its Foreign Service Officers to pick one
region of the world (or even one country), specialize in that
area, and return to it over and over. To do so, the Foreign Ser-
vice could provide incentives to promote taking time off for
language training. Currently, many Foreign Service officers
complain that if they take time away for extensive language
training, they penalize themselves, since it becomes harder for
them to get back on career tracks.
Responding to the Charm Offensive :,,
This emphasis on better language skills may allow the
United States to avoid what the Council on Foreign Relations
scholar Julia Sweig calls the “8o/:o problem,” in which the
United States relies on English-speaking elites—:o percent of
the population—to understand foreign countries. If diplo-
mats enjoy a more in-depth understanding of a country, they
may interact more with the “other” 8o percent of populations,
including more nongovernmental organizations, political ac-
tivists, advocates for the poor, and religious leaders.
19
The United States could steal other moves from China.
As we have seen, in its formal diplomacy China woos countries
by bringing its cabinet-level officials on regular trips to na-
tions. Call this using the whole bench—leveraging even minor
cabinet members to boost relations, the way good basketball
teams bring in sixth and seventh men to spell the starters.
Washington could do the same, making sure everyone from
the secretary of agriculture to the trade representative devotes
as much face time to Asia, Latin America, and Africa as they
currently do to Europe.
The United States could take other lessons in formal
diplomacy from China. China seems to sign bilateral agree-
ments on cooperation, trade, and security at a moment’s no-
tice. Washington will never be able to make deals without an-
alyzing each agreement. Still, the United States can appear
open to moving more quickly, and to being a partner that lis-
tens to other nations’ concerns. Washington could sign the As-
sociation of Southeast Asian Nations’ Treaty of Amity and
Cooperation (TAC), for example, which would not necessarily
bind the United States to any concrete promises but would
please many countries in Asia. (US officials suggest that Amer-
ica could sign the TAC in such a way that would allow it to
:,8 Responding to the Charm Offensive
be ratified by the Senate, which is historically suspicious that
treaties will cost America sovereignty.) The United States could
match China’s trade diplomacy by using trade and investment
framework agreements, which are means of signaling to other
nations that the United States will move toward a free trade
agreement with them.
20
During a visit to Southeast Asia in May :oo,, former
Deputy Secretary of State Robert Zoellick, an experienced
diplomat, showed how it could be done. Rather than arriving
at meetings touting his own agenda, Zoellick emphasized that
he wanted to listen to other countries’ concerns. He touted
“consulting with our partners, sharing some ideas, and listen-
ing to their thoughts.” He brought with him new aid not re-
liant on counterterrorism cooperation, though behind closed
doors he discussed terror issues. He talked up America’s desire
to engage with regional groups. Even “when he publicly dis-
cussed thorny issues such as Burma’s upcoming chairmanship
of ASEAN and religious freedom in Vietnam, Mr. Zoellick was
consciously diplomatic in appearing firm but not overbearing,”
gushed Evelyn Goh, a Singaporean scholar.
21
None of this public diplomacy or formal diplomacy will
matter, though, if the globe continues to detest American poli-
cies. The world’s anger will not be easily placated—it is more
intense than anti-American sentiment during the Vietnam
War. But it can be addressed. It can be addressed, first of all, if
Washington reconsiders its opposition to multilateral institu-
tions, an opposition that has fostered perceptions of America
as bully. This does not mean supporting a multilateral organi-
zation that seriously limits American sovereignty. But the UN
cultural treaty, the treaty on land mines, the International
Responding to the Charm Offensive :,,
Criminal Court, and other institutions—participating in
these could help rehabilitate America’s image.
Washington should not only reengage with multilateral
organizations but also remind the world that the United States
was the driving force behind the modern international sys-
tem—the World Trade Organization, the United Nations, the
World Bank, the International Monetary Fund. By creating
and participating in these institutions after the Second World
War, Washington demonstrated that America would follow in-
ternational law. According to Ivo H. Daalder and James M.
Lindsay, authors of America Unbound: The Bush Revolution in
Foreign Policy, “The hallmark of [Harry] Truman’s foreign pol-
icy . . . was its blend of power and cooperation. Truman was
willing to exercise America’s great power to remake world
affairs, both to serve American interests and to advance Amer-
ican values. However, he and his advisers calculated that U.S.
power could more easily be sustained, with less chance of en-
gendering resentment, if it were embedded in multilateral in-
stitutions.”
22
Developing countries today do not want America to go
away; they want America involved in the world, if the United
States plays the Truman-era role of an arbiter of fairness and a
defender of freedom. “The US should stand up for free trade.
Washington should resist new protectionist measures . . . and
curb the frequent abuses of trade measures,” notes Tommy
Koh, ambassador at large in the Singapore Ministry of Foreign
Affairs. Indeed, citizens of developing countries still see the
United States as a symbol of economic freedom and a country
committed to global economic prosperity. In a poll of Thai cit-
izens by the US embassy in Bangkok, ,, percent of respondents
believed that Thailand and America were working together to
boost economic prosperity in Asia.
23
:¡o Responding to the Charm Offensive
America’s core values can still resonate, too. As we have
seen, many average people around the world desire a free,
rights-oriented political system. When they perceive the United
States as helping them achieve that type of system, America’s
appeal booms: as Julia Sweig writes, during the I,,os the
United States often “set forth a positive agenda”in Latin Amer-
ica by backing civil societies recovering from years of war and
by promoting democracy. Though by the end of the decade
many Latin American nations had become alienated by the
failure of the free-market “Washington consensus” to boost
economic growth, the US commitment to democracy did res-
onate with many average Latin Americans. “Latin America
welcomed the new approach. . . . The message from the North
was largely positive, inclusive, and respectful,” Sweig notes.
24
When foreigners perceive the United States as ignoring
those core values, America’s appeal plummets. To avoid this,
America will have to live up to these values in its own actions.
This means showing the world that, even when the United
States makes mistakes, it remains an open society capable of
criticizing itself—for example, by conducting well-publicized
investigations of allegations of abuse at places like secret pris-
ons to which the United States allegedly sends terrorism sus-
pects. It means rallying the world to pay attention when real
catastrophes threaten, like the genocide in Darfur. It means
reinvigorating America’s commitment to the post–World War
II institutions it created, whether by helping countries enter
the WTO so that poor nations benefit from trade, or by resist-
ing American companies’ own protectionist impulses, or by
taking the lead in revamping the United Nations, rather than
giving up when UN reforms falter.
Washington also can subtly push other countries to em-
brace these democratic values, while minimizing fears that the
Responding to the Charm Offensive :¡I
United States’ promotion of democratization means that it
will be going around the world dominating other countries’
internal affairs. Indonesia provides an example. As the world’s
largest Muslim nation has solidified its young democracy, the
United States has assisted by promoting visits of Indonesian
parliamentarians to Washington and supporting elite Indone-
sian universities germinating the next generation of Indone-
sian leaders.
25
Yet the White House has largely ceased lecturing
Indonesia on how it should manage its democratization, and
it has pushed to eliminate previous sanctions on the country,
signaling that it approves of changes in Indonesia. Building on
these efforts, the United States could create an informal com-
munity of democracies in regions like Africa or Asia. In Asia
that community might include Indonesia, Australia, Thailand,
South Korea, Japan, and Singapore. Washington would consult
closely with the democracies on important regional issues—
suggesting that there are clear rewards for countries that pur-
sue a democratic path.
If the United States regains this appeal in the world, it can
then deal with a more powerful China from a position of
greater strength, and can more easily cooperate with Beijing
and tolerate Beijing’s becoming a greater power in regions like
Southeast Asia. As we have seen, Washington and Beijing have
many overlapping interests: both are major energy consumers
and desire global stability in order to access resources like oil
and gas; neither has any desire to see a nuclear North Korea or
a nuclear standoff in South Asia; both want to combat HIV,
avian flu, and other transnational disease threats; both are
committed to counterterrorism and counternarcotics; both
desire continued reductions in barriers to free trade; both
want to prevent failed states in the developing world. In fact, in
:¡: Responding to the Charm Offensive
the long run the United States, which has asked China to be-
come a “responsible stakeholder” in the world, may push Bei-
jing to take a larger international role on aid, trade, and many
other issues.
Working together on these issues will require Beijing to
use its charm and, potentially, to amass more soft power in
parts of the world—changes that could cause alarm in the
United States if America remains weak and unpopular abroad.
By contrast, if America seems popular and strong, allowing
China to assume more responsibility for the globe will become
easier for America to accept.
During a trip to Burma in :oo,, I happened to be in Rangoon
during Christmas. Although few people in Buddhist Burma
actually celebrate Christmas, as in other parts of Asia the hol-
iday provides a welcome opportunity to throw parties and buy
presents for friends.
From my hotel in Rangoon, I called my old friend Khin
Maung Thwin, who once worked with me at the newswire
Agence France Presse; he would send his stories from Rangoon
to Bangkok, where I would edit them and ship them out to the
world. A tall Burmese man with smooth, almost babyish skin,
Khin Maung Thwin, whom everyone called Eddie, had been
working at the wire for more than three decades, after previ-
ously having developed the best sources in the military gov-
ernment as a tennis instructor at one of Rangoon’s top clubs.
Though aging, Eddie remained one of the few reporters
able to produce a relatively independent story in his closed, au-
tocratic country. Perhaps his old military tennis buddies pro-
vided him some protection. Perhaps his advanced age saved
him from the worst abuses by his government.
Responding to the Charm Offensive :¡,
When I reached Eddie on a crackling phone line, he in-
vited me to the annual Christmas party at the Rangoon sailing
club, on the shores of Rangoon’s Inya Lake. Sailing was a bit of
an overstatement—it was more like a floating club. Though
the club had been around since the I,:os, then the lair of sod-
den British colonials, its boats, like the Burmese economy, had
fallen into disrepair. Today the club’s collection of “yachts”
consisted of wooden dinghies that looked like they might sink
at any moment; though the club attracted Rangoon elites, they
apparently did not have enough money to repair the boats
properly.
I met Eddie and his wife in the club at nightfall. Rangoon
elites dressed in crisp sarongs sat on the lawn sipping tiny
glasses of Johnnie Walker and munching on nuts and samosas.
Near the water, a band of Burmese rockers in spiked hair played
tinny pop songs for teenagers. Eddie and I chatted about work-
ing for Agence France Presse, recalling how I used to scream
into the phone in Bangkok so that he could hear me through
Burma’s antiquated phone lines.
A middle-aged Burmese businessman double-fisting
glasses of Johnnie Walker cornered me when Eddie strolled off
to get his wife a drink. The man, whom I will call Zaw, intro-
duced himself—I seemed to be the only foreigner at the
party—and took my arm to guide me into the clubhouse. In-
side, plaques honored past skippers and captains of the year,
dating back to the British colonial era. “My father used to bring
me here,” Zaw said with a smile, revealing stubby teeth stained
red by years of chewing betel nut, the mild narcotic popular in
Burma. He tossed back one drink and got a quick refill from the
bartender. “It was great then, but now. . . ”His voice trailed off.
We walked back outside. “The economy is just getting
worse,” he told me. “Foreign companies are pulling out, and I
:¡¡ Responding to the Charm Offensive
have to switch jobs all the time to keep making money.” He
passed me his business card, which listed his numerous occu-
pations—antiques dealer, export-import manager, and other
titles. “I need to get out here,” Zaw said. “Nothing works.” He
pointed around at the other guests, many of whom seemed to
be drinking themselves to sleep.
As the evening wore on, our conversation turned to Iraq;
in March, US forces had invaded the country, and by Decem-
ber, before the Iraqi insurgency gained strength, the invasion
still seemed a success. I did not want to discuss the Iraq War,
but Zaw kept bringing it up. He seemed to have faith that the
invasion ultimately would bring benefits to Iraqis, telling me
that he envied people in Baghdad, even though security had al-
ready begun to deteriorate in the Iraqi capital.
Zaw’s eyes were turning red, and he held my arm more
firmly. “I’ll do anything to leave,” he told me. “Or maybe Bush
will invade Burma?” I smiled weakly and said that I did not
think Rangoon was high on the list of US military targets. Zaw
sighed and let go of my arm and almost fell onto the ground.
He righted himself and grinned, but it was a grin that con-
cealed fear and anger. “Only the US can save us,” he said. He
started to walk away, and I saw him collapse in the back seat of
a car. I turned back to the party and watched as the rock band
attempted mangled versions of Christmas carols.
Responding to the Charm Offensive :¡,
Notes
Preface
For comparisons of US and Chinese military spending, see Esther Pan, “The
Scope of China’s Military Threat,” Council on Foreign Relations, online pub-
lication available at:¡/, accessed June
:ooo, and Adam Segal, Chinese Military Power: Independent Task Force Re-
port (New York: Council on Foreign Relations Press, :oo,).
Chapter I:
Courting the World
I. “Bush Hecklers Ordered Out,” CNN.com, :, Oct. :oo,, online pub-
lication available at
Io/:,/apec.special.bush.heckle/index.html, accessed June :ooo.
:. Adam Harvey, “Mister Untouchable,” Sunday Sydney Telegraph, :o
Oct. :oo,; “Bush Hecklers Ordered Out.”
,. Louise Perry, “Hu a Lesser Evil Among Activists,” The Australian, :,
Oct. :oo,; Nick Squires, “The Chorus of Dissent Is Muted as Protestors
Change Their Tactics,” South China Morning Post, :, Oct. :oo,.
¡. Nick Squires, “China’s Growth Benefits Region, Says Downer,”
South China Morning Post, ,o Oct. :oo,.
,. Ivan Cook, Australians Speak, :oo,: Public Opinion and Foreign Pol-
icy (Sydney: Lowy Institute, :oo,).
o. Joseph S. Nye Jr., Soft Power: The Means to Success in World Politics
(New York: Public Affairs, :oo¡), ,–o.
,. Ibid., o.
8. USIA helped oversee the US-Soviet Exchange Initiative, for ex-
ample, which promoted exchanges of scholars. See “VOA History,” http://, accessed Nov. :ooo.
,. Nye, Soft Power, I,.
Io. Melinda Liu, “Divide and Conquer,” Newsweek, , Mar. :oo,, I¡; see
also “Interview with Thaksin Shinawatra: Thailand Aims to Further En-
hance Thailand-China Strategic Partnership,” People’s Daily, :8 June :oo,.
Philip P. Pan, “China’s Improving Image Challenges U.S. in Asia,” Washing-
ton Post, I, Nov. :oo,.
II. Though Australia historically was not included in Southeast Asia,
I will include it, since Southeast Asia is the region of Asia closest to Australia.
I:. “Wen Calls for More Help for Africa,” China Daily, I, Dec. :oo,;
BBC/PIPA poll, I, Nov. :oo¡ –, Jan. :oo,.
I,. Andrew Moravcsik, “Dream on, America,” Newsweek, ,I Jan.
:oo,, ::.
I¡. For more on the idea of a Chinese Monroe Doctrine, see Marvin
C. Ott, “China’s Strategic Reach into Southeast Asia,” Presentation to US-
China Economic and Security Review Commission, :: July :oo,.
Chapter ::
Changes on the Home Front
I. See, for example, Mao Tse-tung, Opening Address at the Eighth Na-
tional Congress of the Communist Party of China, I,,o.
:. For an insightful analysis of the Great Leap Forward and its conse-
quences, see Jasper Becker, Hungry Ghosts: Mao’s Secret Famine (New York:
Free Press, I,,o).
,. On “righteous struggles” see, for example, Mao, Opening Address.
On Burma see, for example, Bertil Lintner, The Rise and Fall of the Commu-
nist Party of Burma (Ithaca: Cornell University, I,,o). On the size and scope
of Chinese assistance to the Khmer Rouge, see, for example, Ben Kiernan,
The Pol Pot Regime: Race, Power, and Genocide Under the Khmer Rouge, :,,,–
:,,, (New Haven: Yale University Press, I,,o). See also Tom Fawthrop,
“Middle Kingdom Puts the Squeeze on Little Kingdom,” Phnom Penh Post,
:, May :ooI. On Chinese influence in Africa and the Middle East, see, for ex-
ample, Stephen A. Cheney, “The Insurgency in Oman, I,o:–I,,o,” http://¡/CSA.htm, accessed Nov.
:ooo; and Drew Thompson, “China’s Soft Power in Africa: From the ‘Beijing
:¡8 Notes to Pages o–I¡
Consensus’ to Health Diplomacy,” China Brief, Jamestown Foundation, I,
Oct. :oo,.
¡. On the history of the Association of Southeast Asian Nations and
its relationship with communism, see Brantly Womack, “China and South-
east Asia: Asymmetry, Leadership, and Normalcy,” Pacific Affairs ,o (:oo,–
:oo¡): ,:,–,¡8; and Carlyle Thayer, “Re-inventing Asean: From Construc-
tive Engagement to Flexible Intervention,” Harvard Asia Pacific Review ,
(I,,,): o,–,o. On the Indonesian response to Chinese intervention, see, for
example, Jemma Purdey, Anti-Chinese Violence in Indonesia, :,,o–:,,,
(Honolulu: University of Hawaii Press, :ooo). On the Sino-Vietnamese War
see, for example, Gerald Segal, Defending China (New York: Oxford Univer-
sity Press, I,8,).
,. Interview with Western diplomat, Washington, Sept. :oo,. On Deng
see, for example, Richard Evans, Deng Xiaoping and the Making of Modern
China (New York: Penguin, I,,,).
o. Willy Lam, “Beijing’s New ‘Balanced’ Foreign Policy: An Assess-
ment,” China Brief, Jamestown Foundation, :o Feb. :oo¡.
,. On modernization see H. Lyman Miller and Liu Xiaohong, “The
Foreign Policy Outlook of China’s Third Generation Elite,” in The Making of
Chinese Foreign and Security Policy in the Age of Reform, :,,8–:ooo, ed.
David Lampton, I:,–I,I (Stanford: Stanford University Press, :ooI). On
Deng’s reforms see Todd Crowell and Thomas Hon Wing Polin, “Asian of the
Century,” Asiaweek, Io Dec. I,,,, I.
8. Lampton, The Making of Chinese Policy. “Enhance Sino-Singa-
porean Ties,” China Daily, I, Nov. :oo,. Interviews with Western diplomats,
Sept.–Dec. :oo,.
,. See, for example, Roderick MacFarquhar and Michael Schoenhals,
Mao’s Last Revolution (Cambridge, Mass.: Belknap Press, :ooo), and Thomas
G. Moore and Dixia Yang, “Empowered and Restrained: Chinese Foreign
Policy in the Age of Economic Interdependence” in Lampton, The Making of
Chinese Policy, I,I–:,o.
Io. Horizon Group Research, I,,,. Joseph Fewsmith and Stanley
Rosen, “The Domestic Context of Chinese Foreign Policy: Does ‘Public
Opinion’ Matter?” in Lampton, The Making of Chinese Policy, I,I–I,o.
II. Minxin Pei, China’s Trapped Transition: The Limits of Developmen-
tal Autocracy (Cambridge: Harvard University Press, :ooo), ,I.
I:. Ibid., ,,.
I,. Tsao Tsing-yuan, “The Birth of the Goddess of Democracy,” in
Popular Protest and Political Culture in Modern China, ed. Jeffrey N. Wasser-
strom and Elizabeth J. Perry, I¡o–I¡, (Boulder: Westview, I,,¡). The most
Notes to Pages I¡–I, :¡,
authoritative account of the internal decision making leading up to the
crackdown is contained in Zhang Liang, The Tiananmen Papers (New York:
Public Affairs, :oo:).
I¡. Horizon Group Research, :oo,.
I,. Charles W. McMillon, “US-China Trade Data and Analyses: Pur-
chasing Power Parity,” paper prepared for US-China Economic and Security
Review Commission, :oo,. “China Sees Trade Surplus Triple,” British Broad-
casting Corporation,¡oo:I:o.stm, ac-
cessed Jan. :ooo. On currency reserves see “China Currency Reserves Top
Japan’s,” China Business News, :8 Mar. :ooo. On China’s reduction of pov-
erty, see the United Nations’ annual reports on Human Development in
China, available at
name=News&file=article&topic=¡o&sid=::8, accessed Nov. :ooo. On for-
eign investment see World Investment Report, United Nations Conference on
Trade and Development (Geneva: Unctad, :ooo).
Io. Interviews with entrepreneurs in Zhejiang Province, :oo:.
I,. Interviews in Kashgar, :oo:.
I8. “One Strategy, Multiple Agendas,”China Development Brief, http://, accessed Aug :ooo; interviews
in Kashgar, :oo¡.
I,. Gal Luft, “Fueling the Dragon: China’s Race into the Oil Market,”
IAGS Spotlight,, accessed Feb :ooo; “Premier
Stresses Exploitation of Oil, Gas,” China Daily, :o June :oo¡. For more on
foreign companies’ China strategies, see Joe Studwell, The China Dream: The
Quest for the Last Great Untapped Market on Earth (New York: Grove, :oo,).
Google’s specific issues are chronicled in Clive Thompson, “Google’s China
Problem (and China’s Google Problem),” New York Times Magazine, :, Apr.
:ooo, o¡.
:o. Peter Hays Gries, China’s New Nationalism: Pride, Politics, and
Diplomacy (Berkeley: University of California Press, :oo,).
:I. “Outward Bound,” Economist, :: June :ooo, ,¡; Fewsmith and
Rosen, “The Domestic Context,” I,o; “I, Nation Pew Global Attitudes
Study,” Pew Project on Global Attitudes, I, June :ooo.
::. Jasper Becker, “Mussolini Redux,” New Republic, :, June :oo,, Io.
:,. Fewsmith and Rosen, “The Domestic Context,” I,:–I,8; Ben Elgin
and Bruce Einhorn, “The Great Firewall of China,” BusinessWeek, I: Jan.
:ooo, ,:.
:¡. Pei, China’s Trapped Transition, 8,–Io,.
:,. Jonathan Unger, “China’s Conservative Middle Class,” Far Eastern
Economic Review, Apr. :ooo, :,; “Prosperity Brings Satisfaction and Hope:
China’s Optimism,” :oo, Pew Global Attitudes Survey, Io Nov. :oo,.
:,o Notes to Pages I,–:o
:o. Author observation of Strong Nation forum, People’s Daily Web
site; Ying Ma, “China’s America Problem,” Policy Review III (:oo:): ¡,–,,.
:,. “Protestors Attack US Embassy in Beijing,” CNN.com,
.cnn.com/WORLD/asiapcf/,,o,/o8/china.bombing.protests.o:/, accessed Nov.
:oo,. In years of conversations with average Chinese since the I,,, bomb-
ing, I have yet to meet anyone convinced that it was an accident.
:8. See, for example, “Who Caused the Crash?” British Broadcasting
Corporation,fic/I:oo:,o.stm, ac-
cessed Nov. :oo,.
:,. Dong-A Ilbo Opinion Poll, :, Apr. :oo,.
,o. Chen Shengluo, “The Events of September II and Chinese College
Students’ Images of the United States,” in Chinese Images of the United States,
ed. Carola McGiffert (Washington, D.C.: CSIS Press, :oo,).
,I. Interview with Chinese academic, Shanghai, Aug. :oo,.
,:. Miller and Liu, “Foreign Policy Outlook”; interviews with Chinese
diplomats, Washington and Beijing, Aug.–Dec. :oo,.
,,. Fewsmith and Rosen, “The Domestic Context,” I,:–I,8.
,¡. Evan S. Medeiros and M. Taylor Fravel, “China’s New Diplomacy,”
Foreign Affairs o (:oo,): ::.
,,. Joshua Cooper Ramo, The Beijing Consensus (London: Foreign
Policy Center, :oo¡), I,–:o.
,o. Susan L. Shirk, “China’s Multilateral Diplomacy in the Asia-
Pacific,” testimony before the US-China Economic and Security Review
Commission, I:–I, Feb. :oo¡; interview with former US diplomat based in
China, Shanghai, :oo¡.
,,. Biwu Zhang, “Chinese Perceptions of American Power, I,,I–
:oo¡,” Asian Survey , (:oo,): oo,–o8o; Sangwon Suh and David Hsieh,
“From Suspicion to Trust,” Asiaweek,
,o/o,:o/index.html, accessed July :oo,.
,8. “China Popularizes HIV/AIDS Knowledge Among Officials,” Xin-
hua, I Dec. :oo¡.
,,. “Afghans to Learn China’s Development Experience, Says Afghan
Vice President,” Xinhua, I8 Apr. :oo,; Zhang, “Chinese Perceptions,” o,,.
¡o. “Former Thai Millionaire Reinvents Himself,” CNN Asia Tonight,
:, Mar. :ooI, transcript. For foreign exploitation of the crisis, see, for ex-
ample, George Wehfritz and Paul Handley, “Beyond Sex and Golf,” News-
week, I: July I,,,, ,¡.
¡I. Interview with US diplomat formerly posted in Thailand, Wash-
ington, Oct. :oo,.
¡:. Interview with former NSC staffers, Washington, Oct. :oo,.
¡,. See, for example, Ministry of Foreign Affairs of the People’s Re-
Notes to Pages :o–,, :,I
public of China, “Proactive Policies by China in Response to the Asian Fi-
nancial Crisis,” I, Nov. :ooo.
¡¡. Ambassador Chan Heng Chee, “China and Asean: A Growing Re-
lationship,” Speech to the Asia Society Texas Annual Ambassadors’ Forum
and Corporate Conference, , Feb. :ooo; Michael Richardson, “Japan’s Lack
of Leadership Pushes ASEAN Towards Cooperation with China,” Interna-
tional Herald Tribune, I, Apr. I,,8; Robert G. Lees, “If Japan Won’t Help Res-
cue Asia China Might,” International Herald Tribune, :I Feb. I,,8; interview
with Thai diplomat, Bangkok, Sept. :oo,.
¡,. See, for example, Ye Zicheng, “Zhongguo shixing daguo waijiao
zhanlue shi zai bixing (China Should Adopt Great Power Diplomacy),”
World Economy and Politics, no. I, :ooo.
Chapter ,:
A Charm Strategy
I. Ministry of Foreign Affairs of the People’s Republic of China,
“China’s Africa Policy,” white paper released Jan. :ooo.
:. Esther Pan, “The Promise and Pitfalls of China’s ‘Peaceful Rise,’”
Council on Foreign Relations, I¡ Apr. :ooo,
Io¡¡o/promise_and_pitfalls_of_chinas_peaceful_rise.html, accessed Nov.
:ooo.
,. David Shambaugh, Power Shift (Berkeley: University of California
Press, :oo,), :8; Terry McCarthy, “Reef Wars,” Time Asia, 8 Mar. I,,,, I8;
Denny Roy, China’s Foreign Relations (Lanham, Md.: Rowman and Little-
field, I,,,).
¡. Yang Qing, “Zhongguo Heping Jeuqi yu Zhongguo Deongmeng
Zhijian de Guanxi,” Journal of the CCP’s Central Party School, Feb. :oo¡;
David Shambaugh, “China Engages Asia: Reshaping the Regional Order,” In-
ternational Security , (:oo¡): o¡; Robert G. Sutter, China’s Rise in Asia:
Promises and Perils (Lanham, Md.: Rowman and Littlefield, :oo,), I:–Io.
,. “President Calls for Further Propaganda Work to Enhance China’s
Image Abroad,” Xinhua, :8 Feb. I,,,; “China Aims to Be a Giant in Science
and Technology Around :o¡,,” People’s Daily, :o Nov. :oo¡.
o. David M. Lampton,“Paradigm Lost,”National Interest , (:oo,): ,,–8I.
,. Hu Jintao, “Speech Marking the ooth Anniversary of the Victory of
the Chinese People’s War of Resistance Against Japanese Aggression and the
World Anti-Fascist War,” , Sept. :oo,.
8. “China Encourages Mass Urban Migration,” People’s Daily, :8 Nov.
:oo,. On Chinese commodity demands, see, for example, “China Effect
:,: Notes to Pages ,o–¡I
Convulses Commodity Markets,” Financial Times, I, Nov. :oo,, and Energy
Information Administration, “China Country Brief,” Aug. :ooo. See also
Andy Rothman, “China Eats the World,”CLSA Asia Pacific Investment Strat-
egy, Spring :oo,. Tom Holland, “Water Wastage Will Soon Leave China High
and Dry,” South China Morning Post, 8 Mar. :ooo; Minnie Chan, “Wen Lays
Down Law on Saving Energy,”South China Morning Post, , July :oo,; “China
to Set up Energy Task Force,” Agence France-Presse, o Mar. :oo,.
,. Interview with Erica Downs, Feb. :ooo; Peter S. Goodman, “Big
Shift in China’s Oil Policy,” Washington Post, I, July :oo,.
Io. Naazneen Barma and Ely Ratner, “Chinese Illiberalism,” Democ-
racy : (:ooo): ,o–o8.
II. Lin teh-Cheng, “Beijing’s Foreign Aid Policy in the I,,os: Conti-
nuity and Change,” Issues and Studies I (I,,o): ,:–,o. Alejandro Reyes,
“Money for Influence?” Asiaweek,
oIIo/cso.html, accessed July :oo,.
I:. Medeiros and Fravel, “China’s New Diplomacy.” Xia Liping,
“China: A Responsible Great Power,” New Generation, New Voices: Debating
China’s International Future, papers for a conference, I,–I¡ Aug. I,,,.
I,. “Speech by Hu Jintao at the APEC CEO Summit,” Ministry of For-
eign Affairs of the People’s Republic of China release, I, Nov. :oo,; An-
toaneta Bezlova, “China’s Soft Power Diplomacy in Africa,” Asia Times, :,
June :ooo. See also Joshua Cooper Ramo, The Beijing Consensus (London:
Foreign Policy Center, :oo¡), ,,.
I¡. Information Office of the State Council of the People’s Republic of
China, “White Paper on China’s Peaceful Development Road,” I: Dec. :oo,;
Wen Jiabao, “Speech to Boao Forum on Asia,” : Nov. :oo,.
I,. “Premier Wen Defends African Oil Deals,” South China Morning
Post, I, June :ooo. On the expanding use of US sanctions in the I,,os, see,
for example, Jeffrey J. Schott, “US Economic Sanctions: Good Intentions,
Bad Execution,” testimony to the House Committee on International Rela-
tions, , June I,,8.
Io. Interview with Alejandro Melchor, undersecretary of defense of
the Philippines, Manila, Mar. :ooo; Amnesty International, “People’s Re-
public of China: Sustaining Conflict and Human Rights Abuses,” II June
:ooo.
I,. Interview with Keo Remy, Phnom Penh, Jan. :ooo.
I8. Yong Deng and Thomas G. Moore, “China Views Globalization:
Toward a New Great Power Politics?” Washington Quarterly , (:oo¡): II,–
I,o. On Chinese involvement in multilateral initiatives, see, for example,
Carlyle Thayer, “China Consolidates Its Long Term Bilateral Relations with
Southeast Asia,” Comparative Connections,
Notes to Pages ¡I–¡8 :,,
pubs/ooo:q.pdf, accessed Mar. :oo,. Interview with Vietnamese policy mak-
ers, Nha Trang, Oct. :oo,. Philip Saunders, China’s Global Activism: Strategy,
Drivers, and Tools (Washington, D.C.: National Defense University Press,
:ooo). See also “Thailand Aims to Further Enhance Strategic Partnership,”
China Daily, :8 June :oo,.
I,. “China, Mexico Sign Seven Cooperation Agreements,” People’s
Daily, :, Jan. :oo,; Foreign Ministry of the People’s Republic of China,
“Great Achievements Obtained in Zeng Qinghong’s Visit to Venezuela,”
,o Jan. :oo,. See also “Forum on China-Africa Cooperation,”
.fmprc.gov.cn/zflt/eng/, accessed Nov. :ooo. Ian Taylor, “Beijing’s Arms and
Oil Interests in Africa,” China Brief, Jamestown Foundation, I, Oct. :oo,.
:o. Interview with Southeast Asian diplomat, Singapore, Sept. :oo,;
interview with congressional staffer focusing on Asia issues, July :oo,.
:I. “Statement by Ambassador Shen Guofang, Deputy Permanent
Representative of China, at the ,oth Session of the General Assembly, on
Item ¡o,” Permanent Mission of the People’s Republic of China to the UN,
:ooI.
::. Interview with former Indonesian activists, Jakarta, Mar. :ooo;
Dane Schiller, “Justice Doesn’t Always Translate Across Border,” San Antonio
Express-News, :, Apr. :oo¡. On China’s response to Mexico, interviews with
Chinese diplomats, Washington, Oct. :oo,.
:,. Robin Ramcharan, “Asean and Noninterference: A Principle
Maintained,” Contemporary Southeast Asia I (:ooo): oo–88.
:¡. Susan Shirk, “China’s Multilateral Diplomacy in the Asia Pacific,”
Testimony before the US-China Economic and Security Review Commis-
sion, I:–I, Feb. :oo¡; interviews with Chinese scholars, Nha Trang, Oct.
:oo,.
:,. Andean Community,
Exterior/asia.htm, accessed May :ooo; Ministry of Foreign Affairs of the
People’s Republic of China, “International and Regional Issues,”
.fmprc.gov.cn/eng/gjhdq/dqzzywt/:o,,/default.htm, accessed May :ooo;
Shirk, “China’s Multilateral Diplomacy”; “Sino-Asean Relations Upgraded
by New Agreements,” Xinhua, ,o Nov. :oo¡; interview with Southeast Asian
diplomats, Singapore, Jan :ooo.
:o. On how American strategy changed after September II, see, for ex-
ample, “The National Security Strategy of the United States of America,”
Sept. :oo:,, accessed Nov. :ooo. On
changing Chinese priorities, see Presentation by Ruan Zongze, Asia Founda-
tion trilateral dialogue on US-Chinese-Vietnamese relations, Nha Trang, Oct
:oo,. “Jiang Zemin’s Report at Ioth Party Congress,” Xinhua, I, Nov. :oo:,¡,oo,.htm, accessed Sept. :oo,.
:,¡ Notes to Pages ¡,–,:
:,. William Ratliff, “China Goes South of the Border,” Hoover Digest I
(:oo,); also, Foreign Ministry of the People’s Republic of China, “Hu Jintao
Holds Talks with the Leaders of India, Brazil, South Africa, and Mexico,” ,
July :oo,. Cheng Siwei, “Bright Prospects for China-Latin American and the
Caribbean Cooperation,” speech to Organization of American States, o Dec.
:oo,; Chang Siwei, speech to conference of Latin American business execu-
tives, name of event withheld by request.
:8. Interview with Federico Macaranas, Manila, Mar. :ooo.
:,. Jonathan Watts, “Chávez says China Deal ‘Great Wall’ Against US,”
Guardian, :, Aug. :ooo. See also Ben Schiller, “The Axis of Oil: China and
Venezuela,”OpenDemocracy,-
china/china_venezuela_,,I,.jsp, accessed Aug. :ooo, and William Ratliff,
“Pragmatism over Ideology: China’s Relations with Venezuela,” China Brief,
Jamestown Foundation, I, Mar. :ooo.
,o. “Treaty Signed with Uzbekistan,” Xinhua, :o May :oo,; also,
Stephen Blank, “Islam Karimov and the Heirs of Tiananmen,” China Brief,
Jamestown Foundation, I¡ June :oo,. David Blair, “Oil Hungry China Takes
Sudan Under Its Wing,” Daily Telegraph, :, Apr. :oo¡.
,I. Tim Johnson, “Ahmadinejad Vows to Consider Plan to Limit Iran’s
Nuclear Program,” Knight Ridder News, Io June :ooo; also, Iran News
Agency, “Headlines in Major Iranian Newspapers,” I, June :ooo. John Cal-
abrese, “China and Iran: Mismatched Partners,” Jamestown Foundation oc-
casional paper, Aug. :ooo.
,:. “China, Ecuador Vow to Further Military Ties,” People’s Daily, :
Dec. :oo¡; interviews with South Korean politicians, Seoul, Aug. :oo,. See
also Jae Ho Chung, “How America Views China-South Korea Bilateralism,”
CNAPS Working Paper, July :oo,.
,,. Interview with senior Filipino defense official, Manila, Mar. :ooo.
,¡. Ramo, Beijing Consensus; Minxin Pei, China’s Trapped Transition:
The Limits of Developmental Autocracy (Cambridge: Harvard University
Press, :ooo), ,o–,:.
,,. Zhang Xiaojing, “Tanshuo jinrong quanqiu shidai de fazhan daolu:
qianxicong Huasheng gongshi dao ‘Beijing gongshi,’” Xueshi Shibao, Io Aug.
:oo¡; Barma and Ratner, “Chinese Illiberalism.”
,o. Drew Thompson, “China’s Soft Power in Africa: From the ‘Beijing
Consensus’ to Health Diplomacy,” China Brief, Jamestown Foundation, I,
Oct. :oo,.
,,. “Survey of Economic and Social Conditions in Africa :oo¡ –:oo,,”
United Nations Economic Commission for Africa, Apr. :oo,.
,8. Interview with Dan Erikson, Nov. :oo,.
,,. Interview with Lao officials, Vientiane, Aug. :oo,.
Notes to Pages ,:–,, :,,
¡o. “Visiting Chinese President Meets Premier,” Xinhua, I¡ Nov. :ooo;
“Lao, Chinese Presidents Reach ‘Complete Consensus’ in Vientiane Talks,”
Xinhua, I: Nov. :ooo.
Chapter ¡:
The Tools of Culture
I. Rumi Aoyama, “Chinese Public Diplomacy in the Multimedia Age:
Public Diplomacy and Civil Diplomacy,” Waseda University papers, Dec.
:oo¡. For one standard definition of public diplomacy, see “What Is Public
Diplomacy?”, accessed Nov. :ooo.
:. “Oceanic Odyssey Remains a Treasure,”China Daily, 8 July :oo¡; see
also Forum on China-Africa Cooperation, “Addis Ababa Action Plan,” , Feb.
:oo¡. Telephone interview with Geoff Wade, expert on Zheng He’s voyages,
National University of Singapore, Aug. :oo,.
,. Interview with Kasetsart professor, Aug. :oo,; “Chinese Volunteers
to Offer Services in Myanmar,” People’s Daily, II Jan. :ooo. See also “China to
Send Overseas More Field Service Volunteers,” Xinhua, ,o Oct. :oo:.
¡. Vivien Cui, “CCTV Tries to Shed its Mouthpiece Image,” South
China Morning Post, o Apr. :oo¡; “People’s Daily Overseas Edition Issued in
ROK,” People’s Daily, I July :oo¡. See also Aoyama, “Chinese Public Diplo-
macy.”“China Launches Satellite TV Service in Asian Region,” Xinhua, I Feb.
:oo,. Also, Eanna O’Brogain, “China’s Troubled TV Star,” South China
Morning Post, I, Mar. :ooo.
,. “Xinhua: The World’s Biggest Propaganda Agency,”Reporters With-
out Borders, :oo,; Joseph Kahn, “China Gives Zhao’s Death Scant Notice,”
New York Times, I8 Jan. :oo,; Interviews with Chinese journalists, Manila,
Bangkok, Kuala Lumpur, Jan.–Mar. :ooo.
o. “Report of the Asean-China Eminent Persons Group,” http://
eminent%:opersons%:ogroup%:: and Boao Forum for Asia,
.boaoforum.org/Html/, both accessed Nov. :ooo, and “China, Arab States
Set up Cooperation Forum,”People’s Daily, ,o Jan. :oo¡. See also “Gu Xiulian
Addresses Beijing Reception on Founding of China-Asean Association,”
Xinhua, , Aug. :oo¡, and Hong Liu, “New Migrants and the Revival of Over-
seas Chinese Nationalism,” Journal of Contemporary China I¡ (:oo,): :,I–
,Io.
,. Interviews with Chinese diplomats in Bangkok, Washington, Ma-
nila, Aug.–Dec. :oo,; “Li Zhaoxing Praises Young Diplomats,” Xinhua, :,
June :oo,; interview with Chinese scholars, Chinese Academy of Social Sci-
:,o Notes to Pages oo–o,
ences, Aug. :oo,; Jorge Dominguez, “China’s Relations with Latin America:
Shared Gains, Asymmetric Hopes,” Inter-American Dialogue publications,
May :ooo.
8. Interviews with Chinese diplomats, Washington, Aug.–Dec. :oo,;
interview with American diplomat, Bangkok, Jan. :ooo; interview with Sin-
gaporean diplomat, Singapore, Jan. :ooo; The United States and Southeast
Asia: A Policy Agenda for the New Administration (New York: Council on For-
eign Relations Press, :ooI), ¡8.
,. Philip Saunders, China’s Global Activism: Strategy, Drivers, and
Tools (Washington: National Defense University Press, :ooo); interview with
Singaporean diplomat, Jan. :ooo; interview with American ambassador,
name and location withheld. See also “Chinese, Thai FMs Meet on Tsunami
Issues,” People’s Daily, :, Jan. :oo,.
Io. The comparison was made by compiling English- and Chinese-
language newswire reports of visits by American and Chinese cabinet-level
officials. Ralph Cossa, “Rice’s Unfortunate Choice,” Asia Times, :8 July :oo,;
Glenn Kessler, “In Asia, Rice Is Criticized for Plan to Skip Summit,” Wash-
ington Post, I: July :oo,; interview with White House official, Washington,
Mar. :ooo.
II. Xing Zhigang, “NPC Deputy Calls for Promoting Chinese,” China
Daily, Io Mar. :ooo.
I:. “China Takes Five Measures to Boost Chinese Teaching Overseas,”
Xinhua, :: July :oo,. See also “Chinese Language School Opens in Seoul,”
China Daily, :, Nov. :oo¡, and “Introduction to the ‘Confucius Institute’
Project,”¡I:,oo.htm, ac-
cessed July :ooo. Paul Marks, “China’s Cambodia Strategy,” Parameters ,
(:ooo): ,:–Io8; see also “:o Chinese School Teacher Representatives to
Guangzhou for Training,” Cambodia Sin Chew Daily, I, May :oo,, and “Dis-
patching Professional Teachers to Cambodia,” Cambodia Sin Chew Daily, ,o
Nov. :oo:. Sirikul Bunnag, “Ministry Pushes Chinese Language,” Bangkok
Post, Io Jan. :ooo. On Mao and Confucianism, see, for example, A. James
Gregor and Maria Hsia Chang, “Anti-Confucianism: Mao’s Last Campaign,”
Asian Survey II (I,,,): Io,,–Io,:.
I,. Bunnag, “Ministry Pushes Chinese Language”; assorted articles
from Cambodia Sin Chew Daily, the major Chinese-language newspaper in
Cambodia, :oo,–:oo,; interviews with Cambodian teachers and education
specialists, Phnom Penh, Jan. :ooo. See also Marks, “China’s Cambodia Stra-
tegy.”
I¡. Hong Liu, “New Migrants.” See also Cao Cong, “China’s Efforts at
Turning a ‘Brain Drain’ into a ‘Brain Gain,’”Background Brief, East Asian In-
stitute, National University of Singapore, I Nov. :oo¡; Sam Dillon, “US Slips
Notes to Pages oo–,o :,,
in Attracting the World’s Best Students,” New York Times, :I Dec. :oo¡; “For-
eign Students in China on the Rise,” People’s Daily, I, Apr. :oo,; and Howard
French, “China Luring Foreign Scholars to Make its Universities Great,” New
York Times, :8 Oct. :oo,. Also, interviews with Chinese education specialists,
Shanghai, :oo¡. David Zweig, “Is China a Magnet for Global Talent?” Paper
presented at the conference Immigration and Canada’s Place in a Changing
World, Vancouver, :¡ Mar. :ooo.
I,. “International Students Find Beijing ‘Home,’” China Daily, :¡ May
:oo,; interviews with Lao and Cambodian ministers, Vientiane and Phnom
Penh, Aug. :oo, and Jan. :ooo; Zweig, “Is China a Magnet?” “Global MBA
Rankings :ooo,” Financial Times,
rankings.html, accessed Nov. :ooo.
Io. Interview with Joanne Chang, Taipei Economic and Cultural Rep-
resentative Office former deputy representative in Washington, Feb. :ooo;
interviews with Lee Poh Ping, Voon Phin Keong, Rita Sim, and several other
leaders of Malaysian Chinese community, Kuala Lumpur, Jan. :ooo.
I,. Carolyn Lochhead, “Drop in US Student Visas by Foreigners,” San
Francisco Chronicle, , Apr. :oo,. See also Eric Lichtblau and Jonathan Peter-
son, “US Will Step up Oversight of Student Visa Program,”Los Angeles Times,
Io May :oo:, and Enhanced Border Security and Visa Entry Reform Act of
:oo:, US Public Law Io,-I,,, I¡ May :oo:. “Fact Sheet: Changes to National
Security Entry/Exit Registration System,” Department of Homeland Secu-
rity, I Dec. :oo,; Catharin Dalpino, “China’s Emergence in Asia and Impli-
cations for US Relations with Southeast Asia,” Statement to US Senate For-
eign Relations Committee, , June :oo,.
I8. World Bank Group, “Philippines Millennium Development
Goals,”?
REPORT_ID=Ioo¡&REQUEST_TYPE=VIEWADVANCED, accessed Nov.
:ooo; “Death Toll in Manila Stampede Rises to ,,,” The Age, Feb. :ooo.
I,. Lynn Pan, ed., The Encyclopedia of the Chinese Overseas (Cam-
bridge: Harvard University Press, I,,,), I8,–I,:.
:o. Ibid., ,8–Ioo.
:I. Ibid., I,I–Io,.
::. Ibid., ::,–::8.
:,. Ibid., II,; “Families under Fire,” Time Asia,
time/asia/covers/,oIo¡o::,/story.html, accessed May :oo,.
:¡. Pan, Encyclopedia, II,. See alsoondon: Taylor and Francis, :ooI);
and “Rise of the Compradore,” China Economic Review,
economicreview.com/subscriber/articledetail/o,,.html, accessed Jan. :oo,.
:,8 Notes to Pages ,o–,,
:,. “The Overseas Chinese: A Driving Force,” Economist, I8 July I,,:;
see also Keith B Richburg, “Ethnic Chinese Waiting to Die in Indonesia,”
Washington Post, :I Mar. I,,,. For more on the tycoons, see Forbes’s rank-
ings of the world’s richest people, available at
billionaires/, accessed Nov. :ooo. For more on Thaksin’s background, see
Pasuk Phongpaichit and Chris Baker, Thaksin: The Business of Politics in
Thailand (Chiang Mai: Silkworm, :oo,).
:o. Vanessa Hua, “Playing the Panama Card: The China-Taiwan Con-
nection,” San Francisco Chronicle, :, June :oo:; interviews with East Timor-
ese merchants, Dili, Mar. :ooo; Pan, Encyclopedia, :,¡.
:,. Handley, “De-Mythologizing Charoen Pokphand”; Hong Liu,
“New Migrants,” ,o8; Zhuang Guoto, “The Factor of Chinese Ethnicity in
China-Asean Relations as Mirrored in Investments from Southeast Asia in
Fujian,” paper presented to Conference on Southeast Asian Studies in China:
Challenges and Prospects,” Singapore, I:–I¡ Jan. :ooo.
:8. Zhuang Guoto, “The Factor of Chinese Ethnicity”; William A.
Callahan, “Diaspora, Cosmopolitanism, and Nationalism: Overseas Chinese
and Neo-Nationalism in China and Thailand,” City University of Hong
Kong Southeast Asia Research Center Working Paper, Oct. :oo:.
:,. Interview with Chinese diplomats, Washington and Beijing, Aug.–
Oct. :oo,.
,o. Hong Liu, “New Migrants”; interview with visa officials at Chinese
embassy, Bangkok, Aug. :oo,; “Cambodian Chinese Organization Docu-
ments China’s Push to Promote Chinese Learning Abroad,” Cambodia Sin
Chew Daily, I, May :oo,; Callahan, “Diaspora, Cosmopolitanism, and Na-
tionalism.”
,I. Interviews with Filipino-Chinese business leaders, Manila, Mar. :ooo.
,:. Vanessa Hua, “Playing the Panama Card: The China-Taiwan Con-
nection,” San Francisco Chronicle, :, June :oo:.
,,. Interview with Amorn Apithanakoon, Bangkok, Jan. :ooo.
,¡. “Overseas Chinese Speak with One Voice Against ‘Taidu,’” People’s
Daily, ¡ Mar. :oo¡.
Chapter ,:
The Tools of Business
I. Interview with Harry Roque, Manila, Mar. :ooo.
:. Joel C. Atencio and Rizal S. Obanil, “Police Conduct Raid on Daily
Tribune,” Manila Bulletin, :o Feb. :ooo; “Arroyo Declares State of Emer-
gency,” Philippine Daily Inquirer, :¡ Feb. :ooo; “Seven More in Media
Watched,” Philippine Daily Inquirer, , Mar. :ooo; “Lift State of National
Notes to Pages ,,–8, :,,
Emergency Now, Lawmakers Urge Malacanang,”BusinessWorld, , Mar. :ooo;
Tarra V. Quismundo, “Arrest Warrant Out for Gringo,” Philippine Daily In-
quirer, : Mar. :ooo; Michael Lim Ubac and Armand Nocum, “Congress
Unites Behind Five Solons Linked to Coup Plot,” Philippine Daily Inquirer,
I Mar. :ooo.
,. Kristine L. Alave, “Framework for RP-China Bilateral Agreements
Inked,” BusinessWorld, o June :ooo; Angelo Samonte, “China Vows to Invest
in RP Industries,” Manila Times, o June :ooo; interview with Harry Roque,
Manila, Mar. :ooo. Also, interviews with a former Philippine senator, and
current Philippine officials, Manila, Mar. :ooo. See also Raissa Robles, “Rail-
way Project Under Fire After Philippine Contractors Are Sidelined,” South
China Morning Post, I Sept. :oo¡.
¡. On the depth of corruption in Philippine politics, see Sheila S.
Coronel, Betrayals of the Public Trust: Investigative Reports on Corruption
(Manila: Philippine Center for Investigative Journalism, :ooo), as well as fre-
quent updates on pcij.org about Philippine corruption issues.
,. Interview with Harry Roque, Manila, Mar. :ooo.
o. See Henry Yep, “China’s Foreign Aid to Asia: Promoting a ‘Win-
Win’ Environment,” master’s thesis, National Defense University, :ooo.
,. Joe Studwell, The China Dream: The Quest for the Last Great Un-
tapped Market on Earth (New York: Grove, :oo,).
8. For annual reports on investment flows, see the annual World In-
vestment Report released by the United Nations Conference on Trade and
Development. Jiang Jingjing, “Wal-Mart’s China Inventory to Hit US $I8 Bil-
lion This Year,” China Business Weekly, :, Nov. :oo¡. World Bank Group,
“Bolivia Country Data Profile,”
CPProfile.asp?SelectedCountry=BOL&CCODE=BOL&CNAME=Bolivia&
PTYPE=CP, accessed Nov. :ooo. For a history of China’s annual growth
rates, see World Bank Group, “China at a Glance,”
bank.org/AAG/chn_aag.pdf; also see Economist Intelligence Unit, “Fore-
sight :o:o,”:ooo. On Chinese trade surpluses, see, for example, “China Trade
Surplus Hits Another Record in July,” Agence France-Presse, 8 Aug. :ooo.
Geoff Dyer, “Figures Show China as Net Vehicle Exporter,” Financial Times,
II Feb. :ooo; Geoff Dyer and James Mackintosh, “Bought the T-Shirt and
TV? Next for the West are Cars ‘Made in China,’” Financial Times, I June
:oo,. “The Frugal Giant,” Economist, :¡ Sept. :oo,; “US Savings Rate Hits
Lowest Level Since I,,,,” Associated Press, ,o Jan. :ooo.
,. Philip Saunders, China’s Global Activism: Strategy, Drivers, and
Tools (Washington, D.C.: National Defense University Press, :ooo).
Io. Foreign Equity Investment in Singapore :oo, (Singapore: Singapore
Department of Statistics, :ooo); Philip Saunders, China’s Global Activism:
:oo Notes to Pages 8,–8,
Strategy, Drivers, and Tools (Washington, D.C.: National Defense University
Press, :ooo). See also “China Makes Direct Investments of $,o Billion Over-
seas in Past Five Years,” People’s Daily, :, Feb. :ooo.
II. “Sino-Cambodian Economic Relations,” Cable from US Embassy,
Phnom Penh, I¡ May :oo¡.
I:. Hu Jintao, “Speech at the Brazilian Parliament,”I, Nov. :oo¡; Chris
Kraul, “China to Invest $, Billion in Venezuela Oil Projects,” Los Angeles
Times, :, Aug. :ooo. Economic Commission for Latin America and the
Caribbean, Foreign Investment in Latin America and the Caribbean :oo,
(Santiago, Chile: United Nations, :ooo), ,–8; also see Kerry Dumbaugh and
Mark P. Sullivan, “China’s Growing Interest in Latin America,” Congres-
sional Research Service report, :o Apr. :oo,. “China’s Africa Expansion,”
United Press International, I, Jan. :ooo. “China Agrees to $:oo Million in
Loans: Jusuf,” Jakarta Post, :, June :oo,; Genalyn D. Kabaling, “RP, China
Sign $I.o Billion Accords; Hu Cites ‘Golden Age’ of Ties at Congress Joint
Session,” Manila Bulletin, :8 Apr. :oo,.
I,. Michael E. Arruda and Ka-Yin Li, “China’s Energy Sector: Devel-
opment, Structure, and Future,” China Law and Practice , (:oo,): I:–I,;
Saunders, China’s Global Activism. For more on the Go Out campaign, see
Friedrich Wu, “China Inc International,” International Economy , (:oo,):
:o–,I. Zhang Jin, “Wu Yi: China to go Further than WTO Promises,” China
Daily, , Sept. :oo¡.
I¡. “China Spreads Its Wings: Chinese Companies Go Global,”Accen-
ture report :oo,.
I,. Ibid.
Io. Interviews with Chinese diplomats, Bangkok, Vientiane, Washing-
ton, Aug. :oo,–Apr. :ooo. See also Foreign Ministry of the People’s Repub-
lic of China, “Program for China-Africa Cooperation in Economic and So-
cial Development,” Forum on China-Africa Cooperation; Dai Yan, “China
Eyeing Regional Investment,” China Daily, , Feb. :oo¡; and Stephen Frost,
“Chinese Outward Direct Investment in Southeast Asia: How Much and
What Are the Regional Implications?”Southeast Asia Research Center work-
ing paper, City University of Hong Kong, July :oo¡.
I,. Interview with Singaporean diplomats, Singapore, Jan. :ooo; on
business delegations, see also Dumbaugh and Sullivan, “China’s Growing In-
terest.” Interview with Vikrom Kromadit, Bangkok, Sept. :oo,.
I8. Andy Rothman, “China Eats the World,” CLSA Asia Pacific Mar-
kets investment strategy report, Spring :oo,, ¡,–,I; see also Paula Dittrick,
“Chinese NOCs Go Shopping,” Oil and Gas Journal, :, Jan. :ooo, I,. Erica
Downs, “China’s Foreign Investments: Comprehensively Planned or ‘Mud-
dled Through’?” Presentation for the National Bureau of Asian Research and
Notes to Pages 8,–,o :oI
the Pacific Northwest Center for Global Security, Washington D.C., :,–:8
Sept. :oo,.
I,. “The Dragon Tucks In,” Economist, ,o June :oo,, ,I. Andrew Yeh,
“China Backs Chavez’s Bid for UN Seat After Oil Deal,” Financial Times, :,
Aug. :ooo; see also William Ratliff, “China and Venezuela: Pragmatism and
Ideology,” statement to the US-China Economic and Security Review Com-
mission, , Aug. :ooo. R. Evan Ellis, “US National Security Implications of
Chinese Involvement in Latin America,”Strategic Studies Institute, US Army
War College, June :oo,. Carolyn Bartholomew, testimony before the US-
China Economic and Security Review Commission Hearing on China’s
Influence in Africa, :8 July :oo,. David Barboza, “Chinese Oil Firm to Invest
Billions in Nigerian Field,” New York Times, , Jan. :ooo. Jephraim P.
Gundzik, “The Ties That Bind China, Russia, and Iran,” Asia Times, ¡ June
:oo,. “CNPC Set to Buy PetroKazakhstan After Concessions,” Energy Com-
pass, :I Oct. :oo,. “Indonesia Country Analysis Brief,” Energy Information
Administration, July :oo¡; David Fullbrook, “Resource-Hungry China to
Devour More of Burma’s Gas and Oil Industry,” Irrawaddy,
.irrawaddy.org/aviewer.asp?a=,¡:,&z=I,,, accessed Mar. :ooo.
:o. Arruda and Li, “China’s Energy Sector”; Saunders, China’s Global
Activism; see also “Dongnanya: Zhongguo qiye ‘zouchuqu de zhongdian
diqu”(Southeast Asia: Area for Chinese Companies), Ministry of Commerce
International Projects, no. Io, :oo,. Interviews with Chinese, US, European,
Thai, and Cambodian diplomats, Beijing, Washington, Bangkok, Vientiane,
Phnom Penh, Nha Trang, Aug. :oo,, Oct. :oo,, Jan. :ooo, Mar. :ooo; see also
Erik Wasson, “With $8o.¡ Million, China Top Investor in Cambodia in
:oo¡,” Cambodia Daily, I8 Feb. :oo,. “China to Remove Cap on Investment
Abroad by Domestic Firms,” Wall Street Journal, , June :ooo. “China Top In-
vestor in Cambodia in :oo¡,” unclassified cable, US Embassy, Phnom Penh,
: Mar. :oo,.
:I. Interview with Walter Lohman, Washington, Aug. :oo,; interview
with Lin Che Wei, Jakarta, Mar. :ooo.
::. “Friend or Forager?” Financial Times, :, Feb. :ooo.
:,. Enzio Von Pfeil, “China: The Third World Superpower,” China
Brief, Jamestown Foundation, I, Mar. :oo¡.
:¡. “Asia Outgrows Japanese Economy,” Reuters, :, Dec. :oo,; Eric
Teo Chu Cheow, “China as the Center of Asian Economic Integration,”China
Brief, Jamestown Foundation, :: July :oo¡.
:,. James Brooke, “China ‘Looming Large’ in South Korea as Biggest
Player, Replacing the US,” New York Times, , Jan. :oo,.
:o. Ian Taylor, “Beijing’s Arms and Oil Interests in Africa,”China Brief,
Jamestown Foundation, I, Oct. :oo,. Dumbaugh and Sullivan, “China’s
:o: Notes to Pages ,I–,¡
Growing Interest,” :; also see “US-Latin Trade Boom,” Latin Business Chron-
icle, Mar. :ooo. Richard Lapper, “A New Challenge for America in Its Own
Backyard,” Financial Times, :: May :oo¡; see also Richard Lapper, “Run for
Investment Bulls as China Shops,” Financial Times, I, Apr. :oo,. John Cala-
brese, “China and Iran: Mismatched Partners,” Jamestown Foundation oc-
casional paper, Aug. :ooo. Matthew Oresman, “Repaving the Silk Road:
China’s Emergence in Central Asia,” in China and the Developing World: Bei-
jing’s Strategy for the Twenty-First Century, ed. Joshua Eisenman, Eric Hegin-
botham, and Derek Mitchell (Armonk, N.Y.: Sharpe, forthcoming, :oo,). I
am indebted to Barry Sautman for the point about Africans’ preference for
cheaper Chinese goods.
:,. Interview with Singaporean diplomats, Singapore, Jan :ooo.
Joseph Yu-shek Cheng, “The Asean-China Free Trade Area: Genesis and Im-
plications,” Australian Journal of International Affairs : (:oo¡): :,,–:,,; see
also John Wong and Sarah Chan, “China-Asean Free Trade Agreement:
Shaping Future Economic Relations,” Asian Survey , (:oo,): ,o,–,:o, and
Asean-China Expert Group on Economic Cooperation, “Forging Closer
Asean-China Economic Relations in the :Ist Century,” Oct. :ooI. o,. Siow
Yue Chia and Chalongphob Sussangkarn, “The Economic Rise of China:
Challenges and Opportunities for Asean,” Asian Economic Policy Review I
(:ooo): Io:–I:8; see also Jane Perlez, “China Promises More Investment in
Southeast Asia,” New York Times, 8 Oct. :oo,.
:8. Gary Clyde Hufbauer and Yee Wong, “Prospects for Regional Free
Trade in Asia,” Institute for International Economics working paper, Oct.
:oo,. “China Winning Resources and Loyalties of Africa,”Financial Times, :8
Feb. :ooo; see also Government of Pakistan Ministry of Commerce, “Pak-
istan-China Early Harvest Programme,”
PCEHP.asp, accessed Nov. :ooo. Ministry of Foreign Affairs of the People’s
Republic of China, “China’s African Policy,” I: Jan. :ooo.
:,. Tran Dinh Thanh Lam, “US ‘Catfish War’ Defeat Stings Vietnam,”
Asia Times, ,I July :oo,; US Department of Agriculture Foreign Agricultural
Service, “International Trade Report: U.S. Seafood Imports Continue to
Soar,” 8 July :oo,; Alan Sipress, “US-Vietnam Ties Raise Hopes, Hackles,”
Washington Post, o Mar. :oo¡. See also US Department of Commerce, “No-
tice of Antidumping Duty Order: Certain Frozen Fish Fillets from the So-
cialist Republic of Vietnam,” Federal Register, I: Aug. :oo,, ¡,,o,– ¡,,Io.
,o. Interviews with Carol Lancaster, Georgetown University, Patrick
Cronin, International Institute for Strategic Studies, and other participants
in conferences on foreign aid held in Beijing, Aug. and Nov. :oo,. See also
Michael A. Glosny, “Meeting the Development Challenge in the Twenty-first
Century: American and Chinese Perspectives on Foreign Aid,” National
Notes to Pages ,,–,, :o,
Committee on United States–China Relations China Policy series report,
Aug :ooo.
,I. Interview with Thai officials, Ministry of Foreign Affairs of the
Kingdom of Thailand, Bangkok, Aug. :oo,.
,:. Interviews with Filipino, Thai, and Cambodian diplomats, Manila,
Bangkok, and Phnom Penh, Jan. :ooo and Aug. :oo,; Export-Import Bank
of China, annual report, :oo:. See also Todd Moss and Sarah Rose, “China
Exim Bank and Africa: New Lending, New Challenges,” Center for Global
Development Note, Nov. :ooo.
,,. Yep, “China’s Foreign Aid to Asia”; Joshua Eisenman and Joshua
Kurlantzick, “China’s Africa Strategy,” Current History , (:ooo): :I,–::¡;
“China Offers New Aid to Pacific Island Countries,” Agence France-Presse,
, Apr. :ooo.
,¡. Interviews with officials at Philippines Department of Trade and
Industry, Manila, Mar. :ooo, and Cambodia Ministry of Commerce, Phnom
Penh, Jan. :ooo; Yep, “China’s Foreign Aid to Asia”; Sin Chew Daily digests,
:oo,–:oo,.
,,. Yep, “China’s Foreign Aid to Asia.”“United States Agency for Inter-
national Development Tsunami Reconstruction Update,” Aug. :ooo, http://, accessed Nov. :ooo; see
also “China Increases Tsunami Aid to $o, Million,”Xinhua, ,I Dec. :oo¡, and
Shen Guofang, “Address to the United Nations Meeting on Humanitarian
Assistance to Tsunami Affected Countries,” I: Jan. :oo,. Sino-Cambodian
Economic Relations,” cable from US Embassy, Phnom Penh, I¡ May :oo¡.
,o. Loro Horta and Ian Storey, “China’s Portuguese Connection,” Yale
Global Online,,¡, accessed
Aug. :ooo.
,,. “Sino-African Economic, Trade Relations to be Promoted: Offi-
cial,” People’s Daily, :¡ Jan. :oo¡; “China to Train ,,ooo Professionals for De-
veloping Countries,” Xinhua, I¡ June :oo¡.
,8. Yep, “China’s Foreign Aid to Asia”; interview with China specialist
in Ministry of Foreign Affairs of the Kingdom of Thailand, Aug. :oo,;
Hisane Misaki, “China and Japan in Mekong Tug-of-War,” Straits Times
(Singapore), :¡ Nov. :oo,; Siriluk Masviriyakul, “Sino-Thai Strategic Eco-
nomic Development in the Greater Mekong Subregion, I,,:–:oo,,” Con-
temporary Southeast Asia : (:oo¡): ,o:–,:o.
,,. Peter Bosshard, “China Exim Bank and China Development Bank
Case Studies,” Report prepared for International Rivers Network, :oo¡;
Jason Kindopp, “China’s Energy Security and NOCs,” Presentation for the
National Bureau of Asian Research and the Pacific Northwest Center for
Global Security, Washington D.C., :,–:8 Sept. :oo,.
:o¡ Notes to Pages ,,–Io:
¡o. Interview with Kraisak Choonhaven, Thai senator, Bangkok, Aug.
:oo,; interviews with Vietnamese officials, Nha Trang, Oct. :oo,; see also
William Ratliff, China’s “Lessons” for Cuba’s Transition? (Miami: University
of Miami Press, :oo¡). Sheng Lijun and Jiang Shuxian, “The Communist
Party of China and Political Parties of Southeast Asia,” Trends in Southeast
Asia I¡ (:oo,). Interviews with Cambodian politicians from ruling party and
opposition, Phnom Penh, Jan. :ooo.
¡I. Interview with Kraisak Choonhaven, Thai senator, Bangkok, Aug.
:oo,.
¡:. Interviews with Lao diplomats, foreign ministry officials, Vien-
tiane, Aug. :oo,.
¡,. “Lai No Longer on First Name Terms with Solomon Islands,”
People’s Daily, :o Apr. :ooo. “China Winning Resources and Loyalties of
Africa,” Financial Times, :8 Feb. :ooo; see also China International Contrac-
tors Association, “:oo¡ Report on Overseas Chinese Labor.” Barry Sautman,
“Friends and Interests: China’s Distinctive Links with Africa,” Working
Paper no. I:, Center on China’s Transnational Relations, Hong Kong Uni-
versity of Science and Technology, :ooo.
¡¡. David Fullbrook, “Chinese Migrants and the Power of Guanxi,”
Asia Times, ,o July :oo¡; interview with Cambodian diplomats, Washington,
Aug. :oo,.
¡,. Interview with Antonella Diana, specialist on Laotian-Chinese
border relations, Australian National University, Feb. :ooo; for more back-
ground on changes in northern Laos, see Chris Lyttleton, Paul Cohen,
Houmphanh Rattanavong, Bouakham Thongkhamkhane, and Souriyanh
Sisaengrat, “Watermelons, Bars, and Trucks: Dangerous Intersections in
Northwest Lao PDR,” Institute for Cultural Research of Laos and Macquarie
University, :oo¡. Interview with Western diplomat, Vientiane, Aug. :oo,;
“China’s Growing Presence in Northern Laos,” cable from US Embassy, Vi-
entiane, obtained through the Freedom of Information Act, :o July :oo,.
¡o. Michael Vatikiotis and Bertil Linter, “The Renminbi Zone,” Far
Eastern Economic Review, :, May :oo,, :¡.
¡,. CLSA Asia Pacific Markets, “Chinese Tourists: Coming, Ready or
Not!” special report, Sept. :oo,; see also World Tourism Organization,
Tourism :o:o Vision (New York: World Tourism Organization Publications,
:ooo). “Tourism Gaining Momentum in China-ASEAN Economic Cooper-
ation: Expert,” People’s Daily, , Nov. :ooo. Ben Blanchard, “Anxious Laos
Gears up for Chinese Tourists,” Reuters, Io Aug. :oo,; Phusadee Arunmas,
“Tripling of Tourists on Agenda,” Bangkok Post, I¡ Sept. :oo,; Data compiled
by the Pacific Asia Travel Association, provided by Ken Scott, PATA Bangkok.
¡8. Many group tours do little to improve the image of China abroad.
Notes to Pages Io,–Io, :o,
In Pattaya, a seedy Thai beach resort, the typical Chinese group tour gener-
ally looks like this: Twenty or thirty people from one city in China each pay
an astonishingly small amount—sometimes less than $¡oo—for a three- or
four-day trip; the price includes a flight from China to Pattaya, all meals, and
ratty accommodations. Arriving in Pattaya, a megaphone-wielding female
guide herds the Chinese group from “attraction” to “attraction”—attrac-
tions being overpriced shops that pay commissions back to the travel agent
(which makes possible the low price for the trip), beaches covered in sewage
and hypodermic needles, and strips of bars packed with blond Russian pros-
titutes wearing long fake mink coats in the tropical heat. At dinnertime,
megaphone girl herds the group into a hotel restaurant or cheap Chinese
buffet, where everyone can pig out before going to bed or heading out again
to Pattaya’s red-light district to get sloshed. CLSA Asia Pacific Markets, “Chi-
nese Tourists.” “Chinese Travelers Step out of Boundaries,” China Today, ,
July :oo¡.
Chapter o:
Mr. Popular
I. For more on the referendum, see “Situation of Human Rights in
East Timor: Note by the Secretary General,” United Nations General Assem-
bly Fifty-Fourth Session, Io Dec. I,,,. For more background on the eco-
nomic devastation, see “World Bank Country Brief: East Timor,”
.worldbank.org/WBSITE/EXTERNAL/COUNTRIES/EASTASIAPACIFICEXT/
TIMORLESTEEXTN/o,,menuPK::,¡o:,~pagePK:I¡II,,~piPK:I¡IIIo~the
SitePK::,¡o::,oo.html, accessed Nov. :ooo.
:. For more on the history of the Timorese resistance, see Constâncio
Pinto and Matthew Jardine, East Timor’s Unfinished Struggle: Inside the Ti-
morese Resistance (Cambridge, Mass.: South End, I,,o), and Joseph Nevins,
A Not-So-Distant Horror: Mass Violence in East Timor (Ithaca: Cornell Uni-
versity Press, :oo,).
,. Interview with João de Câmara, Dili, Mar. :ooo.
¡. Interviews with Timorese and American diplomats, Dili, Mar. :ooo;
Ian Storey, “China and East Timor,” China Brief, Jamestown Foundation, I,
Aug. :ooo.
,. Interview with Elisabeth Huybens, World Bank East Timor, Dili,
Mar :ooo; interview with Constâncio Pinto, minister-counselor, Embassy of
Timor Leste, Washington, Feb. :ooo; interviews with Timorese business-
people, Dili, Mar. :ooo.
:oo Notes to Pages Io,–IIo
o. Interviews with Timorese, Chinese, and US diplomats, Washington
and Dili, Mar. :ooo.
,. Jill Jolliffe, “East Timor Says China Is Its Closest Ally,”Sydney Morn-
ing Herald, II July :oo:; Michael Richardson, “East Timor Edges Toward Oil
Deal with Australia,” New Zealand Herald, I, June :oo,. See also Timor Sea
Office,ffice.gov.tp/, accessed Nov. :ooo.
8. Department of State, Office of Research, “U.S. Image Positive in
Urban Thailand, Bolstered by a Sense of Shared Security Interests: But Pub-
lic Sees U.S. Becoming Less Important as an Economic Partner in ,–Io
Years,” obtained from U.S. Embassy, Bangkok, Aug. :oo,.
,. Program on International Policy Attitudes, “:: Nation Poll Shows
China Viewed Positively by Most Countries Including its Asian Neighbors,”
gions_bt/IIo.php?nid=&id=&pnt=IIo&lb=btvoc, accessed Nov. :oo,; Program
on International Policy Attitudes, “,, Nation Poll on Views of Countries,”
Feb. :ooo; Jorge Domínguez, “China’s Relations with Latin America: Shared
Gains, Asymmetric Hopes,”Inter-American Dialogue publications, May :ooo.
Io. Interview with Indonesian businessman, Jakarta, Mar. :ooo.
II. Gail Dutton, “Grassroots Diplomacy,” Across the Board, May–June
:oo,, I– ¡; Josef Joffe, Überpower: The Imperial Temptation of America (New
York: Norton, :ooo), ,,.
I:. Bruce Kligner, “China Shock for South Korea,” Asia Times, II Sept.
:oo¡.
I,. Sophie Diamant Richardson, “China, Cambodia, and the Five
Principles of Peaceful Coexistence: Principles and Foreign Policy,” Ph.D.
diss., University of Virginia, :oo,.
I¡. “Hun Sen Cancels Trip to UNGA,”cable from US Embassy, Phnom
Penh, , Sept. :oo¡; interviews with Cambodian ministers, politicians, jour-
nalists, Phnom Penh, Jan. :ooo.
I,. Vinod Sreeharsha, “East Meets West, with an Argentine Twist,”
Christian Science Monitor, ,o Sept. :oo,; Sin Chew Media Corporation,
Prospectus, :oo¡; Chye Wen Fei, “Sin Chew Media Corporation BHD,” SBB
Securities Report, :¡ Sept. :oo¡; Interviews with Lin Zhen Chao, president
of Vientiane Chinese Association, Vientiane, Aug. :oo,. See also Marks,
“China’s Cambodia Strategy”; “Chinese Teachers Spread the World to Pass
Heritage,” China Daily, : Jan. :oo,; and Jean Lin, “Ministry Will Fund Stu-
dents to Teach Mandarin Abroad,” Taipei Times, 8 June :ooo.
Io. Austin Ramzy, “Get Ahead, Learn Mandarin,” Time Asia, I, June
:ooo, Io; see also James Brooke, “China Looming Large in South Korea as
Biggest Player, Replacing the US,”New York Times, , Jan. :oo,. Jae Ho Chung,
Notes to Pages III–II, :o,
“Korea Between Eagle and Dragon: Perceptual Ambivalence and Strategic
Dilemma,” Asian Survey , (:ooI): ,,,–,,o.
I,. Ministry of Foreign Affairs of the People’s Republic of China,
Zhongguo Waijaaio (China’s Diplomacy) (Beijing: World Affairs Press, :oo,);
also, Paul Marks, “Impressions of Chinese Government Involvement in In-
vestment in Vietnam,”unpublished paper, Mar. :ooo; Kurlantzick and Eisen-
man, “China’s Africa Strategy.” Jane Perlez, “Chinese Move to Eclipse U.S.
Appeal in Southeast Asia,” New York Times, I8 Nov. :oo¡.
I8. “Number of Foreign Students in China Rises :o Percent Annually,”
Xinhua, I, Jan. :ooo; “China Expects Influx of Foreign Students,” China
Daily, :, Sept. :oo¡ interview with Eric Teo Chu Cheow, Singapore, Jan.
:ooo; Ministry of Commerce of the People’s Republic of China, China Com-
merce Yearbook :oo,.
I,. “Constantly Increasing Common Ground: Hu’s Speech to the Aus-
tralian Parliament,” :¡ Oct. :oo,, australianpolitics.com/news/:oo,/Io/o,-
Io-:¡b.shtml, accessed Nov. :ooo; James Hookaway, “Many Asians Flaunt
Roots to China as Nation Gains Cachet,” Wall Street Journal, Io Mar. :oo¡;
interview with N. C. Siew, Sin Chew Media, Kuala Lumpur, Jan. :ooo.
:o. Interviews with art professors in Kuala Lumpur, Bangkok, Jakarta,
Aug. :oo, and Mar. :ooo; Pallavi Aiyar, “The Great Chinese Art Bazaar,”
Hindu, ,o Apr. :ooo; Martin Baily, “China Is the World’s Second Largest Ex-
porter of Art,” Art Newspaper, , Feb. :ooo; Carol Vogel, “Sotheby’s Bets on a
Windfall for Today’s Chinese Art,” New York Times, :, Mar. :ooo. Carol
Vogel, “China: The New Contemporary Art Frontier,” New York Times, I Apr.
:ooo. Carol Vogel, “Christie’s Going, Going to China to Hold Auctions,” New
York Times, :o Oct. :oo,.
:I. Interviews with Vietnamese officials, Nha Trang, Oct. :oo,. “Chi-
nese Film Festival :oo, Held in Metro Manila,” Bulletin of the Chinese Em-
bassy in the Philippines, I, June :oo,; David Barboza, “Hollywood Studios
See the Chinese Film Market as Their Next Rising Star,” New York Times, ¡
July :oo,. Alexandra Seno, “China’s Starring Role in the Philippines,” Inter-
national Herald Tribune, : Feb. :ooo. Luca Bruno, “Chinese Movie Wins Top
Prize in Venice,”Associated Press, II Sept. :ooo. Interviews with South Korean
arts figures and journalists, Seoul, Aug. :oo,.
::. Analysis was completed by studying samples of leading Thai and
Indonesian newspapers in I,,, and :oo, and comparing analysis of China,
columns about China, and news coverage of China. See also “Devastating
Blows: Religious Repression of Uighurs in Xinjiang,” Human Rights Watch
report, Apr. :oo,.
:,. Interview with Lee Poh Ping, Kuala Lumpur, Jan. :ooo; Foreign
:o8 Notes to Pages II,–I:I
Ministry of the People’s Republic of China, “President Hu Jintao Meets Thai
King,” I8 Oct. :ooo; Larry Rohter, “China Widens Economic Role in Latin
America,” New York Times, :o Nov. :oo¡.
:¡. For a history of the Indonesian crisis, see Adrian Vickers, A History
of Modern Indonesia (Cambridge: Cambridge University Press, :oo,).
:,. For a history of the Chinese in Indonesia, see Leo Suryadinata,
Pribumi Indonesians, the Chinese Minority, and China: A Study of Perceptions
and Policies (Singapore: Eastern University Press, :oo,); Jemma Purdey,
Anti-Chinese Violence in Indonesia, :,,o–:,,, (Singapore: Singapore Uni-
versity Press, :ooo).
:o. Purdey, Anti-Chinese Violence; Leo Suryadinata, “Chinese Politics
in Post-Suharto’s Indonesia,” Asian Survey , (:ooI): ,o:–,:¡.
:,. Suryadinata, Pribumi Indonesians, I:,–I:,, :Io–:I,; “China Voices
Concern for Chinese Indonesians,” Straits Times, Io July I,,8.
:8. Interview with A. B. Susanto, Jakarta, Mar. :ooo.
:,. Ibid.
,o. “The Happy Chinese,” Economist, ¡ Feb. :ooo; interview with
Christine Susanna Tjhin, specialist in Chinese Indonesian politics, Jakarta,
Mar. :ooo. Jay Solomon, “Indonesia’s Chinese Embrace New Role,” Wall
Street Journal, , Feb. :oo,; Christine Susanna Tjhin, “More Chinese-Indone-
sians Become Actively Involved in Politics,” Jakarta Post, :, Mar. :oo¡.
,I. “Thai PM Seeks Out Roots in Meizhou,” China Daily, ¡ July :oo,;
“Thai PM Concludes China Tour,” Xinhua, , July :oo,.
,:. Khien Theeravit, “Thaksin Lays Out Regional Vision,” Nation
(Thailand), :o Apr. :oo:. Perlez, “Chinese Move to Eclipse U.S. Appeal”; see
also Phusadee Arunmas, “Thai-Chinese Car Venture to Challenge Japanese
Firms,” Bangkok Post, :, Dec. :oo,, and Phusadee Arunmas, “Pact with
China Signed to Boost Bilateral Trade to $,o Billion by :oIo,” Bangkok Post,
:, Sept. :oo,. Interview with Kraisak Choonhaven, Bangkok, Aug. :oo,.
,,. Subhatra Bhumiprabhas, “FTA Watch: Movement ‘Is Gaining
Strength,’ ” Nation (Thailand), I, Jan. :ooo; interviews with US trade nego-
tiators, Washington, Oct. :oo,. Interviews with Thai and American trade ne-
gotiators, Washington and Bangkok, Jan. and Mar. :ooo. See also “Bigots
Against FTA,”,
accessed Nov. :ooo.
,¡. Interviews with senior CP executives, Bangkok, Aug. :oo,;on-
don: Taylor and Francis, :ooI).
Notes to Pages I::–I:, :o,
Chapter ,:
Goal Oriented
I. M. Taylor Fravel, “Regime Insecurity and International Coopera-
tion: Explaining China’s Compromises in Territorial Disputes,”International
Security : (:oo,): ¡o–8,.
:. Vincent Wei-Cheng Wang, “The Logic of China-ASEAN FTA: Eco-
nomic Statecraft of “Peaceful Ascendancy,” in China and Southeast Asia:
Global Changes and Regional Challenges, ed. Ho Khai Leong and Samuel C. Y.
Ku, I,–¡I (Singapore: Institute of Southeast Asian Studies, :oo,).
,. Robert Sutter, “China’s Rise and U.S. Influence in Asia: A Report
from the Region,”Atlantic Council of the United States Issue Brief, July :ooo.
¡. Interviews with Alejandro Melchor, Philippine Department of De-
fense, Ambassador José V. Romero, and Leticia Ramos Shahani, former
Philippine senator, Manila, Mar. :ooo; National Defense University, “China’s
Growing Influence in Southeast Asia: March :oo, Trip to Philippines and In-
donesia,” INSS Staff Report, ¡ May :oo,; “Workshop on Asean Relations with
China and the United States: Event Report,” National Bureau of Asian Re-
search, , Nov. :oo,; David Shambaugh, “China Engages Asia: Reshaping the
Regional Order,” International Security , (:oo¡): o¡ –,,.
,. Interviews with Thai diplomats and politicians, Bangkok, Aug. :oo,
and Jan. :ooo.
o. Robert G. Sutter, China’s Rise in Asia: Promises and Perils (Lanham,
Md.: Rowman and Littlefield, :oo,), Ioo–Io,.
,. Interviews with Vincent Lim, political secretary to the prime min-
ister of Malaysia, and Jawhar Hassan, director general, ISIS Malaysia, Kuala
Lumpur, Jan. :ooo.
8. Philip Pan, “China’s Improving Image Challenges U.S. in Asia,”
Washington Post, I, Nov. :oo,; Tom Fawthrop, “Middle Kingdom Puts
Squeeze on Little Kingdom,” Phnom Penh Post, :, May :ooI; “Cambodia-
China Relations: Steady Improvement, Growing PRC Influence,” Cable from
US Embassy, Phnom Penh, I June :oo¡; Philip P. Pan, “China’s Improving
Image Challenges US in Asia,” Washington Post, I, Nov. :oo,.
,. Interviews with Vietnamese officials and diplomats, Nha Trang,
Oct. :oo,; see also Eric Teo Chu Cheow, “China Lights Vietnam’s Path,”
Japan Times, I: Jan. :oo¡. Interview with Bounnheuang Songnavong, deputy
director, Ministry of Foreign Affairs, Lao PDR, Aug. :oo,.
Io. Afshin Molavi, “Fine China,” New Republic, 8 Sept. :oo,, I¡.
II. James Mahon, “Goodbye to the Washington Consensus?” Current
History : (:oo,): ,8–o¡; Michael Shifter, “The US and Latin America
Through the Lens of Empire,” Current History : (:oo¡): oI–o,.
:,o Notes to Pages I,o–I,¡
I:. Barry Sautman, “Friends and Interests: China’s Distinctive Links
with Africa,” Working Paper no. I:, Center on China’s Transnational Rela-
tions, Hong Kong University of Science and Technology, :ooo.
I,. Interview with I Wibowo, Jakarta, Mar. :ooo; interview with Dewi
Fortuna Anwar, Jakarta, Mar. :ooo; interview with Gavin Khoo, Kuala Lum-
pur, Jan. :ooo.
I¡. Frank Ching, “China Woos Influence with Softer Style,” Japan
Times, Io June :oo¡.
I,. Francisco Guerrera, “China Is in Danger of Sinking,” Financial
Times, o May :ooo; Conn Hallinan, “China: A Troubled Dragon,” Foreign
Policy in Focus Commentary,,
accessed Sept. :ooo; Edward Cody, “China Grows More Wary over Rash of
Protests,” Washington Post, Io Aug. :oo,; Kristin Jones, “China’s Hidden Un-
rest,” Committee to Protect Journalists, special report, May :ooo.
Io. Interviews with Burmese monks, tour guides, laborers, Mandalay
and Chiang Mai, Mar. :ooo; interviews with Uighur and Kazakh traders,
Kashgar, Aug. :oo¡; phone interview with Antonella Diana, Jan. :ooo.
I,. Lai Hongyi, “China’s Regional Oil Diplomacy” and “China’s Oil
Diplomacy Going Global,” Background Briefs, East Asian Institute, National
University of Singapore, :oo,.
I8. Mamoun Fandy, “China vs. US: A View from the Arab World,”
paper prepared for Energy Security: Implications for US–China–Middle
East Relations conference, Rice University, I8 July :oo,.
I,. “China, Saudi Arabia Ink Oil Cooperation Deal,” Associated Press,
:, Jan. :ooo; see also “China, Saudi Arabia Forge Closer Relationship,” China
Daily, :¡ Jan. :ooo. Samuel Blatteis, “Dueling for Economic Dominance: The
Quiet Fight for the Persian Gulf,” San Francisco Chronicle, ,o Apr. :ooo;
David A. Andelman, “The Sino-Saudi Connection,” Forbes, I, Apr. :ooo, I8.
:o. See, for example, Peter Maass, “The Breaking Point,” New York
Times Magazine, :I Aug. :oo,, ,o.
:I. Interview with Singaporean diplomats, Singapore, Jan. :ooo.
::. John Reed, “Beijing Flexes Its Muscles in Zambian Election,” Fi-
nancial Times, , Sept. :ooo.
:,. Sam Rith, “China Revives Dreams of Kampot Mega-Dam,” Phnom
Penh Post, ¡ Nov. :oo,. Interviews with Masao Imamura, Unit for Social and
Economic Research, Chiang Mai, Aug. :oo,, and Muanpong Juntamas, Mekong
River Commission, Vientiane, Aug. :oo,; see also Charlotte McDonald-Gibson,
“No Regard for the Neighbors: Blasting the River in China’s Backyard,” Phnom
Penh Post, I, Jan. :oo,; and John Vidal, “Dammed and Dying: The Mekong and
Its Communities Face a Bleak Future,” Guardian, :, Mar. :oo¡. Interview with
Cambodian environmental specialist, Phnom Penh, Jan. :ooo.
Notes to Pages I,,–I¡I :,I
:¡. Interview with Cambodian environmental specialist, Phnom
Penh, Jan. :ooo.
:,. Interviews with Singaporean diplomats, Singapore, Jan. :ooo;
interview with James Wong, Kuala Lumpur, Mar. :ooo.
:o. Melody Chen, “Grenada, Beijing Re-Establish Links,”Taipei Times,
:I Jan. :oo,; “China, Commonwealth of Dominica Establish Diplomatic
Ties,” Xinhua, :, Mar. :oo¡; “Trying to Win Over Taiwan’s Allies,” Latin
America Special Reports, : May :ooo. Kerry Dumbaugh and Mark P. Sullivan,
“China’s Growing Interest in Latin America,” Congressional Research Ser-
vice report, :o Apr. :oo,.
:,. “Changes in Republic of China and Panama’s Diplomatic Rela-
tionship?” United Daily News, :: Apr. :oo¡; Melody Chen, “Taiwan Foreign
Ministry Closely Monitoring PRC Official’s Tour to Panama,” Taipei Times,
I8 June :oo¡. Interview with Daniel Erikson, Inter-American Dialogue,
Washington, Aug. :oo,.
:8. Department of Foreign Affairs of the Republic of South Africa,
“China, History of Relations,”
.html, accessed Nov. :ooo; see also Ministry of Foreign Affairs of the People’s
Republic of China, “China and Central Africa White Paper,” I: Oct. :oo:.
“China, Liberia Resume Diplomatic Ties,” People’s Daily, I, Oct. :oo,; “Tai-
wan: President Defends Africa Tour,” Taiwanese Central News Agency, , July
:oo:; “Senegal Picks Taiwan over China,” BBC News, :o Oct. :oo,. “China,
Chad Resume Diplomatic Ties,” People’s Daily, , Aug. :ooo. Interview with
Joanne Chang, Washington, Feb. :ooo.
:,. “PM Goh Makes Surprise Taiwan Stopover,” Reuters, :8 Nov. I,,,.
Samuel Ku, “Taiwan’s Southward Policy and Its Changing Relations with
Southeast Asia, I,,o–I,,,,” East Asian Institute Background Brief, National
University of Singapore, I8 Nov. :oo,; Samuel Ku, “Taiwan’s Relations with
Southeast Asia post-I,,,,” East Asian Institute Background Brief, National
University of Singapore, I8 Nov. :oo, Ian Storey, “China’s Tightening Rela-
tionship with Cambodia,”China Brief, Jamestown Foundation, :o Apr. :ooo.
Lin Chieh-yu and Monique Chu, “Lu Pans China for Restricting her Trip,”
Taipei Times, Io Aug. :oo:; see also “Annette Lu not Allowed to Enter Jakarta:
Spokesman,” People’s Daily, I, Aug. :oo:. Monique Chu, “Foreign Ministry
Seeking to Improve Ties with Southeast Asia,” Taipei Times, :I Aug. :oo:.
“Malaysia Bars Ministers from Making Visits to Taiwan,” People’s Daily, :¡
July :oo¡.
,o. “Taiwan Has Invested $¡o Billion in China,” Central News Agency,
:o Jan. :oo,.
,I. Interview with Leticia Ramos Shahani, former Philippine senator,
Manila, Mar. :ooo.
:,: Notes to Pages I¡I–I¡¡
,:. Interviews with DPP officials, Washington, Aug. :oo, and Nov. :oo,.
,,. “Overseas Chinese Speak with One Voice Against ‘Taidu,’” People’s
Daily, , Mar. :oo¡; “Overseas Chinese in Panama Do Not Welcome Chen
Shui-Bian’s Visit,” Xinhua, I, May :ooI; interview with Ellen Palanca,
Manila, Mar. :ooo; interview with Francis Chua, president of the Federation
of Filipino-Chinese Chambers of Commerce, Manila, Mar. :ooo.
,¡. “World Buddhism Summit,” The Times of London, Io Aug. :oo:;
Mickey Spiegel, “Rejection of Visa for Dalai Lama,” Korea Times, I, June
:ooo. For more on China’s treatment of Falun Gong, see Human Rights
Watch, “Dangerous Meditation: China’s Campaign Against Falun Gong,”
Jan. :oo:, and Thomas Lum, “China and Falun Gong,” Congressional Re-
search Service report, :, May :ooo. Gregg Jones, “China Is Working Hard to
Enhance Its Image in Asia,” Dallas Morning News, :, Mar. :ooI. “Indonesian
Court Jails Falun Gong Activists for Chinese Embassy Protest,” Xinhua, ,
May :oo,; “Court Convicts I: Falun Gong Supporters over Protest,” Jakarta
Post, :8 Apr. :oo,; Committee to Protect Journalists, “Asia Cases :oo,,” in At-
tacks on the Press in :oo,, ed. Paul E. Steiger and Ann Cooper (New York:
Committee to Protect Journalists, :ooo).
,,. Joshua Eisenman, untitled chapter, in China and the Developing
World: Beijing’s Strategy for the Twenty-First Century, ed. Joshua Eisenman,
Eric Heginbotham, and Derek Mitchell (Armonk, N.Y.: Sharpe, forthcom-
ing, :oo,).
Chapter 8:
Wielding the Charm
I. Interview with Songpol Kaoputumptip, Bangkok Post reporter who
has frequently visited Mong La, Bangkok, Aug. :oo,.
:. Ibid. See also Xia Hailong, “Casino Town Loses Out,” Asia Times, :,
Nov. :oo,.
,. Interview with Songpol Kaoputumptip. See also Andrew Marshall
and Anthony Davis, “Soldiers of Fortune,” Time Asia, , Dec. :oo:, Io.
¡. Clive Parker, “The Rise and Fall of Burma’s Casino Capital,” Ir-
rawaddy, Feb. :ooo; interview with Songpol Kaoputumtip. See also Joan
Williams, “Mong La: Burma’s City of Lights,” Irrawaddy, Jan.–Feb. :oo,.
,. Parker, “Rise and Fall”; “Burma,” CIA World Factbook, https://, accessed Nov. :ooo.
o. Freedom House, Freedom in the World: The Annual Survey of Polit-
ical Rights and Civil Liberties (Lanham, Md.: Rowman and Littlefield, :oo,).
On Burma’s health spending, see United Nations Development Program,
Notes to Pages I¡,–I,o :,,
Human Development Report :oo, (New York: Oxford University Press, :oo,).
On its military spending, see Gerhard Will, “Case Study: Burma,” paper pre-
sented to Third Europe–Southeast Asia Forum, Berlin, I,–I, Dec. :oo¡.
,. Andrew Marshall, “Soldiers of Fortune,” Time Asia, Io Dec. :oo:.
See Interpol statistics on global opium and heroin production at
.interpol.int/Public/Drugs/heroin/default.asp, accessed Nov. :ooo. James
East, “Up to Two Million Thai Students into Drugs,” Straits Times, :, Dec.
I,,,; see also Aung Zaw, “Drugs, Generals, and Neighbors,” Irrawaddy, June
:ooI. Kyaw Zwa Moe, “Yunnan’s Sin City,” Irrawaddy, Jan. :oo,; see also
“Anatomy of an Epidemic,” Economist, :8 July :oo,; Naw Seng, “Drug Trade
Booms on China-Myanmar Border,” Asia Times, ,I Mar. :oo¡; and “Drugs-
Wa Link to Triads Confirmed,” Bangkok Post, :: Dec. :ooo.
8. Interviews with Chinese diplomats, Bangkok and Washington, Aug.
:oo, and Mar. :ooo; interview with Curtis Lambrecht, specialist on the
Burmese military, Hua Hin, Jan. :ooo. See also Michael Schuman, “Going
Nowhere,” Time Asia, ,o Jan. :ooo, :o; and Thomas Carroll, “China’s Pene-
tration into Burma,” M.S. thesis, Georgetown University, :ooI.
,. Parker, “Rise and Fall”; Naw Seng, “Chinese Troops on Burma’s
Border,” Irrawaddy,:,, ac-
cessed Jan. :oo,. “Chips Are Down for Cadres,” South China Morning Post, ,I
Dec. :oo¡; see also Edward Cody, “China Targets Corrupt Officials in a Battle
Against Temptation,” Washington Post, :o Feb. :oo,. “Io, Foreign Casinos
Compelled to Close,” People’s Daily, :, Mar. :oo,. Interview with Chinese
officials, Beijing, Aug. :oo,. See also “China Presses Myanmar to Crack
Down on Drug Trafficking,” Deutsche Press-Agentur, I¡ Feb. :ooo.
Io. “China Watch,” Jane’s Intelligence Review, Jan. :oo¡; see also Eliza-
beth Economy, “China’s Rise in Southeast Asia: Implications for Japan and
the United States,” Japan Focus, o Oct. :oo,. Michael Black and Roland
Fields, “Virtual Gambling in Myanmar’s Drug Country,” Asia Times, :o Aug.
:ooo. Parker, “Rise and Fall.”
II. Global Witness, “A Choice for China: Ending the Destruction of
Burma’s Frontier Forests,” Global Witness publications, Oct. :oo,.
I:. Ibid.
I,. “Chinese Environmentalist Goes on Trial Over State Secrets,”
Agence France Presse, I, May :ooo; E-mail interviews with Chinese scholars,
Kunming, Aug. :oo,; interview with Thai monk based in Burmese border
areas, Chiang Mai, Aug. :oo,. See also Kyaw Zwa Moe, “The ‘Made in China’
Syndrome,” Irrawaddy, Nov. :oo¡, and Graeme Lang and Cathy Hui Wan
Chan, “The Impact of China on Southeast Asian Forests,” Southeast Asia Re-
search Center Working Paper Series, City University of Hong Kong, June
:oo,.
:,¡ Notes to Pages I,o–I,:
I¡. Global Witness, “A Choice for China.”
I,. Ibid.; “China and the Global Market for Forest Products: Trans-
forming Trade to Benefit Forests and Livelihoods,” Forest Trends report,
the%:oGlobal%:oForest%:oMarket-Forest%:oTrends.pdf, accessed Apr.
:ooo.
Io. National Intelligence Council, “NIC :o:o Project: NIC-Sponsored
Seminar on Asian Responses to the United States,” :¡ Nov. :oo,; Robert
Zoellick, “Whither China? From Membership to Responsibility,” Remarks to
the National Committee on U.S.-China Relations, :I Sept. :oo,.
I,. State Council Information Office, “China’s Peaceful Development
Road,” white paper, :: Dec. :oo,; Fu Ying, “China and Asia in a New Era,”
China: An International Journal : (:oo,): ,o¡ –,I:; interview with Chinese
diplomat, Washington, Sept. :oo,.
I8. “Frequent Blasts Make Coal Mining Most Dangerous Job in
China,” People’s Daily, I¡ Nov. :oo¡. See also Li Qiang, “The World’s Most
Dangerous Job?” South China Morning Post, :: Feb. :oo,, and Zijun Li, “The
Cost of China’s Energy Boom: Miners’ Lives,” Worldwatch Institute report,
Io Nov. :oo,.
I,. “Chinese Peacekeepers Sent to Liberia,” China Daily, :, Nov. :oo,;
Michael Fullilove, “Angel or Dragon?” National Interest, Sept.–Oct :ooo,
o,–,I.
:o. Richard Paddock, “Rumor of Thai Actress’ Words Salted a
Wound,” Los Angeles Times, , Feb. :oo,. See also Andrew Perrin and Matt
McKinney, “Blast from the Past,” Time Asia, : Feb. :oo,, ¡:.
:I. Paddock, “Rumor”; see also “Khmers Raze Embassy,” Nation
(Thailand), ,o Jan. :oo,. Howard Altman, “The King of Bling Bling,” Amer-
ican Journalism Review, Sept. :oo:, ,¡-,,.
::. Perrin and McKinney, “Blast from the Past”; Kimina Lyall, “Thais
Flee Cambodia as Mobs Riot,” The Australian, ,I Jan. :oo,.
:,. Interviews with Cambodian diplomats, Phnom Penh, Jan. :ooo;
see also “China Hopes Thailand, Cambodia Settle Unrest Calmly,” Xinhua,
,o Jan. :oo,. Seth Mydans, “Thailand: Apology from Cambodia Accepted,”
New York Times, , Feb. :oo,. “Cambodian Border: Checkpoints Reopen,”Na-
tion (Thailand), :: Mar. :oo,.
:¡. Johanna McGeary, “Look Who’s Got the Bomb,”Time Asia, :I Oct.
:oo:. ,8; Leon V. Sigal, “Negotiating with the North,” The Bulletin of the
Atomic Scientists o (:oo,): I,–:,.
:,. “China and North Korea: Comrades Forever?” International Crisis
Group report, Feb. :ooo. Robert Marquand, “US Looks to China to Influ-
ence North Korea,” Christian Science Monitor, Io July :ooo; see also Mark E.
Notes to Pages I,,–I,8 :,,
Manyin, “U.S. Assistance to North Korea: Fact Sheet,” Congressional Re-
search Service Report, ,I Jan. :ooo. Craig S. Smith, “North Korean Leader
Kicks the Tires in Shanghai,” New York Times, I8 Jan. :ooI. “With Unusual
Praise for Shanghai’s Great Changes, North may Pursue Chinese-Style
Opening,” Chosun Ilbo, :I Jan. :ooI.
:o. “China and North Korea: Comrades Forever?”
:,. State Council Information Office, “China’s Peaceful Development
Road”; “A Regional Discussion of the Six-Party Process,” transcript, Brook-
ings Institution, II Mar. :oo,.
:8. Interviews with former South Korean officials, Seoul, Aug. :oo,.
:,. “China,”International Narcotics Control Strategy Report :oo:, US
Department of State, released Mar. :oo,; Economy, “China’s Rise”; Zhang
Yan, “Speech to the ¡,th Session of the Commission on Narcotics Drugs,”Vi-
enna, I, Mar. :oo¡.
,o. Interview with Heather Peters, Bangkok, Aug. :oo,; “China, Viet-
nam Launch Joint Campaign to Combat Trafficking in Border Area,” Xin-
hua, , June :oo¡.
,I. For a comprehensive account of the SARS crisis, see Karl Taro
Greenfield, China Syndrome: The True Story of the ::st Century’s First Great
Epidemic (New York: HarperCollins, :ooo). Wen Jiabao, “Speech to Ministe-
rial Meeting of the International Pledging Conference on Avian and Human
Pandemic Influenza,” I8 Jan. :ooo; Margie Mason, “Donors Pledge $I., Bil-
lion to Fight Bird Flu,” Associated Press, I8 Jan. :ooo.
,:. Centro de Investigación y Docencia Económicas, “Mexico y el
Mundo: Global Views :oo¡,” Mexican Public Topline report, Sept. :oo¡;
“Trade, Investment, and Economic Cooperation Between China and South-
east Asia: The Case of Malaysia,”JETRO report, Nov. :oo,–Feb. :oo¡; “Prime
Minister: China Not a Threat to Economy,” Star (Malaysia), :, Feb. :oo¡.
,,. Chia Siow Yue, “Asean-China Free Trade Area,” Paper for presenta-
tion at the AEP Conference Hong Kong, I:–I, Apr. :oo¡; interview with
Bounnheuang Songnavong, deputy director, Ministry of Foreign Affairs, Lao
PDR, Aug. :oo,; interview with Takao Tsuneishi, JETRO Bangkok, Aug. :oo,;
see also Robert Devlin, Antoni Estevadeordal, and Andrés Rodríguez-Clare,
The Emergence of China: Opportunities and Challenges for Latin America and
the Caribbean (Washington: Inter-American Development Bank, :ooo), II–
I,, and Key Indicators :oo,: Labor Markets in Asia (Manila: Asian Develop-
ment Bank, :ooo), :,,–:,o. Jorge Domínguez, “China’s Relations with Latin
America: Shared Gains, Asymmetric Hopes,”Inter-American Dialogue work-
ing paper, June :ooo, ,,–¡o. Petchanet Pratruangkrai, “Service Sector Can
Profit from Asean-China FTA: Thanong,” Nation (Thailand), :8 June :oo,.
,¡. James Allen, “Lula Admits He Made Political Decision,” O Estado
:,o Notes to Pages I,8–Io:
de São Paulo, I, Nov. :oo¡; Devlin, Estevadeordal, and Rodríguez-Clare, The
Emergence of China, I¡o.
,,. Jonathan Wheatley, “China Dashes Brazil Trade Hopes,” Financial
Times, , Oct. :oo,; Matt Moffett and Geraldo Samor, “Brazil Regrets its
China Affair,” Wall Street Journal, Io Oct. :oo,; Mark O’Neill, “Record Trade
Surplus Raises Ire of Foreign Partners,” South China Morning Post, Io Oct.
:oo,; Devlin, Estevadeordal, and Rodríguez-Clare, The Emergence of China,
I8,; Joel Millman and Peter Wonacott, “For China, a Cautionary Tale,” Wall
Street Journal, II Jan. :oo,; Greg Hitt, “Latin Trade Deal Has Chinese Flavor,”
Wall Street Journal, :o Jan. :oo,.
,o. Busakorn Chantasasawat, “Burgeoning Sino-Thai Relations:
Heightening Cooperation, Strengthening Economic Security,” China: An In-
ternational Journal I (:ooo): 8o–II:; interviews with representatives of man-
ufacturers, electronics companies, textile associations, Phnom Penh, Kuala
Lumpur, Jakarta, Jan. :ooo and Mar. :ooo.
,,. “Chinese Are Oil Thieves,” Business in Africa, ¡ May :ooo; Laurie
Goering, “China’s Investment, Clout in Africa Cause Concern,”Chicago Trib-
une, I, Feb. :ooo; Joseph J. Schatz, “Zambian Hopeful Takes a Swing at
China,” Washington Post, :, Sept. :ooo; David Blair, “Ignored by the Mob,”
Daily Telegraph blog, : Oct. :ooo,
davidblair/octoo/mobI.htm, accessed Nov. :ooo.
,8. See Elizabeth C. Economy, The River Runs Black: The Environmen-
tal Challenge to China’s Future (Ithaca: Cornell University Press, :oo,).
,,. Ben Schiller, “The China Model of Development,” Open Democ-
racy, :o Dec. :oo,,
,I,o.pdf, accessed Nov. :ooo; interview with Tod Ragsdale, environmental
impact consultant, Washington, Aug. :oo,. On Chinese dams see also
Michael Richardson, “Damming up the Flow of Information,” South China
Morning Post, , May :ooo.
¡o. Interviews with Cambodian, Lao, and Singaporean diplomats,
Aug. :oo,. Southeast Asian Rivers Network, “Downstream Impacts of Hy-
dropower and Development of an International River: A Case Study of Lan-
cang-Mekong,” paper prepared for the UN Symposium on Hydropower and
Sustainable Development, Beijing, :,–:, Oct. :oo¡; see also “Trying to Save
a Catfish as Big as a Bear,” Associated Press, I Dec. :oo,, and Seth Mydans,
“Mission on the Mekong: Save the Giant Catfish,” New York Times, I8 Dec.
:oo:. Milton Osborne, “River at Risk: Mekong and the Water Politics of
Southeast Asia,”Lowy Institute paper, :¡ Aug. :oo¡; see also Peter Goodman,
“Manipulating the Mekong,” Washington Post, ,o Dec. :oo¡, and Milton Os-
borne, “The Strategic Significance of the Mekong,” Contemporary Southeast
Asia , (:ooo): ¡:,– ¡¡¡.
Notes to Pages Io:–Io, :,,
¡I. Kuch Naren, “Villagers Say Officials Gave Land to the Chinese,”
Cambodia Daily, , July :oo,; see also Cambodia Business Press digest, no. ,,,
, July :oo,. “UN Asks Cambodia Cancel Land Grant to China Firm,”Reuters,
, July :oo,. “UN Official Calls on Cambodia to Cancel Concession on In-
digenous Land,” UN News Service, o July :oo,.
¡:. “Human Rights in Cambodia: The Façade of Stability,” Licadho
Report,files/8o8:LICADHOFacadeDemoc
racyReport:oo,-oo.pdf, accessed June :ooo; Cambodia Business Press di-
gest, no. ,,, , July :oo,.
¡,. Paul Magnusson, “A Milestone for Human Rights,” BusinessWeek,
:¡ Jan. :oo,, o,.
¡¡. Minxin Pei, “The Dark Side of China’s Rise,” Foreign Policy, Mar.–
Apr. :ooo, ,:– ¡o; Minxin Pei, China’s Trapped Transition: The Limits of De-
velopmental Autocracy (Cambridge: Harvard University Press, :ooo), I,,.
¡,. “Bank of China Facing Another Scandal,” Agence France-Presse, 8
Mar. :ooo.
¡o. Interview with oil executive, Jakarta, Mar. :ooo.
¡,. Robin Emmott, “Peru Miners Feel Oppressed by China’s Shou-
gang,” Reuters, :I July :oo,.
¡8. Ibid.
¡,. Joel Millman and Peter Wonacott, “For China, a Cautionary Tale:
Insularity, Unfamiliar Ways Strain Investments,” Wall Street Journal, II Jan.
:oo,; Stephen Frost, “Chinese Investments Abroad; Shougang and Labor
Protests in Peru,” CSR Asia Weekly I, week ,,. Emmott, “Peru Miners Feel
Oppressed.”
,o. Millman and Wonacott, “For China, a Cautionary Tale”; Frost,
“Chinese Investments Abroad.”
,I. Millman and Wonacott, “For China, a Cautionary Tale”; Frost,
“Chinese Investments Abroad.”
,:. Simon Zadek, “China’s Route to Business Responsibility,” Open
Democracy, ,o Nov. :oo,,
PDF/,o,o.pdf, accessed Nov. :ooo.
,,. Rory Carroll, “China’s Goldmine,” Guardian, :8 Mar. :ooo; Goer-
ing, “China’s Investment, Clout.”
,¡. Goering, “China’s Investment, Clout.”
,,. Interview with Filipino mining activists, Manila, Mar. :ooo; Ben
Schiller, “The Axis of Oil: China and Venezuela,” Open Democracy, , Feb.
:ooo,
8,&articleId=,,I,, accessed Nov. :ooo.
,o. “Overview: Millennium Challenge Corporation,”
.gov/about/index.php, accessed Mar. :ooo; Donald Greenless, “At World
:,8 Notes to Pages Io,–I,:
Bank, a Pledge to Focus on Corruption,” International Herald Tribune, ,I
May :ooo.
,,. “Cambodia to Lose Much of Foreign Aid over Poor Governance,”
Kyodo News Service, o Dec. :oo¡; “Statement by Peter Leuprecht,” oIst Ses-
sion of the United Nations Commission on Human Rights, I, Apr. :oo,.
,8. Interview with Sokhem Pech, Phnom Penh, Jan. :ooo; “China
Pledges $ooo Million in Grants, Loans for Cambodia,” Kyodo News Service,
Io Apr. :ooo; interviews with French, Canadian diplomats, Phnom Penh,
Jan. :ooo; interviews with World Bank, Asian Development Bank officials,
Washington and Vientiane, Aug. :oo,.
,,. “Country Reports on Human Rights :oo,: Central African Repub-
lic,”US Department of State, released :, Feb. :oo¡; Louisa Lombard, “Africa’s
China Card,” Foreign Policy,?
story_id=,¡I,, accessed Oct. :ooo.
oo. “All the President’s Men,” Global Witness report,
.globalwitness.org/reports/show.php/en.oooo:.html, accessed Jan. :oo,;
John Reed, “A Peace Dividend,” Financial Times, I¡ Nov. :oo,.
oI. Schiller, “The China Model of Development.”
o:. Ibid.; see also John Reed, “A Patchy Performance,” Financial Times,
I Mar. :ooo.
o,. “Election Budget: Angola,” Africa Confidential, ,I Mar. :ooo.
o¡. Reed, “A Patchy Performance.”
o,. John Donnelly, “China Scooping Up Deals in Africa as US Firms
Hesitate,” Boston Globe, :¡ Dec. :oo,.
Chapter ,:
America’s Soft Power Goes Soft
I. Program on International Policy Attitudes, “:, Nation Poll: Who
Will Lead the World?” I, Nov. :oo¡ –, Jan. :oo,; Program on International
Policy Attitudes, “,, Nation Poll on Views of Countries,” Feb. :ooo; Richard
Holbrooke, “Get the Message Out,” Washington Post, :8 Oct. :ooI.
:. “Tumultuous Crowd Welcomes Clinton to Hanoi,” Cnn.com, I,
Nov. :ooo,
.vietnam.o:/, accessed Nov. :ooo.
,. Kishore Mahbubani, speech to Carnegie Council, : Mar. :oo,.
¡. Foreign Affairs Council, “Secretary Colin Powell’s State Depart-
ment: An Independent Assessment,” Mar. :oo,; “America’s Overseas Pres-
ence in the :Ist Century,” Report of the Overseas Presence Advisory Coun-
cil, Department of State, Nov. I,,,.
Notes to Pages I,:–I,, :,,
,. US Department of State, “Program Alumni—International Visitor
Leadership Program,”,
accessed Nov. :ooo; Martha Bayles, “Goodwill Hunting,” Wilson Quarterly ,
(:oo,): ¡o–,,; US Department of State, Bureau of Educational and Cultural
Affairs budgets, I,,,–:oo:; Juliet Antunes Sablosky, “Recent Trends in De-
partment of State Support for Public Diplomacy, I,,,–:oo:,” Center for
Arts and Culture, :oo,.
o. Andrew Kohut and Bruce Stokes, America Against the World (New
York: Times Books, :ooo), ,,; Program on International Policy Attitudes,
“Americans on UN Peacekeeping: A Study of US Public Attitudes,” Center
for the Study of Policy Attitudes, :8 May I,,,.
,. Cynthia Watson, “Testimony to the Western Hemisphere Subcom-
mittee of the US House of Representatives Committee on Foreign Affairs,” o
Apr. :oo,.
8. Carol Matlack and Pallavi Gogoi, “What’s This? The French Love
McDonald’s?” BusinessWeek, I, Jan. :oo,, ,o.
,. Interviews with business leaders in Bangkok, Jakarta, Singapore,
Seoul, Aug. :oo,–Mar. :ooo.
Io. Craig Charney and Nicole Yakatan, A New Beginning: Strategies for
a More Fruitful Dialogue with the Muslim World (New York: Council on For-
eign Relations Press, :oo,), ¡,.
II. Thom J. Rose, “US Visas: Applications Down, Prices Up,” United
Press International, I, Apr. :oo¡; see also Government Accountability Office,
“Improvements Needed to Reduce Time Taken to Adjudicate Visas for Sci-
ence Students and Scholars,” Feb. :oo¡. Steve Clemons, “United States Visa
Application Rejection Rates,”, ac-
cessed Nov :ooo.
I:. Sanford J. Ungar, “Pitch Imperfect,” Foreign Affairs , (:oo,): ,–I,;
see also Art Levine, “Voice Over America,” American Prospect, Sept. :oo,, II–
I:. Glenn Kessler, “The Role of Radio Sawa in Middle East Questioned,”
Washington Post, I, Oct. :oo¡.
I,. Interviews with State Department consular service officials, July
and Aug. :oo,; interview with Allan Gyngell, Washington, Dec. :oo,.
I¡. Government Accountability Office, “State Department Efforts to
Engage Muslim Audiences Lack Certain Communication Elements and Face
Significant Challenges,” GAO Reports, May :ooo.
I,. Karen Hughes, “Remarks with Turkish Foreign Ministry Under
Secretary Ambassador Ali Tuygan,”,¡o,,
.htm, accessed Jan. :ooo.
Io. Interviews with Millennium Challenge Corporation officials and
:8o Notes to Pages I,,–I8o
former officials, Oct. :oo,; Farah Stockman, “US to Shift Envoys to Devel-
oping Countries,” Boston Globe, I, Jan. :ooo. For information on the Mil-
lennium Challenge Corporation, see mcc.gov.
I,. Jane Perlez, “Letter from Asia: China Is Romping with the Neigh-
bors (US Is Distracted),” New York Times, , Dec. :oo,.
I8. “Does Paul O’Neill Have Argentina Issues?” Financial Times, :I
Aug. :ooI.
I,. Interview with Mean Sophea, Phnom Penh, Jan. :ooo.
:o. Cambodia Bilateral Textile Agreement,
embassy.gov/uploads/images/M,rzdrzMKGioAjfoSIuJRA/uskh_texttile.pdf
#search=%::us%:ocambodian%:obilateral%:otextile%:oagreement%::,
accessed Nov. :ooo; interviews with United States Trade Representative offi-
cials, Washington, Sept. :oo,; “U.S.-Cambodian Textile Agreement Links In-
creasing Trade with Improving Workers’ Rights,” Office of the United States
Trade Representative, , Jan. :oo:.
:I. Sheridan Prasso, “Trading Up,” The New Republic, Io Aug :oo¡, II–
I:; Tom Fawthrop, “The Price of Free Trade, Part II,” Yale Global Online,¡o:,, accessed Feb. :oo,; inter-
view with Mean Sophea, Phnom Penh, Jan. :ooo.
::. Peter S. Goodman, “Pinning Hope on Fair Labor Standards,”
Washington Post, I, Nov. :oo¡.
:,. Phann Ana and Kevin Doyle, “Radicals Try to Strengthen Ties in
Cambodia,” Cambodia Daily, I, Sept. :oo,; US Department of State, “Coun-
try Reports on Terrorism: East Asia and the Pacific,” released :8 Apr. :ooo;
Tariff Relief Assistance for Developing Economies Act of :oo,,
.theorator.com/billsIo,/hr88o.html, accessed Nov. :ooo.
:¡. Interview with Mean Sophea, Phnom Penh, Jan. :ooo.
:,. Stanley Foundation, “US Human Rights Policy in Southeast Asia:
New Issues for a New Era,” Stanley Foundation report, Io May :oo¡, ,.
:o. “US Human Rights Record in :ooo,” Information Office of State
Council, released Feb. :ooI; “Human Rights Record of the US in :oo¡,” In-
formation Office of State Council, released Mar. :oo,.
:,. Frances Williams, “US Stands Alone over Cultural Diversity
Treaty,” Financial Times, :o Oct. :oo,; Nicholas Kristof, “Schoolyard Bully
Diplomacy,” New York Times, Io Oct. :oo,; Anholt Nation Brands Index,
:oo,, I Aug. :oo,; see nationbrandindex.com.
:8. Charney and Yakatan, A New Beginning, ,:.
:,. Park Song-wu, “¡8% of Youth Would Side with North Korea in
Case of US Attack,” Korea Times, :: Feb. :ooo.
,o. Council on Graduate Schools, International Graduate Admissions
Notes to Pages I8o–I,: :8I
Survey :oo¡, :oo,; United Nations High Commissioner for Refugees, “Asy-
lum Seekers and Trends in Industrialized Countries, :oo,,” report released I,
Mar. :ooo.
,I. Kohut and Stokes, America Against the World, :¡.
,:. Joseph Nye, Soft Power: The Means to Success in World Politics (New
York: Public Affairs, :oo¡); Pew Global Attitudes Survey, released :, June
:oo,.
,,. Kohut and Stokes, America Against the World, ,¡; Anholt Nation
Brands Index :oo,.
,¡. Joseph Nye, “Grand Strategy and Global Public Goods,” New Per-
spectives Quarterly,,
accessed Jan. :oo,.
,,. Interview with US policy makers responsible for US-Indonesian
relations, Washington, Aug. and Sept. :oo,.
,o. Anthony Shadid and Steve Fainaru, “Militias on the Rise Across
Iraq,” Washington Post, :I Aug. :oo,.
,,. Interview with US policy makers responsible for US-Indonesian
relations, Washington, Aug. and Sept. :oo,; Ellen Nakashima and Alan Si-
press, “Southeast Asia’s New Corps of Suicide Bombers, Washington Post, Io
Aug. :oo,.
,8. Glenn Kessler and Robin Wright, “Report: U.S. Image in Bad
Shape,” Washington Post, :¡ Sept. :oo,.
Chapter Io:
What’s Next?
I. Ministry of Foreign Affairs of the People’s Republic of China,
“Shanghai Cooperation Organization,” brief released , Jan. :oo¡. The SCO’s
genesis was in an international grouping founded in I,,o called the “Shang-
hai Five.”
:. Interview with senior State Department planning officials, Wash-
ington, Oct. :oo,; Greg Austin, “European Union Policy Responses to the
Shanghai Cooperation Organization,” European Institute of Asian Studies
publications, European Institute of Asian Studies, Dec. :oo:; “Country Brief:
Kazakhstan,” Energy Information Agency, US Department of Energy.
,. Gao Fuqiu, “The Real Purpose of the American March into Central
Asia,” Outlook (Liaowang), Io May :oo:.
¡. “Chinese Delegation Visits Confucius Institute in Tashkent,” Uz-
bekistan National News Agency, I Nov. :oo,; Jeremy Bransten, “Central Asia:
China’s Mounting Influence,” Eurasia Insight, :, Nov. :oo¡.
:8: Notes to Pages I,,–I,,
,. “China’s Growing Influence in Central Asia,” Radio Free Asia, I,
Nov. :oo¡; Andrew Kohut, “American Public Diplomacy in the Islamic
World,” Remarks to the Senate Foreign Relations Committee, :, Feb. :oo,.
o. Interviews with Chinese, US diplomats, Washington and Beijing,
June and Aug. :oo,; Stephen Blank, “Islam Karimov and the Heirs of Tianan-
men,” Eurasia Daily Monitor, Jamestown Foundation, I¡ June :oo,.
,. “Central Asian Security Group Demands Deadlines for Western
Bases to Pull Out,” AFX News, , July :oo,; Josh White, “Uzbekistan Senate
Says U.S. Troops Must Leave,” Washington Post, :, Aug. :oo,; Ann Scott
Tyson, “Russia and China Bullying Central Asia, US Says,” Washington Post,
I, July :oo,; Bates Gill and Matthew Oresman, China’s New Journey to the
West: China’s Emergence in Central Asia and Its Implications for US Interests
(Washington, D.C.: CSIS, :oo,), I–Io.
8. Sam Knight, “China to Send I,ooo Peacekeepers to Lebanon,” Times
(London), I8 Sept. :ooo; “China Ratifies UN Safety Convention,” Xinhua, :8
Aug. :oo¡.
,. Anthony Lake, Christine Todd Whitman, Princeton N. Lyman, and
J. Stephen Morrison, eds., More Than Humanitarianism: A Strategic U.S. Ap-
proach Toward Africa (New York: Council on Foreign Relations Press, :oo,),
¡8; interview with Elizabeth Huybens, World Bank East Timor, Dili, Mar.
:ooo; interview with Western diplomats, Phnom Penh, Jan. :ooo; interview
with Carol Lancaster, Georgetown University aid specialist, Washington,
Aug. :oo,; interview with Chinese officials, Washington and Beijing, July
:oo, and Aug. :oo,.
Io. Elizabeth Economy, “China’s Rise in Southeast Asia: Implications
for Japan and the United States,” Japan Focus, Io Oct. :oo,; interview with
Burma activists, Washington, Bangkok, Jan. :ooo; “Premier Wen Jiabao
Holds Talks with Prime Minister of Myanmar Soe Win,” Foreign Ministry of
the People’s Republic of China statement, I¡ Feb. :ooo; Larry Jagan, “Burma,
China Strengthen Bilateral Ties,” Bangkok Post, I, Feb. :ooo; “UN Votes to
put Burma on Agenda,” BBC news, Io Sept. :ooo.
II. Interview with Dom LaVigne, American Chamber of Commerce
Malaysia, Kuala Lumpur, Jan. :ooo.
I:. Web Japan, “Major Recipient Countries of Japan’s Bilateral ODA,”, accessed Nov. :ooo; Citizen-
ship and Immigration Canada, “Immigrants in Canada: Census :ooI High-
lights,”, ac-
cessed Dec. :oo¡.
I,. Interview with Japanese diplomat, Washington, Oct. :oo,.
I¡. Michael Green, “Is Japan a Responsible Stakeholder?” CSIS Com-
mentary, : June :ooo.
Notes to Pages I,,–:o, :8,
I,. Satoshi Nakagawa, “ODA Reform Essential to Regain Public Trust,”
Yomiuri Shimbun, :, Dec. :oo¡; personal visit to Yasukuni Shrine, Aug. :ooo.
Io. Robert Marquand, “Gulf Widens Between Japan, China,”Christian
Science Monitor, II Apr. :ooo.
I,. Interview with State Department official, Washington, Nov. :oo,;
interviews with Japanese diplomats, Washington and Tokyo, Aug. :oo,;
Mayumi Negishi and Kanako Takahara, “Japan Settles for ‘Low Risk, Low Re-
turn’ FTA Goals,” Japan Times, :: Apr. :oo,.
I8. Interview with Ajit Singh, Kuala Lumpur, Jan. :ooo; interview with
State Department official, Washington, Nov. :oo,.
I,. Energy Information Administration, Annual Energy Outlook, :oo,,
available at; John Vidal, “The End of Oil Is
Closer than You Think,” Guardian, :I Apr. :oo,.
:o. Erica Downs, “The Chinese Energy Security Debate,”China Quar-
terly, Mar. :oo¡, :I–¡I; Mikkal Herberg, “Asia’s Energy Insecurity, China,
and India,”Testimony Before the Senate Committee on Foreign Relations, :o
July :oo,; R. Evan Ellis, US National Security Implications of Chinese Involve-
ment in Latin America (Carlisle, Pa.: Strategic Studies Institute, :oo,), ,.
:I. Danna Harman, “Chávez Seeks Influence with Oil Diplomacy,”
Christian Science Monitor, :, Aug. :oo,.
::. William Ratliff, “Pragmatism Over Ideology: China’s Relations
with Venezuela,” China Brief, Jamestown Foundation, I, Mar. :ooo; Ellis, US
National Security Implications, 8.
:,. Michelle Billig, “The Venezuelan Oil Crisis,” Foreign Affairs ,
(:oo¡): :.
:¡. “China’s National Defense in :oo¡,” State Council Information
Office release, :, Dec. :oo¡.
:,. Downs, “The Chinese Energy Security Debate”; Gal Luft and Anne
Korin, “The Sino-Saudi Connection,” Commentary, Mar. :oo¡, :o–:,.
:o. Ilan Greenberg and Andrew E. Kramer, “Cheney, Visiting Kazakh-
stan, Wades into Energy Battle,” New York Times, o May :ooo; Peter Baker,
“US Warns Russia to Act More Like a Democracy,” Washington Post, , May
:ooo; Peter Baker, “With Kazakh’s Visit, Bush’s Priorities Clash,” Washington
:,. Peter Maass, “A Touch of Crude,”Mother Jones, Jan/Feb :oo,, ¡8–,o.
:8. Dennis Blair, “Address to Carnegie International Non-Prolifera-
tion Conference,”Io Mar. :ooo; interviews with Singaporean and Thai diplo-
mats, Singapore and Bangkok, Jan. :ooo.
:,. Interview with Philippine defense planners, Manila, Mar. :ooo.
:8¡ Notes to Pages :oo–:I,
,o. John Wong, Zheng Yongnian, and Tok Sow Keat, “China’s Reaction
to DPM Lee Hsien Loong’s Visit to Taiwan,” East Asian Institute Background
Brief, :, Aug. :oo¡; John Burton, “Singapore Warns Taipei on Indepen-
dence,” Financial Times, :, Aug. :oo¡.
,I. “Australians Speak :oo,: Public Opinion and Foreign Policy,”Lowy
Institute Poll, :, Mar. :oo,; “BHP Billiton Posts Record Interim Profit,” Aus-
tralian Broadcasting Corporation,
:oooo:/sI,,oI¡o.htm accessed Mar :ooo.
,:. Richard Baker, “US Sent ‘Please Explain’ to Downer over China
,,. John Kerin, “Beijing’s ANZUS Warning,” The Australian, 8 Mar.
:oo,.
,¡. Freedom House, Freedom in the World :oo, (Lanham, Md.: Row-
man and Littlefield), :oo,.
,,. Human Rights Watch, “Human Rights Overview: China,” http://
hrw.org/english/docs/:ooo/oI/I8/chinaI::,o.htm, accessed Nov. :ooo; United
States Department of State, “Country Reports on Human Rights Practices,
:oo,: China,”, accessed
Nov. :ooo.
,o. “The National Security Strategy of the United States of America,”
Sept. :oo:,, accessed Nov. :ooo, ,–
¡; Paul Starobin, “John Kerry: Leader of the Free World,” National Journal,
Sept. :oo¡, :,,:–:,,,.
,,. Alberto Abadie, “Poverty, Political Freedom, and the Roots of Ter-
rorism,” National Bureau of Economic Research, Oct. :oo¡, working paper,
available at; Alan B.
Krueger and Jitka Maleckova, “Education, Poverty, and Terrorism: Is There a
Causal Connection?” Journal of Economic Perspectives ¡ (:oo,): II,–I¡¡.
,8. “Zimbabwe,” in Amnesty International Report :ooo: The State of the
World’s Human Rights (New York: Amnesty International, :ooo); Andrew
Meldrum, “Gloating Mugabe Vows to Rule Until He Is Ioo,” Guardian, ¡ Apr.
:oo,; Michael Wines, “Opposition in Zimbabwe Sees Fraud in Vote Data,”
New York Times, , Apr. :oo,.
,,. Human Rights Watch, “Zimbabwe: Mass Evictions Lead to Mas-
sive Abuses,” Human Rights Watch Report, II Sept. :oo,.
¡o. Abraham McLaughlin, “A Rising China Counters US Clout in
Africa,” Christian Science Monitor, ,o Mar. :oo,; Hu Jintao, “Consolidate
Traditional Sino-African Friendship, Deepen Sino-African All-round Co-
operation,” Address to the National Assembly of Gabon, : Feb. :oo¡.
Notes to Pages :I¡–:I, :8,
¡I. “Zimbabwe Press Review,” BBC Monitoring, ,o Jan. :ooo; “Zim
Varsity Students Will be Forced to Learn Chinese,” Africa News, :o Jan. :ooo;
interview with Chinese diplomats, Washington, July :oo,; Carolyn Bar-
tholomew, Testimony Before the House of Representative Committee on In-
ternational Relations Subcommittee on Africa, :8 July :oo,.
¡:. Robert Mugabe, Interview with SkyNews (UK), :¡ May :oo¡; An-
drew Meldrum, “Mugabe Turns Back on West and Looks East,” Guardian, I,
Apr. :oo,.
¡,. Nazila Fathi, “Wipe Israel Off the Map, Iranian Says,” New York
Times, :, Oct. :oo,; Ramita Navai and Richard Beeston, “Iran Sacks Diplo-
mats in Purge of Reformers,” Times (London), : Nov. :oo,; “Iran Cracks
Down on Bloggers,”Associated Press, :8 Mar. :ooo. “Iran Nuclear Plan ‘Irre-
versible,” BBC.com, :, Apr. :ooo,
¡,,,:8:.stm, accessed Nov. :ooo. Robert Tait and Ewen MacAskill, “Iran De-
clares: We Are in the Nuclear Club,” Guardian, I: Apr. :ooo.
¡¡. John Tkacik, “Confront China’s Support for Iran’s Nuclear Wea-
pons,” Heritage Foundation Web memo,
AsiaandthePacific/wmIo¡:.cfm, accessed June :ooo; John Calabrese, “China
and Iran: Mismatched Partners,” Jamestown Foundation occasional paper,
Aug. :ooo.
¡,. For extended background on the crisis in Darfur, see http://
sudanreeves.org/, accessed Nov. :ooo.
¡o. Eric Reeves, “Next Casualty,” New Republic, I, May :ooo, I8–I,;
Glenn Kessler and Colum Lynch, “U.S. Calls Killings in Sudan Genocide,”
Washington Post, Io Sept. :oo¡.
¡,. Peter S. Goodman, “China Invests Heavily in Sudan’s Oil Indus-
try,” Washington Post, :, Dec. :oo¡; Yitzhak Shichor, “Sudan: China’s Out-
post in Africa,” China Brief, I, Oct. :oo,; Stephanie Giry, “Out of Beijing,”
New Republic, I, Nov. :oo¡, I,–:I; Howard W. French, “China in Africa: All
Trade, with No Political Baggage,” New York Times, 8 Aug. :oo¡.
¡8. For all Human Rights Watch documents on Darfur, see http://, accessed Nov. :ooo.
¡,. Peta Thornycroft, “Mugabe Rejects Call for Dialogue; Looks to
China for Help,” Voice of America News,
:oo,-o8/:oo,-o8-o8-voa,:.cfm?CFID=,,8oI,,,&CFTOKEN=Io¡:,,8: ac-
cessed Dec :oo,.
,o. Interview with Burma activist, Bangkok, Aug. :oo,.
,I. Lyall Breckon, “A Lull—and Some Complaints,” Comparative Con-
nections, Ist Quarter :oo¡,¡oIq.pdf,
o,–,o.
:8o Notes to Pages :I,–::,
Chapter II:
Responding to the Charm Offensive
I. Joseph Nye, “Can America Regain Its Soft Power After Abu Ghraib?”
Yale Global Online,¡,o:, ac-
cessed Nov. :ooo.
:. Tom McCawley, “US Tsunami Aid Still Reaps Goodwill,” Christian
Science Monitor, :8 Feb. :ooo; “Taliban: ‘No Jihad Unless US Attacks,’”
Guardian, I8 Sept. :ooI; Susilo Bambang Yudhoyono, “Keynote Address,”
USINDO Dinner, Washington, :, May :oo,.
,. Office of Research and Opinion Analysis, “US Image Positive in
Urban Thailand, Bolstered by a Sense of Shared Security Interests,” Depart-
ment of State, ,I Oct. :oo,; interview with Vietnamese official, Nha Trang,
Oct. :oo,.
¡. What the World Thinks in :oo:, Pew Global Attitudes Project
(Washington, D.C.: Pew Publications, :oo:).
,. “Academic Ranking of World Universities :ooo,” Shanghai Jiao
Tong University,, accessed Nov. :ooo.
o. To-Chol Sin and Jason Wells, “Is Democracy the Only Game in
Town?” Journal of Democracy : (:oo,): 88–IoI; Simon S. C. Tay, “Asia and the
United States After ,/II: Primacy and Partnership in the Pacific,” Fletcher
Forum of World Affairs I (:oo¡): II,–I,:.
,. Andrew Kohut and Bruce Stokes, America Against the World (New
York: Times Books, :ooo), I,o.
8. Interviews with Cambodian politicians, Phnom Penh, Jan. :ooo.
,. Zheng Yonginan and Tok Sow Keat, “How China Views Singapore,”
Background Brief, East Asian Institute publications, Io June :oo¡.
Io. Woranuj Maneergungsee, “China Likely to Profit Most from Asean
Free Trade Deal,” Bangkok Post, Io Sept. :oo,; “Trade, Investment, and Eco-
nomic Cooperation Between China and Southeast Asia: The Case of Malay-
sia,” Institute of Developing Economies—Japan External Trade Organiza-
tion, Nov. :oo,–Feb. :oo¡.
II. Interview with Dwi Hartanto, Jakarta, Mar. :ooo; interview with
Ong Hok Ham, Jakarta, Mar. :ooo; interview with Phil Overmyer, Singapore,
Jan. :ooo.
I:. Paul Handley, “De-Mythologizing Charoen Pokphand: An Inter-
pretive Picture of the CP Group’s Growth and Diversification,” in Ethnic
Business: Chinese Capitalism in Southeast Asia, ed. Jomo K. S. and Brian C.
Folk, I,,–I8I (London: Taylor and Francis, :ooI); Ben Dolven, “Suzhou Proj-
ect: Wounded Pride,” Far Eastern Economic Review, 8 July I,,,, ,I.
Notes to Pages ::,–:,, :8,
I,. Interview with senior US official, Washington, Oct. :oo,.
I¡. “U.S.-China Engagement Act of :ooo,” introduced :o Apr. :ooo,,,, accessed Nov. :ooo.
I,. Joseph Nye, “Europe’s Soft Power,” Globalist,
ist.com/DBWeb/printStoryId.aspx?StoryId= ,88o, accessed Dec :oo,; Stephen
Johnson, “Voice of America’s Death by a Thousand Cuts,” Heritage Founda-
tion Web memo,
IoI,.cfm, accessed June :ooo; see also Tri Evers, “Successes of and Challenges
Facing U.S. Public Diplomacy: Statement Before the House Committee on
Government Reform Subcommittee on National Security, Emerging Threats
and International Relations,”:, Aug. :oo¡. Iam Limbach, “Wooing Back For-
eign Travelers,” Financial Times Special Report: Global Traveler, I, May :ooo;
see also Condoleezza Rice, “Secure Borders and Open Doors in the Infor-
mation Age,”speech at Dean Acheson Auditorium, Washington, I, Jan. :ooo.
Io. Phone interview with Jamie Metzl, former senior adviser to the
undersecretary for public diplomacy and public affairs, Nov. :oo,.
I,. National Defense University, “China’s Growing Influence in
Southeast Asia: March :oo, Trip to Philippines and Indonesia,” INSS Staff
Report, ¡ May :oo,; Craig Charney and Nicole Yakatan, A New Beginning:
Strategies for a More Fruitful Dialogue with the Muslim World (New York:
Council on Foreign Relations Press, :oo,), o; Documents on March :oo,
visit to Southeast Asia, obtained from Department of Defense through Free-
dom of Information Act request.
I8. Kohut and Stokes, America Against the World, :o; “Aid for Indone-
sia,” Advertiser, ,I Aug. :oo¡; interview with congressional staff for Senator
Sam Brownback, Washington, June :oo,.
I,. See Julia E. Sweig, Friendly Fire: Losing Friends and Making Enemies
in the Anti-American Century (New York: PublicAffairs, :ooo).
:o. Richard P. Cronin, “A New U.S.-Asean Trade Track,” Wall Street
Journal, , Feb. :ooo.
:I. Robert Zoellick, “Remarks at a Press Roundtable in Thailand,”
Bangkok, ¡ May :oo,; Evelyn Goh, “Renewed American Diplomacy: Keep-
ing Southeast Asia on US Radar Screen,” IDSS Commentaries, :¡ May :oo,.
::. Ivo H. Daalder and James M. Lindsay, America Unbound: The Bush
Revolution in Foreign Policy (New York: Wiley, :oo,), ,.
:,. Tommy Koh, “America’s Role in Asia,” PacNet ,,, :I Dec. :oo¡,¡,,.pdf, accessed Feb. :oo,; “U.S
Image Positive in Urban Thailand, Bolstered by a Sense of Shared Security
Initiatives,” State Department Office of Research, ,I Oct. :oo,.
:88 Notes to Pages :,,–:¡I
:¡. Sweig, Friendly Fire, I,o.
:,. Alphonse F. La Porta, “Statement for Hearing on Indonesia in
Transition,” Committee on International Relations Subcommittee on Asia
and the Pacific, Io Mar. :oo,.
Notes to Pages :¡I–:¡: :8,
Index
Abadie, Alberto, :I,
Abu Ghraib prison, I:I
Accenture, 8,
Afghanistan, ,:, I,,, I8¡, I,8, :I,
African Development Bank, ,I, I,,
African Union, ,I
Agence France Presse, :¡,, :¡¡
agriculture, Io, Io,
Ahmadinejad, Mahmoud, ,¡, ::o
aid programs: American, I,8–,,,
I8:, I8,, I,I, :,o–,,; Japanese,
:o¡ –,, :oo, :o,; Western model
of, I,I–,:, I,,. See also Chinese
aid
Al-Azhar mosque (Jakarta), I::
Al Jazeera television, I,I–,:
Alkatiri, Mari, IIo
All China Federation of Trade
Unions, I,¡
Al Qaeda, I8,, I,8
Amata Corporation, ,o
Amazon Watch, I,I
American Centers, I,,, :,,
American culture, :o, ,,, ,,, II¡,
I,,, I,:–,,; Australia and, :;
demand for, I8:, ::,; domina-
tion of, I,8; exchange programs
and, I,,, :,,
American foreign policy: Central
Asia and, :oo–:oI; Chinese
influence and, III–:¡; Chinese
soft power’s impact on, :o8–I,;
extreme unpopularity of, I,:–
,¡; interventionism and, ¡¡ –¡,,
:Io–I,, ::,; post–Cold War
changes in, ,,, I,,, I,8–8I, I,,,
:Io; recommended changes in,
:,,–,8; Truman policies and,
:¡o; unilateralism and, I,,. See
also counterterrorism; public
diplomacy; soft power
American values, I,,, I,o, I,:–
,,, I,,–,o, :I,; appeal of, ::,,
::,, :¡I
Amorn Apithanakoon, ,,–8o
Andean Community, ,I
Andijan massacre (:oo,), :oo
Angkor Wat, I,o, I8,
Angola, o,, Io:, IIo, I,,–,,
anti-Americanism, ¡, ,–Io, :,, :,,
II:–I,, I8o–,o, :oo; Asian
financial crisis and, ,,; Australia
and, :–,; Chinese positive image
vs., I,,; of Chinese students, :8;
image decline and, ,:–,o, ¡,,
I:o–:I, I:,, I,:, I,8–,,, I,o–,,;
impact of, I,¡–,,; recommended
countermeasures, :,,–¡o, stri-
dency of, I,:–,,, :,,; tsunami
relief moderating, ::,
Anwar, Dewi Fortuna, I,,
Anwar, Jusuf, 88
ANZUS Treaty, :I¡, :I,
Aoyama, Rumi, o:
Applegarth, Paul, I8,
Arabic language, I,,
Argentina, ,o, ,,, o8, 8,, II,, IIo,
Io:; economic crises in, I8o–8,
artists and art market, II,
Asean-Chinese Eminent Persons
Group, o,
Asean Regional Forum, ,I
Asia Cooperation Fund, ,I
Asian Center for Media Studies, I,,
Asian Development Bank, Io¡
Asian financial crisis, :o, ,,–,o, I:I–
:¡, I,,, I8:; Chinese aid and, ,8–,,
Asia Pacific Economic Coopera-
tion, ,:–,,, I8o
Association of Southeast Asian
Nations, I¡, ,o, ¡8–,I, IoI, I¡o,
:o8; Amity and Cooperation
Treaty, ¡,–¡8, ¡,, :o,, :,8–,,
Austin, Greg, I,,
Australia, o8, Io8, IIo, III, :¡:;
American vs. Chinese reception
in, I– ¡, II, I,o, I8¡, :I¡ –I,, ::o
authoritarian regimes, ¡,, ¡,, ,o,
,,–,¡, I,:, I¡o; China as, I,:, I,,,
:Io; Chinese backing of, ¡:, I,o,
I,:–,,, :o:–,, :o,, :I,–Io, :I8,
:I,–:,, :,o; Chinese develop-
ment model and, ,o, ,,–,8, ::,;
corruption and, Io,–o8, I,:;
instability of, :o:–,, :I8; oil
resources and, :I:, :I8
automobile industry, 8o, :o¡
avian flu, Ioo, :¡:
Azhar mosque (Jakarta), I::
Badawi, Abdullah, IoI
Bai Chunli, ,,
Bali, ¡, I:,, I¡,, I,¡
Bandung Conference, I,
Bangkok Declaration, 8I
banking, :o, 88–8,, ,,, I,o
Bank of China, Io,
Bashir, Omar, ,¡
Becker, Jasper, :,, :¡
Beers, Charlotte, I8,
Beijing Art Fair, II,
“Beijing Consensus” vs. “Washing-
ton Consensus,” ,o–,8
Beijing Diplomacy Institute, Io:–,
Beijing University, ,:, ,I
Belgrade Chinese embassy bomb-
ing, :o–:8
BHP Billiton, :I¡
Bhumibol Adulyadej, I,o
Billig, Michelle, :Io
“Billion Boomer” generation, Ioo
Biwu Zhang, ,:, ,,
Blair, Dennis, :I,
Blair, Tony, :I,
Boao Forum for Asia, o¡ –o,, I:o
Bolivia, ,,–,¡, ,,, 8o, :Io
border regions: Chinese goals for,
,,–,8, ¡,–¡8, ,:, I,o, I,,; Chi-
nese investments in, ,I–,:;
Chinese mediation and, I,,–,,;
Chinese migrants and, Io¡ –o;
problems in, I¡,–,I, I,,
Index :,I
Bové, José, I8I–8:
Brazil, ,:, o,, 8,, I,¡, I,o, Io:, I,I;
Hu’s welcome in, I:I
Britain, I,I, ::o, :,o
British Broadcasting Corporation,
:,o
British Council, o8
Burma, 8, Io, ¡,, Io,, I¡o, I¡,, Ioo,
:,,, :¡,– ¡,; authoritarian gov-
ernment of, ¡:, I,o, :o:–,; Chi-
nese anti-junta policies and, :o:–
,, :I8, ::¡; Chinese influence in,
o,, ,I, ,:, I¡o, I,o, I,:–,,, Io¡,
I,I, :o,; Chinese migrants to,
Io¡, Io,; Chinese tourists in, I¡,,
I,I; Chinese vs. US aid to, ,8;
drug trafficking and, I,o, I,I,
I,,, :o:; migrants to China
from, I,,–,8; opposition groups
in, I,–I¡, :o,; US policies and,
I8o, :¡,
Bush, George H. W., :Io, :I,
Bush, George W. (Bush adminis-
tration), I–¡, Io, ,I, ,¡, ,,, I,o,
I8o, :¡,; critics of, I,:; Darfur
genocide and, ::,; Iran nuclear
program and, ::o; public diplo-
macy failures of, I8,–8,, I,o,
I,I, I,¡, I,,, :I:, :,,. See also
Iraq War
business interests, 8:–Io,, IIo, I:I,
I,,, I,8; American companies
and, I,:–,,; Chinese bad poli-
cies and, I,,, Io,–o8; Chinese
entrepreneurship and, Io, :I, :,;
diaspora Chinese and, ,¡ –,,,
,,–8o, IIo, I:¡ –:,, :,I–,:; law-
less climate of, 8,; soft power
and, ,–o, ,, 8¡. See also corporate
governance; foreign investments
Câmara, João de, Io,
Cambodia, 8, I¡, II,–I,, I¡,; Chi-
nese bad practices and, Io,, I,I–
,,; Chinese development model
and, I,,; Chinese interests in,
¡,–¡o, o8–,o, 8,, ,I, ,8–Ioo,
Io:–,, IIo, I,,, I¡o– ¡I, I¡,, Io,,
:o:; Chinese mediation and,
I,,–,,; Chinese visitors to,
Io¡; Chinese vs. US diplomacy
with, o,; US counterrorism and,
I8,–,o
Campbell, Colin, :o8
capitalism, ,o, I,¡, I,,, I,8, I8:, :¡I
Carnegie Endowment, :,, Ioo
casino gambling, I¡8–,I, :o,
Castro, Raúl, Io:, I,¡
catfish, ,o–,,, Io¡
CCTV (Chinese state television), o,
cell phones, ::
censorship, o¡, II,, I:o
Central Academy of Fine Arts, I,
Central African Republic, I¡,, I,,
Central American free trade, Io:
Central Asia, II, :o, ,I, ,¡; Chinese
wooing of, ,8, I,,–:oI; regional
organization, ,¡, I,,, I,,, :oo;
strategic importance of, :oI, :o,,
:I:; US bases in, I,8–,,, :oo
Central Party School, ,o
Chad, I¡,, :::
Chang, Joanne, I¡,
Chan Heng Chee, ,o
Charoen Pokphand, ,¡ –,o, I:,,
I:8, :,,
Chávez, Hugo, ,, ,,, ,I, :o,, ::,
Cheney, Richard, :I:
Cheng Siwei, ,:
Chen Shui-bian, ¡o, I¡,, I¡,
Chery (automobile company), 8o
:,: Index
Chia Eksaw, ,¡
Chiang Kai-shek, I:, :,
Chile, ,o, I8o, I8o, I,¡
China Association of Youth Volun-
teers, o,
China-Caribbean Economic and
Trade Cooperation Forum, o¡
China Council for Peaceful Reuni-
fication, I¡,
China Export-Import Bank, ,,–
,8, IoI, Io:, Io¡
China Institute for International
Studies, ,:
China-Latin America Friendship
Association, ,:
China model, ,o–,,, 8¡, I,o, I,,–
,,, :I,; appeal of, I,o–,,, ::,;
authoritarian regimes and, :Io;
government corruption and,
Io,–o8; top-down control of, ,o,
Io,; US negative image and, I8:
China National Petroleum Corpo-
ration, ,o–,I, I,,, ::I–::
China Radio International, oI–o:
China Reform Forum, ,o
“China’s Peaceful Development
Road” (:oo: policy), ¡¡
Chinese Academy of Sciences, ,,
Chinese Academy of Social Sci-
ences, ,o
Chinese aid, ,,, ,,–Io:, Io,, IIo,
III, I,,, I¡o, I¡I, I¡,, I,o; Central
Asia and, I,,, :oo; negative
aspects of, I,I–,,, :I,; as non-
realized, :,o; positive uses of,
:o:–,; Venezuela and, :o,–Io
Chinese Chamber of Commerce, I¡,
Chinese Communist Party, I:–Io,
I8, o:–o¡, Io:, :o,; antiliberal
purge in, I,; Asian foreign pol-
icy and, I,I; Chinese cultural
outreach and, o8; economic
reforms and, ,o; intellectuals’
view of, :,, :o; labor control by,
I,¡; priorities (:oo:) of, ,:;
youth of Politburo members, :,.
See also communism; Maoism
Chinese consumption, 8o–8,, ,,,
Ioo, :o,– ¡, :I,
Chinese foreign policy: external
security affairs and, :oI–:; goals
of, ,8– ¡,, I,o, I,,; Japan and,
:oo–,; Maoist tools and, I,–I,;
new pragmatism and, ¡,–¡8;
peaceful development emphasis
of, ¡¡, ¡,, o:, I,o, I,I, I,:, I,,–,¡;
quick shifts in, ::o; rethinking
of, :,–,o, ,:, ,o, ,,–,8, ,:; small
nations focus of, ,8–oo. See also
formal diplomacy; public diplo-
macy; soft power
Chinese-language and -culture
programs, oI, o,, o,–,I, ,,, Io,,
Io,, I:,, ::8–:,; and Cambodia,
o8–,o, IIo; for diaspora Chi-
nese, ,,, ,8; and East Timor, III;
popularity of, IIo–:o; and Thai-
land, I:o–:,; and Uzbekistan,
I,,; and Zimbabwe, :I,
Chinese tourism. See travel and
tourism
Ching, Frank, I,o
civil liberties, ,,, I,:, :I8, :,o, :¡I
civil society, :Io, :I,, :,o, :¡I
Clinton, Bill, Io, :,–:8, ,o, ,,, I,,–
8o, :,,; globalization and, I8I,
I8,; impeachment trial of, I,8;
overseas popularity of, I,,
CLSA Asia Pacific Markets, ,o,
Ioo–,
Index :,,
CNOOC (Chinese oil company), ,I
Coca-Cola, ,
Cold War, ¡, I,–I8; Chinese policy
changes following, ,o; US policy
changes following, ,,, I,,, I,8–
,,, :Io; US soft power and, ,–8,
Io, ,8, I8:, I,,, :,¡
collectives, I,
colonialism, ,:, o:, :,I–,:
communism, I:, I,, ,8–oo; Chi-
nese aid and, Io:–,; Chinese de-
velopment model and, I,,–,¡;
Chinese nationalism as ideologi-
cal substitute for, :,–:¡; Chi-
nese new pragmatism vs., ¡,;
economic liberalization under,
,8. See also Chinese Communist
Party; Maoism
Comprehensive Test Ban Treaty, I,I
Confucius Institutes, o8, I,,
consumer products, I8I, I,,, :Io
copper, ¡o, I¡o, I,o–,I
corporate governance, I,¡, I,,, Io,–
o,, I,o, I,I, I8I, :,o; American
model of, I,8; scandals and, Io
corruption, ,o, o,, 8¡, Ioo–o8, I,I–
,,, I,,, I8I, :I:
Council of Foreign Relations, o,, :,8
Council of Graduate Schools, I,:
counterterrorism: Central Asia’s
importance to, I,8, :oI; US focus
on, ,I, I8,, I8¡, I8o, I8,, I8,, I,o,
I,¡, :,,, :¡:; US policy readjust-
ment needs and, :I,–I8, :,,, :,o
Cuba, ¡,, ,,, Io:, I,¡
cultural diversity, I,I
Cultural Revolution, I,, I,, I,, :¡ –
:,, :8
culture: Chinese tools of, oI–8I, ,,,
Io,, II8–:o; Japanese, I,,, :o,;
soft power and, ,, o, ,, Io, o,
currency, I,, Io,–o; Chinese
undervaluation of, Io:; Thai
devaluation crisis, ,,–,,
Daalder, Ivo H., :¡o
daguo (great power), ,o, ¡:
Dalai Lama, I¡,
dam projects, I¡I, Io¡ –o,, :,o
Darfur genocide, ::I, :::, ::,,
::¡, :¡I
Dashanzi area (Beijing), II,
deforestation, I,:–,,, I,I
democracies, ,o–,,, I,¡, I,,, I,o,
I¡,, I¡¡, I¡o– ¡,, :o,
Democratic Progressive Party (Tai-
wan), I¡¡, I¡,
democratization, I8, I,, ¡:, ,8, Ioo;
effects of US counterterror
excesses and, I,o; Indonesia
and, I:¡, I:,; popular support
for, ::,–,o; post–Cold War
spread of, I,,, I,8; US policy
and, ¡¡, ,o, I,8, I8o, I,¡, :I:,
:Io, :I,, :,¡, :¡I– ¡:
Deng Xiaoping, I,, Io, I,, I8, I,, :,,
,o, ,o
developing nations: China as, ::8;
Chinese vs. US approach to, ,,,
,,–,o, ,,–,8, oo, o,; definition
of, ,; democratization and, :I,;
diaspora Chinese changed
image in, I:,–:,; international
aid model for, I,I; US policies
and, I8,, ::8, :¡o– ¡I. See also
specific nations
development. See China model
“Develop the West” plan, :I
Diana, Antonella, I,8
diaspora Chinese, ,, Io, I¡, ,o–8¡,
II8, :o,; Burmese instability
and, :o:–,; China’s rebuilt rela-
:,¡ Index
tions with, ,o–,I, ,,–,8; com-
plaints about mainland China
by, :,:–,,; new migrants, Io,–,,
IIo; position of, I::–:8, I:,; Tai-
wan and, I¡¡, I¡,
Dili (East Timor), Io8, IIo, III
diplomacy. See formal diplomacy;
public diplomacy
Dominica, I¡:
dos Santos, José Eduardo, I,,
Downer, Alexander, ,, :I,
Downs, Erica, ¡I, ,o, :II
drug trafficking, ,:, I,o, I,I, I,,,
:o:, :o,, :,¡, :¡:
Dubai-US ports deal, I8o
dumping, ,o–,,, IoI, Io:–o,
Early Harvest trade concessions, ,o
East Asia Barometer, ::,
East Asia Summit, ,I, I,:, I¡:, :I,
Eastern bloc, ,–8, Io, I,,
East Timor, ,, ,,, Io8–II, I,,, :o:
economy: Chinese communist, I,;
Chinese post-I,,, growth of,
I,–::, :,, ,I, ,:–,,, ,,, ¡o, oI,
,¡ –,,, I:o, I,o, ::8; Chinese
soft power benefits and, Ioo–o,;
Chinese vs. US model of, ,o–oo;
Chinese vs. US statistics, 8o, ,¡,
,,; diaspora Chinese influence
on, ,¡, ,,; fear of Chinese power
from, 8o; Japan and, I,,, :o¡,
:o,, :oo; US preeminence and,
,,, ::8, :¡o. See also globaliza-
tion; trade
Economy, Elizabeth, Io,
Ecuador, ,¡ –,,, Io:, :Io
education, ::, :8–,I, o,, o,–,o;
Chinese-language overseas pro-
grams and, o8–o,, IIo, II,; Chi-
nese textbook rewriting and, :¡;
diaspora schools and, ,,, ,8; for-
eign students in Chinese second-
ary schools and, ,o; US assis-
tance to, :,,. See also students;
universities
Egypt, I,I–,:
electronics, :,I
Ellis, R. Evan, :o,
energy, ::, ¡I, ,,, ,o–,I, III; Chi-
nese consumption of, ¡o–¡I, ,,,
I,o, I,8, Ioo, I,I; Chinese-US
clash over, :o8–I,. See also
gas; oil
English language, II,, I,8, :,8
Enron, Ioo, Io,
environmental standards, I¡I; Chi-
nese disregard of, I,:–,,, I,¡,
Io,–o,, Io8, I,o, I,I, I,:, :,o
EP-, incident (:ooI), :,, :8, 8o
Equatorial Guinea, :I:
Erikson, Dan, ,8
Eritrea, I¡,
Estrada, Joseph, ,8
ethnic Chinese. See diaspora Chinese
European Union, I,,, Io:, I,,, I8:
exports. See trade
Extractive Industries Transparency
Initiative, I,¡
ExxonMobil, ,:, I,8
Fairbank, John King, I,o
Falun Gong, I¡o
Fandy, Mamoun, I,8–,,
Filipino-Chinese Chamber of
Commerce, ,8
films, I,I; American, I,8, I8I, ::,;
Chinese, II,–:o
Fischer, Joschka, :I,
Ford Motor Company, :o¡
foreign aid. See aid programs; Chi-
nese aid
Index :,,
Foreign Corrupt Practices Act
(US), Ioo
foreign investments, ¡:; by China,
,¡, 8,–8,, 8,–,:, I,8, I¡,, I,o,
Io:, Io,, :oo, :,o; in China, Io,
I,, :o–::, ,¡ –,o, 8o–8,, ,¡, I:,,
I,o, I¡¡, Io,, :oo, :,I–,:; by
Japan, 8,, :o¡, :o,, :oo; soft
power and, o, I¡,; US domi-
nance in, ::8; Western-Chinese
competition for, ,:
foreign policy. See American for-
eign policy; Chinese foreign
policy
foreign students. See students
formal diplomacy, ¡:, I¡o; Chinese
diplomats’ skills and, o,, III, I,,,
I¡:, :,,, :,8; Chinese mediator
role and, I,,–,,; Chinese vs. US
approach to, ¡,, o,–oo, 8,, III,
I,o, I,,, :oo, :I8, :,¡, :,8; recog-
nition of Taiwan and, I¡:–¡,;
US Foreign Service and, o,, I8¡ –
8o; US funding cuts for, I,8–,,.
See also public diplomacy
Forman, Milos, ,–8
Forum on China-Africa Coopera-
tion, ¡8
France, I8:, I,:, ::o
Fravel, M. Taylor, ,o–,I, ¡:–¡,
Freedom House, I,o, :I,
free market. See capitalism
free trade: China–Southeast Asia,
,,, IoI, IoI–o,, :o¡, :o,; Chinese
border zones and, I,,; Chinese
policy and, ,,–,o, I,,, :¡:; US
policy and, Io:, I8I, I88–8,, :,,,
:¡o, :¡:
Fudan University, :8, ,I
Fu Yin, I,,–,¡
Galaxy, ,,
Games, Dianna, I,,
Gao Fuqui, I,8–,,
garment industry, Io:, I88–,o
gas, ¡I, ,¡, ,o–,:, III, I,8, I¡o, Ioo,
:o,, :o8, :¡:
Geely (automobile company), 8o
Geng Biao, II,
genocide, ,,, I8o, :Io–I,, ::I–:,,
:¡I
Georgia, I,8
Gill, Bates, :oo
globalization, 8,, I,8, I8I–,o
Global Overseas Chinese Congre-
gation of Anti–Taiwan Indepen-
dence, I¡,
global power: China as, ,, I,–:o,
:,, :¡, ,I–,:, ,,–,o, ,8, ,,, ¡:–
¡,, o,–o,, I,o, I,:, I,¡; China vs.
United States as, I:I, :oo–:oI,
::,–:¡, :¡:– ¡,; US advantages
over China as, ::,–,o, :,,– ¡,
Global Witness, I,:–,,, I,,
“Goddess of Liberty,” I,
Goh, Evelyn, :,,
Goh Chok Tong, I¡,
Golden Triangle, I,o
Goldman, Merle, I,o
Google, ::, o,
“Go Out” (“Go Global”) cam-
paign, 88
Great Leap Forward, I,
Great Wall Industry Corporation, ,:
Green Watch, I,:
Grenada, I¡:
Gries, Peter Hays, ::–:,
Guantánamo Bay, :, ,, Io, I:I, I,o
Guatemala, I¡:
guochi (national humiliation), ,,
Gusmão, Xanana, Io,
:,o Index
Habibie, B. J., I::
haigui pai (scholars), o,–,o
Hamzah Haz, ::,
hard power, ,8, ,,
heping jueqi. See “Peaceful Devel-
opment” policy
Herberg, Mikkal, :o8–,
heroin, I,o, I,I, I,,
He Yafei, ¡¡
Hierro de Peru, Io8
HIV, ,:, I,o, I,I, Ioo, :o:, :,¡, :¡:
Holbrooke, Richard, I,o
Hong Kong, o¡, ,o, ,,–,,, Ioo–,,
I,o
Hong Liu, ,,
Horizons Group, I8, I,
Howard, John, I
Hua Guofeng, I,
Huawei, 8,, ,,
Hughes, Karen, I8,, I,,, :,,
Hu Jintao, ,, ¡, ,:, ,,, ¡o, o,–,o,
II8; authoritarian regime of, :Io;
developing nations and, ,:, 8,–
88; foreign visits of, I:I; non-
interference and, :I,, :::; “Win-
Win” speech of, ¡,–¡¡
humanitarian aid, ¡¡, :Io, ::,–:8
human rights abuses: Burma and,
:o,; Cambodia and, Io,, I,:;
China and, ,, :8, ,:, ¡,, I:o,
I¡o– ¡,, I,o–,I, :I,, :Io; Ka-
zakhstan and, :I:; Philippines
and, 8,; Sudan and, :::; UN
no-action resolution and, I¡,;
US instances of, :–,, Io, I,o–,I,
:¡I; US policies and, ,o, ,¡, ,,,
I,o, I¡o–¡,, :I:
Human Rights Watch, I:I, :Io, :::
human trafficking, I,,–oo
Hun Sen, ¡o, ¡,, I,,, I¡I, I¡,, I,:
Hurricane Katrina, II¡, I8:
Hu Youqing, o,
Ilitchev, Aleksandr, I,,
immigration, ¡, Io, ::8
income gap: Angola and, I,,;
China and, I,o–,,; United
States and, I8:, I,o–,I
India, ,:, I,o, I,o
Indonesia, 8, ,I, II,, I¡o, :¡:; anti-
American turnaround in, ::,–
:8; Chinese interests in, o8, 88,
,:, II,, I:o, I:,–:,, I,8, Io,–o8,
I,I; Chinese vs. US aid to, ,8;
diaspora Chinese in, I¡, ,,, ,,,
,o, I::–:o, :,I; East Timor and,
Io8–,, III; financial crisis in,
I:I–:¡, I,,; human rights abuses
in, ,o; Japanese aid in, :o,; Tai-
wan and, I¡¡; terrorism and, ¡,
I,¡, I,,; US policy and, II,, I8,–
8o, I,I–,:, I,¡ –,o, :,o, :,,, :¡:;
US tsunami relief and, ::,–:8
informal summits, o¡ –o,
information technology, I,,–,8
infrastructure projects, Io:, :o:
insurgencies, I,–I¡, I,, ¡,, ::¡ –:,
Inter-American Development
Bank, ,I
Inter-American Dialogue (think
tank), ,8
International Criminal Court, ,¡,
I,,, I,I, :,,–¡o
International Labor Organization,
I88
international law, :, :¡o
International Monetary Fund, ,,,
I:I, I,¡, I8,, :o:, :¡o
international organizations: aid
model and, I,I; China’s allies in,
Index :,,
international organizations
(continued)
I¡,–¡,, :oI; China’s potential
in, I,,; developing nations and,
,:; soft power and, o, ,, I,,; US
role in creation of, I,8, :¡o, :¡I
Internet, ::, :¡, :o, ,,, I,,–,8, I8:
Iran: authoritarian government
of, ¡:, :I,–Io, ::o–:I; Chinese
development model and, I,,,
I,¡; Chinese vs. American values
and, ::,; Chinese wooing of, ¡¡,
,¡, ,¡, ::o–:I, ::,–:¡; oil inter-
ests in, ,I, I,8, ::o, ::I; United
Nations and, I¡o, ::o
Iraq War, I, Io, ,,, ¡¡, ,,, I8o, I8,,
:Io, :I,, :¡,; interethnic conflict
and, I,,; lack of international
support for, I,¡; US human
rights abuses and, I,o, I,I
Islam. See Muslims
Israel, ,¡, I8o, :oI, ::o
Jagan, Larry, :o,
Jakarta Consulting Group, I:,–:¡
Japan, ,I, ,,, 8,, II,, :¡:; Australian
relations with, ¡, :I¡; Chinese
relations with, ¡,, I¡:, :o¡ –,,
:o,–8; cultural influence of, I,,;
foreign aid and, 8¡, ,8, ,,, Io:;
soft power and, :o¡ –,; Thai
financial bailout by, ,,; trade
and, ,¡, ,,, ,o, IoI; US bases in,
I,8; World War II and, :, :o,,
:oo–,
Jazeera television, I,I–,:
Jemaah Islamiah, I8,
Jiang Yuande, o,
Jiang Zemin, :,, :¡, ,:, ,o, ,,, oo, :Io
Joffe, Josef, II¡
Jordan, ,I, :,o
JW Marriott Hotel (Jakarta), I,,
Kachin State, I,:
Karimov, Islam, ,–Io, ,¡, :oo
Karzai, Hamid, I,,
Kasetsart University, o,
Kashgar, :o–::
Kavi Chongkittavorn, I,,
Kazakhstan, I,,, I,8, I,,, I,8, :I:
Kelly, Jim, I,,
Kenya, o8, II,, :o¡
Keo Remy, ¡,– ¡o, ¡,
Kerry, John, :I,
Khameini, Ayatollah, ,¡, I,¡
Khin Maung Thwin (“Eddie”),
:¡,– ¡¡
Khmer Rouge, I¡, II,–Io, I,,
Khoo, Gavin, I,,
Kidman, Nicole, :
Kim Dae Jung, ,,
Kim Jong Il, I,,, I,8
Kitti Jinsiriwanich, II8
Koh, Tommy, :¡o
Koizumi, Junichiro, :oo
Kolbe, Jim, I8,
Kraisak Choonhavan, Io,, I:,
Krueger, Alan B., :I8
Kull, Steven, II:
Kuok, Robert, ,,
Kuomintang, I¡¡, I¡,
Kyoto Protocol, I,,, I,I
Kyrgyzstan, I,,, I,8
labor, 8o, ,:, Ioo; Cambodian-US
trade agreement and, I88–8,;
Chinese policies and, I,¡ –,,,
IoI, Io:, Io8–,o, I,o, :,o
Laden, Osama bin, I,o
Lampton, David, Io, ¡o
:,8 Index
land mines treaty, :,,
languages: Chinese diplomat train-
ing in, o,, oo, I,,, :,,; domi-
nance of Chinese vs. English,
II,, I,8; US Foreign Service
deficits in, :,,–,8
Laos, 8, ,8; Chinese development
model and, 8I, I,,–,¡, I,,, I,8;
Chinese interests in, ,8–oo, o,,
,o, 8,, Io,, IIo, IoI, Io¡, I,I, I,:;
Chinese migrants to, Io,, Ioo;
Chinese vs. US aid to, ,8; drug
traffic to, I,o
Lebanon, :oI, :,o
Ledger, Heath, :
Lee Hsien Loong, I¡¡, :I¡
Lee Kuan Yew, :,,
Lee Teng-hui, ¡:
Liberia, I¡,, I,,
Li Gun, I,,
Li Ka-Shing, ,,
Lindsay, James M., :¡o
Li Peng, I,,
Liu Xiaohong, :,
Li Zhaoxing, :o,
Lohman, Walter, ,:
Lowy Institute, ¡, :I¡
Lu, Annette, I¡¡
Lula de Silva, Luiz Inácio, I:I, I,¡
luxury goods, ::, Ioo
Ma, Ying, :o, :8
Maass, Peter, :I:
Macapagal-Arroyo, Gloria, ,,, 8:–
8,, 88
Macaranas, Federico, ,,
Macau, I,8
Mae Fah Luang University, I:o
magazine publishers, II8–I,
Mahathir Mohamad, I¡,, :o,
Mahbubani, Kishore, I,8
Malaysia, 8, I,, I¡o; Chinese trade
and, IoI, Io,, :,I–,:; Chinese
wooing of, o:, 8o, IIo, I:I, I,:, I,,;
diaspora Chinese in, ,, ,I, ,,, ,o,
:,I; Taiwan and, I¡:, I¡,, I¡¡
Maleckova, Jitka, :I8
Mandarin, o8, o,, IIo, :,I
Manila diaspora Chinese cemetery,
,I–,,
Manila Film Festival, I:o
manufacturing, I,, IoI, Io:, Io,, :,:
Maoism, I,–I,, o8; insurgencies
and, ¡,, ::¡ –:,; Khmer Rouge
and, II¡–I,; overseas Chinese and,
,,, ,¡, ,,, I:,
Mao Tse-tung, I:–I,, Io, :,, :,,
,,, ,¡
maquiladoras, IoI
Marks, Paul, ,,
Marshall Plan, ,
Marxism, III, :Io
MBA programs, ,o
McDonald’s, ,, I8:
Mean Sophea, I8,–,o
Medeiros, Evan S., ,o–,I, ¡:– ¡,
media, I8, ::, :,, :¡, ,o, ,o, ,,, II¡,
Io,; China’s portrayal in, I:o–:I,
I,,; Chinese censorship of, o¡;
Chinese culture and, o,, II8–I,;
critique of US policy by, I,I–,:;
public diplomacy and, I8,–8¡,
:,o; US products and, I8I. See
also specific types
mediation, I,,–,,
Megawati Sukarnoputri, I,,
Mekong River, IoI, I¡I, Io¡ –o,,
I,I, :,o
Mekong River Commission, I¡I
Menem, Carlos, ,o
Index :,,
mercantilism, :,I–,:
meritocracy, I8:, I,,
Mexico, ,o, ,:, II,, I,o; Chinese
competition and, IoI, Io:; Chi-
nese diplomacy and, ¡8, o,; Iraq
War and, I,¡; US bailout of, ,¡
middle class, I,
Middle East, I¡, o,; Chinese woo-
ing of, Io, ¡,– ¡¡, I,8–,,, :II; US
public diplomacy failures and,
I8,–8¡, :II. See also Iraq War;
specific countries
migration, Io,–,, IIo, I,,–,8; Chi-
nese rural to urban, ¡o–¡I
military: Burmese rule by, I,o;
Chinese strength and, ,8, ¡o,
:Io–II, :,o–,I; Chinese vs. US
Asian influence and, :I,–I¡; as
soft power complement, ::,–:8;
US Central Asian bases and,
I,8–,,; US diplomacy and, I,¡
Millennium Challenge Corpora-
tion, I,I, I8,
Miller, H. Lyman, :,
Ming government, ,,
mining, ,,, I,,, Io8–,I, :I¡
Mong La (Burma), I¡8–,o, I,I
Mongolia, ,, I,8
moral agency, I,,, I8o, I,o
Morales, Evo, ,,–,¡, :Io, ::,
Moravcsik, Andrew, Io
Morocco, I8:, I,I–,:, :,o, :,o
Mozambique, Ioo–IoI, IIo
Mugabe, Robert, :I8–:o, ::,
multilateral institutions: China
and, ¡,– ¡8, ,o–,I, I,,, I,,, :I,,
:,o, :,I; drug control and, I,,;
soft power and, o, Io; US neglect
of, ,,, ,I, I,,, I,I, :I,, :,,–¡o. See
also international organizations
multinational companies, Ioo, :o¡
music, I,I; American, I,8, I,,, I8¡,
::,; Chinese, II,, I:o
Muslims, ¡, I,o, I,¡ –,,, I,8; Chi-
nese abuses of, :o, II,, I:o; de-
sire for democratic freedoms by,
:,o; Indonesia and, I::, :I,; US
policies toward, ,I, I:I, :,o; US
public diplomacy failures and,
I8,, I,o, :II
Myers, Richard B., :oo
Nanjing massacre, :oo
National Awakening Party
(Indonesia), I:¡
National Bureau of Asian
Research, I,I
National Defense University, oo, ,8
National Development and Re-
form Commission, ,o
nationalism, Chinese, I,, I,,
::–:,, ,o
National People’s Congress
(China), o,
National Security Council (US),
,¡ –,,
National Security Strategy (US), :I,
National University of Singapore, ,,
NATO, :o–:,
Nazarbayev, Nursultan, :I:
Neighbors, Lloyd, I,,
neoconservatives, ¡¡
neoliberal economics model, I8I,
I8o–8,
Nepal, ¡,
New People’s Army (Philippines),
::¡ –:,
new pragmatism. See pragmatism
new security concept, ¡,– ¡8
newspapers, :¡, o,, IIo
,oo Index
Niger, I,I
Nigeria, ,I, ,:, Io¡, II,, I,,, Io,, :II
Nit Pibulsongkram, I:,
Nobel Peace Prize, Io,
Nokia, II8
nongovernmental organizations,
I,,, :,8
noninterference/nonintervention,
,,–,8, ¡I–¡:, ¡¡ –¡,, ¡,, ,o, I:,,
I,o, I,:, I,o, I,,, :,o; vs. Ameri-
can initiatives, I,,, :II, ::,; ap-
peal of, ::,; authoritarian gov-
ernments and, I,,, :I8–::
North Korea, ,,, ,,, I,,, I¡o, I,I, I,:,
:o,, ::,, :¡:; Chinese six-party
talks mediation and, I,,–,,
Northrail project, 8,–8,
nuclear weapons, ¡8, :,¡; Iran and,
::o, ::I, ::¡; North Korea and,
I,,–,,, I,:, :¡:; US treaty with-
drawal and, I,I
Nye, Joseph, ,–,, ::o–:,
Obiang Nguema Mbasogo,
Teodoro, :I:
oil, ,, ::, ,,, ¡I, ,¡, III, I¡o, :o,,
:¡:; Angola and, I,,, I,¡; Cen-
tral Asia and, I,8, :oI; Chinese
need for, ¡o, ,o–,:, I,8–,,,
Ioo, :I8, ::o, ::I, ::¡; Chinese-
US clash over, :o8–I,; Nigeria
and, Io,, :II; Sudan and, ::I–::,
::¡; Venezuela and, ,o–,I,
:o,–Io
Oman, I¡, I,8
O’Neill, Paul, I8,
Ong Hok Ham, :,I
opium poppies, I,o
Opium Wars, I,
Oresman, Matthew, :oo
Organization of American States,
,I, I¡:
Overmyer, Phillip, :,:
overseas Chinese. See diaspora
Chinese
Overseas Chinese Affairs Office,
,o, ,,
Pacific Islands, ,8, I,o, ::¡
Pakistan, 8,, ,I, ,o, I,8, I8o, I,8
Palanca, Ellen, I¡,
Panama, ,,, ,8, I¡:– ¡,, I¡,, :o,
Paris, Chinese tourists in, Io,
patriotism, Chinese, :,
“Peaceful Development” policy,
,,–,8, ¡:, ¡¡ –¡,, ¡,, o:, I,,–,¡
peacekeeping, I,,, I8I, :oI–:
Pei, Minxin, :,, ,o, Ioo, Io,
People’s Daily, :¡, o,, ::I
Peru, ,,, ,o, ,I, Io8–,o
Peters, Heather, I,,–oo
PetroChina, ,I
PetroKazakhstan, ,I
Petroleos de Venezuela, ,o–,I
Philippines, 8, 8:–8,, ,o; Chinese
interests in, ¡,, ,,, 8,–8,, 8o, 88,
II:, I:o, I,I, IoI, I,I, :I,; Chinese
threats to, ,,, ::¡ –:,, :,I; Chi-
nese vs. US policies in, ,,–,o,
,8; diaspora Chinese in, ,, ,I–
,,, ,,–,8; Taiwan and, I¡¡, I¡,;
US defense and, I,8
Phnom Penh, I8,–,o; anti-Thai
mob crisis in, I,,–,o
Pluspetrol, ,I
political asylum, I8,, I,:
political capital, 8,, Io:–,, I,,
popular culture. See American cul-
ture; culture; media
Portman, Rob, o,
Index ,oI
Portuguese language, o,, IIo
poverty, :,, ,:, II,, I8:; Africa’s
problems with, ,,, ,,, oo,
I,,; Chinese growth out of, :o,
I,¡, Io,
Powell, Colin, ::I, :,,
pragmatism, Io, I,, I,, :,, ¡,– ¡,,
III, I:,
Prasso, Sheridan, I88
Pritchard, Charles, I,8
Program for China-Africa Coopera-
tion in Economic and Social
Development, ¡8–¡,
propaganda, oI–o:
protests, I8–I,, I,,, I¡o, I,o; anti-
American, :, I:,; anti–ethnic
Chinese, I::–:,, I:¡; antiglobal-
ization, I8,; in Cambodia, Io,;
Chinese repression and, I,:, I,¡,
:Io. See also Tiananmen Square
protests
PT Danareksa, ,:
public diplomacy: China and, I,,
I,, ,I, oI–8I, I,,; definition of,
oI; United States and, ,,, o,,
I,8–,,, I8,–8,, ::,, :,,–,8. See
also soft power
public opinion: antiglobalization,
I8I–8:, I8,; Australian shift in,
,– ¡, I,o, :I¡ –I,; on China
vs. United States, I,o–,,; on
diaspora Chinese, I:o–:8; gov-
ernments’ cultivation of, oI;
positive view of China, ,, II:,
I:,, I,:, I,o; positive view of
United States, I8. See also anti-
Americanism
Putin, Vladimir, :I:
Qaeda, Al, I8,, I,8
Radio Sawa, I8,–8¡
Ramo, Joshua Cooper, ,I, ,o
Ramos, Fidel, I¡¡
Ramos Horta, José, Io,, III
Rangoon, I¡,, :¡,–¡,
Raslan, Karim, I8o
Ratliff, William, I,¡
Ray, Charles A., I,,
Reagan, Ronald, I,,
Red Guards, I,, I,
Reeves, Eric, :::
regional organizations, I¡, ,o, ,I,
I,,–¡o, I,¡, I,,, I,,–:oI
rencai qiang guo policy, o,
renminbi, Io,–o
Reporters Without Borders, o¡
Reuters, o,, o¡, Io,
Rice, Condoleezza, o,, I8,–8o, :I:
Roh Moo-Hyun, ,,, I,,
Roque, Harry, 8:, 8,, 8¡ –8,
Roy, Denny, ,8
Ruan Zongze, ,:
Rubin, Robert, I8I
Rumsfeld, Donald, I,8
rural areas, ¡o– ¡I, I,o–,,
Russia, II, ,8, ,I, ,8, I,,, I,o, :I:,
::,; Shanghai Cooperation Or-
ganization and, I,,, I,,, :oo
Rwandan genocide, ,,, I8o, :I,
safety standards, I,,, Io8–o,, I,o–,I
Sam Rainsy Party (Cambodia),
¡,– ¡,
sanctions, US use of, ¡¡, ¡,, ¡,, I,o,
I8o, :I¡, ::,
San Juan de Marcona (Peru), Io8–,o
Sanxia Haoren (film), I:o
SARS epidemic, Ioo
Sata, Michael, Io,
satellite technology, o,, ,,
,o: Index
Saudi Arabia, ¡I, I,8, I,,, :o8, :II
Saunders, Philip, oo
Sautman, Barry, Io¡, I,,
savings rate, Chinese vs. US, 8o
scholars, o,–,o
science, ,,, ::8
Senegal, I¡,
September II attacks, :8, ,I, ,I, I,8,
:,o; anti-Americanism and, ::,.
See also counterterrorism
Severino, Rodolfo, ,o
Shambaugh, David, ,,, I,I
Shanghai Cooperation Organiza-
tion, ,¡, I,,, I,,, :oo
Shangri-La Hotels chain, ,,
Shenzhen Special Economic Zone,
Io, ,o
Shirk, Susan, ,I, ,o
Shougang International Trade and
Engineering, Io8–,o
Sihanouk, Norodom, I,,
Sihasak Phuangketkeow, I,,
Singapore, 8, I,, ,o, 8,, ,o, :¡:;
Chinese relations with, o:, oo–
o,, I¡:, :I¡, :,I; diaspora Chinese
in, ,, ,,, ,o, ,,, :,:, :,,; students
in China, II8; Taiwan and, I¡,,
I¡¡; terrorist threat and, I8o; US
relations with, I,8, :I¡
Sinopec, :o,
Sirindhorn Center, I:o
Sirivat Voravetvuthikun, ,¡
soft power, ,–II, I,, ,o; characteris-
tics of, o; China and, o, 8–II, I,,
,o, ,,–¡o, o,, Io,, I:I, I:,, I,o–
¡o, I,,– ¡o, I,o, :oo–:oI, :o,–8,
:I:, ::o; Chinese negative use
of, I,:–,,, I,¡ –,,, IoI–,o, :I,–
:,; Chinese positive use of, I,I,
I,,, I,¡, I,,–oI, :oI–:, :o,–,;
Chinese potential dangers from,
:Io, :,o–,I; Chinese-US coop-
eration and, :¡:–¡,; Chinese vs.
US influence and, I,o, :oI, :o8–
I,; definition of, o; Japanese fail-
ure with, :o¡ –8; tools of, ,–o, ,,
8¡, ,,, Io,, I,,; United States
and, ,–8, Io, II, ,:–,,, I,o–,o;
US need for rebuilding of, :,,–
¡,; US strengths and, I,,, I,8,
I,,–,o, ::,–,o; US weaknesses
and, ,:–,,, II¡, I,o–,,
Sokhem Pech, I,:
South Africa, ,:, I¡,, I,o, :o¡, ::,
South China Sea, ,8, I,I, :,I; code
of conduct for, ¡8
Southeast Asian Nuclear Weapons
Free Zone, ¡8
South Korea, II, ,,, I,8, :¡:; anti-
Americanism and, I,:; “China
fever” and, ,,–,¡, IIo–I,, I:o,
I,:, I¡,; Chinese vs. US influ-
ence in, ,,, o8, II,, I,:, I,,;
North Korea and, I,,, I,:
Soviet Union, ,, I,o, I,,, I8:, I,,,
I,8. See also Cold War; Russia
space program, :¡
Spanish language, o,, o,
special economic zones, Io, ,o
Starobin, Paul, :I,
State Department (US), ,I, ,,, o,,
I8¡, :I,, :Io, :,,; visa policy of,
I8,, :,,
Still Life (film), I:o
Strong Nation forum, :o
students, I8, ::; in Australia, :; in
China, :,, :8–:,, o,, o,–,I, ,¡,
II,–I8; Chinese vs. US policies
and, ,I, II,; in United States,
::,; US visa restrictions and, I8,
Index ,o,
Sudan, ,¡, ,I, I¡o, I¡,; authoritar-
ian regime of, :I,–Io, :I8, ::I–
::; Chinese investments in, ,I,
Io:, Io¡, ::I–:¡, :,o
Suharto, I:I, I::, I:,–:o
Summers, Larry, I8I
Susanto, A. B., I:,–:¡, I:,, I:o
Sutter, Robert G., ,,, I,I, I,:
Sweig, Julia, :,8, :¡I
Syria, ¡,, I,¡
Taipei Economic and Cultural
Offices, I¡,
Taiwan, Io, ,o, ,:, o¡, ,o–,:, ,o, ,8;
Cambodia and, ¡,, ¡o; Chinese
moves to isolate, ¡:, I,o, I¡:– ¡,;
Chinese-US war potential over,
:I¡, :I,
Taiwan Straits, ,o
Tajikistan, I,,
Tan, Lucio, ,,, ,,–,8
Tariff Relief Assistance for Devel-
oping Economies Act (US), I8,
technology, I,, ::, ¡8, ,,, II8; Chi-
nese growth of, ,,; US leader-
ship in, ::8
technology transfer, ,:
telecommunications, ,,, 8,, ,:,
:Io, :,,
television, o,, II¡, I,I–,:, :,o;
American, I,8, ::,; Chinese-
language, II,, I:o
Teo Chu Cheo, Eric, II8
terrorism, ¡, Ioo, I,¡, :o,, :I,, :¡I;
political freedom vs., :I,–I8. See
also counterterrorism; Septem-
ber II attacks
Thailand, I¡, I¡o, :o¡, :¡:; Chinese
economic partnership with, II:,
I:o–:8, I,,; Chinese influence
in, 8, ,o, o,, o8, o,, ,o, ,I, IoI, Io,,
IIo, I:o, I:I, I,I–,:, I¡o, I,I; Chi-
nese mediation and, I,,–,,;
Chinese migrants to, Io¡, Io,;
Chinese strategic partnership
with, ¡8; Chinese tourists in, Ioo,
Io,; Chinese trade and, IoI, Io,,
:,I; Chinese vs. US relations with,
o,, :I,–I¡; diaspora Chinese in,
,,–,,, ,o, ,,, ,8–8I, Io¡, II8, I:o–
:8, :,I, :,,; drug traffic to, I,o; fi-
nancial crisis in, ,,–,,; human
rights abuses and, I,o; US rela-
tions with, I:,, I,,, I,8, ::8, :¡o
Thaksin Shinawatra, ,,, I:o, I,I–,:
think tanks, ,o, ,:, ,o, o,, I8¡ –8,
Thompson, Drew, ,,
Tiananmen Square protest, I8–I,,
::, :¡, :,, :,, ,o, ,:, o¡, ,¡, I¡o, I,,
Tibet, ,, o¡
timber, ¡o, I,:–,,, Io¡, I,I
Timor Sea, III
Tolong Menolong, I:o
Tonle Sap, I¡I
torture, ,o
tourism. See travel and tourism
trade: Australia and, ¡, :I¡; Cam-
bodia and, ¡,, I8,–,o; Central
Asia and, ,¡, :oI; Chinese
growth and, ,,, 8,, ,,–,o, IoI,
Ioo, I,,, :o,– ¡, :I,, :,,; Chi-
nese potential problems with,
:,I–,:; Chinese surpluses and,
:o, 8o, :,I–,:; Chinese unfair
competition and, IoI–o,; Saudi
Arabia and, I,,; as soft power
tool, Io, ,,; Thailand and,
I:,, I:8, IoI, Io,, :,I; Vietnam
and, ,o–,,. See also free trade;
sanctions
,o¡ Index
travel and tourism: to China, ,,,
IIo, I:,–:o; Chinese eased re-
strictions on, I,, Io,– ¡, Ioo;
Chinese outbound, :,, Ioo–,, I¡,,
I,I; US visa curbs and, I8,, :,,
“Travel to China to Find your
Roots” program, ,,
Truman, Harry, :¡o
tsunami aid, o,, ,,, I:o, :o:, ::,–:8
Tuol Sleng prison, II,
Turkey, I8o, I,¡, I,,
Tutwiler, Margaret, I8,
Twelve Angry Men (film), 8
Uighurs, :o
Ukraine, ¡¡
UNESCO, II,
unions. See labor
United Kingdom. See Britain
United Nations, ,, I,, II,, I,8, :o,;
Cambodia and, I,:; China and,
¡,, I¡o–¡,, I,¡, I,,, :oI, :o,, ::o,
:::; Commission on Africa, ,,;
drug conventions and, I,,; East
Timor trusteeship under, Io,,
IIo; Global Compact Summit,
I,o; human rights and, I¡o–¡,,
Io,, :o,; Iran and, ::o; Iraq War
and, I,¡; peacekeeping and, I,,,
I8I, :oI–:; Security Council di-
vide, I¡o; Security Council seat
bids, ,,, :o,; Sudan censure and,
::I, :::, ::,; US policies and,
I,8–,,, I,I, :,,, :¡o, :¡I
United States Agency for Interna-
tional Development, :o:
United States Information Agency,
,, ,,, I,,
United Wa State Army (Burma),
I¡8, I,o
Uniting Chinese, 8o
universities: Chinese-language and
-culture programs, o8, IIo, I:o–
:,; Chinese MBA programs, ,o;
Chinese scholarship programs,
o,–,o, II,, II8; Chinese upgrad-
ing of, o,; Indonesia and, :¡:;
US decline in foreign applicants
to, I,:; US quality of, ::,
University of Buenos Aires, IIo
Unocal, Ioo
urbanite elites, I,, :,, :,
urban migration, ¡o– ¡I
US-Asean Business Council, ,:
U.S.-China Engagement Act, :,,–,¡
Uzbekistan, ,¡, o8, I,8, I,,; Andi-
jan massacre and, :oo; anti-
Americanism in, I,,; authori-
tarian regime of, :I,–Io;
Chinese wooing of, ,–Io, ,¡, ,8,
I,,, :oo, :I,
Venezuela, ,, :II; Chinese vs.
American values and, ::,; Chi-
nese wooing of, ¡¡, ¡8, ,,, I,:,
:o,–Io, ::,, ::¡; oil interests in,
,o–,I
vertical integration, :o,
Vietnam, 8, ,, I¡, ,,, Io¡, I:,, I,o,
:,,; Chinese development
model and, I,,; Chinese rela-
tions with, ¡8, ,I, II,, II,, IoI,
Io,, :,o, :,I; Clinton’s reception
in, I,,; human trafficking and,
I,,–oo; US superpower status
and, ::8; US trade relations
with, ,o–,,
Vietnam War, ,,, ,o, ::o–:,, :,,
Vikrom Kromadit, ,o
visa restrictions, I8,, :,,
Index ,o,
Voice of America, ,, I8, I8,, :,,, :,o
“Voyage of Chinese Culture to
Africa” tour, o:
Wal-Mart, 8o
Wang Guangya, :::
Wang Jisi, ,:–,,
Wang Yi, I,,
war crimes, :oo
war on terrorism. See counter-
terrorism
Washington Consensus, I,¡, ::,
Watson, Cynthia, I8I
Wei, Lin Che, ,:
Wen Jiabao, ::, ,8, ¡I, ¡¡, ¡,, ,8,
I,:, :o,
Wenzhou, :o
white-collar crime, Io,
Wibowo, I., I,,
“win-win” relations, ¡,– ¡,, 8,,
:,o, :,I
Wolfowitz, Paul, I,I
Wong, James, I¡:
World Bank, ,,, I,,, I8,, :o:, :¡o;
aid model, I,I–,:, I,,
World Chinese Entrepreneurs
Convention, ,,
World Economic Forum, o,, I:o
World Health Organization, I¡I,
Io¡, ::I
World Tourism Organization, Ioo
World Trade Organization, IoI, I8,,
I88, :¡o
World War II, :, ,,, :o,, :oo–,;
American soft power following,
,, II¡, I,I, I,8, :¡o
Wu Yi, ,o
Wuzhishan LS, Io,
Xia Liping, ¡,
Xiamen Special Economic Zone, ,o
Ximenes Belo, Carlos Filipe, Io,
Xinhua, o,–o¡, oo, I,,
Xinjiang Province, :I, II,, I:o
Xu Zu-yuan, o:
Yangtze River, Io¡
Yasukuni Shrine, :oo–,
Yemen, I¡
Yep, Henry, ,8
Yudhoyono, Susilo Bambang,
::,–:8
Yunnan Province, Io:, I¡I
Zambia, I¡o, Io,, I,o–,I
Zaw (pseudonym), :¡,–¡o
Zeng Qinghong, ¡8
Zhang Xizhen, ,:
Zhao Ziyang, I8, I,, o¡
Zheng Bijian, ,,–,8
Zheng He (Cheng Ho), o:
Zhou Wenzhong, :::
Zhu Rongii, ,o, I,¡
Zimbabwe, ¡:, I¡,, :I8–:o, :::–
:¡, :,o
Zoellick, Robert, I,,, :,,
,oo Index
|
https://www.scribd.com/doc/185644254/1-Charm-Offesive
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Working with Maps on iOS 10 with MapKit and the MKMapView Class
In the preceding chapters we spent some time looking at handling raw geographical location information in the form of longitude, latitude and altitude data. The next step is to learn about the presentation of location information to the user in the form of maps and satellite images. The goal of this chapter, therefore, is.. This class is a subclass of UIView and provides a canvas onto which map and satellite information may be presented to the user. Information may be presented in map, satellite or hybrid (whereby the map is superimposed onto the satellite image) form. The displayed geographical region may be changed manually by the user via a process of pinching stretching and panning gestures, or programmatically from within the application code via method calls and property manipulation on the MkMapView instance. The current location of the device may also be displayed and tracked on the map view.
The MapKit Framework also includes support for adding annotations to a map. This takes the form of a pin or custom image, title and subview that may be used to mark specific locations on a map. Alternatively the annotation can take the form of a custom view controller.
Implementation of the MKMapViewDelegate protocol allows an application to receive notifications of events relating to the map view such as a change in either the location of the user or region of the map displayed or the failure of the device to identify the user’s current location or to download map data.
Understanding Map Regions
The area of the map that is currently displayed to the user is referred to as the region. This is defined in terms of a center location (declared by longitude and latitude) and span of the surrounding area to be displayed. Adjusting the span has the effect of zooming in and out of the map relative to the specified center location. The region’s span may be specified using either distance (in meters) or coordinate based degrees. When using degrees, one degree of latitude is equivalent to 111 km. Latitude, however, varies depending on the longitudinal distance from the equator. Given this complexity, the map view tutorial in this chapter will declare the span in terms of distance.
Getting Transit ETA Information
A MapKit feature that was introduced in iOS 9 allows the departure and arrival times and estimated travel duration to a destination using public transit to be obtained from within an iOS app. This involves the use of an MKDirectionsRequest object configured for travel by transit and initialized with start and end locations combined with a call to the calculateETA(completionHandler:) method of an appropriately configured MKDirections instance. The following method, for example, outputs the estimated arrival time for a journey by transit from the Empire State Building in New York to JFK Airport:
func getTransitETA() { let request = MKDirectionsRequest() let source = MKMapItem(placemark: MKPlacemark(coordinate:CLLocationCoordinate2D(latitude: 40.748384, longitude: -73.985479), addressDictionary: nil)) source.name = "Empire State Building" request.source = source let destination = MKMapItem(placemark: MKPlacemark(coordinate:CLLocationCoordinate2D(latitude: 40.643351, longitude: -73.788969), addressDictionary: nil)) destination.name = "JFK Airport" request.destination = destination request.transportType = MKDirectionsTransportType.transit let directions = MKDirections(request: request) directions.calculateETA { (response, error) -> Void in if error == nil { if let estimate = response { print("Travel time \(estimate.expectedTravelTime / 60)") print("Departing at \(estimate.expectedDepartureDate)") print("Arriving at \(estimate.expectedArrivalDate)") } } } }
About the MKMapView TutorialThe objective of this tutorial is to develop an iOS application designed to display a map with a marker indicating the user’s current location. Buttons located in a navigation bar are provided to allow the user to zoom in on the current location and to toggle between map and satellite views. Through the implementation of the MKMapViewDelegate protocol the map will update as the user’s location changes so that the current location marker is always the center point of the displayed map region.
Creating the Map Project
Begin by launching Xcode and creating a new iOS project named MapSample using the Single View Application template configured with the Universal device option and the Swift programming language.
Later stages of this tutorial will require the services of a navigation controller. Since the presence of the navigation bar will have implications for the layout of the user interface of the main view, it makes 79-1:
Figure 79 Kit 79-2
Select the MKMapView object in the scene and use the Auto Layout Add New Constraints menu located in the lower right-hand corner of the Interface Builder panel to configure Spacing to nearest neighbor constraints of 0 on all four sides of the view with the Constrain to margins option switched off. Once the four constraints have been added to the MKMapView object, repeat these steps with the Toolbar view selected.
Select the MKMapView object in the view canvas, display the Assistant Editor panel and verify that the editor is displaying the contents of the ViewController.swift file. Ctrl-click on the MKMapView object and drag to a position just below the class declaration line in the Assistant Editor. Release the line and in the resulting connection dialog establish an outlet connection named mapView.
Click on the “Zoom” button to select it (note that in order to select a toolbar button item it may be necessary to click on it twice since the first click selects the toolbar parent). With the button item selected, Ctrl-click on the button object and drag the line to the area immediately beneath the viewDidLoad method in the Assistant Editor panel. Release the line and, within the resulting connection dialog, establish an Action method on the Touch Up Inside event configured to call a method named zoomIn. Repeat this step to connect the “Type” button to a method named changeMapType.Select the ViewController.swift file from the project navigator panel and verify that the outlets and actions have been set up correctly. Also take this opportunity to import the MapKit framework and to declare the class as implementing the MKMapViewDelegate protocol:
import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() } @IBAction func zoomIn(_ sender: AnyObject) { } @IBAction func changeMapType(_ sender: AnyObject) { } . . . }
Perform a test run of the application’s progress so far by clicking on the run button in the Xcode toolbar. The application should run on the iOS simulator or device as illustrated in Figure 79-3:
Figure 79-3
Obtaining Location Information Permission
The next task is to request permission from the user to track the current location of the device. Since this needs to occur when the application loads, an ideal location is in the application delegate didFinishLaunchingWithOptions method in the AppDelegate.swift file:
import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var locationManager: CLLocationManager? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { locationManager = CLLocationManager() locationManager?.requestWhenInUseAuthorization() return true } . . }
Setting up the Usage Description Key
The above code changes included a method call to request permission from the user to track location information when the application is running in the foreground. This method call must be accompanied by a usage description string which needs to be added to the project’s Info.plist file assigned to the NSLocationWhenInUseUsageDescription key. Within the project navigator panel, load the Info.plist file into the editor. The key-value pair needs to be added to the Information Property List dictionary. Select this entry in the list and click on the + button to add a new entry to the dictionary and, from the resulting menu, select the Privacy – Location When in Use Usage Description item. Once the key has been added, double-click in the corresponding value column and enter the following text:
This information is required to show your current location
Configuring the Map View
By default the Map View does not indicate the user’s current location. By setting the showsUserLocation property of the MKMapView class the map is instructed to display a representation of the current location on the map in the form of a blue marker. Before user location information can be obtained, however, it is first necessary to seek permission from the user. In order to achieve these goals, select the ViewController.swift file and locate and modify the viewDidLoad method as follows:
override func viewDidLoad() { super.viewDidLoad() mapView.showsUserLocation = true }
Changing the MapView Region
When the Zoom button is tapped by the user the map view region needs to be changed so that the user’s current location is set as the center location and the region span needs to be changed to 2000 meters (analogous to zooming in to the map region). The code to implement this belongs in the zoomIn method which now needs to be implemented in the ViewController.swift file:
@IBAction func zoomIn(_ sender: AnyObject) { let userLocation = mapView.userLocation let region = MKCoordinateRegionMakeWithDistance( userLocation.location!.coordinate, 2000, 2000) mapView.setRegion(region, animated: true) }
This method performs some very simple operations in order to achieve the desired effect in the mapView object. First, the user’s current location is ascertained by accessing the userLocation property of the map view object. This is stored in the form of an MKUserLocation object which, in turn, contains the coordinates of the user. Next, the MKCoordinateRegionMakeWithDistance function is called in order to generate an MKCoordinateRegion object consisting of the user’s location coordinates and a span that stretches 2000 meters both to the North and South of the current location. Finally, this region object is passed through to the setRegion method of the mapView object.
Now that the Zoom functionality has been implemented it is time to configure the map type switching feature of the application.
Changing the Map Type
The map type of a map view is controlled by the object’s mapType property. Supported values for this property are MKMapType.standard, MKMapType.satellite MKMapType.hybrid, MKMapType.satelliteFlyover and MKMapType.hybridFlyover. For the purposes of this example application the map will switch between standard and satellite modes. Within the ViewController.swift file modify the changeMapType action method connected to the Type button as follows:
@IBAction func changeMapType(_ sender: AnyObject) { if mapView.mapType == MKMapType.standard { mapView.mapType = MKMapType.satellite } else { mapView.mapType = MKMapType.standard } }
This very simple method simply toggles between the two map types when the button is tapped by the user.
Testing 79-4
To get real location information, load the application onto a physical iOS device.).
In order to configure the application so that the map automatically tracks the movements of the user, the first step is to make sure the application is notified when the location changes. At the start of this tutorial the view controller was declared as conforming to the MKMapViewDelegate delegate protocol. One of the methods that comprise this protocol is the mapView(didUpdate userLocation:) method. When implemented, this method is called by the map view object whenever the location of the device changes. We must, therefore, first specify that the MapSampleViewController class is the delegate for the mapView object, which can be performed by adding the following line to the viewDidLoad method located in the ViewController.swift file:
mapView.delegate = self
The next task involves the implementation of the mapView(didUpdate userLocation:) method in the ViewController.swift file:
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { mapView.centerCoordinate = userLocation.location!.coordinate }
The delegate method is passed as an argument an MKUserLocation object containing the current location coordinates of the user. This value is simply assigned to the center coordinate property of the mapView object such that the current location remains at the center of the region. When the application is now installed and run on a device the current location will no longer move outside the displayed region as the device location changes. To experience this effect within the simulator, simply select the Debug -> Location -> Freeway Drive menu option and then select the Zoom button in the user interface.
Summary
This chapter has demonstrated the basics of using the MKMapView class to display map based information to the user within an iOS 10.
|
http://www.techotopia.com/index.php/Working_with_Maps_on_iOS_8_with_Swift,_MapKit_and_the_MKMapView_Class
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
C#, or C Sharp was built to be used with the .NET Microsoft framework. C Sharp is mainly used for developing applications for Windows, for web development and for networking. C# is a fully object oriented language – it supports polymorphism, data abstraction, data encapsulation and inheritance. The character “#” comes from the musical key “sharp”, which corresponds to an increase in the pitch in music. Similarly, the language C# was designed to address the shortcomings of C and C++ and provide an improved, updated language to the programmer. C# has an improved garbage collector which the available memory automatically, without the developer having to worry about it. C# also is much more stable than C and C++, and you don’t have to type as much code to perform programming tasks. C# is also a platform-independent language, in the mold of Java. This means that you can run a C# program on any machine, regardless of the architecture present (as long as the .NET framework has been installed). Learn more about how C# works with the .NET framework with this course.
We’re going to take a look at the C# partial class in this tutorial. You need to be familiar with the basics of the language (the structure and syntax of the program) to understand the tutorial. Microsoft and other developers have invested a lot of effort into it. Chances are, it will become one of the most popular programming languages in the future. It’s definitely worth your while to learn it. You can sign up for our simple, easy-to-understand C# course for complete beginners. We’ll teach you everything you need to know about the language- you’ll be writing your own programs in no time. You’ll find it easier to learn the language if you have some knowledge of C, C++ and Java. Those pressed for time, can instead take this primer to learn C# in just 1 hour.
What is a C# Partial Class?
A partial class is a class that has been separated into parts. If you use the partial keyword when you’re declaring a class, your class may be split into separate files. You can provide separate methods for the different parts of your class.
Why do you need a partial class? In C#, a single project cannot have two separate classes. But sometimes you do need two classes for it – if the code is bloating the class, for example. In this case, you can use the partial modifier to divide the class. In applications that use partial classes, you will find that one of the partial classes contains code that has to be edited frequently while the other partial class will be rarely edited or contain machine-generated code that isn’t understandable to the user. Sometimes several developers need to work on a single project. In this case, it’s easier to make several partial classes with separate code. This code is then gathered together during runtime and executed as a single unit.
Example of a C# Partial Class
Let’s write a simple program that demonstrates the concept of a C# partial class.
class Employee { static void Main() { E.E1(); E.E2(); } } //part 1 of the partial class using System; partial class E { public static void E1() { Console.WriteLine("This is Employee Number 1"); } } //part 2 of the partial class using System; partial class E { public static void E2() { Console.WriteLine("This is Employee Number 2"); } } Output: This is Employee Number 1 This is Employee Number 2
First, we created a class called Employee. In the main method of the program, we declared two files, which were a part of E: E1 and E2. E can then be declared as a partial class. In the 1st part of the partial class declaration, we printed “This is Employee Number 1” to the screen using the Console.WriteLine method. In the 2nd part of the partial class declaration, we printed “This is Employee Number 2” using the same method. Simply put, all we’ve done is divide a single class into two separate files. The 1st file will be saved as E1.cs, while the 2nd file will be saved as E2.cs in the system. The “partial” keyword must be included in the declaration, of course. You will encounter an error without it. The name of every section of a class that you make partial has to be the same (during declaration). The name of the source file for every section of the partial class, however, can be different. Also, it’s required that you keep all parts of the partial class in the same namespace.
For additional resources on this topic, you can check out the official Microsoft documentation. Alternatively, you can just sign up for our C# sharp course – we cover all the aspects of C# in 10 easy steps.
Keep in mind that partial classes have the same accessibility – if you declare one of them public, all of them must be public. Also, if a partial class inherits an interface, all of the other partial classes inherit it too.
During Compile Time
What happens to the partial classes at compile time? The partial classes will be merged into a single class. The files E1.cs and E2.cs will be merged into a single file for class E. The methods found in class E1 and class E2 will be merged into a single code block, while the two partial classes will be merged into class E. It will look like this:
internal class E { public static void E1() { Console.WriteLine(“This is Employee Number 1”); } public static void E2() { Console.WriteLine(“This is Employee Number 2”); } }
As you can see, the two classes have been merged into a single internal class E. The methods of those two classes are also placed inside the same class and are executed simultaneously.
Benefits of Using a Partial Class
So what are the benefits of using a partial class? Let’s take a look at some of them:
- Several developers can work on a project simultaneously if they work with partial classes. This is, perhaps, the biggest benefit of using a partial class. Large projects that require many developers can be finished faster and with less effort because of this.
- Large, bloated classes can be made smaller by making them partial. This allows you to make a program that is easier to understand and maintain. It also allows you to divide code into understandable sections, or separate machine level code from normal code, or to separate code that you regularly edit with code you don’t edit at all. For example, when Windows Forms programs are created in Visual Studio, the machine generated code is categorized separately from the normal code.
- It’s easier to categorize code with partial classes. You can separate business logic from design logic, for example- which is often done in Visual Studio. Developers with experience in different aspects and applications of C# sharp can work on separate parts of the same project because of this.
- Another major advantage of partial classes is that it’s easier to add new code without editing the original source file. Just declare a new partial class and you’re done.
Learning to use partial classes will help you develop efficient and easy to maintain applications. Once you’re comfortable with the basics, you can even learn how to build Android applications using C# with this special course!
|
https://blog.udemy.com/c-sharp-partial-classes/
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
11 November 2011 11:42 [Source: ICIS news]
BUCHAREST (ICIS)--Rompetrol’s petrochemicals business reported a net loss of $2.53m (€1.87m) for the first nine months of 2011, compared with a net loss of $454,460 in the same period last year, the company said on Friday.
Rompetrol Petrochemicals attributed its results to operating lower capacity rates and “to the bad economic context following the military conflict in ?xml:namespace>
The company’s turnover increased by 36% year on year to $292m.
In the first nine months, Rompetrol Petrochemicals processed 57% more ethylene year on year. It processed 4% more propylene compared with the corresponding period last year, the company said.
The company is investing $18m to raise the capacity of its high density polyethylene (HDPE) plant at Navodari in eastern
The company also has a 60,000 tonne/year low density polyethylene (LDPE) plant at Navodari.
Rompetrol Petrochemicals is part of oil refiner Rompetrol Group, which is owned by Kazakhstan's KazMunaiGaz (KM
|
http://www.icis.com/Articles/2011/11/11/9507380/romanias-rompetrol-petrochemicals-reports-net-loss-of-2.53m.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
29 May 2012 09:29 [Source: ICIS news]
SINGAPORE (ICIS)--Germany's Brenntag said on Tuesday it has been distributing Evonik’s household care products in ?xml:namespace>
The distribution deal between the two German firms covers the full product portfolio of Evonik’s consumer specialties business unit, Brenntag said in a statement.
Financial details of the deal were not disclosed.
Under its consumer specialties unit, Evonik produces and supply raw materials and additives to the household, detergent, car care, as well as the industrial and institutional
|
http://www.icis.com/Articles/2012/05/29/9564756/brenntag-distributes-evonik-household-care-products-in-switzerland.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
This is the second article in a series describing my experience exploring the new realm of cloud development. It's predicted that within just a couple of years, over a third of all development will be cloud based. So it makes sense that we should become familiar with that environment if we don't want to be left behind. My approach to learning new technologies is to envision their application. Specifically, I try to look at how they might be applied to solving business problems. I think there is a tremendous number of opportunities for business ventures utilizing the cloud. For the sake of providing some concrete examples and to provide some focus to the discussion, I've decided to make Bing Maps services a central theme of the business scenarios discussed in these articles. And to make things a little more interesting, I'm really focusing on business scenarios that would make use of Bing Maps services and phone as part of the solution. The reason being that, in my opinion, phone will be a major player in business solutions developed for the cloud.
The previous article provided information on getting started with Bing Maps services as well as setting up the application structure that we wanted to follow. In this article, we get down to the nitty-gritty and demonstrate how we can add functionality to the basic map control. At the same time, we discuss some typical business scenarios that could benefit from the functionality being presented.
Let's start by first changing the current solution so that it is hosted on Azure. You'll need to download and install the Windows Azure SDK if you have not done it already. You can find everything you need for Azure here. Once you've installed the SDK, you'll have access to a new 'cloud' project template in Visual Studio. On the Solution Explorer tab, right click to add a new project. And on the new project dialog, select 'cloud' and name it "SLAzureMapTest". Then in the subsequent role selection dialog, simply click OK without selecting any roles. This will create the project without any roles and we can use the existing Web project.
You'll see the newly created project in Solution Explorer but with an empty Role folder. Right click on the folder to add a new role, as shown below:
In the subsequent dialog, you should see the existing SLMapTest.Web project, so select it to make the association. That is all that's needed to take an existing Web project and modify it for hosting on Azure.
If you re-compile and try to run the application, you'll get a message that says that you need to start Visual Studio as Administrator in order to run the application. So from now on, always start Visual Studio as Administrator for this project.
I've made some minor structural changes to the project which we started in the previous article. Nothing major, just factored out the map view which we had on the main page into a separate control. This means that there are also new entries for the View:ViewModel association. But that's all the change that I've made. In the download, I've included a revised version which you can use as the starting point if you want to follow along with the code or see the revised code.
OK, so let's start by adding some user interaction with the map. The first thing we'll do is allow the user to click on the map and we'll provide some feedback in the form of data associated with the clicked location. The map services can only relate to geo coordinates (latitude/longitude), but our view mouse clicks are in screen coordinates, so we have to translate between the two. Luckily for us, the map control exposes a method that provides just that translation!
Start by creating a mouse click event handler in the code-behind. Since we have to have access to the map control for the translation and we are going to be doing some UI rendering, it fits there.
So, to be able to draw on the map, we make use of MapLayers. These are types exposed by the map control, and are essentially overlays on the map. We'll start with an overlay to identify where the user clicked, and we'll add additional layers later to segregate different types of information on the display. Here's the change for the XAML file that shows the SelectionLayer.
MapLayer
SelectionLayer
...
<m:Map x:
<m:MapLayer x:
...
And the change to the code-behind file for the click event handler is as follows:
public SLMapView()
{
InitializeComponent();
//An event handler for the mouse clicks...
bingMap.MouseClick +=
new EventHandler<MapMouseEventArgs>(bingMap_MouseClick);
//Subscribe to message, we know what to do with user input
Messenger.Default.Register<SetMapViewMsg>(this, SetViewHandler);
}
void bingMap_MouseClick(object sender, MapMouseEventArgs e)
{
Location pointLocation =
bingMap.ViewportPointToLocation(e.ViewportPoint);
Rectangle r = new Rectangle();
r.Fill = new SolidColorBrush(Colors.Red);
r.Stroke = new SolidColorBrush(Colors.Yellow);
r.StrokeThickness = 1;
r.Width = 8;
r.Height = 8;
SelectionLayer.Children.Clear();
SelectionLayer.AddChild(r, pointLocation);
//Pass the translated point to request reverse geocoding
Messenger.Default.Send<MapPointClickMsg>(
new MapPointClickMsg() { ClickLocation = pointLocation });
}
You can add UI elements to the MapLayer just like any other rendering surface. If you compile and run, you'll see the results below. You'll note that the user can scroll the view and change zoom levels and the selected location remains displayed correctly. Of course, you can change the rendering to be whatever is appropriate. How about a push-pin? And of course, it doesn't have to be as a result of a click. You may have a collection of items that you want to display at known locations. The point is that you can draw anything on the map and associate it with a physical location.
The code above provides a hint as to what we want to do next. In the event handler, we are sending a message (to whomever subscribed, nobody yet) and passing the geo coordinates of the clicked location. What we want to do next is display the street address that corresponds to the location that the user clicked, if one exists. Of course, we have to determine what that address is. But before we embark on that, let's add an important feedback feature to the user interface.
When dealing with network communication, there is one thing that is guaranteed, and that is that the response time is unpredictable. In our application, we are making asynchronous calls to services which will undoubtedly have varying response times due to various network issues. In order to control the state of the application and also to provide feedback to the user, we need to provide some indication to the user that some lengthy activity is taking place. In searching to see what might be available, I came across this control which David Poll developed and has shared with the community. The control behaves as an activity indicator for an application. It is very flexible and pretty intuitive to use. You can download the source and all related information from here. To use it, simply wrap the desired UI area with the control and then just toggle a flag to display/hide the busy indicator and enable/disable user interaction. In the code shown below, the whole MainPage is wrapped with the control.
...
xmlns:activity="clr-namespace:System.Windows.Controls;assembly=ActivityControl"
xmlns:ctl="clr-namespace:SLMapTest.View"
mc:
Now anytime we are making a call to the service, we set the flag to show that we are busy, and clear the flag when a response is received from the service.
OK, so now, let's show some information to the user associated with the location of the click. The information will be the address closest to the clicked location. To do that, we'll need to add some fields to the view to display the address. The revised MainPage showing the resulting functionality is shown below:
So in the click message handler shown previously, we are sending out a message containing the coordinates of the clicked location. But there is no one listening, so let's add a listener. SLMapViewModel is the one that knows how to call the Bing service so that's where we will add a subscription to the message. When we get the results back, we'll publish a corresponding message with the results. And since we are binding the controls on the MainPage to the MainViewModel, that's where we will add the subscription to the response message. So let's start with the call to the service as a response to MapPointClickMsg. First, we register for the message and provide a handler:
SLMapViewModel
MainViewModel
MapPointClickMsg
public SLMapViewModel()
{
...
//Register to receive message when user clicks on the map
Messenger.Default.Register<MapPointClickMsg>(this, MapClickHandler);
}
void MapClickHandler(MapPointClickMsg msgData)
{
ReverseGeocode(msgData.ClickLocation);
}
The Bing Maps service that we used last time exposes an additional method that provides the reverse to the geocode method. It is appropriately called ReverseGeocodeAsync, and it returns an address (if one exists) for a given location coordinate. So it does the exact opposite of what we did previously. Again, as before, since it's an asynchronous call, we need to provide a callback handler where we can process the results of the call. Here's the rest of the code along with a definition of a message used to publish the result from the call:
ReverseGeocodeAsync
private void ReverseGeocode(Location pointLocation)
{
//Pack up a request
BingGeocodeService.ReverseGeocodeRequest request =
new BingGeocodeService.ReverseGeocodeRequest();
// Don't raise exceptions.
request.ExecutionOptions = new BingGeocodeService.ExecutionOptions();
request.ExecutionOptions.SuppressFaults = true;
request.Location = pointLocation;
request.Credentials = new Credentials();
request.Credentials.ApplicationId =
(string)App.Current.Resources["BingCredentialsKey"];
// Make asynchronous call to fetch the data
GeocodeClient.ReverseGeocodeAsync(request);
}
void geocodeClient_ReverseGeocodeCompleted(object sender,
BingGeocodeService.ReverseGeocodeCompletedEventArgs e)
{
string callResult = "";
try
{
if (e.Result.ResponseSummary.StatusCode !=
BingGeocodeService.ResponseStatusCode.Success ||
e.Result.Results.Count == 0)
{
callResult = "Can't find it!";
}
else
{
//Publish results, somebody will know what to do with it
ReverseGeocodeResultMsg resultMsg = new ReverseGeocodeResultMsg()
{
StreetAddress = e.Result.Results[0].Address.AddressLine,
City = e.Result.Results[0].Address.Locality,
State = e.Result.Results[0].Address.AdminDistrict
};
Messenger.Default.Send<ReverseGeocodeResultMsg>(resultMsg);
}
}
catch
{
callResult = "Error processing request.";
}
resultString = callResult;
this.RaisePropertyChanged("ResultString");
}
public struct ReverseGeocodeResultMsg
{
public string StreetAddress;
public string City;
public string State;
}
Now in the MainViewModel, we subscribe to the ReverseGeocodeResultMsg message so we can update the display with the data that was returned from the call to the service.
ReverseGeocodeResultMsg
public MainViewModel()
{
Messenger.Default.Register<ReverseGeocodeResultMsg>(
this, ReverseGeocodeMessageHandler);
}
#region messenger message handler
void ReverseGeocodeMessageHandler(ReverseGeocodeResultMsg msgData)
{
currentSelection = msgData;
this.RaisePropertyChanged("Address");
this.RaisePropertyChanged("City");
this.RaisePropertyChanged("State");
}
#endregion
And that's it. If you compile and run the application, you'll see the results shown above. I've included a second project in the download that contains all the source for this version. Still, nothing terribly impressive so far. But we already know how to process user interaction with the map, we can translate a user mouse click position to latitude/longitude coordinates, we can render figures on the map at specific latitude/longitude coordinates, and now we can retrieve address information associated with these coordinates. So that's already quite a bit of functionality. However, the really interesting aspects (at least for me) come when you create a unique solution to a common business problem. Let's continue by taking the core functionality we've learned and add some additional functionality that could then be applied to real world business scenarios.
I think there are numerous opportunities for cloud based solutions that can benefit from the functionality we've been describing. One such category of businesses centers around product distribution. The milk that gets delivered to your corner grocery store or convenience store is delivered by a company in this category. The magazines and candy at the checkout aisles are typically managed by outside companies that service the racks. The soda machines that you see around campus, at the rest areas, and many other locations, are serviced by companies in this category. You'll often see Pepsi or Budweiser trucks parked at a store, they are making their delivery rounds. I can continue, but you can see that there are plenty of examples of these types of businesses. All of these companies have processes that are similar in nature. For one thing, they all have one or more products that are being delivered to locations. The delivery is being made by a driver that normally follows a specific route on a periodic schedule. The stops (locations) on the route are arranged in order to minimize the time required to complete the deliveries.
Now, it goes without saying that simply providing driving directions does not make a business solution. Any solution needs to encompass more of the business processes in order to provide a benefit to the business enterprise. And that benefit is usually in the form of cost reductions, it's always about the bottom line. If a solution can make the business more profitable by optimizing their operations and reducing their cost (less wrong deliveries, less product damage, etc.), you've got a sale. And I'll add that using phone as part of the solution facilitates a whole new world of cost reducing opportunities.
So one component of any solution targeted at these business entities has to include a route editor. A utility that will allow the business the ability to define their area of service. A route is the path that a particular driver will traverse to deliver a product. A route, in turn, is a collection of one or more route segments. And a route segment is a continuous stretch of the same road or street. When you get back driving directions from Bing, it is in the form of a bunch of route segments. However, those segments have finer granularity because they are used as driving instructions to humans. For our consideration, we won't require as much detail.
As we said above, one requirement that is common for all of these applications is to allow the business entity to define a set of routes that comprises the territory of service. And that's what we want to accomplish now. First, we'll create an entity definition for a route segment. Then we'll provide the user interface to allow the user to define new segments that form a route. We'll add route management later.
The following screen shows the user interface as modified for our demo project. You can see the complete source code for the project in the final version of the project included in the download.
So we want to be able to provide the user with the ability to define a route which is a collection of route segments. And a route segment is simply a contiguous portion of a street or road. We define a route segment to have the following properties:
public class RouteSegment
{
public int ID { get { return id; } }
public int RouteID { get; set; }
public string StreetName { get; set; }
public int StartNumber { get; set; }
public int EndNumber { get; set; }
public Location StartXStreet { get; set; }
public Location EndXStreet { get; set; }
public List<Location> PlotPoints { get { return plotPoints; } }
List<Location> plotPoints;
int id;
public RouteSegment(int id)
{
this.id = id;
plotPoints = new List<Location>();
}
public override string ToString()
{
return StreetName + "(" + StartNumber + "-" + EndNumber + ")";
}
}
In our demo project (shown above), the user can define segments simply by selecting a street on the map which specifies the segment (name). Then the 'boundaries' of the segment are specified by selecting the start and end intersecting streets. We've seen how to get the coordinates of addresses by using the GeocodeAsync method of the map service. To get the coordinates of an intersection, all that is needed is to adjust the format of the query that we present to the map service. In place of the street address, we'll pass in the names of the intersecting streets. For example, "38th St & Hudson Ave" will return the coordinates for the intersection of 38th Street and Hudson Avenue. Here's how we handle the user pressing the StartX button to set the current selection as the start intersection.
GeocodeAsync
StartX
void SetStartXStreetClick()
{
//Cross street name can't be same as segment street
string streetName = GetCurrentSelectionStreet();
if (streetName != currentSegment.StreetName)
{
//Get intersection, if exists
Messenger.Default.Send<GetStreetIntersectionMsg>(
new GetStreetIntersectionMsg()
{
SegmentStreet = currentSegment.StreetName,
XStreetName = streetName,
XCity = currentSelection.City,
XState = currentSelection.State
});
}
else
{
Messenger.Default.Send<UserActionAlertMsg>(
new UserActionAlertMsg() { AlertText="Streets are same!"});
}
}
Because we want only the street name, we make use of a helper method, GetCurrentSelectionStreet, which strips out the address number. We then compose a message since the service is being hosted by SLMapViewModel. Since we are making a request from two different sources, and the calls to the service are asynchronous, we pass a token along with the call to enable us to determine what to do when we get the response. That's the purpose for the RequestType indicated below and in the callback.
GetCurrentSelectionStreet
RequestType
void StreetIntersectionHandler(GetStreetIntersectionMsg msgData)
{
GeocodeAddress(msgData.XStreetName + " & " + msgData.SegmentStreet +
"," + msgData.XCity + "," + msgData.XState, RequestType.XRequest);
}
...
private void GeocodeCompleted(object sender,
BingGeocodeService.GeocodeCompletedEventArgs e)
{
//Clear busy flag...
showBusy = false;
this.RaisePropertyChanged("IsBusy");
string callResult = "";
Location xLocation = new Location();
string xStreets = "";
bool foundIntersection = false;
try
{
//Was the service able to parse it? And did it return anything?
if (e.Result.ResponseSummary.StatusCode !=
BingGeocodeService.ResponseStatusCode.Success ||
e.Result.Results.Count == 0)
{
if ((RequestType)e.UserState == RequestType.FindRequest)
callResult = "Can't find it!";
else
Messenger.Default.Send<StreetIntersectionResultMsg>(
new StreetIntersectionResultMsg());
}
else
{
//What are we getting back?
if ((RequestType)e.UserState == RequestType.FindRequest)
{
Location geoLocation = new Location(
e.Result.Results[0].Locations[0].Latitude,
e.Result.Results[0].Locations[0].Longitude);
// Zoom the map to the desired location
Messenger.Default.Send<SetMapViewMsg>(
new SetMapViewMsg() { CenterLocation = geoLocation });
}
else
{
xLocation = e.Result.Results[0].Locations[0];
xStreets = e.Result.Results[0].Address.AddressLine;
foundIntersection = true;
StreetIntersectionResultMsg result =
new StreetIntersectionResultMsg();
result.IntersectionLocation = xLocation;
result.Intersection = xStreets;
result.StreetsIntersect = foundIntersection;
Messenger.Default.Send<StreetIntersectionResultMsg>(result);
}
}
}
catch
{
callResult = "Error processing request.";
}
resultString = callResult;
this.RaisePropertyChanged("ResultString");
}
Once we have the coordinates for the intersection, we save the information and draw an 'X' at the intersection as feedback to the user. And we already know how to draw things on the map.
void GetIntersectionMessageHandler(StreetIntersectionResultMsg msgData)
{
//Start or end intersection?
if (definitionState == SegmentDefinitionStates.StartXStreet)
{
if (msgData.StreetsIntersect)
{
currentSegment.StartXStreet = msgData.IntersectionLocation;
//Plot an 'X' at the intersection
Messenger.Default.Send<PlotIntersectionMsg>(
new PlotIntersectionMsg(){ IntersectionLocation =
msgData.IntersectionLocation});
definitionState = SegmentDefinitionStates.EndXStreet;
}
else
{
//Tell user that the selected street does not intersect segment street
Messenger.Default.Send<UserActionAlertMsg>(
new UserActionAlertMsg() { AlertText = "Streets do not intersect!" });
}
}
else
...
}
There is one last piece to figure out and we'll have the basic functionality for a route editor. Once the user has selected the start and end intersections, we need to draw the route on the map. Yes, we know how to draw anything on the map, which means we can easily draw a line. But we need to show 'navigable' paths. In other words, we can't show a path that cuts through buildings or crosses rivers where there are no roads. So we need to draw a path along a route that can be walked or driven. One possible way to do this is to force the user to specify all intersections along the path. Then we could simply draw lines connecting those points. This doesn't work because streets are normally not always built as straight lines. The solution, fortunately, comes from using another Bing Maps service: Route Service. Once we know the start and end coordinates, we can simply pass them to the route service and we'll get back a collection of coordinates that corresponds to the path to follow. These will correspond to center street coordinates and can be used to draw the path. As many points as necessary will be returned to ensure that we can draw lines that lie on the center of the street that is being followed.
Continuing with our demo project, right click on Service References to add a service proxy as we did for the geocode service. For the WSDL address, type in:. And for the namespace, change the default to BingRouteService and don't forget about the Advanced button to eliminate the name clashes. Since we'll be using this service in MainViewModel, we'll add a member property there.
private BingRouteService.RouteServiceClient RouteClient
{
get
{
if (null == routeClient)
{
BasicHttpBinding binding =
new BasicHttpBinding(BasicHttpSecurityMode.None);
UriBuilder serviceUri = new UriBuilder("" +
"webservices/v1/routeservice/routeservice.svc");
//Create the Service Client
routeClient = new BingRouteService.RouteServiceClient(binding,
new EndpointAddress(serviceUri.Uri));
routeClient.CalculateRouteCompleted +=
new EventHandler<BingRouteService.CalculateRouteCompletedEventArgs>(
routeClient_CalculateRouteCompleted);
}
return routeClient;
}
}
As you can see, we also defined the callback method for the asynchronous call. Here's the code for the helper method that packages the request for the call to the service:
private void GetRouteSegmentPlot(Location startLocation,
Location endLocation, int segmentID)
{
BingRouteService.RouteRequest request =
new BingRouteService.RouteRequest();
request.Waypoints = new ObservableCollection<BingRouteService.Waypoint>();
BingRouteService.Waypoint start = new BingRouteService.Waypoint();
start.Location = new Location();
start.Location.Latitude = startLocation.Latitude;
start.Location.Longitude = startLocation.Longitude;
start.Location.Altitude = startLocation.Altitude;
request.Waypoints.Add(start);
BingRouteService.Waypoint end = new BingRouteService.Waypoint();
end.Location = new Location();
end.Location.Altitude = endLocation.Altitude;
end.Location.Latitude = endLocation.Latitude;
end.Location.Longitude = endLocation.Longitude;
request.Waypoints.Add(end);
request.Options = new BingRouteService.RouteOptions();
request.Options.RoutePathType = BingRouteService.RoutePathType.Points;
request.Options.TrafficUsage = BingRouteService.TrafficUsage.None;
request.Options.Optimization =
BingRouteService.RouteOptimization.MinimizeDistance;
request.Options.Mode = BingRouteService.TravelMode.Walking;
// Don't raise exceptions.
request.ExecutionOptions = new BingRouteService.ExecutionOptions();
request.ExecutionOptions.SuppressFaults = true;
request.Credentials = new Credentials();
request.Credentials.ApplicationId =
(string)App.Current.Resources["BingCredentialsKey"];
// Make asynchronous call to fetch the data. Set busy indicator...
RouteClient.CalculateRouteAsync(request, segmentID);
}
From the code above, you can see the service provides options for a lot more than what we are using it for in this application. It is primarily intended for traveling directions, which usually involves optimization for distance or time, traffic effects, etc. So we are not really using it for its intended purpose, but serves our needs. As with the geocode service, we can pass a token with the call that allows us to identify the result. In this case, we are passing the segmentID to keep track of what we asked. We are not making use of it at this point, but will be necessary if we want to persist the data. The callback processing is shown next.
void routeClient_CalculateRouteCompleted(object sender,
BingRouteService.CalculateRouteCompletedEventArgs e)
{
try
{
if (e.Result.ResponseSummary.StatusCode !=
BingRouteService.ResponseStatusCode.Success)
{
Messenger.Default.Send<UserActionAlertMsg>(
new UserActionAlertMsg() {
AlertText = "Could not determine route segment." });
}
else
{
BingRouteService.RoutePath routePath = e.Result.Result.RoutePath;
currentSegment.PlotPoints.AddRange(routePath.Points);
//Plot the segment
PlotRouteSegmentMsg msg = new PlotRouteSegmentMsg();
msg.segmentPoints = new List<Location>(routePath.Points);
Messenger.Default.Send<PlotRouteSegmentMsg>(msg);
}
}
catch
{
Messenger.Default.Send<UserActionAlertMsg>(
new UserActionAlertMsg(){ AlertText="Got an exception calling route service."});
}
}
Now that we have a collection of points, all we need to do is draw them on a layer on the map. The map control includes a number of types that facilitate rendering operations. We've already used MapLayer, there is also PushPin, MapPolygon, and the one which we'll make use of next is MapPolyline. This is exactly what we need to render our route segment. Here is how we process the PlotRouteSegmentMsg message:
PushPin
MapPolygon
MapPolyline
PlotRouteSegmentMsg
void PlotSegmentHandler(PlotRouteSegmentMsg msgData)
{
Color routeColor = Colors.Blue;
SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
MapPolyline polyLine = new MapPolyline();
polyLine.Locations = new LocationCollection();
polyLine.Stroke = routeBrush;
polyLine.Opacity = 0.65;
polyLine.StrokeThickness = 5.0;
foreach (Location pt in msgData.segmentPoints)
{
polyLine.Locations.Add(pt);
}
SegmentLayer.Children.Clear();
SegmentLayer.Children.Add(polyLine);
}
The above shows the editor in action. The start and end address numbers are not really required for the definition of a segment, but are included to show how solution entities (store address, soda machine location, etc.) could be related with a route.
Suppose that a business enterprise did not follow a specific route as described above for the product distribution scenarios. Instead, this business type is one that has an area of coverage. The above editor could be easily modified to allow the user to select an arbitrary number of intersections as the defining boundary of their delivery area. The defined area could be drawn on a separate layer for identification and any number of areas could be supported. All the addresses that exist in the defined area would constitute their customers. To determine which area (if any) contained a specific address, we could use the coordinates and perform a simple inclusion check. Similar to checking if a point is within a rectangle or figure.
As an example, consider a national or regional pizza chain that may have several locations. Each of these would in turn serve a pre-defined area simply so that they can deliver the product within the allowable time. For this type of business, a route is required but is not pre-defined. This type of business would benefit from a solution that would dynamically determine the most efficient route for a given set of locations (deliveries). Given a set of delivery coordinates (addresses) and the restaurant as the starting point, an algorithm could easily determine the best delivery route(s). The solution could even be smart enough to evenly distribute the work load between available drivers. Of course, a phone app for the solution would direct the deliveries without any paper instruction, without the driver needing to know the area, and allows a manager to keep track of each delivery as it is taking place (the system knows where the phone is).
In most metropolitan cities, there are companies that offer same day delivery service. These companies have a fleet of messengers (usually on bike) that pick up packages at one location and deliver to another location within the city or close vicinity. Using the facilities we have been describing, such a company can be provided with a service that would make the business process completely automated. In other words, no office personnel. Customers could enter pick-up/drop-off information through a Web page. The system could then automatically determine the most efficient way to accomplish the delivery. This would involve an algorithm that would determine which messenger is the closest to the pick-up location, the orders that are still in the queue, the destination location compared to other pick-up orders, etc. The orders are then issued to each messenger through a phone app as well as all other pertinent business logic information. Some of the 'wiz-bang' features could be a page where customers could see their package in motion as well as a dynamically updated estimated delivery time. Brainstorming can be a lot of fun!
One of the core pieces of the targeted applications we have been describing is the phone. So next up, I'm planning on taking a look at what it takes to bring the phone into the solution. At the same time, we'll brainstorm some more business solutions that could benefit from the functionality that we've been.
|
http://www.codeproject.com/script/Articles/View.aspx?aid=148608
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Oct 18, 2011 08:45 AM|yenni104|LINK
Hi, I am using MVC 3 unobtrusive client side validation and I need to implement some custom validation rules for my DateTime field.
I got ExpiryDate and Storagedate, where Expirydate should be later or equal to today's date. Also, the Expirydate should not be earlier than the StorageDate.
However, I got no idea how to implement the custom validation. I got the partial class to customize the validation in my Model like this:
[MetadataType(typeof(FoodMetaData))] public partial class FOOD { [Bind(Exclude = "FoodID")] public class FoodMetaData { [ScaffoldColumn(false)] public int FoodID { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter a name")] public object FoodName { get; set; } public object StorageDate { get; set; } public object ExpiryDate { get; set; } } }
Any idea how can I declare a custom validation for the DateTime field?? I googled a lot but still no able to find similar solution... Please help...
Oct 18, 2011 09:49 AM|francesco abbruzzese|LINK
Use the DateTimeInput and the DateRangeAttribute of my Mvc Controls Toolkit. You can define both the previous constraint, on the client side and on the server side, easily by placing two DateRange attributes on the ExpiryDate each for each constraint and by adding a new property called ToDay to your ViewModel (it has just a get returning today). User would not be able to enter a date is nort allowed at all. You have also the option, when the user choose a storageDate, to change expiryDate automatically to make the constraint holds instead of limiting the value of ExpiryDate.
The example application here show an example of use. Other examples of the use of the DateTimeInput are...pratically in almost all tutorials.
Oct 18, 2011 10:32 AM|yenni104|LINK
Hi, can you give me some example??
Because I need something like [DateRange(SMaximum = "2012-1-1", SMinimum = "2008-1-1")] but if for ExpiryDate, i only need the minimum part which is Today's date && StorageDate. I not really understand how to do this since there is no example available there..
Sorry and thanks for your kind help..
Oct 18, 2011 02:04 PM|francesco abbruzzese|LINK
There are examples....you have to see the ViewModel used in the page of the software distribution. Anyway:
1) define a property you call Today (for example):
[Milestone]
public DateTime Today {
get{
return DateTime.Now;
}
}
please notoce the milestone attribute, this inform the engine that the proprty will not be renderedi in the page;
now you write:
[DateTange(DynamicMinimum='Today')]
[DateTange(DynamicMinimum='StorageDate')]
public DateTime ExpiryDate{get; set;}
This way when user will introduce a wrong date the date will be automatically corrected to match the constraint.
if you use [DateTange(DynamicMinimum='StorageDate', RangeAction = RangeAction.Propagate)]
instead when user will introduce e data that is smaller than ExpiryDate ExpiriDate will be decreased in the Html page to keep the constraint valid.
Th minimum you have define are called Dinamic because they depends on the value of other properties. I suggest to addr also some fixed minimum and fixed maximum, say 1900 and 2100 or less, do force the date to be in an interval tha male sense for your application in any case:
[DateTange(DynamicMinimum='StorageDate', SMaximum = "2000-1-1", SMinimum = "2100-1-1")]
You can add as many date range attribute you like to the same property.
Oct 19, 2011 12:01 AM|yenni104|LINK
Hi, really thanks for your detailed answer. But I still cant it work.. Do I need to add anything else (in script or etc..) for the DateRange validation to work? Currently even I put my expirydate to < today's date, nothing happen (no validation message, no auto-correct). I could not find the problem.. I will show my code here:
[MetadataType(typeof(FoodMetaData))] public partial class FOOD { [Bind(Exclude = "FoodID")] public class FoodMetaData { [ScaffoldColumn(false)] public int FoodID { get; set; } [DateRange(DynamicMinimum="Today", ErrorMessage="Test")] [DateRange(DynamicMinimum="StorageDate", ErrorMessage="Test storage date")] public DateTime ExpiryDate { get; set; } } [MileStone] public DateTime Today { get { return DateTime.Now; } } }
The Form:
@using (Html.BeginForm("CreateFood", "Stock", FormMethod.Post, new { Expiry Date </div> <div class="editor-field"> @Html.EditorFor(model => model.ExpiryDate, new { @class = "expirydate" }) @Html.ValidationMessageFor(model => model.ExpiryDate) </div> }
Validation for other field do works, just for date i get nothing.. Please help... Really appreciate it....
Oct 19, 2011 08:21 AM|francesco abbruzzese|LINK
1) The autorrect behaviour happens just if you use the DateTimeInput of the Mvc Controls Toolkit: otherwise, normal unobtrusive validation is performed and when the field is invalid the usual validation message is shown.
2) For everything to work properly you have to install the Mvc Controls Toolkit since it has custom Validation and Metadata provider. It is available throught Nuget (Mvc3ControlsToolkit or Mvc2ControlsToolkit), or you can install it manually as explained here:
Oct 19, 2011 08:32 AM|yenni104|LINK
Hi, I did install it.. but I still cant get any validation message.. is it a must to use Html.DateTimeFor for the validation to work? If yes, do you have any idea how to assign a class to Html.DateTimeFor helper like what I did for the EditorFor?
<div class="editor-field">
@Html.EditorFor(model => model.ExpiryDate, new { @class = "expirydate" })
@Html.ValidationMessageFor(model => model.ExpiryDate)
</div>
And is it any additional steps needed because I am using a datepicker?
Really thanks for your help....
Oct 19, 2011 10:39 AM|francesco abbruzzese|LINK
In my previous post I have not noticed you use editorFor....It is not compulsory to use DateTimeFor...but you can't use editorfor on the single datetime value for the reasons I explain below. In any case I strongly suggest to use DateTimeFor...it offers you more options. DateTimeFor returns an object you can use to render separately the date part and the time part. You can style both with separate css.
The date part can be rendered with three dropdowns(Date method) or with a jQuery picker(DateCalendar method). Both methods have an html attributes dictionary new Dictionary<object, string> {{"class", "expirydate"}}.
However if you use the jquery picker the html attributes will apply just to the textbox the DatePicker will be attached to. To style the picker you have to customiza a jQuery UI css file
Now I can explain why the editorfor cannot be used: the point is that bot fields that need to be compared need to be in the same model, otherwise there is no way for the mvc engine to read the value to compare. This means both the field Today and ExpiryDate MUST be in the same model because the value of Today must be read and inserted in the validationattributes of ExpiryDate....Now if you use EditorFor on the single ExpiryDate property behind the scene Mvc creates a new model containing just this field ExpiryDate and pass it to a new View....so it is impossible to read the value of Today from there :) THERE IS NO WAY TO OVERCOME THIS LIMIT, that apply to all conditional validation attributes, since it depends on how the core data structure of the Mvc engine were designed.
However the constraint on Storagedate should work, because it is resolved on the client side, since the Storagedate filed is rendered in the View (at least I have understood ...this way)
Oct 19, 2011 04:35 PM|francesco abbruzzese|LINK
See the example of use of the DateTimeFor here: BinariesWithSimpleExamples
Basically:
@{var DT = DateTimeFor(m => m.ExpiryDate, dateInCalendar : true)}
@DT.DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions
{
ChangeYear=true,
ChangeMonth=true,
},
containerHtmlAttributes: new Dictionary<string, object> {{"class", "expirydate"}})
There are various calendar option you can choose....I put the ones I like more
I have chosen to use the jQuery picker, so you have to include the relateive js files, and css
Oct 20, 2011 12:28 AM|francesco abbruzzese|LINK
Sorry I have written that code directly in the post without compiling it..and in a hurry...so I forgot the Html before the DateTimeFor and a ;
This should work:
@{var DT = Html.DateTimeFor(m => m.ExpiryDate, dateInCalendar : true);}
@DT.DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions
{
ChangeYear=true,
ChangeMonth=true,
},
containerHtmlAttributes: new Dictionary<string, object> {{"class", "expirydate"}})
Oct 20, 2011 07:59 AM|francesco abbruzzese|LINK
The point is that you showed me just the MetaDataType...so I don't know too much of your model. Does your ExpiryDate is a DateTime? ie a nullable DateTime ?
In such a case you have to furnish a default date to be used as initial date when the Date is null as shown below:
@{var DT = Html.DateTimeFor(m => m.ExpiryDate, dateInCalendar : true, emptyDate: DateTime.Now);}
Obviously you can set emptyDate to whatever you like not necessaruly to DateTime.Now.
Don't forget to include also the js and css files needed by the jQuery datepicker. Finally, either you render the StorageDate in yiour page with a DateTimeInput, or apply to it the Milestone attribute as you have done with the Today property.
Oct 21, 2011 08:27 AM|francesco abbruzzese|LINK
Pls motice, you will see no error message, but the user will simply unable to insert a wrong date, because any wrong date will be ccorrected to be withing the constraints.
Pls prepare a selfcontained example with no db and send it to me through the contact form of my blog(it has the option to attach files).
Oct 23, 2011 01:48 PM|Young Yang - MSFT|LINK
Hi yenni
You can write the code as follow:
public sealed class ExpiryDateAttribute : ValidationAttribute { public override bool IsValid(object value) { DateTime expiryDate = (DateTime)value; return (expiryDate >= DateTime.Now); } } public sealed class StoragedateAttribute : ValidationAttribute { public string expiryDateProperty { get; set; } public override bool IsValid(object value) { string expiryDateString = HttpContext.Current.Request[expiryDateProperty]; DateTime storagedate = (DateTime)value; DateTime expiryDate = DateTime.Parse(expiryDateString); return expiryDate < storagedate; } }
And in your view model:
[ExpiryDate] public DateTime ExpiryDate { get; set; } [Storagedate(expiryDateProperty = "ExpiryDate")] public DateTime Storagedate { get; set; }
Hope this helpful
Regards
Young Yang
Oct 23, 2011 02:06 PM|yenni104|LINK
Hi, amazingly it works! Really thanks a lot for your help...
I got one more question, do you have any idea how I can validate both the datefield to ensure it is a valid Datetime in a specific format? Because even with the datepicker, user can input any string/numbers in the textfield and click submit.. so I want to validate those manually entered value to ensure it is a DateTime which match the format of my datepicker's Date declared as:
$('#expirydate').datepicker({ constrainInput: true, minDate: 0, dateFormat: 'D, dd M yy' });
And one of the datetime form field with the format:
<div class="editor-label"> Expiry Date </div> <div class="editor-field"> @Html.TextBox("ExpiryDate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" }) @Html.ValidationMessageFor(model => model.ExpiryDate) </div>
Really thanks a lot for your help!
Oct 24, 2011 02:26 AM|Young Yang - MSFT|LINK
Hi yenni,
You just need to add a regularexpression attribute in your model, you can do it like this:
[ExpiryDate] [RegularExpression(@"^(19|20)dd([- /.])(0[1-9]|1[012])2(0[1-9]|[12][0-9]|3[01])$”)] public DateTime ExpiryDate { get; set; }
You can change the expression to what you want.
Hope this helpful
Regards
Young Yang
Oct 24, 2011 03:54 AM|Young Yang - MSFT|LINK
Please find the expression from here:. If you still not found it. Please create a new thread about regular expression.
Hope this helpful
Regards
Young Yang
20 replies
Last post Oct 24, 2011 03:54 AM by Young Yang - MSFT
|
http://forums.asp.net/t/1731351.aspx?Custom+DateTime+Validation+for+MVC+3+unobtrusive+client+side+validation
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
collection. For example, if the collection is assigned to a variable named collListItems, use collListItems[index] in Microsoft C#, or collListItems(index) in Microsoft Visual Basic, where index is the index number of the item in the collection, or the internal name or display name of a list field. For an indexer based on a name,.
Unlike all other members in the object model, the indexer for a DateTime field returns values in local time on the site. In a query, set the DatesInUtc property of the SPQuery object to true for the indexer to return values in Universal Coordinated Time (UTC). If the values are returned in local time and you want to convert them to UTC, use the LocalTimeToUTC method, as follows:
For more information about the conversion and format of date and time values in SharePoint Foundation, see Converting Date and Time Values.
Using the SPListItem class to modify an event that is linked to a Meeting Workspace site will not update the associated Meeting Workspace site and is not supported.
The type that is returned for the value of a Calculated field depends on the output type of the calculated column.
A Lookup field contains a string in the form ID;#VALUE, where ID is the list item ID and VALUE is the value of the lookup field in the other list. For multivalued lookups, a Lookup field contains a collection.
The value of a MultiChoice field is represented as a string that contains all the selected choices separated by ;#.
The URL field uniquely consists of two strings that are separated by a comma and space. One string contains the URL path and the other contains the description that is used as hyperlinked text.
You can set the value for a User field with an SPUser object, as shown in the following example, which updates an item in the Assigned To field of a tasks list.
A User field contains a string in the form ID;#User_Display_Name, where ID is the member identifier (ID) of the associated user. The following example parses the value of an Assigned To field to return an SPUser object.
When you are creating a list item, you can set the Author, Editor, Created, and Modified fields the same way that you set other fields of an SPListItem object. The code must be running with site administrator rights in order to function correctly. Set the Author and Editor fields by using the numerical ID of the user, which you can obtain through the object model by using members of SPUser and related classes. The following examples show how to set these fields.
Note that there are no methods or properties for retrieving the metadata for the currently approved version of a list item. (This presumes that you have enabled both versioning and content approval for the list item.) To work around this problem, you can retrieve metadata for the current approved version using the following
using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; using System.Collections; namespace GetListItemVersionInformation { class Program { static void Main(string[] args) { SPSite oSite = new SPSite(""); SPWeb oWeb = oSite.OpenWeb(); SPList oList = oWeb.Lists["MyCustomList"]; SPListItem oListItem = oList.Items.GetItemById(1); SPListItemVersionCollection oVersionInfo = oListItem.Versions; int i=0; foreach (SPListItemVersion oVersion in oVersionInfo) { if (oVersion.Level == SPFileLevel.Published) { // here we retrieve all metadata properties // for this item with the current approved version. // after taking these values we can export them Console.WriteLine(oListItem.Versions[i]["Address"].ToString()); Console.WriteLine(oListItem.Versions[i]["Title"].ToString()); Console.ReadLine(); return; // after getting the latest approved version // we are exiting the code } i++; } } } }
The following code example uses an indexer to verify the value of a particular field in the specified list. If the value does not equal "None", indexers for two other fields are used to display values from particular fields.
This example requires using directives (Imports in Microsoft Visual Basic) for the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.>"; } }
The previous code example assumes the existence of an .aspx page that contains a label control.
The following code example adds an item to an Announcements list, using date and time indexers to assign values to different fields.(); } }
|
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem(v=office.15).aspx
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Central logging agent. More...
#include <qpid/log/Logger.h>
Central logging agent.
Thread safe, singleton.
The Logger provides all needed functionality for selecting and formatting logging output. The actual outputting of log records is handled by Logger::Output-derived classes instantiated by the platform's sink-related options.
Definition at line 36 of file Logger.h.
Add a statement.
Reset the logger.
Set the formatting flags, bitwise OR of FormatFlag values.
Set format flags from options object.
Log a message.
Add an output destination for messages.
Reset the log selectors.
Select the messages to be logged.
Set a prefix for all messages.
|
http://qpid.apache.org/apis/0.12/cpp/html/a00131.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
09 December 2011 07:08 [Source: ICIS news]
SINGAPORE (ICIS)--Asia’s naphtha prices will stay firm in December, supported by the expectations of fresh spot demand from ?xml:namespace>
In line with the strong prices, the naphtha spread between the contracts for the second half of January and the second half of February widened to $5.50/tonne (€4.13/tonne) in backwardation from parity a month ago, ICIS data showed.
The naphtha crack spread versus Brent crude futures nearly tripled from the levels seen in early November to above $90/tonne on the close of trade on 8 December, the data showed.
“The demand for heavy grade naphtha is strong and there isn’t much supply available,” a trader said, adding that the premium for heavier grade naphtha was more than $10/tonne.
Both
South Korea’s Honam Petrochemical bought 25,000 tonnes of naphtha for delivery into Daesan in the first half of January at a premium of $4/tonne to Japan quotes CFR (cost & freight) earlier in the week, while LG Chem subsequently bought supplies for delivery into Yeosu in the second half of January at a wider premium of $5/tonne, the traders said.
“Supply is tight for January, especially for the first half of the month,” a third trader added.
The rising naphtha prices in Asia, which increased to above the $900/tonne CFR Japan level seen this week, have sparked off a rally in the east-west spread, boosting the opening of the arbitrage window to bring in barrels from
The east-west spread strengthened to $21.72/tonne on 8 December from $21.02/tonne on the close of 7 December, the traders said. The spread was at $10.49/tonne four weeks ago, they added.
For December, around 150,000 tonnes of deep-sea Western naphtha will be shipped to
Meanwhile, a recovery in butadiene (BD) prices, which are supported by limited supply and production cuts, is boosting the naphtha market, the traders added.
Spot BD prices continued to increase, rising to above $2,100/tonne
The BD prices, which were assessed at $1,570-1,650/tonne CFR NE Asia four weeks ago, drew support from increased Chinese demand and limited availability.
The market is bracing for
FPCC has raised the operating rates at its three naphtha crackers to meet a stronger demand from its downstream derivative products. The company operates a 700,000 tonne/year No 1 cracker, a 1.03m tonne/year No 2 unit and a 1.2m tonne/year unit in Mailiao. “The market is hopeful,” a fourth trader said.
($1 = €0.75)
For more on butadiene and naphtha,
|
http://www.icis.com/Articles/2011/12/09/9515243/asia-naphtha-to-firm-on-fpcc-buying-hopes-firm-butadiene.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Comment:
Changes (1)View Page History
{note:title=Superceded}
This page has been superceded by [Zend Framework 2.0 Requirements]; please direct further discussion to that page.
{note}
This page has been superceded by [Zend Framework 2.0 Requirements]; please direct further discussion to that page.
{note}
{note:title=Participate in the Discussion}
Please participate in the discussion! You can either do so in comments to these pages, or by subscribing to the zf-contributors@lists.zend.com -- simply send an email to zf-contributors-subscribe@lists.zend.com!
Please participate in the discussion! You can either do so in comments to these pages, or by subscribing to the zf-contributors@lists.zend.com -- simply send an email to zf-contributors-subscribe@lists.zend.com!
Z.
h2.:
{code:php}
namespace zend;
class Options
{
public static function setOptions($object, array $options)
{
if (!is_object($object)) {
return;
}
foreach ($options as $key => $value) {
$method = 'set' . self::_normalizeKey($key);
if (method_exists($object, $method)) {
$object->$method($value);
}
}
}
public static function setConstructorOptions($object, $options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (is_array($options)) {
self::setOptions($object, $options);
}
}
protected static function _normalizeKey($key)
{
$option = str_replace('_', ' ', strtolower($key));
$option = str_replace(' ', '', ucwords($option));
return $option;
}
}
use zend\Options as Options;
class Foo
{
public $bar = '';
public $baz = '';
public function __construct($options = null)
{
Options::setConstructorOptions($this, $options);
}
public function setOptions(array $options)
{
Options::setOptions($this, $options);
}
public function setBar($value)
{
$this->bar = $value;
}
public function setBaz($value)
{
$this->baz = $value;
}
}
$foo = new Foo(array('bar' => 'baz'));
echo $foo->bar; // "baz"
$foo->setOptions(array('bar' => 'boo', 'baz' => 'bat'));
echo $foo->bar . $foo->baz; // "boobat"
{code}
* .
* *Exceptions*.:
{code:php}
namespace \Foo\Bar;
interface Exception
{
}
class InvalidArgumentException
extends \InvalidArgumentException
implements Exception
{
}
try {
throw new InvalidArgumentException();
} catch (\Foo\Bar\Exception $e) {
}
{code}
* *.).
* [Specifics on Plugin architecture changes|Plugin Architectures]
h2..
Finally, one possibility offered by PHP 5.3 is the idea of having the front controller be a state machine, due to the addition of _goto_.
For more information on proposed MVC refactoring, please visit the following pages:
* [Zend_Controller 2.0|]
* [Zend_Controller_Router 2.0|]
* [Zend_View 2.0|]
* [Zend_Session 2.0|]
* [Zend_Form 2.0]
h2. Other components
* [Zend_Soap 2.0|]
* [Zend_Mail 2.0|]
|
http://framework.zend.com/wiki/pages/diffpages.action?pageId=45023323&originalId=22249562
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Dmitry Baryshkov <dbaryshkov@gmail.com> wrote:> > > +#ifdef CONFIG_DEBUG_FS> > > + struct dentry *dir;> > > + struct dentry *info;> > > +#endif > > > > Can't you hide this in the code, say by wrappering the> > struct with something else when it is registered? > > It is allocated dynamically by drivers. I can move this to> struct clk_private to specify that it's private, but it should be> visible outsideActually, I don't think it _should_ be private. Low-level clock driversmight want to provide debugfs nodes on their own, and those nodesnaturally belong in the same directory as the clklib ones. So thedebugfs root node must be exposed somehow.You can get rid of the "info" field if you apply this patch:
|
http://lkml.org/lkml/2008/7/4/56
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
21 August 2012 17:08 [Source: ICIS news]
LONDON (ICIS)--Low water levels in the river Rhine in Germany have led ship owners and charterers to achieve higher freight rates on barge journeys, sources said on Tuesday.Continued hot weather across Europe has seen water levels on the ?xml:namespace>
“On current water levels, a 3,000 tonne barge is able to take around 39% to 44% of its capacity to the upper
With barge owners not fully utilising their capacities and bunker fuel costs remaining at high levels, another broker said that; “charterers and owners continue to push for higher rates to recoup on losses made on these inefficient journeys.”
“Many have achieved success in gaining higher rates,” he added.
According to data from the German waterways authority, levels in Kaub,
With rainfall forecasts in the region lower than expected for this time of year, sources expect rates to increase further as water levels continue to fall.
Last week, sources in the methanol market said transport barges on the river Rhine had been forced to reduce their loads along certain stretches because of low water levels, caused by recent warm weather and a lack of rain.
Additional reporting by Ross Ye
|
http://www.icis.com/Articles/2012/08/21/9588794/barge-rates-increase-on-low-river-rhine-water-levels.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
21 February 2013 17:16 [Source: ICIS news]
WASHINGTON (ICIS)--US sales of existing homes rose marginally in January from December, the National Association of Realtors (NAR) said on Thursday, noting that the market for previously owned homes is running 9% ahead of January 2012.
In its monthly report, the NAR said that existing home sales rose by about 0.4% in January to a seasonally adjusted annual rate of 4.92m units compared with the downwardly revised sales pace of 4.90m in December.
December’s sales of existing homes had initially been put at 4.94m units. Had December’s figure not been revised downward, the January total would have shown a decline.
While sales growth in the existing homes market remains modest, the NAR noted that January’s sales pace was 9.1% ahead of the same month last year, a sign that the housing recovery is gaining strength.
Sales of existing homes would be stronger, the NAR said, if there were more single-family homes, condos and co-ops available for sale.
“Tight inventory is a major factor in the market,” said NAR chief economist Lawrence Yun.
“Buyer traffic is continuing to pick up, while seller traffic is holding steady,” he said. “In fact, buyer traffic is 40% above a year ago, so there is plenty of demand but insufficient inventory to improve sales more strongly.”
The availability of existing homes for sale was lower in January, the NAR said, with the inventory of for-sale homes off by nearly 5% from December to 1.74m units.
At the current sales pace, those 1.74m homes for sale represent a 4.2-month supply. That inventory level marks the lowest housing availability since April 2005 when the US housing boom was still in full flower.
In January 2012, the inventory of for-sale existing homes constituted a 6.2-month supply.
The ?xml:namespace>
|
http://www.icis.com/Articles/2013/02/21/9643337/us-existing-home-sales-rise-marginally-in-jan-up-9-from-2012.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
As discussed in my last Android coding article, one of the neat features of coding for a phone is the ability to use its motion sensors. As well as just detecting a motion event, as I covered in that tutorial, you can also use the information from the sensor to change what you're drawing on the screen. In this tutorial, we'll look at how to draw shapes on Android, and at doing a bit more with the information given by the acceleration sensor.
There are two ways to draw on Android; via a Canvas, or using a custom View. This tutorial will look at using a custom View to draw a moving bubble on the screen; watch Linux.com for a follow-up on drawing with a Canvas and detecting touch events. I won't go into too much detail on handling sensors; check out the last tutorial for detailed info.
Making a custom view and bubble
First, let's extend View to create a custom View:
public class BubbleView extends View { private int diameter; private int x; private int y; private ShapeDrawable bubble; public BubbleView(Context context) { super(context); createBubble(); } private void createBubble() { x = 200; y = 300; diameter = 100; bubble = new ShapeDrawable(new OvalShape()); bubble.setBounds(x, y, x + diameter, y + diameter); bubble.getPaint().setColor(0xff00cccc); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); bubble.draw(canvas); } }
We use ShapeDrawable to create an oval on the custom View. It's important both to set the bounds (the box within which the oval will be drawn; here it's square, so the oval will be a circle), and the paint colour. Then
onDraw() is the important method to override -- this is the method which will be called every time your View is drawn. Here all we do is to call
super, then draw the bubble.
You can set this as the View to use with this code in your Activity:
public class BubbleActivity extends Activity { private BubbleView bubbleView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bubbleView = new BubbleView(this); setContentView(bubbleView); } }
Compile and run, and you should see a blue bubble in the centre of the screen. (Note: I found that this worked fine on a handset, but not on the emulator.)
XML Views
An alternative approach to using code to set up your custom View is to describe it in XSL. Here's a simple XML file, res/drawable/circle.xml, to draw a solid blue circle on the screen:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns: <solid android: <size android: </shape>
To call this from your Activity, you'll need to use a bit more code than you do when extending View:
private LinearLayout layout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layout = new LinearLayout(this); ImageView i = new ImageView(this); i.setImageResource(R.drawable.circle); i.setAdjustViewBounds(true); i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); layout.addView(i); layout.setGravity(Gravity.CENTER); setContentView(layout); }
This sets up a new Layout and ImageView, and adds the image defined by the file res/drawable/circle.xml to the ImageView.
setAdjustViewBounds() sets the ImageView bounds to the same as the size of the Drawable. We then set the layout parameters to wrap the content, and add the ImageView to the layout. Run this, and you'll see a solid circle in the top left of the screen. To put it in the centre of the screen, add the line
layout.setGravity(Gravity.CENTER);layout.setGravity(Gravity.CENTER);
Using XML, you can also set up some neat graphical effects, like this shaded circl:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns: <gradient android: <size android: </shape>
However, this is really only suitable for a static shape, while we want a moving one. So we'll stick with our custom View class.
Moving with the sensor
Now we have our custom View with a bubble in it, the next job is to grab a sensor and make the ball move with the accelerometer. Let's do some work with BubbleActivity:
public class BubbleActivity extends Activity implements SensorEventListener { private SensorManager manager; private BubbleView bubbleView; private Sensor accel; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bubbleView = new BubbleView(this); setContentView(bubbleView); manager = (SensorManager)getSystemService(SENSOR_SERVICE); accel = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); manager.registerListener(this, accel, SensorManager.SENSOR_DELAY_GAME); } public void onAccuracyChanged(Sensor sensor, int accuracy) { // don't do anything; we don't care } public void onSensorChanged(SensorEvent event) { bubbleView.move(event.values[0], event.values[1]); bubbleView.invalidate(); } protected void onResume() { super.onResume(); manager.registerListener(this, accel, SensorManager.SENSOR_DELAY_GAME); } protected void onPause() { super.onPause(); manager.unregisterListener(this); } }
As per the last tutorial, we extend SensorEventListener, which means implementing
onAccuracyChanged() and
onSensorChanged(). We also get the SensorManager in
onCreate(), grab the accelerometer, and register the listener. It's important to remember to unregister it in
onPause() and reregister in
onResume(), to avoid running straight through your battery.
When something happens, the SensorEvent has three values: x, y, and z (axes are defined in the API). We're passing the x and y of those to the BubbleView. Let's look at
BubbleView.move():
protected void move(float f, float g) { x = (int) (x + f); y = (int) (y + g); bubble.setBounds(x, y, x + diameter, y + diameter); }
If you try running this now, you'll notice that the View flips from landscape to portrait as you move the device. To avoid this, edit
AndroidManifest.xml to look like this:
... <activity android: ...
Run again, and you'll see it working as expected.
Finding the center and edges of the screen
We're using hard-coded values for the starting point of the bubble, but ideally it would start in the centre of the screen. Unfortunately, the 2D coordinates start from the top left
corner of the screen, so we'll need to find the device screen size:
private int width; private int height; private void createBubble() { WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); width = (size.x)/2; height = (size.y)/2; x = width; y = height; diameter = 100; bubble = new ShapeDrawable(new OvalShape()); bubble.setBounds(x, y, x + diameter, y + diameter); bubble.getPaint().setColor(0xff74AC23); }
This requires API 13; if you'd rather stick with a lower API, you can use the
getWidth() and
getHeight() methods instead, which are now deprecated.
You'll also notice that the bubble drifts off the screen. Experiment with the code a bit yourself (log lines may be helpful) to find a way of avoiding that. You could also use the z value of the SensorEvent (
event.values[2]) to refine the movement of the bubble a bit further. As ever, the more you play around with the code yourself, the more you'll learn about how it all works.
Sheila Wambui Said:
Very interesting..............awesome work!!!
|
http://www.linux.com/learn/tutorials/703911-2d-drawing-with-android-motion-sensors
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Welcome to LLVM! In order to get started, you first need to know some basic information.
First, LLVM comes in two pieces. The first piece is the LLVM suite. This contains all of the tools, libraries, and header files needed to use the low level virtual machine. It contains an assembler, disassembler, bytecode analyzer, and bytecode optimizer. It also contains a test suite that can be used to test the LLVM tools and the GCC front end.
The second piece is the GCC front end. This component provides a version of GCC that compiles C and C++ code into LLVM bytecode. Currently, the GCC front end is a modified version of GCC 3.4 (we track the GCC 3.4 development). Once compiled into LLVM bytecode, a program can be manipulated with the LLVM tools from the LLVM suite.
Here's the short story for getting up and running quickly with LLVM:
Specify the full pathname of where the LLVM GCC frontend is installed.:
The LLVM suite may compile on other platforms, but it is not guaranteed to do so. If compilation is successful, the LLVM utilities should be able to assemble, disassemble, analyze, and optimize LLVM byte:
There are some additional tools that you may want to have when working with LLVM:
If you want to make changes to the configure scripts, you will need GNU autoconf (2.57 or higher), and consequently, GNU M4 (version 1.4 or higher). You:
LLVM is very demanding of the host C++ compiler, and as such tends to expose bugs in the compiler. In particular, several versions of GCC crash when trying to compile LLVM. We routinely use GCC 3.3.3 and GCC 3.4.0 and have had success with.3.2: This version of GCC suffered from a serious bug which causes it to crash in the "convert_from_eh_region_ranges_1" GCC function. cfrontend/platform/llvm-gcc.
In order to compile and use LLVM, you have access to our CVS repository, you can get a fresh copy of the entire source code. All you need to do is check it out from CVS specify a label. The following releases have the following label:
If you would like to get the GCC C front-end.
If the main CVS server is overloaded or inaccessible, you can try one of these user-hosted mirrors:
Before configuring and compiling the LLVM suite, you need to extract the LLVM GCC front end from the binary distribution. It is used for building the bytecode libraries later used by the GCC front end for linking programs, and its location must be specified when the LLVM suite is configured.
To install the GCC front end, do the following:
If you are using Solaris/Sparc or MacOS X/PPC, you will need to fix the header files:
cd cfrontend/platform
./fixheaders
The binary versions of the. This is not for the faint of heart, so be forewarned.
Once checked out from the CVS repository, the LLVM suite source code must be configured via the configure script. This script sets variables in:. known broken version of GCC to compile LLVM with.!
One useful source of information about the LLVM source base is the LLVM doxygen documentation available at. The following is a brief introduction to code layout:
Every directory checked out of CVS will contain a CVS directory; for the most part these can just be ignored. libraries which are compiled into LLVM byte.
- gccld
- gccld links together several LLVM bytecode files into one bytecode file and does some optimization. It is the linker invoked by the GCC frontend when multiple .o files need to be linked together. Like gccas, the command line interface of gccld is designed to match the system linker, to aid interfacing with the GCC frontend.
This directory contains utilities for working with LLVM source code, and some of the utilities are actually required as part of the build process because they are code generators for parts of LLVM infrastructure.
#include <stdio.h> int main() { printf("hello world\n"); return 0; }
Next, compile the C file into a LLVM bytecode file:
% llvmgcc.
Run the program. To make sure the program ran, execute one of the following commands:
% ./hello
or
%:
|
http://www.llvm.org/releases/1.3/docs/GettingStarted.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
#include <fam.h> extern int FAMOpen(FAMConnection* fc); extern int FAMOpen2(FAMConnection* fc, const char* appName); extern int FAMClose(FAMConnection* fc); extern int FAMMonitorDirectory(FAMConnection *fc, char *filename, FAMRequest* fr, void* userData); extern int FAMMonitorFile(FAMConnection *fc, char *filename, FAMRequest* fr, void* userData); int FAMSuspendMonitor(FAMConnection *fc, FAMRequest *fr); int FAMResumeMonitor(FAMConnection *fc, FAMRequest *fr); int FAMCancelMonitor(FAMConnection *fc, FAMRequest *fr); int FAMNextEvent(FAMConnection *fc, FAMEvent *fe); int FAMPending(FAMConnection* fc); typedef struct { int fd; } FAMConnection; #define FAMCONNECTION_GETFD(fc) (fc->fd) typedef struct { int reqnum; } FAMRequest; enum FAMCodes { FAMChanged=1, FAMDeleted=2, FAMStartExecuting=3, FAMStopExecuting=4, FAMCreated=5, FAMMoved=6, FAMAcknowledge=7, FAMExists=8, FAMEndExist=9 }; typedef struct { FAMConnection* fc; FAMRequest fr; char hostname[MAXHOSTNAMELEN]; char filename[NAME_MAX]; void *userdata; FAMCodes code; } FAMEvent; extern int FAMErrno; extern char *FamErrlist[];
FAM comes in two parts: famd, the daemon that listens for requests and provides notifications, and libfam, a library that client applications can use to communicate with FAM.
libfam's routines are found in libfam.a, which is loaded if the option -lfam is used with cc or ld.
An application calls routines described here to establish a list of files for famdto monitor. famdgenerates events on a socket to communicate with the application. The famd process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.
The FAMConnection data structure is created when opening a connection to famd. Subsequently it is passed into all FAM procedures. This structure has all the information in it to communicate to fam.
Use the macro FAMCONNECTION_GETFD to access the file descriptor inside the FAMConnection, rather than accessing it directly.
The FAMRequest Structure
When famd is called on to monitor a file, it passes back a FAMRequest structure. This structure uniquely identifies the request so that it may be cancelled, using FAMCancelMonitor or suspended, using FAMSuspendMonitor.
The FAMEvent Structure
Changes to files and directories are encoded in the FAMEvent structure. The code field of this structure contains one of the following enumeration constants:
If a FAM event applies to a file or directory being monitored, the FAMEvent's filename field contains the full pathname that was passed to famd. If an event applies to an entry in a monitored directory, the filename field contains the relative path only. For example, if the directory /tmp/xyzzy were monitored, and the file /tmp/xyzzy/plugh were deleted, a FAMDeleted event would be generated containing "plugh" in filename. If the directory itself were deleted, filename would contain "/tmp/xyzzy".
FAMOpen, FAMClose
The application opens a connection to famd by calling FAMOpen. FAMOpen initializes the FAMConnection structure passed in to it and returns 0 if successful, otherwise -1. The parameter appName of FAMOpen2 should be set to the name of your application. The FAMConnection structure is passed to all subsequent FAM procedure calls.
FAMClose frees resources associated with files still being monitored and closes a famd connection. It returns 0 if successful and -1 otherwise.
FAMMonitorDirectory, FAMMonitorFile
FAMMonitorDirectory and FAMMonitorFile tell famd to start monitoring a directory or file, respectively. The parameters to this function are a FAMConnection (initialized by FAMOpen), a FAMRequest structure, a filename and a user data pointer. The FAMRequest structure is modified to subsequently identify this request. When the file or directory changes, a FAM event structure will be generated. The application can retrieve this structure by calling FAMNextEvent (see description under FAMNextEvent).
FAMMonitorDirectory monitors changes that happens to the contents of the directory (as well as the directory file itself); FAMMonitorFile monitors only what happens to a particular file. Both routines return 0 if successful and -1 otherwise.
The filename argument must be a full pathname.
FAMSuspendMonitor, FAMResumeMonitor
FAMSuspendMonitor temporarily suspends monitoring of files or directories. This is useful when an application is not displaying information about files, when it is iconified, for example. FAMResumeMonitor signals famd to start monitoring the file or directory again. Changes which occur while monitoring is suspended are enqueued and delivered when monitoring is resumed.
Both of these routines take a FAMConnection and a FAMRequest structure. The FAMRequest Structure is returned from the FAMMonitorFile or FAMMonitorDirectory routines and return 0 if successful and -1 otherwise.
Because famd runs as an asynchronous process, FAMNextEvent may return a few events regarding a given request after that request has been suspended.
FAMCancelMonitor
When an application is finished monitoring a file or directory, it should call FAMCancelMonitor. This routine will signal famd not to monitor this directory anymore. The FAMRequest structure is returned from the FAMMonitorFile or FAMMonitorDirectory routines. FAMCancelMonitor returns 0 if successful and -1 otherwise.
FAMPending, FAMNextEvent
FAMPending returns 1 if an event is waiting and 0 if no event is waiting. It also returns 1 if an error has been encountered. This routine returns immediately to the caller.
FAMNextEvent will get the next FAM event. If there are no FAM events waiting, then the calling application blocks until a FAM event is received. If blocking is not desirable, call FAMPending before FAMNextEvent, and only call FAMNextEvent when FAMPending says an event is available.
There are two ways to for applications to receive FAM events:
1. The Select approach - The application selects on the file
descriptor returned from FAMOpen, in the FAMConnection structure.
When this file descriptor becomes active, the application calls
FAMPending to determine whether a complete event is ready, and
FAMNextEvent to retrieve the pending FAM event.
2. The Polling approach - The application calls FAMPending
periodically (usually when the system is waiting for input).
When FAMPending returns 1, the application calls FAMNextEvent to
retrieve the pending FAM event.
FAMNextEvent reads any information that is on the famd socket, and returns it to the application in the form of a FAMEvent.
FAMNextEvent returns 1 if successful and -1 otherwise.
FAMNextEvent may not initialize the FAMEvent's filename field for FAMEndExist and FAMAcknowledge events. Use the request number to determine the file or directory to which those events refer.
FAMErrno and FamErrlist are not set when errors occur.
When a shell script is run, notification is generated for the shell executing the script.
Each process is limited to 1000 active requests at a time.
When using the Linux DNotify kernel monitor, a file handle will be opened for each file famd is asked to monitor, meaning the file system the file resides on can not be unmounted.
|
http://www.makelinux.net/man/3/F/fam
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Download the code for this article: UnderTheHood0500.exe (264KB)
Over the years, one of the dominant themes in my columns and seminars has been the benefits of techniques that optimize your executables. Typically this means basing and binding, but might also include importing functions by ordinal or changing executable page alignment. Intuitively, these strategies should make your code load faster. However, I've always had a nagging question about this topic—namely, just how much of an improvement can be expected with these techniques? This month, I've put my money where my mouth is and come up with some concrete numbers.In this column, my goal is to measure the load time speed effects of several scenarios:
Shortly, I'll explain why the second scenario depends on the first. That is, binding your executables against DLLs that aren't loading at their preferred address is a waste of time. Binding assumes that you have a properly based system where DLLs load according to their header specification.
A Quick Review of Load Time Performance Tuning
Before getting into the performance improvement details, a quick synopsis of basing, binding, and importing by ordinal is in order. Basing is a good place to start. When creating a DLL, the linker assumes that the DLL will load at a particular address. Certain pieces of the code and data contain hardcoded addresses that are only correct if the DLL loads at the preferred address. However, at runtime it's possible that the operating system may have to load the DLL at a different memory location.
To handle the situation where the OS has to move the DLL, the linker adds base relocations to the DLL. Base relocations are addresses that require modification so that they contain the correct address for where the DLL loaded in memory. The more base relocations a DLL has, the more time the OS needs to process them and to load the DLL. A properly based DLL loads at its preferred address, and can skip processing the base relocation records.
When not given explicit directions, the Microsoft® linker creates each DLL with a preferred load address of 0x10000000. If your program uses more than one DLL of your own devising, you'll have multiple DLLs with the same preferred load address. The result is that every DLL but the first one will be relocated by the operating system at load time. This is sometimes referred to as a load address collision. However, if you intervene you'll be able to prevent this from happening.
The REBASE program that comes with Microsoft Visual Studio® and the Platform SDK is a handy tool for getting rid of load address collisions. You supply REBASE with a list of all the modules that make up your program (not counting system DLLs), and it picks new load addresses for the DLLs and modifies them accordingly.
Binding an executable builds on the premise that all DLLs can be tweaked to load at their preferred address. When you import a function from a DLL, the information necessary for the Windows® loader to find the imported function is stored in your executable. Typically, this information is the imported DLL's name and the name of the imported function. When the loader resolves an imported function, it's essentially executing the same code that GetProcAddress uses.
Normally at startup time, the loader spins through all the imported functions and looks up their addresses. However, if the imported DLLs don't change from run to run, the addresses that the loader gets back don't change either. An easy optimization is to write the target function's address to the importing executable, which is exactly what the BIND program does.
Normal Win32® executables have two identical copies of the information needed to look up an imported function. One is called the import address table (IAT), while the other is called the import name table. kosher,.
BIND.EXE is the most well-known way to bind an executable. However, it optimizes your executables based upon your system DLLs. If you distribute your program to users, they probably will have different system DLLs, so you'll want to bind your executables on their system. The Windows Installer has the BindImage action, which looks pain-free to use (although I must confess I've never written an installation script). Alternatively, you can use the API BindImageEx that's part of IMAGEHLP.DLL.
The final performance optimization under the microscope this month is importing by ordinal. Normally when you import a function, your binary contains the name of the imported functions. When the Win32 loader looks up the imported names, it has to do string comparisons to match the names you're importing to the names exported by the DLLs you're importing from.
When a Portable Executable binary exports functions, it contains an array of offsets to the exported functions. When you import by ordinal, the importing binary contains an array index (here, called the ordinal) into this array. This method of finding the imported function's address is a simple array lookup, so it's very fast. Importing by name is a lot more work, since the Win32 loader takes the name and does a search to find the corresponding ordinal value. From there, the loader continues as if you had specified an ordinal in the first place. Importing by name just adds an additional layer of code on top of importing by ordinal.
So why does Win32 allow importing and exporting by name? There's a variety of reasons, but two immediately come to mind. First, it can be a pain to keep the same export ordinal assigned to a given API if its DLL evolves over time, as the Win32 system DLLs tend to do. Keeping track of hundreds of functions in a .DEF file can be tedious. In addition, there's more than just one KERNEL32.DLL; there's one for Windows 2000, one for Windows 98, and so on. Second, exporting by name allows you to use the function's name with GetProcAddress, rather than its ordinal value. If you dump a random selection of import libraries from the Platform SDK or Visual Studio, you'll find that most DLLs export by name, but a few export by ordinal.
How do you import and export by ordinal? The importing part is actually done automatically for you by the Microsoft linker. However, in exchange you must export the APIs by ordinal. When the linker generates the import library corresponding to a DLL, it generates import records that will tell the linker how the APIs should be imported. The best way to export by ordinal is to explicitly tell the linker through a .DEF file. For instance, in a .DEF file, you'd have:
EXPORTS
MyExportedAPI @1
If you don't use the @1 modifier, the Microsoft linker exports the API by name.
Besides the faster load time associated with importing and exporting by ordinal, there's another more subtle benefit. When exporting an API by ordinal, you can tell the linker not to store the exported API name in the exporting DLL. This means a smaller export section, and potentially a smaller binary with less data to demand page in. To eliminate the API name, use the NONAME modifier when exporting by ordinal.
EXPORTS
MyExportedAPI @1 NONAME
If you look at MFC42.DLL, you'll see that it exports almost all of its 6000+ APIs by ordinal, and with the NONAME modifier. Imagine the added bulk if MFC42.DLL had to store all 6000 mangled C++ names in its exports!
Creating the Optimization Tests
To test the effects of proper basing, binding, and importing by ordinal, I wrote a program called MakeLoadTimeTest.EXE that generates the program to be benchmarked. The program I created allows me to easily tweak things like the number of imported functions, how many DLLs it calls, and the number of relocations each DLL has. The source for MakeLoadTimeTest is in this month's download files.
The MakeLoadTimeTest.CPP code isn't particularly pretty. However, you don't have to read it too closely, since the things you might want to change are isolated at the top—particularly these three lines:
const unsigned nDLLs = 10;
const unsigned nExportedFunctions = 100;
const unsigned nGlobalVariablesPerFunction = 5;
Based on these constants, the generated program (LoadTimeTest) will import 10 DLLs (in addition to KERNEL32.DLL). Each of these DLLs will export 100 functions, and the main executable will import all 100 functions. Finally, each exported function references five global variables. Why reference a global variable? It's an easy way to force a base relocation to be generated. The more base relocations, the more work the loader needs to do when a DLL doesn't load at its preferred address.
Figure 1 shows the code generated for one exported function. It starts out with five global variable declarations (for example, g_var_n2_0). Next is a #ifdef block that lets you decide at compile time whether the function is exported by name or by ordinal. Finally, the function itself (in this case, LoadTimeDLL_10_func_2) simply stores a value into previously declared variables. Why the funny variable and function names? The numbers at the end of the names make them all unique, so I avoid naming collisions.
void * g_var_n2_0;
void * g_var_n2_1;
void * g_var_n2_2;
void * g_var_n2_3;
void * g_var_n2_4;
#ifdef ORDINAL_EXPORTS
#pragma comment( linker, "/EXPORT:_LoadTimeDLL_10_func_2,@2,NONAME")
#else
#pragma comment( linker, "/EXPORT:_LoadTimeDLL_10_func_2")
#endif
extern "C" void LoadTimeDLL_10_func_2(void)
{
g_var_n2_0 = LoadTimeDLL_10_func_2;
g_var_n2_1 = LoadTimeDLL_10_func_2;
g_var_n2_2 = LoadTimeDLL_10_func_2;
g_var_n2_3 = LoadTimeDLL_10_func_2;
g_var_n2_4 = LoadTimeDLL_10_func_2;
}
Figure 1 A LoadTimeTest Function
As for the LoadTimeTest executable, it only needs a simple function main that references all the functions exported by the generated DLLs. The entire function is over 1000 lines long, but here's the relevant snippet:
#include "LoadTimeTest.H"
#include <windows.h>
int main(int argc)
{
TerminateProcess( GetCurrentProcess(), 0 );
LoadTimeDLL_1_func_1();
LoadTimeDLL_1_func_2();
LoadTimeDLL_1_func_3();
LoadTimeDLL_1_func_4();
// ...
}
You might be wondering why I used the TerminateProcess call. In an ideal world, I would be able to time just how long it takes to load my target process, right up to the point where its entry point is invoked. However, I couldn't come up with a simple way to do exactly this.
The hack I eventually decided on is to make the main function call TerminateProcess. This kills the process immediately without sending the DLL_PROCESS_DETACH notifications to the DLLs. In addition, because I don't actually call all the generated APIs (such as LoadTimeDLL_1_func_1), I don't incur the overhead of demand paging the code in. However, because I referenced all the generated exported functions in function main, the loader is forced to load the DLLs and potentially apply the base relocations.
Besides the code generator (MakeLoadTimeTest), and the generated program (LoadTimeTest), there's one more program in this benchmarking suite. The LoadTimer executable runs the LoadTimeTest program and times how long it takes to execute. Because Windows is a preemptive multitasking system, I expended a fair amount of effort to get fairly reliable timing information. The source code in the download files contains all the details, but it's worth summarizing here.
For starters, LoadTimer doesn't rely on a single run of LoadTimeTest. The first time LoadTimeTest runs, disk overhead adds to its load time. Subsequent runs are usually faster because the operating system has cached the pages from the EXE and DLLs. I time 30 invocations of LoadTimeTest and use the fastest run—the one with the least amount of external overhead from factors such as thread switching and interrupt processing.
In order to minimize the overhead of these external events, LoadTimer sets its priority to REALTIME_PRIORITY_CLASS. In addition, when it starts LoadTimeTest.EXE, the code specifies REALTIME_PRIORITY_CLASS for the process. This ensures that both the CreateProcess code executed in the LoadTimer process, as well as the code in the LoadTimeTest process, are run with the highest possible priority. As a result, the effect of external happenings should be minimized.
For the timing, I used the QueryPerformanceCounter API. I originally had tinkered with using the x86 architecture's RDTSC instruction, which can be as accurate as a single CPU clock cycle. However, it requires knowing the CPU's speed to calculate an actual time. While you can read the CPU's speed from the registry in Windows NT® (HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\ System\CentralProcessor\0), this number isn't exact. For instance, on my 550Mhz machine, the registry reports a speed of 548Mhz. (Who can I sue for missing 2Mhz ?) In the end, the granularity of QueryPerformanceCounter seemed perfectly adequate for the durations under consideration.
To make my benchmark code flexible, I made LoadTimer usable on any program that will exit on its own without user intervention. LoadTimer takes a command-line argument, specifying the file name to run. In my test, the command-line argument was LoadTimeTest.EXE.
The LoadTimeTest Benchmark Process
Here are the steps needed to reproduce my results from the code files in the download. First, build MakeLoadTimeTest and LoadTimer from the project files. Next, run MakeLoadTimeTest.EXE. The results will be 11 .CPP and 11 .H files. Running the BuildLoadTimeTest.BAT file compiles these files into LoadTimeTest.EXE and 10 associated DLLs. If you specify "ORDINAL" as the argument to BuildLoadTimeTest.BAT, LoadTimeTest.EXE imports the APIs by ordinal; otherwise, they're imported by name.
If you look at BuildLoadTimeTest.BAT, you'll see that it uses the linker defaults for the 10 DLLs. Thus, all of the generated DLLs will have the same preferred load address: 0x10000000. This is intentional, as it starts the benchmark with nine DLLs that will be relocated at runtime.
Now, on to the actual testing. First, run the command
LoadTimer.EXE LoadTimeTest.EXE
several times, and record the lowest time. This is the worst-case-scenario timing.
Now, let's fix the problem of all those DLLs needing to be relocated. Run the RebaseLoadTimeTest.BAT file, which uses REBASE.EXE on the EXE and the 10 generated DLLs, so that each one has a unique load address. Rerun the timing sequence, and record the lowest time. This gives you a feel for how much rebasing can affect loading times.
Now that the EXE and all the DLLs are loading at their preferred load address, it's worthwhile to see what additional gains can be had by binding them. Run BindLoadTimeTest.BAT and then rerun the timing sequence, again recording the lowest time.
At this point, you should have three load times: the default time without any intervention, the time after rebasing the executables, and the time after basing and binding. To see the effect of importing by ORDINAL, rerun the previous tests, but with one change: at the beginning specify "ORDINAL" as the argument when running BuildLoadTimeTest.BAT.
LoadTimeTest Results
Before getting to the actual numbers, let me first say that I was amazed at how fast programs can load. I intentionally created LoadTimeTest.EXE to make a lot of work for the Win32 loader. It has a fair number of DLLs and lots of exported functions and relocations. Even under the slowest scenario, my machine still loaded the program under Windows 2000 in less than 1/50th of a second. If your program takes a long time to load, don't blame the loader. The problem is almost certainly that somebody's initialization code is taking too long.
Figure 2 shows the results I obtained. The test machine was a Dell XPS T550, a single Pentium III CPU running at 550Mhz. The only visible process running (other than the Explorer shell) was a command prompt. The tests were run from a FAT16 partition so that I could test on both Windows 2000 and Windows 9x.
================================================
Windows 2000 By Name, FAT16
Default:
Fastest time: 58286 ticks, 0.016283 seconds
Ticks: 58286
Ticks/second: 3579545
Based:
Fastest time: 52611 ticks, 0.014698 seconds
Ticks: 52611
Ticks/second: 3579545
Bound:
Fastest time: 49006 ticks, 0.013691 seconds
Ticks: 49006
Ticks/second: 3579545
================================================
Windows 2000 By Ordinal, FAT16
Default:
Fastest time: 57824 ticks, 0.016154 seconds
Ticks: 57824
Ticks/second: 3579545
Based:
Fastest time: 50609 ticks, 0.014138 seconds
Ticks: 50609
Ticks/second: 3579545
Bound:
Fastest time: 49251 ticks, 0.013759 seconds
Ticks: 49251
Ticks/second: 3579545
================================================
Windows 98 SE By Name, FAT16
Default:
Fastest time: 32738 ticks, 0.027438 seconds
Ticks: 32738
Ticks/second: 1193180
Based:
Fastest time: 30150 ticks, 0.025269 seconds
Ticks: 30150
Ticks/second: 1193180
Bound:
Fastest time: 28944 ticks, 0.024258 seconds
Ticks: 28944
Ticks/second: 1193180
================================================
Windows 98 SE By Ordinal, FAT16
Default:
Fastest time: 31812 ticks, 0.026662 seconds
Ticks: 31812
Ticks/second: 1193180
Based:
Fastest time: 29569 ticks, 0.024782 seconds
Ticks: 29569
Ticks/second: 1193180
Bound:
Fastest time: 29513 ticks, 0.024735 seconds
Ticks: 29513
Ticks/second: 1193180
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
================================================
Windows 2000 By Name, Compressed NTFS
Default:
Fastest time: 61087 ticks, 0.017066 seconds
Ticks: 61087
Ticks/second: 3579545
Based:
Fastest time: 53834 ticks, 0.015039 seconds
Ticks: 53834
Ticks/second: 3579545
Bound:
Fastest time: 50388 ticks, 0.014077 seconds
Ticks: 50388
Ticks/second: 3579545
================================================
Windows 2000 By Ordinal, Compressed NTFS
Default:
Fastest time: 58607 ticks, 0.016373 seconds
Ticks: 58607
Ticks/second: 3579545
Based:
Fastest time: 51755 ticks, 0.014459 seconds
Ticks: 51755
Ticks/second: 3579545
Bound:
Fastest time: 50204 ticks, 0.014025 seconds
Ticks: 50204
Ticks/second: 3579545
Figure 2 LoadTimeTest Results
You can slice the data in a variety of ways, but here are the numbers I found interesting. On Windows 2000, properly basing the DLLs improved the load time by roughly 12 percent. Basing and binding the EXE and the DLLs improved the load time by around 18 percent. Importing by ordinal versus importing by name provided a 4 percent improvement. On Windows 98, Second Edition, properly basing the DLLs improved the load time by roughly 8 percent. Basing and binding the EXE and the DLLs improved the load time by around 12 percent. Importing by ordinal versus importing by name provided a mere 2 percent improvement.
Importing by name instead of ordinal doesn't affect the load time very much when the program is properly based and bound. When everything is properly configured, the loader can read the address of the imported function directly from the DLL doing the importing. The loader doesn't need to bother looking up names or indexing into arrays to get the address of the function.
Random Observations
While working through the code, I was thinking about the effects of DLLs loading at a nonpreferred address. In my test code, each of the DLLs exports 100 APIs, yet those APIs are never called. Because of demand paging, it's conceivable that the pages containing those APIs might not be brought into memory. As such, the overhead of applying the base relocations might not apply. With this in mind, I contacted a performance expert in Microsoft research. He told me that under Windows 9x, my hypothesis about not needing to apply the base relocations was correct.
However, under Windows NT and Windows 2000 the pages are set temporarily to read/write, are modified, and then returned to their original permission. As a result, any pages modified in this way are no longer shared between processes. Essentially, under Windows NT and Windows 2000, any executable that does not load at its preferred load address will have all of its code and data demand paged in when the executable first loads.
On a different note, I was surprised at the results of QueryPerformanceFrequency under Windows 2000. Looking at Figure 2, notice that under Windows 2000 the timer operates at 3.57Mhz. This is exactly three times faster than the 1.19 Mhz frequency used on Windows 98. If you're a PC old-timer, you may recall that motherboards traditionally have a 1.19Mhz oscillator that drives the 8254 chip.
Intrigued, I ran my tests on a Pentium Pro 200Mhz running Windows 2000 and got the 1.19Mhz frequency. I then ran LoadTimer on some dual processor machines and found that the frequency matched the CPU speed. The conclusion I've drawn from this is that Windows 2000 observes what the motherboard is capable of doing and uses the best available timer frequency for the QueryPerformanceXXX APIs. Yes, I admit to being a nerd and spending way too much time on this minor detail, but I enjoyed the experimentation and the opportunity to ponder things at the hardware level.
Matt Pietrek performs advanced research for the NuMega Labs of Compuware Corporation, and is the author of several books. His Web site, at, has a FAQ page and information on previous columns and articles.
More MSDN Magazine Blog entries >
Browse All MSDN Magazines
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
|
http://msdn.microsoft.com/en-us/magazine/bb985014.aspx
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Unit testing RESTful web services is rather complex. Ideally, the services are tested in isolation before being packaged as a service. However, sometimes people will want to test the "finished" or "integrated" web services technology stack because (I suppose) they don't trust their lower-level unit tests.
Or they don't have effective lower-level unit tests.
Before we look at testing a complete RESTful web service, we need to expose some underlying principles.
Principle #1. Unit does not mean "class". Unit means unit: a discrete unit of code. Class, package, module, framework, application. All are legitimate meanings of unit. We want to use stable, easy-to-live with unit testing tools. We don't want to invent something based on shell scripts running CURL and DIFF.
Principle #2. The code under test cannot have any changes made to it for testing. It has to be the real, unmodified production code. This seems self-evident. But. It gets violated by folks who have badly-designed RESTful services.
This principle means that all the settings required for testability must be part of an external configuration. No exceptions. It also means that your service may need to be refactored so that the guts can be run from the command line outside Apache.
When your RESTful Web Service depends on third-party web service(s), there is an additional principle.
Principle #3. You must have formal proxy classes for all RESTful services your app consumes. These proxy classes are going to be really simple, since they must trivially map resource requests to proper HTTP processing. In Python, it is delightfully simple to create a class where each method simply uses httplib (or http.client in Python 3.2) to make a GET, POST, PUT or DELETE request. In Java you can do this, also, it's just not delightfully simple.
TestCase Overview
Testing a RESTful web service is a matter of starting an instance of the service, running a standard unit testing TestCase, and then shutting that instance down. Generally this will involve setUpModule and tearDownModule (in Python parlance) or a @BeforeClass and @AfterClass (in Java parlance).
The class-level (or module-level) setup must start the application server being tested. The server will start in some known initial condition. This may involve building and populating known database, too. This can be fairly complex.
When working with SQL, In-memory databases are essential for this. SQLite (Python) or (Java) can be life-savers because they're fast and flexible.
What's important is that the client access to the RESTful web service is entirely under control of a unit testing framework.
Mocking The Server
A small, special-purpose server must be built that mocks the full application server without the endless overheads of a full web server.
It can be simpler to mock a server rather than to try to reset the state of a running Apache server. TestCases often execute a sequence of stateful requests assuming a known starting state. Starting a fresh mock server is sometimes an easy way to set this known starting state.
Here's a Python script that will start a server. It writes the PID to a file for the shutdown script.
import http.server
import os
from the_application import some_application_feature
class AppWrapper( http.server.BaseHTTPRequestHandler ):
def do_GET( self ):
# Parse the URL
id= url.split("/")[-1]
# Invoke the real application's method for GET on this URL.
body= some_application_feature( id )
# Respond appropriately
self.send_response( 200, body )
... etc ...
# Database setup before starting the service.
# Filesystem setup before starting the service.
# Other web service proxy processes must be started, too.
with open("someservice.pid","w") as pid_file:
print( os.getpid(), file=pid_file )
httpd = http.server.HTTPServer("localhost:8000", AppWrapper)
try:
httpd.serve_forever()
finally:
# Cleanup other web services.
Here's a shutdown script.
import os, signal
with open("someservice.pid") as pid_file:
pid= int( pid_file.read() )
os.kill( pid, signal.CTRL_C_EVENT )
These two scripts will start and stop a mock server that wraps the underlying application.
When you're working in Java, it isn't so delightfully simple as Python But it should be respectably simple. And you have Jython Java integration so that this Python code can invoke a Java application without too much pain.
Plus, you can always fall further back to a CGI-like unit testing capability where "body= some_application_feature( id )" becomes a subprocess.call(). Yes it's inefficient. We're just testing.
This CGI-like access only works if the application is very well-behaved and can be configured to process one request at a time from a local file or from the command line. This, in turn, may require building a test harness that uses the core application logic in a CGI-like context where STDIN is read and STDOUT is written.
|
http://slott-softwarearchitect.blogspot.com/2012/09/restful-web-service-testing.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Branching Logic vs. Guard Logic When It Comes To Function Control Flow
When it comes to Functions in computer programming, the Return statement is pretty badass. When your program's control flow hits a return statement, it completely exits out of the current context, halting the execution of the function. In the past few weeks, since I've started playing with Node.js (a heavily asynchronous environment), I've noticed myself starting to use the return statement in lieu of the branching whenever possible. And, I've been loving it.
I don't feel like a classically trained computer programmer (despite the fact that I went to school for computer science). As such, I am quite sure that I misuse terminology all the time. So, for the sake of this blog post only, let's just get on the same page for a few concepts:
- Branching Logic - This is the term I am going to use to indicate two or more possible control flows within a function that may each terminate with a Return statement (ie. IF-ELSE).
- Guard Logic - This is the term I am going to use to indicate a single branch in control flow that either terminates with a return statement or returns to the primary control flow of the function.
In the past, I think I would err on the side of branching. But, in recent times, I've started to use guard-style logic and I'm actually finding it much easier to read. Instead of thinking about my logic in terms of two separate-but-equal paths (ie branching), guard logic allows me to think of a single primary path with multiple exit opportunities.
To illustrate the difference, take a look at this function:
NOTE: I am leaving many of the critical tag attributes out of this code so as to draw attention directly to the control flow aspects.
- <cffunction name="doSomethingWithBranching">
- <!--- Define arguments. --->
- <cfargument name="style" />
- <!--- Check to see if the value indicates branching. --->
- <cfif (arguments.style eq "branching")>
- <cfreturn true />
- <cfelse>
- <cfreturn false />
- </cfif>
- </cffunction>
As you can see, the control flow of this function uses a branching IF-ELSE statement. This allows both branches to exit in a return statement.
Now, take a look at this function, which accomplishes the same exact intent with guard-style logic:
- <cffunction name="doSomethingWithGuard">
- <!--- Define arguments. --->
- <cfargument name="style" />
- <!--- Check to see if the value indicates guard. --->
- <cfif (arguments.style eq "guard")>
- <cfreturn true />
- </cfif>
- <!---
- If we have made it this far then no other conditions
- held true. As such, simply return false.
- --->
- <cfreturn false />
- </cffunction>
As you can see, both versions of the function have two return statements. However, in the former, those return statements both reside in a separate branch of logic; in the latter, only one of the return statements exists in a branch - the other remains in the primary control path of the function.
Given that both of these approaches yield the same outcome, I believe I am favoring guard-style control flow because it's easier to mentally model. When it comes to branching, you have to juggle at least 3 things - the primary control of the function and at least two branches (IF and ELSE). With guard-style statements, you only need to juggle 2 things - the primary control flow of the function and the IF statement. This means that at any time, you are either in or out of the primary control flow of the function. And, that's exactly the kind of duality that my brain can handle more efficiently.
So what would you do in the case of three possible exits?
Would you do:
<cfif x = y>
<cfreturn 1>
</cfif>
<cfif x = z>
<cfreturn 2>
</cfif>
<cfreturn many nested if/else statements, a bit of refactoring is probably in order anyway...
@Jessie,
Honestly, yeah, that might be what I would do. Of course, it always depends on a bit of context. Typically, the innards of the branching is more complex than a single return statement; in those cases, I do find the guard-style logic much easier to read and understand.
But, to be fair, if all I had were conditions with single return statements, I'd probably just stick to IF/ELSE; I don't think I'd get much readability benefit from the guard-style approach.... not until the branching logic got more complex.
@Seb,
Yeah, the nested IF statements is definitely one of those things that you can start to cut down on if you leverage the Return statement as more of a primary control flow entity.
Food for thought is always good - I am finding that I am constantly tweaking the methodology with which I code.
@Jessie - cfswitch with defaultcase?
@Michael,
I still tend to use use CFSwitch cases when dealing with including many different templates (depending on a value - ie. an "action" variable). points, especially when heavily nested, to be confusing. If possible, I try to use a single exit point at the end of the function and leverage variables to determine how to exit.
For example:
<cffunction name="doSomething">
<cfargument name="style" />
<cfset var result = false />
<cfif (arguments.style eq "guard")>
<cfset result = true />
</cfif>
<cfreturn result />
</cffunction>
Ben, good stuff. For "branching" how about "procedural"? I was given a lecture by a bad mannered client with a computing degree, and this is the only part I remember.
@Scott,
I tried to keep the examples simple in order to demonstrate the difference between the two; I can definitely see the "betterness" of either approach not coming through. And, as you say, it can be very subjective - for me, it's a mental modeling limitation; I can simply keep guard statements in my head more effectively.
As far as the single return statement, I have heard of this before; though, I am not sure what the original intent behind this concept was.
@Scott,
Usually guard clauses are used when the function does normally does something non-trivial, but for some inputs a trivial result can be returned.
<cffunction name="sluggingPercentage">
<cfif variables.cachedsluggingPercentage neq "">
<cfreturn cachedsluggingPercentage>
</cfif>
<cfif arrayLen(variables.atBats) eq 0>
<cfreturn 0>
</cfif>
<!---
This part shall be left to the imagination, as it was during
my childhood, before the internet ruined everything.
--->
<cfreturn computedSluggingPercentage>
</cfif> excessive complexity or I really want to make the "guard" nature very clear.
All of that being said, I like your idea of putting terms to these different approaches to make the decision a little easier to see and conceptualize.
Not only that, but I think this makes an argument that I have likely been to strict in my "a function should only have a single return" philosophy.
@Steve,
I'm pretty sure I was taught at one point that functions should only have one return value. But, I honestly can't remember what the reasoning was. Just because you can see that there is a return statement doesn't necessarily mean that value contained within the return is any more clear.
Meaning, that even with a single return statement, there is no implicit value to the value. You would still have to trace the path of branching to figure out what that would be.
The nice thing to seeing a Return statement is that it very clearly indicates: "This is the last thing you have to worry about in the function."
If you have branching AND a single return value, even if you get to the bottom of the branch, you still need to keep reading through the function to see if any additional logic gets applied to the value.
Maybe that's what appeals to me it lately - the definitive ending of each branch.
One of the places I find "Guard Logic" to be useful is in my Model-Glue apps. In Model-Glue, if a certain condition is met, you can issue a statement in your controller function to add a "result" to the event object. That result ends up acting like a return statement/interrupt that skips over any of the other message broadcasts (which are calls to other controller functions to execute model code) in that event handler and goes straight to the result code. It's a nice way of avoiding unnecessary code execution when you've already reached a success or failure condition.
I guess it's fine as long as your function is short. However, multiple return points are not encouraged when I was in college. They prefer a short if block for guards and long if block for actual "Branching Logic", and then follow by a single return statement. - sort of like....
Using a struct in a standard format for all non-trivial functions lets me pass a status value and message back and makes it really easy to bubble-up error conditions.
It also makes the logic really easy to read as exception conditions are just 'thrown' out as they occur, leaving what amounts to a pretty liniar, easy to understand flow in the rest of the function.
I guess this is the 'guard logic' model, but with the added benefit of a bail-out which you can nevertheless guarantee passes through a single 'exit' point.
@Ian,
I definitely use a Try/Catch approach when it comes to developing an API control flow. Since so much is involved with APIs - credentials, input validation, format validation, return type validation, etc., there are many opportunities for errors to arise in each request. Try/Catch has been awesome for that (especially when using several different "typed" CFCatch tags).
@Henry,
I believe I was taught that also. But, I can't remember what the reasoning was.
@Brian,
That sounds cool. I don't know much about the Model-Glue framework.
Like you, I prefer what you're calling guard logic.
I REALLY like how it keeps indention down.
Although it's fallen into disfavor in recent years, another advantage of guard logic is that you can often get away with not coding braces on an immediate return:
Most folks nowadays would code
The purpose of braces is to group together MULTIPLE statements, but it seems like religion nowadays that we have to always code braces, just in case we want to add more statements in the future, I guess.
But even the most code-like-me-or-you're-uncool firebrands seem to tolerate a braceless break, continue or return as the only statement following an if.
And this is the same thing (no braces), but now you'll REALLY think I'm crazy:
I hope the code tag lines up columns the way I did when I wrote it. Isn't it REALLY easy to read? You know exactly what's going on in a glance.
*sigh* I'll get the hang of the code tag here someday, I *promise*.
3 spaces were truncated before the first 2 "return true" statements.
6 spaces were truncated before the first .onchange() in the onsubmit.
@WebManWalking,
Ha ha, sorry - I wish my Code tag was better :) I used to be more flexible; but I realize that the flexibility broke after 3 sets of 2-spaces (I didn't know if it was supposed to be three sets or 2 tabs.
While I like the guard logic, I also am a huge fan of braces to define code blocks. I personally find non-brace too hard to follow since I don't code that way. I've been so conditioned to believe that braces will be there.
I call this Short Circuit programming, as you're short circuiting the rest of the logic and taking the quickest route out of the method.
I've been using it for years and it creates VERY fast and readable code. Additionally, there are branching limitations. I've come across nasty validation logic code that consists of a ton of nested if/else statements. Coldfusion (actually java) returns an error about something to do with exceeding small int branching branching paths 128 after an upgrade to CF8. I presume it was using a signed byte to count how many branching paths, and when it reaches 128, it's just too complex. Most of that code got broken into discreet functions and short circuiting logic. Speed also drastically improved as well.
@Jim,
128 maximum branches :) Awesome. That just seems like a huge number.
It's reassuring to hear that you've been using this type of approach and are also finding it very readable. Sometimes, I get concerned that maybe its only readable because I am the one that wrote it.
@Ben,
I also use it in conjunction with formatted structs as a lazy (nay, Creative and Efficient!) way to bubble up nested error messages without relying on try catch when I don't need to.
crude example:
inside component:
inside cfm:
The 'universal' error keys in the struct only exist if Success is false (and no data will be present other than the error keys. don't want partial data. Either success, or nothing). If success is true, the data keys i expect I know will be present.
@Ben,
A more practical example: that have returns and no else because you can easily find code duplication and refactor for AOP style advice later.
ex.
function example(...) {
if (...) return true;
if (...) return true;
// compute something
return computation;
}
Both of those return statements might be candidates for refactoring into advice. If we had a bunch of nested if statements that'd be harder to notice though.
@Jim,
That's exactly the kind of stuff I am talking about.
@Elliott,
I had never even considered AOP stuff for this kind of logic; but that makes sense. Excellent point!
statements, cause thats just useless and a waste of time. I always use the guard logic, not because I read about it, it's just logic to me; one main stream down and whathever doesn't follow, get out right away.
I know you tackled this question in ColdFusion, but I just had a revelation that this could kill JS performance and jsperf confirmed it: return/assignments.
Note that a decent JS compiler may rewrite the entire function to remove the early return (or add one). And that all modern browsers are going to turn both into very efficient assembly code when the JIT kicks in. Language constructs have very little performance impact (except "with" which turns off optimizations and makes everything slow...)
@Elliott,
Math.random() probably is affecting the performance, but so is the function call itself. Branching logic has a major impact on performance this was just not a good test of it. A true test would remove the function call as well.
well write this test in C.
@Elliott,
@Elliott,
I wanted to test returns inside a function, I can't test those without paying the cost of opening a function :P. So obviously, calling a method costs far more than premature returns 'guarded logic' inside it.
Of course, some code that requires no if/then/else would be faster than some that did, so thats not relevant. If the CPU can just burn through the numbers, it would outpace having to make decisions along the way. Again, this isn't what I was looking into, I wanted to see if returning early had an impact on performance.
@Drew Your test is flawed. When doing short circuiting logic, you typically do such in a function with a high amount of comparisons such as validation of a whole form. In this case, the first instance you fail and return early, then better as you jump over comparisons that don't need to be made. When your method returns an object, you will have some default state of the object, only filling out and returning a more complete object later in the method if you need to get that far. Your test doesn't do nearly enough work to be a valid comparison.
@Drew,
I'm a bit late to this conversation; but, I think we wouldn't want to test a return vs. no-return. We're already in a use-case where we're in a function that has to return a value. As such, the case where no value is return doesn't necessarily apply.
@All,
I know this thread is old, but I've been recently making a lot of mistakes in an asynchronous workflow when I forget to use return():
Seems like a related-enough topic.
|
http://www.bennadel.com/blog/2195-branching-logic-vs-guard-logic-when-it-comes-to-function-control-flow.htm
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
02 March 2011 18:00 [Source: ICIS news]
HOUSTON (ICIS)--Here is Wednesday’s midday ?xml:namespace>
CRUDE: Apr WTI: $101.55/bbl, up $1.92; Apr Brent: $117.13/bbl, up $1.71
NYMEX WTI crude futures surged in response to geopolitical worries and to weekly EIA statistics showing a drawdown in crude and gasoline inventories. WTI topped out at $102.20/bbl before retreating.
RBOB: Apr: $3.0424/gal, up 5.90 cents
Reformulated gasoline blendstock for oxygenate blending (RBOB) broke through the $3.00/gal level on rising crude oil stockpiles and EIA data that showed US stockpiles falling by 3.6m bbl week on week.
NATURAL GAS: Apr: $3.809/MMBtu, down 6.4 cents
The front month natural gas contract picked up from Tuesday’s slide and selling continued, as two-week weather forecasts began to show much milder temperatures. Also, analysts predicted a narrow withdrawal in Thursday’s storage report.
ETHANE: up at 73.0-74.5 cents/gal
Mont Belvieu ethane prices picked up steam to start Wednesday, gaining more than 2-3 cents/gal while tracking surging crude futures.
AROMATICS: benzene up at $4.17-4.22/gal
Prompt US benzene spot prices were 2 cents/gal higher this morning, traders said. The range was up following the increase in crude on Tuesday.
OLEFINS: RGP up at 66.75 cents/lb
US Gulf refinery-grade propylene (RGP) was heard traded at 66.75 cents/lb, up more than 5 cents from deals at 61.00-61.50 cents/lb
|
http://www.icis.com/Articles/2011/03/02/9440247/noon-snapshot-americas-markets-summary.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
07 December 2012 19:35 [Source: ICIS news]
MEDELLIN, Colombia (ICIS)--Petroleos Mexicanos (Pemex) said on Friday that it must strengthen its resources through partnerships with the private sector, but the state-run oil company ruled out the possibility of privatisation.
“Public resources are no longer sufficient to develop the various entities of the state,” Pemex general director Emilio Lozoya Austin said. “We need more direct investment in cost-effective activities that generate greater added value.”
He said the need for investment and modernisation does not signify privatisation.
“?xml:namespace>
The "Pact for
However, the three-party deal precludes privatisation of Pemex installations.
Pemex has been dogged in recent years by accusations of corruption and inefficiency.
In May this year, Mexican opposition legislators accused Pemex of hiding $30bn (€23bn) of losses.
“My administration will have zero tolerance for behaviour that falls short of the legal framework,”
He also called for a more positive relationship with the company’s trade-union members.
Local media reported last week that
“We will address their concerns in an orderly and efficient manner,”
The Mexican president also appointed Pedro Joaquin Coldwell as the country's new energy secretary.
(
|
http://www.icis.com/Articles/2012/12/07/9622414/pemex-pushes-private-sector-partnerships-rules-out.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Hi,
Is there a way in python to convert the html response to a json(non-api websites). By html response I mean the response from any websites.Is there some library functions/modules for doing that?
Thanks
from urllib2 import urlopen
r = urlopen('')
bhishan wrote:I plan to do this
Return to General Discussions
Users browsing this forum: Bing [Bot] and 2 guests
|
http://www.python-forum.org/viewtopic.php?f=10&t=11999
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Hiber
Delete Query using HQL Can we write 'AND' with 'WHERE' clause in delete query using HQL?
For example:
delete from table name
where field1... a look at the following link:
Hibernate Delete Query
In this section we will discuss how to delete record of table using HQL
HQL
HQL What is the HQL in hibernate ? Explain the use of HQL.
Hi Friend,
Please visit on this link.......
Hibernate Query Language
delete row from a table using hibernate
delete row from a table using hibernate //code in java file
String hql="delete from CONTACT c where ID=6";
Query query=session.createQuery(hql);
//error when executing above code
CONTACT is not mapped-HQL subquery - Hibernate
Hibernate-HQL subquery Hi,
I need to fetch latest 5 records from... in HQL which should return list of "Status" type beans.Is it possible?If yes... for more details
delete query problem - Hibernate
= sess. beginTransaction();
String hql = "delete from STUDENT where name = 'mitha...,
String hql = "delete from Insurance insurance where id = 2";
Query...delete query problem SessionFactory fact = new Configuration
Case-insensitive search using Hibernate Query Language(HQL).
Case-insensitive search using Hibernate Query Language(HQL). What is Case-insensitive search using Hibernate Query Language
database using the hibernate. Lets first write a java class to delete
a row from...
Hibernate Delete Query
... (DeleteHQLExample.java),
which we will delete a row from the insurance table using the - Hibernate
hibernate is there any tutorial using hibernate and netbeans to do a web application add,update,delete,select
Hi friend,
For hibernate tutorial visit to :
What is Hibernate Query Language (HQL)?
What is Hibernate Query Language (HQL)? Hi,
What is Hibernate Query Language (HQL)?
thanks;
import org.hibernate.Session;
import org.hibernate.*;
import...();
//Create Select Clause HQL
String SQL_QUERY ="Select...-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter
Hibernate hibernate delete query execution
Hibernate How to create Dynamic array of Objects during HQL
hibernate joins
hibernate joins how to fetch the data from multiple tables in mysql using HQL. Give me one example using joins
Hibernate Tutorial Roseindia
, HQL , criteria , transaction, tips and performance.
The online hibernate examples... Hibernate <generator> element
Using Hibernate <generator> to generate id incrementally
Hibernate Update Query
Hibernate Delete Query
Developing POJO
|
Using
Hibernate <generator> to generate id incrementally |
Hibernate
Update Query |
Hibernate
Delete Query |
Introduction to Hibernate Query... Clause |
HQL Select
Clause |
Hibernate
Count Query |
Hibernate Avg
Count distinct value in HQL.
Count distinct value in HQL. How do you count distinct value in HQL...));
}
}
Output:
Hibernate: select count(distinct employee0_.salary) as col_0_0...
Description: This example counts the number of employee having distinct salary by using
HQL Query
HQL Query Hibernate query language:
How to use a left join in Hibernate query language. Can somebody help with an example. I am getting a unexpected token error in HQL Query tool If I use joins
HIBERNATE
HIBERNATE How u connects database using hibernate 3.0? Where you have written the database configuration details
hibernate
hibernate How to know how many columns changed in a table when we are using hibern
Complete Hibernate 4.0 Tutorial
min() Function
Hibernate Named HQL Query using XML mapping...
Hibernate Application : Insert Record using Hibernate Save Method
Hibernate 4...
Hibernate Query Language (HQL)
Introduction To Hibernate Query HQL Update
In this section we will discuss HQL update with example
Hibernate Training
Learning Fundamentals of
Hibernate by using the Hibernate persistence engine.
How to persist different types of objects using the Hibernate.
How to use HQL (Hibernate Query Language)
for querying objects query - Hibernate Interview Questions
Hibernate query Hi,In my one interview i face one question that is how to write query without using hql and sql.If any body knows please give the answer thank Architecture
and
delete operations.
Hibernate uses the Java classes which represents... these operations
against database.
Hibernate manages the transactions using....
You can make the transaction aware applications using Hibernate.
Following
HQL order by.
HQL order by. HQL Order by query giving problem.
Order... into descending order you can follow the following HQL ?
String hql="Select emp FROM...();
String hql="Select emp FROM Employee emp ORDER BY name";
Query query
Hibernate - Hibernate
prog using hibernate query Hibernate update query
This will show you how to update records in hibernate!
regards
Meeya...............
hibernate............... goodevining. I am using hibernate on eclipse, while connection to database Orcale10g geting error .........driver
ARNING: SQL Error: 0, SQLState: null
31 May, 2012 8:18:01 PM
Hibernate
application is using
Hibernate to access the relational databases.
Hibernate...
Hibernate CRUD operation
HQL
Native Query
Hibernate Transactions...Hibernate
Hibernate is a framework for Java technology, which is used - Hibernate
Hibernate What is the exact difference between HQL query and Criteria and the differences between the two
Hibernate Query Language
;
Hibernate Query Language or HQL for short is extremely
powerful... be used while using
Hibernate. These are Query By Criteria (QBC) and Query BY Example... operations: HQL
allows representing SQL queries in the form of objects. Hibern Tutorials
Understanding Hibernate O/R Mapping
Hibernate Update Query
Hibernate Delete Query...Hibernate Tutorials
Hibernate is popular open source object relational mapping... to providing mapping of Java classes to database tables, Hibernate also
Complete Hibernate 3.0 and Hibernate 4 Tutorial
.
Hibernate
Session.delete() Example - Learn how to delete the entity using... instructions on using Hibernate 3.0. Hibernate
is popular open source object relational.... Hibernate also allows
you to express queries using native SQL or Java-based
hibernate - Hibernate
hibernate I have written the following program
package Hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import...();
session =sessionFactory.openSession();
//Create Select Clause HQL
String SQL
Using of Hibernate - Hibernate
Using of Hibernate I have a requirement that my table names are dynamic. For example suppose we have two different court using this system then we... friend,read for more information.
Hibernate code - Hibernate
Hibernate code how to write hql query for retriveing data from multiple tables
Hibernate Overview and Architecture
() Example - Learn how to delete the entity using
Hibernate.
The latest... Environment - Learn How you can setup development
environment using Hibernate ORM...Hibernate Overview and Architecture - Learn the basics of the Hibernate ORM
Hibernate Named HQL in Annotation
In this section, you will learn how to execute Named HQL written in Model class Annotation
Hibernate - Framework
Hibernate hi.....
how i insert,update,delete data to Insurence table using nativesql query.i m not getting the code.
thnx
hi - Hibernate
to delete a particular record using DAO.
Here I provide MyEclipse automatiically...;
}
}
}
pls let me know how to delete one particular record using this code...hi hi all,
I am new to hibernate.
could anyone pls let me know
Hibernate Tutorials
;
Using Hibernate <generator> to generate id incrementally... Hibernate Query. In this example you will learn how to use the HQL from clause... code to select the data from Insurance table using Hibernate Select Clause Tools
from hibernate mappings/ EJB
annotations
Learn how to use HQL/EJBQL query... (.hbm.xml)
generation
Installing and using Hibernate tools on eclipse...
Hibernate Tools
Hibernate Tools:
Hibernate Tool is yet another cool ORM 4.2.14.Final released
Session.delete() Example - Learn how to delete the entity using
Hibernate...
How to use Hibernate 4.2.14 in project?
If you are using the Maven build tool...
environment using Hibernate ORM framework.
Hibernate Configuration files - Learn
Hibernate:What is hibernate?
Hibernate:What is hibernate? What is hibernate?
Hibernate: -Hibernate is an Open Source persistence technology. It provides Object....
Hibernate works as a bridge between application and database.
Application Query Language
Hibernate Query Language
Introduction
to Hibernate Query Language
Hibernate Query Language or HQL for short is extremely powerful query language. HQL
Hibernate Architecture
:
The above diagram shows that Hibernate is using the
database... of the hibernate
is used to select, insert, update and delete the records form... Hibernate Architecture
web project - Hibernate
hibernate web project hi friends,very good morning,how to develop and execute web project using myeclipse ide.plz give me step-by-step procedure... links:
|
http://www.roseindia.net/tutorialhelp/comment/88231
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
V. wrote:In that case, since voting is on again, the 5 is yours
V. wrote:Which movie?
public class Naerling : Lazy<Person>{
public void DoWork(){ throw new NotImplementedException(); }
}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Lounge.aspx?msg=4476764
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
23 January 2008 10:49 [Source: ICIS news]
(updates closing share, oil and naphtha prices in paragraphs 4-9, 12 and 15)
By Jeanne Lim
SINGAPORE (ICIS news)--Asia-Pacific petrochemical stocks bounced back on Wednesday from a two-day meltdown as the US Federal Reserve’s move to cut interest rates boosted investor sentiment.
In a rare policy move outside of its ordinary meetings, the Federal Reserve cut interest rates by 75 basis points to 3.5% on Tuesday, its biggest cut in more than 23 years.
By lowering borrowing costs, such a move should help industry by boosting spending as well as lowering investment costs, and possibly stave off an ?xml:namespace>
Japanese chemical stocks ended 2-3% higher as the Nikkei 225 index closed 2% up at 12,829.06 points.
The share price of chemical major Asahi Kasei closed 2.4% higher after gaining as much as 5.4% earlier in the day while Mitsubishi Chemical and Mitsui Chemical stocks closed at 2.3% and 2.9% respectively.
The shares of Chinese state-owned refiners PetroChina and Sinopec continued their upward trend and closed 17.5% and 17.6% higher respectively as
The Standard & Poors/Australia Stock Exchange (ASX) 200 index jumped 4.4% to close at 5,412.30 points while the Stock Exchange of Thailand (SET) index recovered from earlier losses to close 2.8% higher.
In South Korea, the Korea Composite Stock Price Index (KOSPI) ended 19.4% higher but stocks of chemical majors such as LG Chemical and Hanwha Chemicals saw their stock price end 1.2-3.8% lower respectively.
SK Energy’s share price closed 3.8% lower after rising slightly in the day while Honam Petrochemical’s stock continued its rise to close higher at 3.8%.
The Federal Reserve interest rate cuts could have boosted market sentiment in
“I think the interest cuts could not remove all the concerns of the market for the time being. Particularly in the first quarter, the stock market will maintain its weak trend,” he added.
Crude oil hovered near $89/bbl, attempting to consolidate a nervous recovery after the
Asian naphtha markets picked up a little, tracking the $3/bbl rebound in crude values.
Discussion levels for second half March naphtha cargoes were heard at $831-834/tonne CFR (cost and freight)
Asian naphtha was traded at $837-839/tonne CFR Japan for second-half March open spec grades.
Some traders were, however, worried that if the
Prices fell $38/tonne on Tuesday, following the stock market meltdown.
The Asian toluene market was quiet on Wednesday following the $15/tonne erosion of offers to $905/tonne FOB (free on board)
However, traders anticipate prices to firm slightly on Wednesday on the back of stabilised crude values and modest overnight gains in the
A higher offer emerged mid morning at $920/tonne FOB
But trade was scant as the
Meanwhile, a South Korean polyethylene terephthalate (PET) producer said that there had been no effect on prices so far on steadying crude values.
“Crude will impact on raw material one month later usually. Our deals have been concluded at lower prices because bid prices are decreasing. Demand is weak,” he said.
Another southeast Asia-based orthoxylene (OX) trader added that he didn’t think that the interest rate cut would have any impact on the market.
($1 = €0.68)
Helen Lee, Prema Viswanathan and Hong Chou H
|
http://www.icis.com/Articles/2008/01/23/9094947/asia-petchem-stocks-close-higher.html
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
public class Object {
private Coord3D origin;
private double intensity; // In range [0..1]
public Light (Coord3D origin, double intensity) {
this.origin = origin;
this.intensity =...
Type: Posts; User: goochasauras
public class Object {
private Coord3D origin;
private double intensity; // In range [0..1]
public Light (Coord3D origin, double intensity) {
this.origin = origin;
this.intensity =...
Nah it isnt called object, im just generalizing the statement...but i checked out the constructor and it seems to be in the correct order and the parenthesis idea didnt work :(
I'm have trouble an object which has three integer values in it along with another parameter which is simply a double. This is my syntax atm:
Object newObject = new Object((1,-2,35),.5);
...
I edited to code so it is a little cleaner like you mentioned...but how do i get, in the while part of the statement, the program to loop until c or r are entered but still quitting when q is entered...
So i have a do while loop and i have user input coming in to detect which character the user entered...i want it to loop until the user enters a valid character...q or Q quits the program, whereas...
so what would be a good alternative to how I'm proceeding through this?
but i did create the variables at the beginning of main() and in the if statements i called functions and assigned the returned value to the variables..but as soon as i try to use those variables...
I added another line of code as an example of how I want to use it...it's at the bottom of Main()...but i get red squigglies saying the local variable may not have been initialized
i edited the statement and threw in a big wad of text, please if read through :)
As you are about to find out, I'm just picking up programming and I have a book in which I'm trying to complete a problem. I believe I'm having scope problems which I don't understand any assistance...
|
http://www.javaprogrammingforums.com/search.php?s=3d7f579a8236a9e9e925c19aa830bdeb&searchid=1203202
|
CC-MAIN-2014-49
|
en
|
refinedweb
|
Checking the state of Tkinter buttons in Python
In this Python tutorial, we will learn how to check and change the states of the button in Tkinter. For this, we first need to install Tkinter into our python environment. We will see a GUI window in which we will change the state of the Tkinter button by pressing it.
First, we need to understand about what is the state in Python Tkinter. Tkinter is a python library by using we can create our own GUI window. The Tkinter button has mainly two states normal state and disabled. In the normal state, we can able to press the button but in the disabled state, we are not able to click the button. So basically in this tutorial, we will learn about the Tkinter button states.
Let us move towards the coding section of the given problem.
import tkinter as tk
Import Tkinter package first.
app = tk.Tk() app.geometry("300x100")
Now we will make an app object and set the size of that window as 300 x 100.
button1 = tk.Button(app, text="Python Button 1", state=tk.DISABLED) button2 = tk.Button(app, text="EN/DISABLE Button 1", command = switchButtonState)
We will add two buttons button1 and button2. We will give an argument as an app as we want to be displayed on app window and give a name by setting text attributes as “Python Button 1”. we will give the value of the state of button 1 as Disabled by assigning value tk.DISABLED.
Likewise, in Button 2 we will pass the command as some function name so that if we press that button it will run that following function. Here we are giving them switchButtonState as function. We will define that function later on.
button1.pack(side=tk.LEFT) button2.pack(side=tk.RIGHT)
Also, we will position those two buttons by using the pack.
def switchButtonState(): if (button1['state'] == tk.NORMAL): button1['state'] = tk.DISABLED else: button1['state'] = tk.NORMAL
Now, this is the actual function that will change the state of that button. By clicking on the button if the state of button1 is normal then it will change the state it with disabled else it will keep the state normal.
app.mainloop()
At last, we have to give app.mainloop() so that the app runs.
Now you can change the state of that Button1 on clicking on the Button2.
Below I have given the complete code.
import tkinter as tk app = tk.Tk() app.geometry("300x100") button1 = tk.Button(app, text="Python Button 1", state=tk.DISABLED) button2 = tk.Button(app, text="EN/DISABLE Button 1", command = switchButtonState) button1.pack(side=tk.LEFT) button2.pack(side=tk.RIGHT) def switchButtonState(): if (button1['state'] == tk.NORMAL): button1['state'] = tk.DISABLED else: button1['state'] = tk.NORMAL app.mainloop()
That’s it. We are successfully able to check and change the state of the Tkinter button.
You can also do the same and see it working by yourself.
|
https://www.codespeedy.com/checking-the-state-of-tkinter-buttons-in-python/
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Tutorial
Using React Hooks in Gatsby.
JavaScript treats functions as first-class citizens. And we can see this in React now more than ever with the introduction of Hooks in version 16.8. They allow for state manipulation and side-effects on functional components.
At its core, Gatsby uses vanilla React with all its features. So this means Hooks are available to use with a simple
import statement. Let’s take a look at some of the ways we can take advantage of them.
Getting Started
There isn’t anything, in particular, we’ll need to install. However, it’s necessary to have the latest version of React and Gatsby or at least v16.8+. We can do so by checking out our package.json and finding which version we already have installed.
If you need to upgrade, we can run the following:
$ npm install react@16.8.0 react-dom@16.8.0 # or $ yarn add react@16.8.0 react-dom@16.8.0
With that, we should be good to go.
Using Hooks
Let’s set up a
header.js component with a scrolled state and a dropdown menu.
Our component will be a fixed header at the top that remains in place while the user scrolls through the page, but displays a box-shadow when the user isn’t at the top. That means our state would be a boolean which toggles based on the current window position. We’ll use native APIs to determine window position.
import React, { useState, useEffect } from 'react'; import { Link } from 'gatsby'; const Header = () => { // determined if page has scrolled and if the view is on mobile const [scrolled, setScrolled] = useState(false); // change state on scroll useEffect(() => { const handleScroll = () => { const isScrolled = window.scrollY > 10; if (isScrolled !== scrolled) { setScrolled(!scrolled); } }; document.addEventListener('scroll', handleScroll, { passive: true }); return () => { // clean up the event handler when the component unmounts document.removeEventListener('scroll', handleScroll); }; }, [scrolled]); return ( <header data-active={scrolled}> <Link to="/">React Hooks on Gatsby</Link> <nav> <Link to="/about/">About</Link> <Link to="/contact/">Contact Us</Link> </nav> </header> ); }; export default Header;
The
window.scrollY property returns the number of pixels that have passed vertically on scroll. We compare that value to 10 pixels and we get a boolean value that will tell us if the user has moved the document or not. We then wrap the conditional property around a function that updates the
scrolled state whenever the user scrolls through the site. This function is then passed to an event listener on the document.
All of this will live inside the useEffect hook, which will return a
removeEventListener on the document to clean up the event handler when the component unmounts. The
useEffect hook allows us to perform side effects on our component. The effect will fire after every completed render by default, however, we can pass a second argument as an array of values on which the effect depends on to fire. In our case,
[scrolled].
With that, we can add an identifying attribute to our HTML to determine the state of the element. We’ll use a
data-active attribute with the boolean from the
scrolled state. And in our CSS, we can add the
box-shadow effect using the attribute selector.
header { position: fixed; top: 0; transition: box-shadow .3s ease; width: 100%; &[data-active='true'] { box-shadow: 0 2px 8px rgba(152,168,188,.2); } }
The same styling can be used with styled-components. Swapping the
header selector with the component’s tagged template literal will provide the same functionality.
Hooks and User Input
We’ll take this example a step further and add a dropdown menu accessible via a toggle button. We can keep most of what was already made and just modify the state change properties. The property will be renamed to
state and
setState while taking an object with our various state variables.
Updating state would be a little different in this case. First, we need to pass the previous state as a spread operator, followed by the updated value. This is because, unlike class components, functional ones will replace updated objects instead of merging them.
import React, { useState, useEffect } from 'react'; import { Link } from 'gatsby'; import Dropdown from './dropdownMenu'; const Header = () => { // determined if page has scrolled and if the view is on mobile const [state, setState] = useState({ scrolled: false, visible: false, }); // change state on scroll useEffect(() => { const handleScroll = () => { const isScrolled = window.scrollY > 10; if (isScrolled !== state.scrolled) { setState({ ...state, scrolled: !state.scrolled, }); } }; document.addEventListener('scroll', handleScroll, { passive: true }); return () => { // clean up the event handler when the component unmounts document.removeEventListener('scroll', handleScroll); }; }, [state.scrolled]); // toggle dropdown visibility const toggleVisibility = () => { setState({ ...state, visible: !state.visible, }); }; return ( <header data-active={state.scrolled}> <Link to="/">React Hooks on Gatsby</Link> <nav> <Link to="/about/">About</Link> <Link to="/contact/">Contact Us</Link> <button onClick={toggleVisibility} Solutions </button> <Dropdown aria-hidden={!state.visible} data-active={state.visible} /> </nav> </header> ); }; export default Header;
We want to have the user click a button that will open up an additional menu. When the Solutions button is clicked, it’ll toggle the
visible boolean. This boolean is passed to the
aria-hidden and
data-active attributes for use in our CSS.
// the section element is our <Dropdown /> component header { top: 0; transition: box-shadow .3s ease; &[data-active='true'] { box-shadow: 0 2px 8px rgba(152,168,188,.2); } &, section { position: fixed; width: 100%; } nav, section { overflow: hidden; } section { height: 0; left: 0; opacity: 0; right: 0; top: 5.5rem; transition: all .3s ease-in-out; visibility: hidden; &[data-active='true'] { height: auto; opacity: 1; visibility: visible; } } }
Conclusion
With Hooks, we get all the benefits of class components with the familiarity of functional ones. Gatsby takes full advantage of that. I recommend you take a look at all the Hooks available in the React documentation. And you can even dive into building your own hooks!
|
https://www.digitalocean.com/community/tutorials/gatsbyjs-react-hooks-gatsby
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Without an example it can be hard to understand how user authentication works in a Play Framework application, so I just created a project on Github named PlayFrameworkLoginAuthenticationExample that demonstrates one way to implement login authentication in a Play Framework 2.6 application.
I can write more about it if people are interested, but the highlights go like this:
- If you have a current version of SBT installed, you can download the project and immediately run it with the
sbt runcommand
- I removed all the database-access code from the project, so you can immediately access the URL
- When you access that URL the routes file sends control to the
showLoginFormmethod in the
UserControllerclass; it displays the userLogin.scala.html template
- You can see in the
UserDaothat the username and password are both
foo
- When you attempt to login, the routes file sends the user form data to the
processLoginAttemptin the
UserControllerclass
- If the login attempt succeeds, control is sent to the
showLandingPageaction in the
LandingPageControllerclass; it shows the loginLandingPage.scala.html template, which includes a “logout” link; it also shows a Flash message that the login succeeded
- User authentication is implemented in the
AuthenticatedUserActionclass
- To make sure that an action can only be accessed by an authenticated user, the method should use an instance of
AuthenticatedUserAction, as shown by the
showLandingPagemethod in the
LandingPageControllercontroller:
def showLandingPage() = authenticatedUserAction { implicit request: Request[AnyContent] => Ok(views.html.loginLandingPage(logoutUrl)) }
What it looks like
Here’s what this little starter application looks like. First, the login page:
Next, the simple landing page with the Flash message:
Next, what you see when you log out:
And finally, what you see if you attempt to access the landing page when you’re not logged in:
Admittedly not too exciting, but it shows the authentication basics.
Summary
If you wanted to see an example of a Play Framework 2.6 login/authentication application, I hope this project is helpful. I think it follows the Play Action Composition docs pretty faithfully. If people have questions about the project I’ll be glad to write more here, but I hope this is helpful as is.
P.S. — If you’re writing a Play Framework server application with a JavaScript client front-end you’ll have to do things a little differently, but hopefully this example can help a little bit in that use case as well.
|
https://alvinalexander.com/scala/play-framework-login-authentication-example-project/
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Byte array to image conversion
Byte array to image conversion
Question
I want to convert a byte array to an image.
This is my database code from where I get the byte array:
public void Get_Finger_print() { try { using (SqlConnection thisConnection = new SqlConnection(@"Data Source=" + System.Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=Image_Scanning;Integrated Security=SSPI ")) { thisConnection.Open(); string query = "select pic from Image_tbl";// where Name='" + name + "'"; SqlCommand cmd = new SqlCommand(query, thisConnection); byte[] image =(byte[]) cmd.ExecuteScalar(); Image newImage = byteArrayToImage(image); Picture.Image = newImage; //return image; } } catch (Exception) { } //return null; }
My conversion code:
public Image byteArrayToImage(byte[] byteArrayIn) { try { MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length); ms.Write(byteArrayIn, 0, byteArrayIn.Length); returnImage = Image.FromStream(ms,true);//Exception occurs here } catch { } return returnImage; }
When I reach the line with a comment, the following exception occurs:
Parameter is not valid.
How can I fix whatever is causing this exception?
Popular Answer
You are writing to your memory stream twice, also you are not disposing the stream after use. You are also asking the image decoder to apply embedded color correction.
Try this instead:
using (var ms = new MemoryStream(byteArrayIn)) { return Image.FromStream(ms); }
Read more... Read less...
Maybe I'm missing something, but for me this one-liner works fine with a byte array that contains an image of a JPEG file.
Image x = (Bitmap)((new ImageConverter()).ConvertFrom(jpegByteArray));
EDIT:
See here for an updated version of this answer: How to convert image in byte array
I'd like to note there is a bug in solution provided by @isaias-b.
That solution assume that
stride is equal to row length. But it is not always true. Due to memory alignments performed by GDI, stride can be greater then row length. This must be taken into account. Otherwise invalid shifted image will be generated. Padding bytes in each row will be ignored.
The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary.
Fixed code:
using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; public static class ImageExtensions { public static Image ImageFromRawBgraArray(this byte[] arr, int width, int height, PixelFormat pixelFormat) { var output = new Bitmap(width, height, pixelFormat); var rect = new Rectangle(0, 0, width, height); var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat); // Row-by-row copy var arrRowLength = width * Image.GetPixelFormatSize(output.PixelFormat) / 8; var ptr = bmpData.Scan0; for (var i = 0; i < height; i++) { Marshal.Copy(arr, i * arrRowLength, ptr, arrRowLength); ptr += bmpData.Stride; } output.UnlockBits(bmpData); return output; } }
To illustrate what it can lead to, let's generate
PixelFormat.Format24bppRgb gradient image 101x101:
var width = 101; var height = 101; var gradient = new byte[width * height * 3 /* bytes per pixel */]; for (int i = 0, pixel = 0; i < gradient.Length; i++, pixel = i / 3) { var x = pixel % height; var y = (pixel - x) / width; gradient[i] = (byte)((x / (double)(width - 1) + y / (double)(height - 1)) / 2d * 255); }
If we will copy entire array as-is to address pointed by
bmpData.Scan0, we will get following image. Image shifting because part of image was written to padding bytes, that was ignored. Also that is why last row is incomplete:
But if we will copy row-by-row shifting destination pointer by
bmpData.Stride value, valid imaged will be generated:
Stride also can be negative:
If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.
But I didn't worked with such images and this is beyond my note.
Related answer: C# - RGB Buffer from Bitmap different from C++
All presented answers assume that the byte array contains data in a known file format representation, like: gif, png or jpg. But i recently had a problem trying to convert
byte[]s, containing linearized BGRA information, efficiently into
Image objects. The following code solves it using a
Bitmap object.
using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; public static class Extensions { public static Image ImageFromRawBgraArray( this byte[] arr, int width, int height) { var output = new Bitmap(width, height); var rect = new Rectangle(0, 0, width, height); var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat); var ptr = bmpData.Scan0; Marshal.Copy(arr, 0, ptr, arr.Length); output.UnlockBits(bmpData); return output; } }
This is a slightly variation of a solution which was posted on this site.
there is a simple approach as below, you can use
FromStream method of an image to do the trick,
Just remember to use
System.Drawing;
// using image object not file public byte[] imageToByteArray(Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; }
|
https://ask4knowledgebase.com/questions/9173904/byte-array-to-image-conversion
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
tfcompile is a standalone tool that ahead-of-time (AOT) compiles TensorFlow graphs into executable code. It can reduce total binary size, and also avoid some runtime overheads. A typical use-case of
tfcompile is to compile an inference graph into executable code for mobile devices.
The TensorFlow graph is normally executed by the TensorFlow runtime. This incurs some runtime overhead for execution of each node in the graph. This also leads to a larger total binary size, since the code for the TensorFlow runtime needs to be available, in addition to the graph itself. The executable code produced by
tfcompile does not use the TensorFlow runtime, and only has dependencies on kernels that are actually used in the computation.
The compiler is built on top of the XLA framework. The code bridging TensorFlow to the XLA framework resides under tensorflow/compiler, which also includes support for just-in-time (JIT) compilation of TensorFlow graphs.
tfcompile takes a subgraph, identified by the TensorFlow concepts of feeds and fetches, and generates a function that implements that subgraph. The
feeds are the input arguments for the function, and the
fetches are the output arguments for the function. All inputs must be fully specified by the feeds; the resulting pruned subgraph cannot contain Placeholder or Variable nodes. It is common to specify all Placeholders and Variables as feeds, which ensures the resulting subgraph no longer contains these nodes. The generated function is packaged as a
cc_library, with a header file exporting the function signature, and an object file containing the implementation. The user writes code to invoke the generated function as appropriate.
This section details high level steps for generating an executable binary with
tfcompile from a TensorFlow subgraph. The steps are:
tf_librarybuild macro to compile the subgraph
Identify the feeds and fetches that correspond to the input and output arguments for the generated function. Then configure the
feeds and
fetches in a
tensorflow.tf2xla.Config proto.
# Each feed is a positional input argument for the generated function. The order # of each entry matches the order of each input argument. Here “x_hold” and “y_hold” # refer to the names of placeholder nodes defined in the graph. feed { id { node_name: "x_hold" } shape { dim { size: 2 } dim { size: 3 } } } feed { id { node_name: "y_hold" } shape { dim { size: 3 } dim { size: 2 } } } # Each fetch is a positional output argument for the generated function. The order # of each entry matches the order of each output argument. Here “x_y_prod” # refers to the name of a matmul node defined in the graph. fetch { id { node_name: "x_y_prod" } }
This step converts the graph into a
cc_library using the
tf_library build macro. The
cc_library consists of an object file containing the code generated from the graph, along with a header file that gives access to the generated code.
tf_library utilizes
tfcompile to compile the TensorFlow graph into executable code.
load("//third_party/tensorflow/compiler/aot:tfcompile.bzl", "tf_library") # Use the tf_library macro to compile your graph into executable code. tf_library( # name is used to generate the following underlying build rules: # <name> : cc_library packaging the generated header and object files # <name>_test : cc_test containing a simple test and benchmark # <name>_benchmark : cc_binary containing a stand-alone benchmark with minimal deps; # can be run on a mobile device name = "test_graph_tfmatmul", # cpp_class specifies the name of the generated C++ class, with namespaces allowed. # The class will be generated in the given namespace(s), or if no namespaces are # given, within the global namespace. cpp_class = "foo::bar::MatMulComp", # graph is the input GraphDef proto, by default expected in binary format. To # use the text format instead, just use the ‘.pbtxt’ suffix. A subgraph will be # created from this input graph, with feeds as inputs and fetches as outputs. # No Placeholder or Variable ops may exist in this subgraph. graph = "test_graph_tfmatmul.pb", # config is the input Config proto, by default expected in binary format. To # use the text format instead, use the ‘.pbtxt’ suffix. This is where the # feeds and fetches were specified above, in the previous step. config = "test_graph_tfmatmul.config.pbtxt", )
To generate the GraphDef proto (test_graph_tfmatmul.pb) for this example, run make_test_graphs.py and specify the output location with the --out_dir flag.
Typical graphs contain
Variables representing the weights that are learned via training, but
tfcompile cannot compile a subgraph that contain
Variables. The freeze_graph.py tool converts variables into constants, using values stored in a checkpoint file. As a convenience, the
tf_library macro supports the
freeze_checkpoint argument, which runs the tool. For more examples see tensorflow/compiler/aot/tests/BUILD.
Constants that show up in the compiled subgraph are compiled directly into the generated code. To pass the constants into the generated function, rather than having them compiled-in, simply pass them in as feeds.
For details on the
tf_library build macro, see tfcompile.bzl.
For details on the underlying
tfcompile tool, see tfcompile_main.cc.
This step uses the header file (
test_graph_tfmatmul.h) generated by the
tf_library build macro in the previous step to invoke the generated code. The header file is located in the
bazel-genfiles directory corresponding to the build package, and is named based on the name attribute set on the
tf_library build macro. For example, the header generated for
test_graph_tfmatmul would be
test_graph_tfmatmul.h. Below is an abbreviated version of what is generated. The generated file, in
bazel-genfiles, contains additional useful comments.
namespace foo { namespace bar { // MatMulComp represents a computation previously specified in a // TensorFlow graph, now compiled into executable code. class MatMulComp { public: // AllocMode controls the buffer allocation mode. enum class AllocMode { ARGS_RESULTS_AND_TEMPS, // Allocate arg, result and temp buffers RESULTS_AND_TEMPS_ONLY, // Only allocate result and temp buffers }; MatMulComp(AllocMode mode = AllocMode::ARGS_RESULTS_AND_TEMPS); ~MatMulComp(); // Runs the computation, with inputs read from arg buffers, and outputs // written to result buffers. Returns true on success and false on failure. bool Run(); // Arg methods for managing input buffers. Buffers are in row-major order. // There is a set of methods for each positional argument. void** args(); void set_arg0_data(float* data); float* arg0_data(); float& arg0(size_t dim0, size_t dim1); void set_arg1_data(float* data); float* arg1_data(); float& arg1(size_t dim0, size_t dim1); // Result methods for managing output buffers. Buffers are in row-major order. // Must only be called after a successful Run call. There is a set of methods // for each positional result. void** results(); float* result0_data(); float& result0(size_t dim0, size_t dim1); }; } // end namespace bar } // end namespace foo
The generated C++ class is called
MatMulComp in the
foo::bar namespace, because that was the
cpp_class specified in the
tf_library macro. All generated classes have a similar API, with the only difference being the methods to handle arg and result buffers. Those methods differ based on the number and types of the buffers, which were specified by the
feed and
fetch arguments to the
tf_library macro.
There are three types of buffers managed within the generated class:
args representing the inputs,
results representing the outputs, and
temps representing temporary buffers used internally to perform the computation. By default, each instance of the generated class allocates and manages all of these buffers for you. The
AllocMode constructor argument may be used to change this behavior. A convenience library is provided in
tensorflow/compiler/aot/runtime.h to help with manual buffer allocation; usage of this library is optional. All buffers should be aligned to 32-byte boundaries.
The generated C++ class is just a wrapper around the low-level code generated by XLA.
Example of invoking the generated function based on
tfcompile_test.cc:
#define EIGEN_USE_THREADS #define EIGEN_USE_CUSTOM_THREAD_POOL #include <iostream> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/compiler/aot/tests/test_graph_tfmatmul.h" // generated int main(int argc, char** argv) { Eigen::ThreadPool tp(2); // Size the thread pool as appropriate. Eigen::ThreadPoolDevice device(&tp, tp.NumThreads()); foo::bar::MatMulComp matmul; matmul.set_thread_pool(&device); // Set up args and run the computation. const float args[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(args + 0, args + 6, matmul.arg0_data()); std::copy(args + 6, args + 12, matmul.arg1_data()); matmul.Run(); // Check result if (matmul.result0(0, 0) == 58) { std::cout << "Success" << std::endl; } else { std::cout << "Failed. Expected value 58 at 0,0. Got:" << matmul.result0(0, 0) << std::endl; } return 0; }
This step combines the library generated by
tf_library in step 2 and the code written in step 3 to create a final binary. Below is an example
bazel BUILD file.
# Example of linking your binary # Also see //third_party/tensorflow/compiler/aot/tests/BUILD load("//third_party/tensorflow/compiler/aot:tfcompile.bzl", "tf_library") # The same tf_library call from step 2 above. tf_library( name = "test_graph_tfmatmul", ... ) # The executable code generated by tf_library can then be linked into your code. cc_binary( name = "my_binary", srcs = [ "my_code.cc", # include test_graph_tfmatmul.h to access the generated header ], deps = [ ":test_graph_tfmatmul", # link in the generated object file "//third_party/eigen3", ], linkopts = [ "-lpthread", ] )
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.
|
https://docs.w3cub.com/tensorflow~guide/performance/xla/tfcompile
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Python Program to read a book (docx Word document) & store it in a DataFrame in Python.
Problem Statement:
Following code will read a book from the system in a document form and store it in a dataframe in Python.
Solution:
- Step 1: Convert a pdf book into .docx format.
- Step 2: Import necessary libraries in the code.
- Step 3: Initialize address(path to the file to be read) and dataframe.
- Step 4: Create a function that will take address(path to the file to be read) as an input, and store it in a dataframe.
- Step 5: Call the function by passing the address as the parameter.
- Step 6: End.
How Does it Work ?
The “docx” package of python allows to read and access the docx documents. To install this package you need to run following on your command prompt:
pip install docx
Then we import this package in our code to access the docx document. Using this package, you can open the document and read all the paragraphs of the word document.
Program/Code To Read Paragraphs in Word Docx:
from docx import Document address='H:/Work/Practice/OOW/1st_text/Heidi_w.docx' # path to the file in your system text_chunks = [] # create an empty dataframe def doc_to_df(address): # define a function document = Document(address) # open the document for paragraph in document.paragraphs: # for loop to read each paragraph and append it to the dataframe text_chunks.append(paragraph.text) doc_to_df(address) # call function
As everything in Word document is represented by paragraphs. Then using a for loop, all the paragraphs is read and appended in a dataframe.
|
https://officetricks.com/python-to-read-word-document-dataframe/
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
A python library that simplify the access to the NOAA digitalelevation map.
Project description
Requirements
If you want to use this library on any GNU/Linux or OSX system you just need to execute:
$ pip install noaadem
If you want to improve this library, you should download the github repository and execute:
$ make deploy
On Ubuntu Desktop there are some other libraries not installed by default (zlibc libbz2-dev) which may need to be installed to use these library. Use the next command to automate the installation of the additional C libraries:
$ make ubuntu deploy
Testing
To test all the project you should use the command:
$ make test
If you want to help us or report an issue join to us through the GitHub issue tracker.
Example
There are 3 methods to obtain the NOAA digital elevation map matrix:
- obtain
- obtain_to
- persist
The obtain method accepts 2 parameters the latitude and longitude numpy matrix:
from noaadem import instrument from datetime import datetime dem_matrix = instrument.obtain(lat, lon)
Next, the obtain_to method needs a standard NOAA CLASS netcdf filename to parse:
from noaadem import instrument from datetime import datetime dem_matrix = instrument.obtain_to('data/goes13.2014.124.123422.BAND_01.nc')
Last, the persist method needs a standard NOAA CLASS netcdf filename to save the variables:
from noaadem import instrument from datetime import datetime from netcdf import netcdf as nc instrument.persist('data/goes13.2014.124.123422.BAND_01.nc') with nc.loader('data/goes13.2014.124.123422.BAND_01.nc') as root: print nc.getvar(root, 'dem')[:]
About
This software is developed by GERSolar. You can contact us to gersolar.dev@gmail.com.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/noaadem/
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Style and Format of the Quiz
Will this be Synchronous or Asynchronous and how much time will I have?
The quiz will of a take-home style, just like last time. It will be released on Tuesday 10/20, 4:45 PM Eastern Time and be due at midnight, Tuesday 10/20, 11:59 PM Eastern Time.
International students who opted into the 4:45 AM Eastern Time quizzing will begin theirs via the INTL Gradescope account at 08:45 GMT 10/21/2020 and submit by 4:00 PM GMT.
On this quiz we will have certain parts due by different times. The memory diagram questions will be due about an hour or so after the quiz opens up, while you will have the rest of the night to finish the code writing.
Am I allowed to use notes, VS Code, and/or the Internet?
Yes to notes, anything on the course site, and VS Code… you are encouraged to try things out in the REPL!
No to using the Internet. While you may think there is no way for us to check whether the Internet was used, it is obvious to tell what methods to program coding were taught in class versus something that was pulled from the Internet. Using obscure methods from the Internet either way will probably get points taken off anyway for not following the conventions we use in class.
And NO to collaboration with other students. As you saw, it is very easy to tell when someone has just changed variable names or move small things around.
Will I need to hand-write anything?
Memory diagrams will be on this quiz, meaning you will have to have some sort of app to take pictures of your diagram to upload to gradescope.
What new topics should I know for the quiz?
- Always good to refresh quick on what we previously covered for last quiz (see FAQ for quizzes 0 and 1!)
- Memory Diagrams
- For lists
- For objects
- For dictionaries
- Dictionaries
- Classes and Objects
- Note: There won’t be any code writing relating to classes and objects. Just know the concepts well enough to interpret them on the memory diagram questions!
What is the breakdown of question styles?
There will be some questions that are similar to the previous quizzes in that they will ask you to implement some sort of function following the requirements given.
In addition to this though, a big focus will be on creating memory diagrams! The bright side of these is that you will not have to worry about writing code, rather you will be given a code snippet and will have to interpret what’s happening, which the diagram should actually help with! There also may be questions about your memory diagram, such as “How many objects are on the heap?” or “What is the value of x in the main frame?”. This is just a matter of interpreting what you drew!
Memory diagrams
Memory diagrams can be a blessing in the sky if you are trying to interpret programs or even trying to test your own! They are an effective way to essentially keep track of what variable values are as the program runs. With many function calls, it can be complicated to track things like lists and objects in your head.
The setup will always be the same. You will have three sections:
- Call Stack
- Heap
- Output
The call stack is where the globals frame will go, along with frames representing any function call that gets made.
The heap is where functions, lists, objects, and dictionaries would go. Any variable that is ‘primitive’ or simple like strings, integers, floats, or booleans will not need to go on the heap, and can instead be written in the small box within the frame.
Output is where printed output gets logged. Only use this section if you see print statements encountered.
Here is how drawing it will start off like (every time!):
Next, we will put functions declared in the program on the heap. Let’s take this:
Main is declared from lines 3-8 and foo is declared from lines 11-14. Let’s put this in our global frame:
Then, whenever any function call is made, we add that to our call stack. The number of times a function is called in the running of the program is the amount of frames that should be drawn on the stack. This does NOT mean you count every call that exists in the code, you have to actually check if those calls are reached when the program runs.
main() is called on line 18, so we will make a frame for this.
One thing to note is that every frame (except for globals) must have a return address and return value declared. Do NOT forget to include these!! Easy points can be given by having the return address and values correct on the frame. Since main was called on line 18, the return address will be marked as 18. As main’s return type is None, we will use a 0 with a slash marked through (which you should do any time a function’s return type is None).
Now time to actually run through the main function! In line 4, we have printed output, and in line 5, an int, x, is declared and initialized. We will put the output under the ‘Output’ column and put x in main’s frame. The variable x can now be accessed within the main frame.
For the string variable, y, that is declared on line 6, we have a function call to foo whose return value is assigned to it, so we have to create a new frame on the stack to account for this! On this new ‘foo’ frame, we can define the return address as 6 since that is where the call to foo is made. We will leave the return value as blank since we know it will return a string by the end of the call.
We can also go ahead and define any parameters within the frame, as they are all local to the function call (you will learn more about this when we discuss scope!) This applies to all functions you may encounter - even though the variables are not declared within the actual block, parameter values are still important to keep track of. Since the argument ‘x’ was passed into this function, we will write in its value 1 as the parameter value within foo, also named ‘x’.
Keep in mind, the x in foo is TOTALLY separate from the one in main. But you might wonder, we passed in the x variable from main as the argument, and therefore the x in foo and x in main have to be related. However, think of it this way, I could have defined the parameter within foo as y. The values of x and y will be the same at the start, but they have no relation at all because whatever changes happen to the parameter in foo will NOT reflect in the variable in main, since we are only dealing with an integer.
As you see in examples with lists, dicts, and objects, this does NOT hold true for those types because those are reference types. When they are passed into functions, a copy of them is not made, but instead, an arrow is drawn to it, meaning the parameter and variable from main would actually be related! Any changes that happen within these will affect all variables that reference it.
In our example though, when the integer gets updated, this change is only made in foo.
Now we have a list to declare on line 13! Now we will create a list on the heap to represent this, and we will draw an arrow from ‘values’ to reflect that it references that list.
The next line is a return statement that returns the value at index ‘x’ from the values list. We know from the diagram that x is 2, and following the values list reference, we know that the value at this index is “it”. This string will now be our return value!
Now we can get out of this frame since we have a return value. This will get assigned to the variable y in main. From there, the value will be printed and so will “End!” to mark the end of the program. Here is what our complete diagram looks like now:
This is a very basic example for review of how a memory diagram is made, but please refer to class notes and practice problems under Resources for more difficult practice!
Important Note regarding For… in loops in Memory Diagrams
Something extremely important to understand about for in loops is that when we define the counter variable within the for statement, that also gets defined on the memory diagram even though no type is explictly declared. in the diagram..
Dictionaries (Dicts)
Think back to when we talked about lists. It was a sequence of values of the same type. How do we access elements within a list? Easy! You just use bracket notation and fill it with the appropriate index. Remember, these indices start from 0 and count up from there.
However, these indices are not something we see when we, for example, print the list. We just know that the value in the second position for example is at index 1, and this holds true for values in a list that whatever is in the nth position is at index n - 1. We can see the limitations however of using indices to refer to values of a sequence:
The index (an integer) does not have any actual significance or relation to the value it represents other than where that value is on the list. It is not practical to remember at which position something on a list exists. If the scores for a class were listed, and we wanted Anna’s grade, we would have to know which position Anna was (in which case we would have to access another list for class names, which we do not even know if the order corresponds with the grades).
grades: list[float] = [ 62.5, 97.8, 83.4 ] names: list[str] = [ ‘Kush’, ‘Anna’, ‘Marc’ ] # Here we assume the order corresponds index: int = -1 for i in range(len(names)): if names[i] == ‘Anna’: index = i print(“Anna’s grade is “ + str(grades[index]))
Dictionaries fix both of these problems!!! With the power of ‘keys’, values in a sequence actually have a meaning visibly associated with it that can be utilized within brackets:
grades: Dict[str, float] = { “Kush”: 62.5, “Anna”: 97.8, “Marc”: 83.4 } print(“Anna’s grade is “ + str(grades[‘Anna’]))
Notice how easy it is to just refer to the grades dictionary and look for Anna’s grade by using “Anna” as the key! This is the power of dictionaries!
Some trivial things to remember include how to import them and how to declare its type.
import Dict from typing grades: Dict[str, float] # First type represents the key type, second type represents the value type
One other really cool thing about dictionaries is that adding values to them is very simple! No need to use special functions like append, all we do is just assign a value to a key that doesn’t exist, and Python is chill with it!
If you want to remove a value from a dictionary, use the .pop(
If you want to check if a key is already in the dictionary, instead of having to use a for loop to find and compare, there is a very simple syntax to check!
Please do not waste time and run a for loop to find if a key exists!! Use
if <key> in <dict> like we did above!
For loops will be useful, however, for finding values. In general, if a function takes in a dictionary, your first thought should be to make a for loop (just like we did with lists) to iterate through the key-value pairs. The for … in syntax is very similar for dictionaries, but instead of the item representing an index or an actual value, the item will represent the key!
Classes and Objects
One limitation about lists and dicts are that the data within have to be all of the same type, which is whatever is specified upon declaration. What if we wanted to hold data of different types?
This is where classes can be very useful! You creating a class essentially is equivalent to you creating a custom data type! The class can hold whatever attributes you want. To define a class with its attributes:
class [className]: [atrr_1_name]: [attr_1_type] = [optional default_value] [attr_2_name]: [attr_2_type] = [optional default_value] [attr_3_name]: [attr_3_type] = [optional default_value]
An example would be if I wanted to hold data for a student. A student has a name, GPA, and could have a value to represent whether or not they are graduating soon. I can define a Student class to hold these attributes:
Notice how I can give a Student a default value for is_graduating if I wanted to!
Now that I have a class declared, I can use it to declare many objects of that class type, each to represent a student!
You are not required to know this now, but we can even make lists of these objects! Exciting!!! You will learn more in future lectures!
The next step is to actually assign values to the attributes of the objects we have created. The way to assign and access attribute values is by using dot notation:
A key thing to note is that these objects are reference types. What does that mean? On an memory diagram, this object would go on the heap as we learned earlier. If an object were declared and assigned to a variable, an arrow from that variable name to the object name would be created, so that name references that object. Therefore, if I had something like this:
The name student_4 points to, or refers to, the same object as student_1. Thus, any changes that happen to student_4 will also reflect in student_1:
Objects being a reference type also implies that if one were to directly pass in an object as an argument to a function, the parameter name in the memory would point to that same object being passed in (a copy is not made).
Again, for the quiz you will just have to be able to recognize the syntax and track the object and its attributes in a memory diagram, so do not spend too much time memorizing the syntax. Just understand how to recognize when an attribute of an object is being accessed or updated, and how overall references work when multiple names are pointing to the same object (the concept is the same in lists and dicts).
How do I best prepare for the quiz?
- For the memory diagrams, definitely work on the practice problems we assign, but also look back at problems done in lecture to ensure you understand the concepts.
- Focus on these the most since we have not done quizzes or exercises involving memory diagrams yet so you want to get comfortable knowing how to draw them!
- Really understand how to iterate through dictionaries and how to access values within them. Good practice is available under resources! Also review the Shakespeare exercise and project for this!
- For classes and objects, as we’ve just talked about them and haven’t had much in terms of practice with those, try to focus on those the most.
- We are 5 weeks away from the end of the semester! We are almost there! Pat yourself on the back for making it this far, you all should be really proud of yourselves! It is not easy to take on a skill as novel as programming! You all challenged yourselves by sticking through this course, and no grade can tell you otherwise. That being said, stress less about the grade you will potentially make on this quiz, and focus more on reviewing concepts that you feel you may be struggling with.
- TA’s are here to help in office hours, please feel free to go through practice problems with them, they will be glad to walk you through understanding these concepts!
|
https://20f.comp110.com/students/resources/quiz2-faq.html
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
- NAME
- Synopsis
- Description
- Distributions
- Installation
- Constructor and Initialization
- Methods
- What is 'path info'?
- Is there any sample code?
- Why did you fork CGI::Application::Dispatch?
- What version of CGI::Application::Dispatch did you fork?
- How does CGI::Snapp::Dispatch differ from CGI::Application::Dispatch?
- There is no module called CGI::Snapp::Dispatch::PSGI
- Processing parameters to dispatch() and dispatch_args()
- No special code for Apache, mod_perl or plugins
- Unsupported features
- Enhanced features
- This module uses Class::Load to try loading your application's module
- Reading an error document from a file
- Handling of exceptions
- How does CGI::Snapp parse the path info?
- What is the structure of the dispatch table?
- How do I use my own logger object?
- How do I sub-class CGI::Snapp::Dispatch?
- Are there any security implications from using this module?
- Why is CGI::PSGI required in Build.PL and Makefile.PL when it's sometimes not needed?
- Troubleshooting
- See Also
- Machine-Readable Change Log
- Version Numbers
- Credits
- Repository
- Support
- Author
NAME
CGI::Snapp::Dispatch - Dispatch requests to CGI::Snapp-based objects
Synopsis
CGI Scripts
Here is a minimal CGI instance script. Note the call to new()!
#!/usr/bin/env perl use CGI::Snapp::Dispatch; CGI::Snapp::Dispatch -> new -> dispatch;
(The use of new() is discussed in detail under "PSGI Scripts", just below.)
But, to override the default dispatch table, you probably want something like this:
MyApp/Dispatch.pm:
package MyApp::Dispatch; parent 'CGI::Snapp::Dispatch'; sub dispatch_args { my($self) = @_; return { prefix => 'MyApp', table => [ '' => {app => 'Initialize', rm => 'start'}, ':app/:rm' => {}, 'admin/:app/:rm' => {prefix => 'MyApp::Admin'}, ], }; }
And then you can write ... Note the call to new()!
#!/usr/bin/env perl use MyApp::Dispatch; MyApp::Dispatch -> new -> dispatch;
PSGI Scripts
Here is a PSGI script in production on my development machine. Note the call to new()!
#!/usr/bin/env perl # # Run with: # starman -l 127.0.0.1:5020 --workers 1 httpd/cgi-bin/local/wines.psgi & # or, for more debug output: # plackup -l 127.0.0.1:5020 httpd/cgi-bin/local/wines.psgi & use strict; use warnings; use CGI::Snapp::Dispatch; use Plack::Builder; # --------------------- my($app) = CGI::Snapp::Dispatch -> new -> as_psgi ( prefix => 'Local::Wines::Controller', # A sub-class of CGI::Snapp. table => [ '' => {app => 'Initialize', rm => 'display'}, ':app' => {rm => 'display'}, ':app/:rm/:id?' => {}, ], ); builder { enable "ContentLength"; enable "Static", path => qr!^/(assets|favicon|yui)!, root => '/dev/shm/html'; # /dev/shm/ is Debian's RAM disk. $app; };
Warning! The line my($app) = ... contains a call to "new()". This is definitely not the same as if you were using CGI::Application::Dispatch or CGI::Application::Dispatch::PSGI. They look like this:
my($app) = CGI::Application::Dispatch -> as_psgi
The lack of a call to new() there tells you I've implemented something very similar but different. You have been warned...
The point of this difference is that new() returns an object, and passing that into "as_psgi(@args)" as $self allows the latter method to be much more sophisticated than it would otherwise be. Specifically, it can now share a lot of code with "dispatch(@args)".
Lastly, if you want to use regexps to match the path info, see CGI::Snapp::Dispatch::Regexp.
Description
This module provides a way to automatically look at the path info - $ENV{PATH_INFO} - of the incoming HTTP request, and to process that path info like this:
- o Parse off a module name
-
- o Parse off a run mode
-
- o Create an instance of that module (i.e. load it)
-
- o Run that instance
-
- o Return the output of that run as the result of requsting that path info (i.e. module and run mode combo)
-
Thus, it will translate a URI like this:
/app/index.cgi/module_name/run_mode
into something that is functionally equivalent to this:
my($app) = Module::Name -> new(...); $app -> mode_param(sub {return 'run_mode'}); return $app -> run;
Distributions
This module is available as a Unix-style distro (*.tgz).
See for help on unpacking and installing distros.
Installation
Install CGI::Snapp::Dispatch as you would for any
Perl module:
Run:
cpanm CGI::Snapp::Dispatch
or run:
sudo cpan CGI::Snapp::Dispatch
or unpack the distro, and then either:
perl Build.PL ./Build ./Build test sudo ./Build install
or:
perl Makefile.PL make (or dmake or nmake) make test make install
Constructor and Initialization
new() is called as
my($app) = CGI::Snapp::Dispatch -> new(k1 => v1, k2 => v2, ...).
It returns a new object of type
CGI::Snapp::Dispatch.
Key-value pairs accepted in the parameter list (see corresponding methods for details [e.g. "return_type([$string])"]):
- o logger => $aLoggerObject
Specify a logger compatible with Log::Handler.
Note: This logs method calls etc inside CGI::Snapp::Dispatch.
To log within CGI::Snapp, see "How do I use my own logger object?".
Default: '' (The empty string).
To clarify: The built-in calls to log() all use a log level of 'debug', so if your logger has 'maxlevel' set to anything less than 'debug', nothing nothing will get logged.
'maxlevel' and 'minlevel' are discussed in Log::Handler#LOG-LEVELS and Log::Handler::Levels.
- o return_type => $integer
Possible values for $integer:
- o 0 (zero)
dispatch() returns the output of the run mode.
This is the default.
- o 1 (one)
dispatch() returns the hashref of args built from combining the output of dispatch_args() and the args to dispatch().
The requested module is not loaded and run. See t/args.t.
- o 2 (two)
dispatch() returns the hashref of args build from parsing the path info.
The requested module is not loaded and run. See t/args.t.
Default: 0.
Note: return_type is ignored by "as_psgi(@args)".
Methods
as_psgi(@args)
Returns a PSGI-compatible coderef which, when called, runs your sub-class of CGI::Snapp as a PSGI app.
This works because the coderef actually calls "psgi_app($args_to_new)" in CGI::Snapp.
See the next method, "dispatch(@args)", for a discussion of @args, which may be a hash or hashref.
Lastly: as_psgi() does not support the error_document option the way dispatch({table => {error_document => ...} }) does. Rather, it throws errors of type HTTP::Exception. Consider handling these errors with Plack::Middleware::ErrorDocument or similar.
dispatch(@args)
Returns the output generated by calling a CGI::Snapp-based module.
@args is a hash or hashref of options, which includes the all-important 'table' key, to define a dispatch table. See "What is the structure of the dispatch table?" for details.
The unfortunate mismatch between dispatch() taking a hash and dispatch_args() taking a hashref has been copied from CGI::Application::Dispatch. But, to clean things up, CGI::Snapp::Dispatch allows dispatch() to accept a hashref. You are encouraged to always use hashrefs, to avoid confusion.
(Key => value) pairs which may appear in the hashref parameter ($args[0]):
- o args_to_new => $hashref
This is a hashref of arguments that are passed into the constructor (
new()) of the application.
If you wish to set parameters in your app which can be retrieved by the $self -> param($key) method, then use:
my($app) = CGI::Snapp::Dispatch -> new; my($output) = $app -> dispatch(args_to_new => {PARAMS => {key1 => 'value1'} });
This means that inside your app, $self -> param('key1') will return 'value1'.
See t/args.t's test_13(), which calls t/lib/CGI/Snapp/App1.pm's rm2().
See also t/lib/CGI/Snapp/Dispatch/SubClass1.pm's dispatch_args() for how to pass in one or more such values via your sub-class.
- o auto_rest => $Boolean
If 1, derived class's dispatch table. See also the next option.
Default: 0.
See t/args.t test_27().
- o auto_rest_lc => $Boolean
If 1, then in combination with auto_rest, this tells Dispatch that you prefer lower cased HTTP method names. So instead of
foo_POSTand
foo_GETyou'll get
foo_postand
foo_get.
See t/args.t test_28().
- o default
Specify a value to use for the path info if one is not available. This could be the case if the default page is selected (e.g.: '/cgi-bin/x.cgi' or perhaps '/cgi-bin/x.cgi/').
- o error_document
Note: When using "as_psgi(@args)", error_document makes no sense, and is ignored. In that case, use Plack::Middleware::ErrorDocument or similar.
If this value is not provided, and something goes wrong, then Dispatch will return a '500 Internal Server Error', using an internal HTML page. See t/args.t, test_25().
Otherwise, the value should be one of the following:
- o A customised error string
To use this, the string must start with a single double-quote (") character. This character character will be trimmed from final output.
- o A file name
To use this, the string must start with a less-than sign (<) character. This character character will be trimmed from final output.
$ENV{DOCUMENT_ROOT}, if not empty, will be prepended to this file name.
The file will be read in and used as the error document.
See t/args.t, test_26().
- o A URL to which the application will be redirected
This happens when the error_document does not start with " or <.
Note: In all 3 cases, the string may contain a '%s', which will be replaced with the error number (by sprintf).
Currently CGI::Snapp::Dispatch uses three HTTP errors:
- o 400 Bad Request
This is output if the run mode is not specified, or it contains an invalid character.
- o 404 Not Found
This is output if the module name is not specified, or if there was no match with the dispatch table, or the module could not be loaded by Class::Load.
- o 500 Internal Server Error
This is output if the application dies.
See t/args.t, test_24().
- o prefix
This option will set the string to be prepended to the name of the application module before it is loaded and created.
For instance, consider /app/index.cgi/module_name/run_mode.
This would, by default, load and create a module named 'Module::Name'. But let's say that you have all of your application specific modules under the 'My' namespace. If you set this option -
prefix- to 'My' then it would instead load the 'My::Module::Name' application module instead.
The algorithm for converting a path info into a module name is documented in "translate_module_name($name)".
- o table
In most cases, simply using Dispatch with the
defaultand
prefixis enough to simplify your application and your URLs, but there are many cases where you want more power. Enter the dispatch table (a hashref), specified here as the value of the
tablekey.
Since this table can be slightly complicated, a whole section exists on its use. Please see the "What is the structure of the dispatch table?" section.
Examples are in the dispatch_args() method of both t/lib/CGI/Snapp/Dispatch/SubClass1.pm and t/lib/CGI/Snapp/Dispatch/SubClass2.pm.
dispatch_args($args)
Returns a hashref of args to be used by "dispatch(@args)".
This hashref is a dispatch table. See "What is the structure of the dispatch table?" for details.
"dispatch(@args)" calls this method, passing in the hash/hashref which was passed in to "dispatch(@args)".
Default output:
{ args_to_new => {}, default => '', prefix => '', table => [ ':app' => {}, ':app/:rm' => {}, ], }
This is the perfect method to override when creating a subclass to provide a richer "What is the structure of the dispatch table?".
See CGI::Snapp::Dispatch::SubClass1 and CGI::Snapp::Dispatch::SubClass2, both under t/lib/. These modules are exercised by t/args.t.
new()
See "Constructor and Initialization" for details on the parameters accepted by "new()".
Returns an object of type CGI::Snapp::Dispatch.
translate_module_name($name)
This method is used to control how the module name is translated from the matching section of the path. See "How does CGI::Snapp parse the path info?".
The main reason that this method exists is so that it can be overridden if it doesn't do exactly what you want.
The following transformations are performed on the input:
- o The text is split on '_'s (underscores)
Next, each word has its first letter capitalized. The words are then joined back together using '::'.
- o The text is split on '-'s (hyphens)
Next, each word has its first letter capitalized. The words are then joined back together without the '-'s.
Examples:
module_name => Module::Name module-name => ModuleName admin_top-scores => Admin::TopScores
What is 'path info'?
For a CGI script, it is just $ENV{PATH_INFO}. The value of $ENV{PATH_INFO} is normally set by the web server from the path info sent by the HTTP client.
A request to /cgi-bin/x.cgi/path/info will set $ENV{PATH_INFO} to /path/info.
For Apache, whether $ENV{PATH_INFO} is set or not depends on the setting of the AcceptPathInfo directive.
For a PSGI script, it is $$env{PATH_INFO}, within the $env hashref provided by PSGI.
Path info is also discussed in "mode_param([@new_options])" in CGI::Snapp.
Similar comments apply to the request method (GET, PUT etc) which may be used in rules.
For CGI scripts, request method comes from $ENV{HTTP_REQUEST_METHOD} || $ENV{REQUEST_METHOD}, whereas for PSGI scripts it is just $$env{REQUEST_METHOD}.
Is there any sample code?
Yes. See t/args.t and t/lib/*.
Why did you fork CGI::Application::Dispatch?
To be a companion module for CGI::Snapp.
What version of CGI::Application::Dispatch did you fork?
V 3.07.
How does CGI::Snapp::Dispatch differ from CGI::Application::Dispatch?
There is no module called CGI::Snapp::Dispatch::PSGI
This just means the PSGI-specific code is incorporated into CGI::Snapp::Dispatch. See "as_psgi(@args)".
Processing parameters to dispatch() and dispatch_args()
The code which combines parameters to these 2 subs has been written from scratch. Obviously, the intention is that the new code behave in an identical fashion to the corresponding code in CGI::Application::Dispatch.
Also, the re-write allowed me to support a version of "dispatch(@args)" which accepts a hashref, not just a hash. The same flexibility has been added to "as_psgi(@args)".
No special code for Apache, mod_perl or plugins
I suggest that sort of stuff is best put in sub-classes.
Unsupported features
- o dispatch_path()
Method dispatch_path() is not provided. For CGI scripts, the code in dispatch() accesses $ENV{PATH_INFO} directly, whereas for PSGI scripts, as_psgi() accesses the PSGI environment hashref $$env{PATH_INFO}.
Enhanced features
"new()" can take extra parameters:
- o return_type
Note: return_type is ignored by "as_psgi(@args)".
This module uses Class::Load to try loading your application's module
CGI::Application::Dispatch uses:
eval "require $module";
whereas CGI::Snapp::Dispatch uses 2 methods from Class::Load:
try_load_class $module; croak 404 if (! is_class_loaded $module);
For CGI scripts, the 404 (and all other error numbers) is handled by sub _http_error(), whereas for PSGI scripts, the code throws errors of type HTTP::Exception.
Reading an error document from a file
CGI::Application::Dispatch always prepends $ENV{DOCUMENT_ROOT} to the file name. Unfortunately, this means that when $ENV{DOCUMENT_ROOT} is not set, File::Spec prepends a '/' to the file name. So, an error_document of '<x.html' becomes '/x.html'.
This module only prepends $ENV{DOCUMENT_ROOT} if it is not empty. Hence, with an empty $ENV{DOCUMENT_ROOT}, an error_document of '<x.html' becomes 'x.html'.
See sub _parse_error_document() and t/args.t test_26().
Handling of exceptions
CGI::Application::Dispatch uses a combination of eval and Try::Tiny, together with Exception::Class. Likewise, CGI::Application::Dispatch::PSGI uses the same combination, although without Exception::Class.
CGI::Snapp::Dispatch just uses Try::Tiny. This applies both to CGI scripts and PSGI scripts. For CGI scripts, errors are handled by sub _http_errror(). For PSGI scripts, the code throws errors of type HTTP::Exception.
How does CGI::Snapp parse the path info?
Firstly, the path info is split on '/' chars. Hence /module_name/mode1 gives us ('', 'module_name', 'mode1').
The value 'module_name' is passed to "translate_module_name($name)". In this case, the result is 'Module::Name'.
You are free to override "translate_module_name($name)" to customize it.
After that, the prefix option's value, if any, is added to the front of 'Module::Name'. See "dispatch_args($args)" for more about prefix.
FInally, 'mode1' becomes the name of the run mode.
Remember from the docs for CGI::Snapp, that this is the name of the run mode, but is not necessarily the name of the method which will be run. The code in your sub-class of CGI::Snapp can map run mode names to method names.
For instance, a statement like:
$self -> run_modes({rm_name_1 => 'rm_method_1', rm_name_2 => 'rm_method_2'});
in (probably) sub setup(), shows how to separate run mode names from method names.
What is the structure of the dispatch table?
Sometimes it's easiest to explain with an example, so here you go:
CGI::Snapp::Dispatch -> new -> dispatch # Note the new()! ( args_to_new => { PARAMS => {big => 'small'}, }, default => '/app', prefix => 'MyApp', table => [ '' => {app => 'Blog', rm => 'recent'}, 'posts/:category' => {app => 'Blog', rm => 'posts'}, ':app/:rm/:id' => {app => 'Blog'}, 'date/:year/:month?/:day?' => { app => 'Blog', rm => 'by_date', args_to_new => {PARAMS => {small => 'big'} }, }, ] );
Firstly note, that besides passing this structure into "dispatch(@args)", you could sub-class CGI::Snapp::Dispatch and design "dispatch_args($args)" to return exactly the same structure.
OK. The components, all of which are optional, are:
- o args_to_new => $hashref
This is how you specify a hashref of parameters to be passed to the constructor (new() ) of your sub-class of CGI::Snapp.
- o default => $string
This specifies a default for the path info in the case this code is called with an empty $ENV{PATH_INFO}.
- o prefix => $string
This specifies a namespace to prepend to the class name derived by processing the path info.
E.g. If path info was /module_name, then the above would produce 'MyApp::Module::Name'.
- o table => $arrayref
This provides a set of rules, which are compared - 1 at a time, in the given order - with the path info, as the code tries to match the incoming path info to a rule you have provided.
The first match wins.
Each element of the array consists of a rule and an argument list.
Rules can be empty (see '' above), or they may be a combination of '/' chars and tokens. A token can be one of:
- o A literal
Any token which does not start with a colon (:) is taken to be a literal string and must appear exactly as-is in the path info in order to match. In the rule 'posts/:category', posts is a literal.
- o A variable
Any token which begins with a colon (:) is a variable token. These are simply wild-card place holders in the rule that will match anything - in the corresponding position - in the path info that isn't a slash.
These variables can later be referred to in your application (sub-class of CGI::Snapp) by using the $self -> param($name) mechanism. In the rule 'posts/:category', ':category' is a variable token.
If the path info matched this rule, you could retrieve the value of that token from within your application like so: my($category) = $self -> param('category');.
There are some variable tokens which are special. These can be used to further customize the dispatching.
- o :app
This is the module name of the application. The value of this token will be sent to "translate_module_name($name)" and then prefixed with the prefix if there is one.
- o :rm
This is the run mode of the application. The value of this token will be the actual name of the run mode used. As explained just above ("How does CGI::Snapp parse the path info?"), this is not necessarily the name of the method within the module which will be run.
- o An optional variable
Any token which begins with a colon (:) and ends with a question mark (?) is considered optional. If the rest of the path info matches the rest of the rule, then it doesn't matter whether it contains this token or not. It's best to only include optional variable tokens at the end of your rule. In the rule 'date/:year/:month?/:day?', ':month?' and ':day?' are optional-variable tokens.
Just as with variable tokens, optional-variable tokens' values can be retrieved by the application, if they existed in the path info. Try:
if (defined $self -> param('month') ) { ... }
Lastly, $self -> param('month') will return undef if ':month?' does not match anything in the path info.
- o A wildcard
The wildcard token '*' allows for partial matches. The token must appear at the end of the rule.
E.g.: 'posts/list/*'. Given this rule, the 'dispatch_url_remainder' param is set to the remainder of the path info matched by the *. The name ('dispatch_url_remainder') of the param can be changed by setting '*' argument in the argument list. This example:
'posts/list/*' => {'*' => 'post_list_filter'}
specifies that $self -> param('post_list_filter') rather than $self -> param('dispatch_url_remainder') is to be used in your app, to retrieve the value which was passed in via the path info.
See t/args.t, test_21() and test_22(), and the corresponding sub rm5() in t/lib/CGI/Snapp/App2.pm.
- o A HTTP method name
You can also dispatch based on HTTP method. This is similar to using auto_rest but offers more fine-grained control. You include the (case insensitive) method name at the end of the rule and enclose it in square brackets. Samples:
':app/news[post]' => {rm => 'add_news' }, ':app/news[get]' => {rm => 'news' }, ':app/news[delete]' => {rm => 'delete_news'},
The main reason that we don't use regular expressions for dispatch rules is that regular expressions did not provide for named back references (until recent versions of Perl), in the way variable tokens do.
How do I use my own logger object?
Study the sample code in CGI::Snapp::Demo::Four, which shows how to supply a Config::Plugin::Tiny *.ini file to configure the logger via the wrapper class CGI::Snapp::Demo::Four::Wrapper.
Also, see t/logs.t, t/log.a.pl and t/log.b.pl.
See also "What else do I need to know about logging?" in CGI::Snapp for important info and sample code.
How do I sub-class CGI::Snapp::Dispatch?
You do this the same way you sub-class CGI::Snapp. See this FAQ entry in CGI::Snapp.
Are there any security implications from using this module?
Yes. Since CGI::Snapp::Dispatch will dynamically choose which modules to use as content generators, it may give someone the ability to execute specially crafted modules on your system if those modules can be found in Perl's @INC path. This should only be a problem if you don't use a prefix.
Of course those modules would have to behave like CGI::Snapp based modules, but that still opens up the door more than most want.
By using the prefix option you are only allowing Dispatch to pick modules from a pre-defined namespace.
Why is CGI::PSGI required in Build.PL and Makefile.PL when it's sometimes not needed?
It's a tradeoff. Leaving it out of those files is convenient for users who don't run under a PSGI environment, but it means users who do use PSGI must install CGI::PSGI explicitly. And, worse, it means their code does not run by default, but only runs after manually installing that module.
So, since CGI::PSGI's only requirement is CGI, it's simpler to just always require it.
Troubleshooting
It doesn't work!::Dispatch -> new -> as_psgi({args_to_new => {logger => $logger} }, ...);
In addition, you can trace CGI::Snapp::Dispatch itself with the same (or a different) logger:
CGI::Snapp::Dispatch -> new(logger => $logger) -> as_psgi({args_to_new => {logger => $logger} }, ...);
The entry to each method in CGI::Snapp and CGI::Snapp::Dispatch is logged using this technique, although only when maxlevel is 'debug'. Lower levels for maxlevel do not trigger logging. See the source for details. By 'this technique' I mean there is a statement like this at the entry of each method:
$self -> log(debug => 'Entered x()');
- o Are you confused about combining parameters to dispatch() and dispatch_args()?
I suggest you use the request_type option to "new()" to capture output from the parameter merging code before trying to run your module. See t/args.t.
- o Are you confused about patterns in tables which do/don't use ':app' and ':rm'?
The golden rule is:
- o If the rule uses 'app', then it is non-capturing
This means the matching app name from $ENV{PATH_INFO} is not saved, so you must provide a modue name in the table's rule. E.g.: 'app/:rm' => {app => 'MyModule}, or perhaps use the prefix option to specify the complete module name.
- o If the rule uses ':app', then it is capturing
This means the matching app name from $ENV{PATH_INFO} is saved, and it becomes the name of the module. Of course, prefix might come into play here, too.
- o Did you forget the leading < (read from file) in the customised error document file name?
-
- o Did you forget the leading " (double-quote) in the customised error document string?
-
- o Did you forget the embedded %s in the customised error document?
This triggers the use of sprintf to merge the error number into the string.
- o Are you trying to use this module with an app non based on CGI::Snapp?
Remember that CGI::Snapp's new() takes a hash, not a hashref.
- o Did you get the mysterious error 'No such field "priority"'?
You did this:
as_psgi(args_to_new => $logger, ...)
instead of this:
as_psgi(args_to_new => {logger => $logger, ...}, ...)
-
CGI::Snapp - A almost back-compat fork of CGI::Application.
As of V 1.01, CGI::Snapp now supports PSGI-style apps.
And see CGI::Snapp::Dispatch::Regexp for another way of matching the path info.
Machine-Readable Change Log
The file Changes was converted into Changelog.ini by Module::Metadata::Changes.
Version Numbers
Version numbers < 1.00 represent development versions. From 1.00 up, they are production versions.
Credits
Please read "CONTRIBUTORS" in CGI::Application::Dispatch, since this module is a fork of the non-Apache components of CGI::Application::Dispatch.
Repository
Support
Author
CGI::Snapp::Dispatch:
|
http://web-stage.metacpan.org/pod/CGI::Snapp::Dispatch
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
LQR with CVXPY
Holy crap this was easy.
And I was able to easily add a constraint on the available force. Hot damn. It is a ridiculously tiny problem I guess, but still pretty damn cool. 0.002 second runtime.
import cvxpy as cvx import numpy as np import matplotlib.pyplot as plt lookahead = 50 dt = 0.1 F = 1.0 objective = 0 A = np.array([[1,dt],[0,1]]) B = np.array([0,dt*F]) x0 = np.array([1,0]) xt = cvx.Variable(2) state = [xt] cost = 0 constraints = [xt == x0] controls = [] for i in range(lookahead): ut = cvx.Variable() xtn = cvx.Variable(2) controls.append(ut) state.append(xtn) constraints.append(xtn == A*xt + B * ut ) constraints.append(ut <= 1.0) constraints.append(ut >= -1.0) cost = cost + cvx.square(xtn[0]) #+ 0.1 * cvx.square(ut) xt = xtn objective = cvx.Minimize(cost) prob = cvx.Problem(objective, constraints) sol = prob.solve(verbose=True) print(sol) pos = np.array(list(map( lambda x: x.value, state))) us = np.array(list(map( lambda x: x.value, controls))) plt.plot(pos[:,0,0]) plt.plot(us) print(pos[:,0,0]) plt.show()
|
http://www.philipzucker.com/lqr-with-cvxpy/
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
I am having a hard time with this.
Although am new here.
I am using Codeigniter, This is the query code.
<?php $is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'"); $check = $is_member->result_array(); if (in_array($id, $check)) { echo "Match found"; } else { echo "Match not found"; } ?>
Which outputs Match not found
but
print_r($check) gives
Array ( [0] => Array ( [user] => 1 ) [1] => Array ( [user] => 2 )
So how am I going to check if a specific integer is in the array which is multidimensional I think.
Note: $id = 1, which is clearly in the array, but it still saying not found.
Any answers? feel free to correct me if am doing something wrong
If you already know the ID you’re looking for and the room ID where you want to check, you might benefit from doing this:
(I’m assuming here that the room number is contained in
$row->id and the user ID you’re looking for is
$id)
$this->db->select('user'); $this->db->from('chatroom_members'); $this->db->where('room', $row->id); $this->db->where('user', $id); $query = $this->db->get(); return ($query->num_rows() == 0) ? false : true;
You’ll save yourself from looping through a huge result array (which may or may not be an issue depending on how large the resultset from the table is) and you’ll get a simple yes/no answer.
I used a
return and a ternary operator but you can easily change that to an if/else and do something else than return true or false depending on what you need.
Answer:
I think the best way to do it is having a foreach loop, in_array wouldn’t work on the root array.
<?php $is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'"); $arrays = $is_member->result_array(); $found = false; foreach ($arrays as $array) { if(in_array($id,$array)) { $found = true; break; } } echo $found === true ? "Match found" : "Match not found"; ?>
Tags: codeigniter, phpphp
|
https://exceptionshub.com/php-how-can-i-check-if-a-value-is-in-codeigniter-result_array.html
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
#include <Adafruit_NeoPixel.h>#define PIN 8//(2, PIN, NEO_GRB + NEO_KHZ800);void setup() { // put your setup code here, to run once: strip.begin(); strip.setBrightness(10); strip.show(); // Initialize all pixels to 'off'}void loop() { // put your main code here, to run repeatedly: strip.setPixelColor(1, strip.Color(255, 0, 0)); strip.setPixelColor(0, strip.Color(255, 0, 0)); strip.show(); delay(1000); strip.setPixelColor(1, strip.Color(0, 255, 0)); strip.setPixelColor(0, strip.Color(0, 255, 0)); strip.show(); delay(1000);}
the data signal did not seem to go from Uno -> LED1_DIN -> LED1_DOUT -> LED2_DIN), but both the LEDs work if I just give them data direct from the Uno.
So I then thought that maybe the "DOUT" and "VDD" pins have been mixed up and that I would just have to wire in accordance to this pinout:
the data out from the Uno is flickering at intervals consistent with the colour changes written in the code
The SK6812 is a set smart control circuit and one of the controlled LED source. The LED has a low driving voltage which allows for environmental protection and energy saving, high brightness, good consistency, low power, and long life.
Update: found the problem! The solder had not actually created a connection between the VDD pin and the pad.
And - your point is?
|
https://forum.arduino.cc/index.php?topic=590124.0
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Important: Please read the Qt Code of Conduct -
[Solved]Qt cant find header, despite proper path(?)(libvlc-qt)
- prawdziwy-sok last edited by
Hi, so my struggle with vlc continues. I have decided to give [url=]libvlc-qt[/url] a go, and, as you can probably guess, it's not working.
I'm running windows 8.1, using microsoft visual c++ compiler 12.0 for amd64, CDB for x64, with Qt 5.3.0(msvc2013_64), qt creator
my project file:
@
#-------------------------------------------------
Project created by QtCreator 2014-05-22T23:35:22
#-------------------------------------------------
QT += core
QT -= gui
TARGET = libvlcqt
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
win32: LIBS += -L$$PWD/../../../Programs/Qt/libvlc_qt/libvlc_qt_0_9_0_win64_msvc2012/lib/ -lvlc-qt
INCLUDEPATH += $$PWD/../../../Programs/Qt/libvlc_qt/libvlc_qt_0_9_0_win64_msvc2012/include
DEPENDPATH += $$PWD/../../../Programs/Qt/libvlc_qt/libvlc_qt_0_9_0_win64_msvc2012/include
@
and my cpp file:
@
#include <QCoreApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<"dupa"<<endl; int e; cin>>e; return a.exec();
}
@
They work brilliantly, debugger works, breakpoints work, so I'd quess that I have everything setup properly.
However, as I mentioned, I want to use libvlc-qt, which i have downloaded and extracted into my
E:\Programs\Qt\libvlc_qt\libvlc_qt_0_9_0_win64_msvc2012 directory. (thats the one I've added in my project file). When I add
#include <vlc-qt/Config.h> (which qt sees for sure, as autofill works)
i get the "E:\Data\QTprojects\libvlcqt\main.cpp:3: error: C1083: Cannot open include file: 'vlc-qt/Config.h': No such file or directory" errror when trying to build. Why might that be? is qt built with msvc 2013 incompatible with library that was built with msvc 2012?
- prawdziwy-sok last edited by
Not solution, but source of the problem- vlc-qt is dependant on libvlc, and my version of libvlc is compatible with qt > 4.6 but less than 5.0.
|
https://forum.qt.io/topic/41736/solved-qt-cant-find-header-despite-proper-path-libvlc-qt
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
I have read through the editing and import guidelines for OSM. Contributing our data would require a considerable number of hours to do properly. Doing it properly is the only way we're interested in contributing.
What kind of protection can be had for any data we might share?
Note: Receiving "notifications" whenever someone edits data we've contributed, with the option to revert the changes, does not interest us. Taking the time to share the data via the OSM guidelines is already a significant burden and we want a 'fire-and-forget' approach. But if it can't be protected from wrong (if well meaning) edits then we don't see much point in sharing in the first place.
Further clarification: There seem to be places where a portion of our data, or data product, has made it into OSM. We are fine with that (since we are not responsible for what someone might do with our data via OSM) but we have also noted subsequent changes to our data that has decreased it's accuracy. Hence my question. No point in contributing data when we have no time to play data-cop to keep it in good condition.
asked
29 Mar '16, 18:09
_jk
24●1●1●4
accept rate:
0%
edited
30 Mar '16, 15:59
Some thoughts:
Adding a remark into description of each way saying that when the way was imported all the points were with accuracy of for example +-0.5m gives a good indication to future editors to trust the locations of the points and not to move them if not truly necessary.
Your imported data will for sure change regarding the tags on the ways and points as I am sure there are things people do wish to add that is not already tagged. Not knowing the details of your data it might be as simple information as surface, reference numbers, speed limits and access rights.
As more detail (smaller roads, footways, paths, speed pumps and all kind of strange things you did not intend to map youreselves) is added over time your imported ways itself do need to change by getting new nodes in points where added roads do link or where new features are.
OSM is open, so I'm afraid you can't do that.
A look at the CT may tell you more about contributing to OSM.
answered
29 Mar '16, 19:01
yvecai
1.4k●12●25
accept rate:
10%
There's nothing you can do to prevent other people from making changes.
You can of course work with them to make sure they understand that their changes are harmful, but there's no mechanism to lock data, and probably quite a lot of resistance to the idea if you survey the community.
One way to do the fire and forget might be to make the data available under a broadly open license and let someone else do the work to integrate it (or maybe people will just use it as a reference). No ongoing burden there.
answered
29 Mar '16, 18:15
maxerickson
12.4k●10●79●174
accept rate:
31%
edited
29 Mar '16, 18:57
OSM has its own mechanisms of producing quality. These mechanisms will be different from yours, and the quality they produce will be different from yours. It is important to understand that OSM is first and foremost a group of humans who curate a world wide data set. Bypassing these humans - trying to share something "through" OSM where you and only you control the data - would be taking the most valuable aspect of OSM out of the equation. Not only is this not possible; it also betrays considerable ignorance about what OSM is in the first place, and what made it great. OSM is a project where data has been surveyed because official data wasn't made available, not a melting pot for official data from different sources. That doesn't mean that your data isn't welcome - au contraire! But your data is like a glass of water that you pour into the ocean that OSM already is. You can release it but you can't hold on to it after.
Why would uncontrolled mean poor quality data ? Why do you expect that people will alter the data you added and replace it with "poor quality" ? I feel insulted by this statement.
I think almost every OSM contributor will try to improve bad data and when the data is good, it will remain unaltered. Please do not think that only your agency is capable of producing quality data.
This may have started as an honest question, but it is completely clear that you are all now just feeding a troll.
Closing the question.
You are welcome to suggest ways to improve and or keep data quality. Simply locking it is not an option as already explained multiple times.
There is no such thing as perfect data. People can always improve upon your work (because you never bothered to map some detail, because a new path is added/blocked/resurfaced, etc). Suggesting that trails could remain unchanged for 10 years would be quaint idea in most parts of the world. Precise data is even more vulnerable to this kind of bitrot; not too long ago somebody mapped a golf course with centimeter accuracy, which sounds great until you realize that this accuracy was casually twarthed by vegetation growth and plate tectonics.
Therefore, no data is untouchable in OSM. This is not a weakness, this is how OSM thrives. It does come at the price of occasional temporary deterioration, but the balance stays overwhelmingly positive. The "how to lock some OSM data" question comes back with some regularity, and the answer from the community is pretty much always that it would be a bad idea and isn't supported.
I find it strange that you think that contributing your data to OSM would only be worth it if said data remains untouched by anyone but you. What are you trying to achieve by puting your data in OSM ? One typical reason is to make the data more broadly available, and that goal remains fullfiled even if some heavy-handed contributor moves a trail by a meter. The general public is still better off if trail data is available in OSM, even if some of it got deteriorated. They can still get at your "perfect" data if they know where to find it and don't need the extra context and improvements. Which source they choose depends on their needs.
If you want this import to be a one-time job but will keep improving your version of the dataset, a good solution is to document your import process so that anybody can redo the import/merge process later. OSM has plenty of QA tools, including some which compare OSM data to other sources.
OSM won't sit still for 10 years, or even a day. This can feel daunting, but this is the right thing to do. Embrace the flow :)
answered
30 Mar '16, 00:08
Vincent de P... ♦
17.1k●17●148●245
accept rate:
19%
Plate tectonics goes faster than you might think. Centimeter-accurate positions will be thrown off by tectonics within one year pretty much anywhere on Earth. Half-meter accuracy will take somewhere between 5 and 20 years depending on where you are. If your agency aims to make very acccurate measurements on a multi-year timeframe, it should not laugh at tectonics.
Many in the OSM community would take offense in the statement that we "garble data". We see the OSM model as a way to achieve supperior completeness and accuracy compared to other providers, and take quality seriously. There are occasional hiccups, but the general trend is overwhelmingly positive. As with all wikis, "it doesn't work in theory, but it works in practice".
If you want your data to thrive in OSM, you need to learn to give up your position of absolute authority and trust the community. OSM is not a hosting platform for your immutable blob of data : it will integrate it, work with it, improve it.
First of all, and most importantly, that's great that your agency wants to contribute your data, Thank you! I'm glad to hear that other groups are taking an interest in OSM, and I'm gland your group wants to do it properly.
I'm not very knowledgeable at all about data imports, after a bit of reading I suspect that you know more than me. Despite that, I would like to underline that it's important to consult with the local community before doing any imports.
As others have said there is not a technical mechanism in place to prevent detrimental edits. I don't think this would be possible to implement without preventing edits that are beneficial. OSM continues to improve everyday, and it's important to allow all objects represented in the database to continue to improve. OSM's solution to the problem of detrimental edits is relying on the editors ensure that other editors are improving the map. While well meaning edits may, as you say, be "wrong", on the whole the map improves with every passing day.
I don't quite understand what benefit you'd get if it was somehow possible to "lock" the roads and trails you are suggesting you import. The vast majority of edits are beneficial so preventing edits is only going to be detrimental to the map.
So to answer your question, as long as the import is accepted by the community, then you are welcome to "fire and forget" it, but it is necessary to trust the community to do the right thing with your data. They will.
answered
29 Mar '16, 19:32
keithonearth
2.7k●48●68●97
accept rate:
17%
As others have pointed out, one of the most important aspects of OSM is that the data in it is available to the general population to use, and even edit, if they see a need to do that. Your high accuracy data, which is certainly welcome, may have other properties besides positioning that will need to be changed by future mappers. The way your objects are tagged, for example, will almost certainly need modification at some point in the future because tagging methodology is constantly evolving. I've seen huge data imports from very respectable sources, state agencies usually, whose tags are completely wrong. The professional GIS specialists who contributed those data were probably convinced they had everything right too. But in the end, some one of us amateurs will have to sit down and correct their work.
@_jk, there is so much more to OSM than positional data. You "seriously doubt anyone is going to beat that", but there is more data that you may not have considered. What if a new path joins up to it later? No, not allowed. They add street lighting? No, you can't add that, this is _jk's private data. A route is run over your way, sharp intake of breath
Accept that when you upload that to OSM, you agree that it can and will be edited. You can't put it on a publically editable medium then get upset when people publically edit it.
@_jk,
Please don't take my comment as a reason to withhold your data. We want your data. I was simply pointing out that protecting it from the OSM community is not only not possible but not desirable.
@_jk, "Just thought we would look into contributing to OSM quality but it's not wanted, like, at all. I get that now." You misunderstand. It is very much wanted, but once you make it available, you can not control it what happens to it.
What are the reasons for all OSM data being so-so, and isn't it in your interest in making other data better?
Show us the data, it matters more than opinions:
Since OSM is a very good data producer and one of the biggest data consumers, I do not think your time spent on this will be wasted. At least if you think other people than you should use your data.
answered
30 Mar '16, 05:12:
import ×184
quality_assurance ×11
data-integrity ×1
locking ×1
question asked: 29 Mar '16, 18:09
question was seen: 10,710 times
last updated: 30 Mar '16, 22:16!
|
https://help.openstreetmap.org/questions/48912/how-do-i-protect-my-data
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
In this tutorial, we will implement an online presentation system where the presenter can share the screen contents and their video and audio in real-time, while attendees who join the presentation can watch.
For the back end portion of this application we will use Flask, a Python web application framework, while the front end will be built using vanilla JavaScript. The Twilio Programmable Video service will be used for video and audio streaming.
The final application is shown below:
Tutorial requirements
To finish this tutorial, you will need to meet the following requirements:
- A computer with Python 3.6 or newer version installed. If your operating system does not provide a Python package, download an official build from python.org. You can check it by typing the
pythonor
python3command then press
Enterin your terminal.
- A free or paid Twilio account. If you use this link to register, you will receive a $10 credit when you upgrade to a paid account.
Project environment setup
First, we need to create a directory to save our project:
$ mkdir presentation
Then change into the directory, create a Python virtual environment with Python's
venv module:
$ cd presentation $ python3 -m venv venv
Note that in the last command above, your Python interpreter may be called
python instead of
python3 if you are using Windows. The second "venv" in the command above is the name of the virtual environment, a folder called "venv" will appear in our project directory after you executed this command.
Now we can activate the virtual environment we just created by using the activate script inside our virtual environment folder. If you are using Linux or macOS:
$ source venv/bin/activate
Or if you are using Windows:
$ venv\Scripts\activate
From now on, you will see a
(venv) prompt in your terminal or command line window, to indicate that you have activated the environment successfully:
(venv) $ _
Next step is install the dependencies for our project, which are:
- Flask: A Python micro web framework.
- twilio: A library for communicating with the Twilio API.
- python-dotenv: A library for importing environment variables from
.env file.
Use the command below to install these packages:
(venv) $ pip install flask twilio python-dotenv
The last step is to generate a requirements file (normally named
requirements.txt) to record the dependencies in the current environment so that you can replicate the same environment on other machines:
(venv) $ pip freeze > requirements.txt
The content of the requirements file will look like this:
certifi==2020.12.5 chardet==4.0.0 click==7.1.2 Flask==1.1.2 idna==2.10 itsdangerous==1.1.0 Jinja2==2.11.2 MarkupSafe==1.1.1 PyJWT==2.0.0 python-dotenv==0.15.0 pytz==2020.4 requests==2.25.1 six==1.15.0 twilio==6.50.1 urllib3==1.26.2 Werkzeug==1.0.1
Twilio service setup
To connect your application with Twilio, we have to create a file called
.env, where we can save the needed Twilio account credentials as environment variables:
TWILIO_ACCOUNT_SID=your-twilio-account-sid TWILIO_API_KEY=your-twilio-api-key TWILIO_API_SECRET=your-twilio-api-secret
These values used to identify your account when you connect and talk to the Twilio servers. You can obtain them from your Twilio Console. You can find the Twilio Account SID field in your dashboard:
The remaining two variables require a bit of extra work. First we need to find the "All products & Services" button on the left sidebar of the Twilio Console page, then find the "Programmable Video" service in the "Communications Cloud" section (click the "Pin" button to pin it on your left sidebar for convenient access). From there access the "API Keys" page on the "Tools" menu. Click the red "+" button to create a new API key for this project. Give it a friendly name (here I used presentation), and keep the "KEY TYPE" as "Standard".
After clicking the "Create API Key" button, you will see the API Key ("SID" field) and the API Secret ("SECRET" field):
Copy and paste these values to the last two variables in your
.env file.
Since these environment variables contain sensitive data, if you are going to use Git to manage your project, be sure to add
.env to your
.gitignore file to prevent it from ever being committed into your Git history.
Now everything is ready, let's start coding!
Implementing the front end page layout
In the Flask application, the HTML templates and static files will be saved in
templates and
static folders respectively. We will create these two folders at the root of the project directory:
$ mkdir templates $ mkdir static
When we have multiple pages in a web application, we don’t need to write the same layout element (e.g.
<head></head>, navigation bar, page footer, etc.) in every HTML template. With Jinja’s template inheritance, we can create a base template which contains the basic page elements and layout. Then we can define some Jinja blocks in the base template that will be filled or updated in the child templates. You can learn more about template inheritance at Flask’s documentation.
In the
templates folder, we will create a base template to display the basic page layout called
base.html. Below is the content of the
templates/base.html file:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href=""> <title>Twilio Online Presentation</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> </head> <body> <h2>Flask & Twilio Online Presentation</h2> {% block main %}{% endblock %} {% block scripts %} <script src=""></script> {% endblock %} </body> </html>
We introduced two static files in the code above. The
style.css in the
<head> section will be added later. This file will have the CSS rules to style our page.
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
At the bottom of the
<body> element, we loaded the Twilio Video JavaScript SDK library. We imported this file from the CDN server provided by Twilio:
<script src="//media.twiliocdn.com/sdk/js/video/releases/2.3.0/twilio-video.min.js"></script>
We also created two blocks. The
main block will house the main content of the page:
{% block main %}{% endblock %}
The
script block will be used to add more JavaScript files in the child templates used for the presenter and attendee pages.
{% block scripts %} <script src=""></script> {% endblock %}
Attendee user interface
Our application is going to have two main URLs, one for the presenter and one for attendees. Below you can see the web page that will be used for attendees. This will be in a template file called
templates/index.html that you need to store in the
templates folder of the project:
{% extends 'base.html' %} {% block main %} <form method="post"> <button id="connect">Join</button> </form> <p id="status">Disconnected</p> <div id="screen"><div id="presenter"></div></div> {% endblock %} {% block scripts %} {{ super() }} <script src="{{ url_for('static', filename='main.js') }}"></script> {% endblock %}
Firstly, we use
extends Jinja tag to declare that this template inherits from the
base.html template added in the previous section.
Secondly, we have a
main block to put our page content. In this block, we create a connection button to let the user join the presentation. The
<p id=”status”> element will be used to display the connection status. The two
<div> elements are where the video streams will be presented: one for the screen track, and one for the presenter video track.
Thirdly, we also have a
scripts block, in order to append the attendee specific JavaScript to the corresponding block in the base template. The
{{ super() }} allows us to preserve the content this block has in the base template.
The new JavaScript file that we are importing is called
main.js. This is where the front end application for attendees will be added.
We will use the following CSS styles, which go in the
static/style.css file. These will help to format the two video elements so that the video window is pinned to the top right corner of the screen window:
#screen { position: absolute; width: 1280px; height: 720px; background: lightgrey; } #presenter { position: absolute; right: 0; width: 320px; height: 240px; background: darkgrey; } #presenter video { width: 100%; height: 100%; }
To help us distinguish the screen and video parts before the presentation starts, we give them different background colors: the screen window will be displayed in
lightgrey, and the video window will be displayed in
darkgrey.
In order to display the index page, we will need to render the HTML file with Flask. Copy the following code in a file named
app.py in the top-level directory of the project:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html')
In the code above, we created a Flask application instance called
app, then registered a function as a route with the
app.route() decorator. The
index() view function is used for rendering the index page we just created.
Run the Flask server with the
flask run command, as follows:
(venv) $ flask run * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on (Press CTRL+C to quit)
Now visit on your web browser, and you will see our main application page:
Flask can automatically restart and reload the application when code changes and display useful debug information for errors. To enable these features in your Flask application, we will need to set the environment variable
FLASK_ENV to
development. We can do this in a file named
.flaskenv, which is used to store Flask-specific environment variables:
FLASK_ENV=development
Now when you run
flask run the application starts in debug mode:
(venv) $ flask run * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 101-750-099 * Running on (Press CTRL+C to quit)
Presenter user interface
Now we will create a template page for the presenter called
presenter.html. The content for this page is shown below. Save the
presenter.html file to the
templates directory.
{% extends 'base.html' %} {% block main %} <form method="post"> <button id="connect">Start Presenting!</button> </form> <p id="status">Disconnected</p> <div id="video"></div> {% endblock %} {% block scripts %} {{ super() }} <script src="{{ url_for('static', filename='presenter.js') }}"></script> {% endblock %}
The content of
presenter.html is very similar to the one we created for
index.html. In the
main block, we changed the text of the connection button to
Start Presenting!. We also do not have the container element of screen share.
In the
scripts block, we referenced a new JavaScript file for the presenter called
presenter.js where we will write the presenter client logic.
To expose the presenter page, we need to create a route for it in
app.py. Add the following code at the bottom of
app.py:
@app.route('/present') def present(): return render_template('presenter.html')
For your reference, here is a diagram with the current project structure:
. ├── .env ├── .flaskenv ├── app.py ├── requirements.txt ├── static │ ├── main.js │ ├── presenter.js │ └── style.css ├── templates │ ├── base.html │ ├── index.html │ └── presenter.html └── venv
Generating access tokens for clients
The JavaScript front end will need to connect to Twilio to access the streaming and sharing features of the Programmable Video service. To connect to the Twilio servers, the clients need to authenticate with an access token, which is generated in our server.
Below you can see an updated
app.py that adds the
login() view function to generate Twilio access tokens for clients.
import os import uuid from flask import Flask, request, render_template, session from twilio.jwt.access_token import AccessToken from twilio.jwt.access_token.grants import VideoGrant from twilio.rest import Client app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev') # get credentials from environment variables account_sid = os.getenv('TWILIO_ACCOUNT_SID') api_key = os.getenv('TWILIO_API_KEY') api_secret = os.getenv('TWILIO_API_SECRET') room_name = 'My Presentation' @app.route('/') def index(): return render_template('index.html') @app.route('/present') def present(): return render_template('presenter.html') @app.route('/token', methods=['POST']) def login(): if request.args.get('present'): username = 'presenter' else: username = uuid.uuid4().hex session['username'] = username # create access token with credentials token = AccessToken(account_sid, api_key, api_secret, identity=username) # create a Video grant and add to token video_grant = VideoGrant(room=room_name) token.add_grant(video_grant) return {'token': token.to_jwt()}
Near the top of the file we retrieve the credential values that we saved in the
.env file, which Flask will automatically import into the system environment when
python-dotenv is installed. For this we use the
os.getenv() function from the Python standard library:
account_sid = os.getenv('TWILIO_ACCOUNT_SID') api_key = os.getenv('TWILIO_API_KEY') api_secret = os.getenv('TWILIO_API_SECRET')
In the new
/login route, we check if the request was sent with a query parameter
present and in that case we assume that the request was sent by the presenter. The query variable can be obtained with
request.args.get() method. If the request came from the presenter, then we set the
username to
presenter. Otherwise, we just generate a random username for the attendee with
uuid.uuid4().hex. The username is stored in the user session, so that it can be recalled later.
if request.args.get('present'): username = 'presenter' else: username = uuid.uuid4().hex session['username'] = username
The
request variable is part of the
flask package, while
uuid is imported directly from the Python standard library.
To use Fask’s
session object, we will need to set a secret key in the Flask application instance:
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
The Twilio package for Python provides the
AccessToken class, which is used to create access tokens. We pass
account_sid,
api_key,
api_secret, and the
identity as arguments:
token = AccessToken(account_sid, api_key, api_secret, identity=username)
We then use the
VideoGrant class to provision the token with access to the video service. The
room argument limits the token to a specific room:
video_grant = VideoGrant(room=room_name) token.add_grant(video_grant)
The room name is defined in the global variable
room_name:
room_name = 'My Presentation'
To complete the function, we generate the token and return a JSON response that contains it:
return {'token': token.to_jwt()}
Connecting the presenter to the presentation
To connect the presenter to the presentation, we will create a function to handle the connection logic. Add this code to a
presenter.js file in the
static directory:
const connectButton = document.getElementById('connect') let connected = false function connectButtonHandler(event) { event.preventDefault() if (!connected) { connectButton.disabled = true connectButton.innerHTML = 'Connecting...' connect().then(() => { connectButton.innerHTML = 'Stop Presentation' connectButton.disabled = false }).catch(error => { alert('Connection failed.') console.error(`Unable to connect: ${error.message}`) connectButton.innerHTML = 'Start Presenting!' connectButton.disabled = false }) } else { disconnect() connectButton.innerHTML = 'Start Presenting!' } } connectButton.addEventListener('click', connectButtonHandler)
In the snippet above, we create a
connectButtonHandler() function that will be triggered when the presenter clicks the “Start Presenting!” button. Note how the function is bound to the
click event of the button in the last line.
To determine the current connection status, we will use a
connected variable that is initialized to
false. The connect button acts as a toggle, so based on the state of the
connected variable it will initiate a connection to the video room, or disconnect from it.
When starting a connection, we call the
connect() function to finish the actual connection process and eventually set
connected to
true. When disconnecting, we will call the
disconnect() function to disconnect the user and end the presentation. The label and status of the connect button is always updated based on the connection status.
Now let's jump into the
connect() function. Add the code below to the
presenter.js file:
let room function connect() { let promise = new Promise((resolve, reject) => { fetch('/token?present=true', {method: 'POST'}).then(res => res.json()).then(data => { return Twilio.Video.connect(data.token, { automaticSubscription: false }) }).then(_room => { room = _room publishPresenterScreen() room.on('participantConnected', participantConnected) room.on('participantDisconnected', participantDisconnected) connected = true updateParticipantCount() resolve() }).catch(error => { console.error(`Unable to connect to Room: ${error.message}`) reject() }) }) return promise }
In this function we return a promise, which will let the caller bind success and error callbacks to it. The result of the promise is controlled by the
resolve() and
reject() functions that are passed as arguments when creating the
Promise object.
We begin the connection process by obtaining an access token from the server. For this we use the
fetch() function to fire an AJAX request:
fetch('/token?present=true', {method: 'POST'})
Notice we pass the query string
?present=true in the URL to tell the server that this is a request from the presenter. We also set the request method to POST by passing an options object.
Next, we use
then() method to continue the call on the return value of the
fetch() call and turn the return value into JSON format with
res => res.json(). Since the
then() method will return a Promise object, we can bind additional
then() clauses to it. In the subsequent
then() call, we grab the token from the JSON response and connect the user to the video room by calling the
Twilio.Video.connect() function from the
twilio-video.js library, with the access token passed as an argument. We also pass an additional options object to set
automaticSubscription to
false. This is because by default, a participant in a video room subscribes to all media streams published by other participants. Since the presenter doesn’t need to subscribe to any other streams, we use this setting to overwrite the default subscribe-to-all rule. You can find more details about this in the Overriding the Default Rule section in the Track Subscriptions Documentation.
.then(res => res.json()).then(data => { return Twilio.Video.connect(data.token, { automaticSubscription: false }) })
In another subsequent
.then() call, we catch the return value of the
Twilio.Video.connect() function, which is the room the user is connected to. Here we save the
_room object returned by
Twilio.Video.connect() to variable
room for future use:
.then(_room => { room = _room // ... }).catch(error => { console.error(`Unable to connect to Room: ${error.message}`) reject() })
Next, we publish the presenter’s screen share track. We will talk about the details of the
publishPresenterScreen() function later.
publishPresenterScreen()
In the remaining code, we define event handlers for when a participant connects or disconnects from the video room, update the state to connected, and finally resolve the promise.
room.on('participantConnected', participantConnected) room.on('participantDisconnected', participantDisconnected) connected = true resolve()
Below you can see the two event handlers for
participantConnected and
participantDisconnected event, which also go in the
static/presenter.js file:
function participantConnected(participant) { console.log(`${participant.identity} just joined the room.`) updateParticipantCount() } function participantDisconnected(participant) { console.log(`${participant.identity} left the room.`) updateParticipantCount() }
In these two functions, we just call the
updateParticipantCount() function, which updates the number of participants shown in the page. Add this function also in
static/presenter.js:
function updateParticipantCount() { if (!connected) { status.innerHTML = 'Disconnected' } else { status.innerHTML = room.participants.size + ' participants are watching.' } }
Publishing the presenter's video feed and screen
The video and audio tracks for the presenter will automatically be published to the video room upon connection, as this is the default. But we also want the presenter to see their own video. To display the video for the presenter, we will create a
displayPresenterVideo function in
static/presenter.js, which will be called when the presenter opens the page:
const videoContainer = document.getElementById('video') function displayPresenterVideo() { Twilio.Video.createLocalVideoTrack().then(track => { videoContainer.appendChild(track.attach()) }) } displayPresenterVideo()
In this function, we call
Twilio.Video.createLocalVideoTrack() to create the local video track. Once the video track is created, we append it to the video element of the page.
In addition to the video and audio tracks, we need to create a video track for the presenter’s screen and publish it to the video room. Below we define a
publishPresenterScreen() function, which will be called when the presenter is connected. Add this function to
presenter.js in the
static directory:
let screenTrack function publishPresenterScreen() { navigator.mediaDevices.getDisplayMedia({ video: { width: 1280, height: 720 } }).then(stream => { screenTrack = new Twilio.Video.LocalVideoTrack(stream.getTracks()[0], {name: 'screen'}) room.localParticipant.publishTrack(screenTrack) screenTrack.mediaStreamTrack.onended = connectButtonHandler }).catch((error) => { alert('Could not share the screen.') console.error(`Unable to share screen: ${error.message}`) }) }
Here we use
navigator.mediaDevices.getDisplayMedia() method exposed by web browsers to capture the screen stream via WebRTC (Web Real-Time Communication) technology, passing an options object to set the video height and width to fit the screen container element that we will use to display the feed to attendees. You can read more on screen sharing in MDN's Screen Capture API Documentation.
The
navigator.mediaDevices.getDisplayMedia() method returns a Promise object. In the callback function, we create a video track object and save it to the variable
screenTrack. We pass the screen sharing stream as an argument, and we also pass an options object that sets the name of the track to
screen. Giving the screen track a custom track name is useful so that we can distinguish it from other tracks when displaying the page for the participants.
We then publish the screen track to the room with
room.localParticipant.publishTrack() method, passing the screen track as an argument.
To complete the screen sharing set up, we bind the
onended event of this stream to the
connectButtonHandler function, so that the presentation ends if the presenter clicks the “Stop sharing” button:
Disconnecting the presenter
The
connectButtonHandler() defined above works as a toggle. When it is invoked to disconnect the video call it calls a
disconnect() function to disconnect the presenter from the room and end the presentation. Here is the
disconnect() function for the presenter, which also goes in
static/presenter.js:
function disconnect() { room.disconnect() connected = false updateParticipantCount() endPresentation() }
This function is quite simple, we just call
room.disconnect() to disconnect the user from the room. This will also unpublish the video and audio tracks. Then we set
connected to
false and call the
updateParticipantCount() and the
endPresentation() function.
In the
endPresentation() function, also in
static/presenter.js, we stop the screen share and unpublish the screen track from the room.:
function endPresentation() { console.log('The presentation is over.') // unpublish screen track room.localParticipant.unpublishTrack(screenTrack) screenTrack.stop() screenTrack = null }
If the presenter refreshes the page or closes the page, the presentation may not reset correctly. To cover these rare cases, we will add a function to listen the
window's
beforeunload event in
static/presenter.js, that will be called when the user refresh/close the browser tab:
window.addEventListener('beforeunload', () => { endPresentation() })
Starting a presentation
Make sure that your Flask server is running, make sure the URL in your browser is in the refresh your page to force the browser to update all the files. You should now see your video stream. Then click the
Start Presenting! button to begin a presentation. The browser will ask for your permission to enable the camera and the microphone:
Then you will be prompted to choose the screen/window/tab to share:
The final application when the presentation starts will look like this:
Connecting attendees to the presentation
In the following sections we are going to implement the attendee front end logic, which has some differences to the presenter, but overall follows the same structure. The JavaScript file that will have the attendee logic is going to be called
main.js, and will also be stored in the
static directory.
The
connectButtonHandler function for participants is almost the same as the one we created for the presenter:
const connectButton = document.getElementById('connect') let connected = false function connectButtonHandler(event) { event.preventDefault() if (!connected) { connectButton.disabled = true connectButton.innerHTML = 'Connecting...' connect().then(() => { connectButton.innerHTML = 'Leave' connectButton.disabled = false }).catch(error => { alert('Connection failed.') console.error(`Unable to connect: ${error.message}`) connectButton.innerHTML = 'Join' connectButton.disabled = false }) } else { disconnect() connectButton.innerHTML = 'Join' } } connectButton.addEventListener('click', connectButtonHandler)
However, the
connect() function is a little different:
function connect() { let promise = new Promise((resolve, reject) => { fetch('/token', {method: 'POST'}).then(res => res.json()).then(data => { return Twilio.Video.connect(data.token, { automaticSubscription: false, audio: false, video: false }) }).then(_room => { room = _room subscribe() room.participants.forEach(participantConnected) room.on('participantConnected', participantConnected) room.on('participantDisconnected', participantDisconnected) connected = true updateParticipantCount() resolve() }).catch(error => { console.error(`Unable to connect to Room: ${error.message}`) reject() }) }) return promise }
When calling the
Twilio.Video.connect() method, we set
audio and
video to
false in the options argument, to prevent the audio and video from the participant from being published to the video room when connecting to the Twilio server. We also set
automaticSubscription to
false to disable the default
subscribe-to-all subscribe rule since we only want the participant to subscribe the presenter’s tracks instead of every participant:
Twilio.Video.connect(data.token, { automaticSubscription: false, audio: false, video: false })
Once the connection is made we call a
subscribe() function to set the participant’s subscribe rule. Here is the definition of this function, which also goes in
static/main.js:
function subscribe() { fetch('/subscribe', {method: 'POST'}).catch(error => { console.error(`Unable to set subscribe rule: ${error.message}`) }) }
In this function, we just send a POST request to the URL
/subscribe on our server, where the subscribe rule will be set. We will define the server route soon.
After setting the subscribe rule, we can receive the presenter’s tracks and display them on the attendee page. We iterate over the whole
room.participants map, which stores the information of all the participants and call the
participantConnected() function for each. We also set up handlers to receive callbacks when new participants join or leave the room in the future:
room.participants.forEach(participantConnected) room.on('participantConnected', participantConnected) room.on('participantDisconnected', participantDisconnected)
Here is the implementation of the
participantConnected() function. Add it at the bottom of
static/main.js:
function participantConnected(participant) { console.log(`${participant.identity} just joined the room.`) // display presenter's tracks for new participant if (participant.identity == 'presenter') { participant.on('trackSubscribed', track => trackSubscribed(track)) participant.on('trackUnsubscribed', trackUnsubscribed) } updateParticipantCount() }
The
participant.identity attribute stores the participant's username. If the joining participant is the presenter, then we define handlers for the
trackSubscribed and
trackUnsubscribed events, which would allow us to receive the video, audio and screen streams.
Here are the implementations of
trackSubscribed() and
trackUnsubscribed(). Add them to
static/main.js:
const screenContainer = document.getElementById('screen') const videoContainer = document.getElementById('presenter') function trackSubscribed(track) { if (track.name == 'screen') { screenContainer.appendChild(track.attach()) } else { videoContainer.appendChild(track.attach()) } } function trackUnsubscribed(track) { track.detach().forEach(element => element.remove()) }
The
trackSubscribed event will be triggered when the presenter track is published to the video room. The event handler receives the track object as an argument. To display the track to the participant, we append it to the related element container. We use the
track.name attribute to assign the video track and the screen track into the right containers.
The
trackUnsubscribed event will be triggered when the track is unpublished, which will happen when the presenter leaves the video room. In the
trackUnsubscribed() callback function, we detach the track from the HTML element and remove the corresponding media element.
Finally, the attendee logic also uses the
updateParticipantCount() function, which is identical to the one used in the presenter logic. Add a copy to
static/main.js:
function updateParticipantCount() { if (!connected) { status.innerHTML = 'Disconnected' } else { status.innerHTML = room.participants.size + ' participants are watching.' } }
To complete the attendee connection logic we have to add the
/subscribe route to our Flask server. Add the following view function at the bottom of
app.py to handle the subscribe rule update:
@app.route('/subscribe', methods=['POST']) def set_subscribe_rule(): username = session['username'] client = Client(api_key, api_secret) client.video.rooms(room_name).participants.get(username)\ .subscribe_rules.update( rules=[ {'type': 'include', 'publisher': 'presenter'} ] ) return '', 204
To set the subscribe rule for a participant, we will need to create a Twilio Client object with
twilio.rest.Client class and passing API Key and API Secret as arguments:
client = Client(api_key, api_secret)
We obtain the username from the Flask user session. To update the subscribe rule for a specific user in a specific room, we use the
client.video.rooms(room_name).subscribe_rules.update() method, passing the
room_name variable and the
username we acquired from the
session object.
username = session['username'] client.video.rooms(room_name).participants.get(username)\ .subscribe_rules.update( rules = [ {'type': 'include', 'publisher': 'presenter'} ] )
The
update() method accepts a list of rules in the
rules keyword argument. Each rule is a dictionary in the following format:
{'type': rule_type, filter_name: filter_value, filter_name: filter_value, ...}
Since we only need the participant to subscribe to the presenter’s tracks, we use the
include rule type and set the
publisher filter to the presenter’s username, which is
presenter.
You can learn more about the subscribe rule at the Specifying Subscribe Rules section in the Twilio Subscriptions documentation.
Disconnecting participants
To disconnect the participants from the presentation, we will create a
disconnect() function in
static/main.js:
function disconnect() { room.disconnect() connected = false updateParticipantCount() }
In this function, we also need to call
updateParticipantCount() to update the participant count message to show that we are disconnected.
We also need to define a
participantDisconnected() event handler in
static/main.js:
function participantDisconnected(participant) { console.log(`${participant.identity} left the room.`) if (participant.identity == 'presenter') { alert('The presentation is over.') } updateParticipantCount() }
Here we add a notification for the participants when the presenter leaves the presentation.
At this point the logic for the presenter and the attendees is complete. You can open two web browser tabs on your computer, connect to in one, and to in the other and test the two sides of this application.
This is how the attendee’s user interface looks like:
Host your online presentation with ngrok
Congratulations! We have finished the whole application. If you want to host a real online presentation and let your friends or coworkers join, you have to make your application public on the Internet. Instead of deploying your application to a web hosting service, we can use a tunnel forwarding tool to expose your local server to the Internet. While this isn’t as robust as a full deployment on a host, it is a good and simple solution to test the application. Here we will use ngrok, we can install it via a third-party Python package called pyngrok. Make sure the terminal on which you run the following command has the Python virtual environment activated:
pip install pyngrok
Make sure your application is still running, then in a different terminal window, activate the virtual environment and type the following commands to let ngrok expose to the Internet:
$ ngrok http 5000
Pyngrok will download and install the ngrok client when you execute the
ngrok command for the first time. Then It will output a command-line dashboard like this:
You can find a randomly generated public URL () in the
Forwarding section. Share this URL to your friends, tell them to join your online presentation! The presenter will use the URL to access the presenter page.
Conclusion
In this tutorial, we only explored some basics of the Twilio Video service. You can learn more about it in the Twilio Programmable Video Documentation. The complete example code for this tutorial can be found on GitHub. Please feel free to fork the project and add more features. Enjoy the adventure!
This tutorial is inspired by two related tutorials written by Miguel Grinberg. If you want to learn more details, check out the following tutorials:
- Build a Video Chat Application with Python, JavaScript and Twilio Programmable Video
- Screen Sharing with JavaScript and Twilio Programmable Video
Grey Li is a freelance web developer and technical writer. He is also a maintainer of the Flask web application framework. You can learn more about him at his website, GitHub, and Twitter.
|
https://www.twilio.com/blog/online-presentation-python-javascript-twilio-programmable-video
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Written by Leonardo Maldonado✏️
CSS-in-JS is a commonly used concept when solving CSS problems and styling modern applications. When starting a new project, it can be tricky to decide on which CSS-in-JS library to use.
A problem we often run into is that most of the time, we’re building applications that will be used by a lot of people. An application can quickly scale to millions of users depending on its success, and choosing the wrong CSS-in-JS library for your project could end up costing a lot in the future.
The ecosystem of CSS-in-JS libraries is getting better every day, libraries are getting more mature and robust, new features and support are being added, and problems that were once really painful to solve are becoming easier.
Emotion is one of these CSS-in-JS libraries that is more mature and consistent, due to the work of the whole community involved. In this post, we will learn more about Emotion, and see the features and advantages that it can bring to our applications.
Emotion
Emotion is a high performance, flexible, and performant CSS-in-JS library. Emotion helps us to style our application in a faster way, with a decent and consistent CSS composition.
Here are some of the features of Emotion.
Performance
Emotion is a really performant library because it uses a philosophy that comes from a library called glam. The idea is to have the best runtime performance without compromising the runtime cost.
The result is a super fast and small library that is really great for prototyping and design systems. With Emotion, objects can be used everywhere and it is easily composable with arrays.
Framework agnostic
Emotion is a framework-agnostic library, which means that it can be used in a different range of frameworks and libraries. You’re able to use it everywhere you want, with the same powerful API and features. This is not something exclusive to Emotion, we have some other CSS-in-JS libraries that are framework agnostic. However, the idea to reuse Emotion in different projects is fascinating because, for example, you could build a whole design system with support for web and mobile just using Emotion.
Emotion has a package called
@emotion/native that’s for React Native itself, so there’s no need for the developer to use Emotion on the web and use another CSS-in-JS library on mobile.
To start to style your React Native apps using Emotion, all you have to do is install the packages:
yarn add @emotion/core @emotion/native
No additional set up
Emotion requires no additional setup to get started. It has support for nested selectors, media queries, and auto vendor-prefixing. It’s really composable and great for prototyping, you can use just the
CSS function and the
cx to compose everything in your application.
To get started with Emotion, all you have to do is install the package:
yarn add emotion
Now you are able to create your first styled component using Emotion:
import { css, cx } from 'emotion' render( <div className={css` padding: 10px; background-color: red; font-size: 16px; border-radius: 6px; `} > Emotion CSS-in-JS </div> )
Emotion is still different in some ways from other famous libraries such as styled-components and Radium. Let’s understand some of the differences that separate Emotion from other CSS-in-JS libraries and what makes it so performant and flexible.
Styling
There are different Emotion packages, that were created for different use cases. When using Emotion in an application, you need to know the differences between these packages so you won’t be installing more than you need and increasing your bundle size.
The
emotion package is framework agnostic, so if you decide to use Emotion in other applications that are not using React, this is the right package for you:
yarn add emotion
The
@emotion/core package requires React, so this is the right package for you if you’re using Emotion in a React application:
yarn add @emotion/core
CSS prop
The first difference that we notice with Emotion compared to the other famous CSS-in-JS libraries is styling. The primary way to style components using Emotion is to use the
CSS prop.
The
CSS prop allows us to apply styles direct to our component or element without having to create a styled component. There are two ways to use the
CSS prop correctly.
First, if you’re working in a project that you are able to configure a custom babel config, you have to use the
@emotion/babel-preset-css-prop in your
.babelrc:
{ "presets": ["@emotion/babel-preset-css-prop"] }
In case you’re using some boilerplate or starter such as create-react-app, you might not be able to configure a custom babel config, you will need to use the second option, the JSX Pragma.
All you have to do is use the JSX Pragma on the top of your file that’s using the CSS prop, and import the
jsx from
@emotion/core, like this:
/** @jsx jsx */ import { jsx } from '@emotion/core'
JSX Pragma is basically a code that tells the babel plugin to use the
jsx function instead of
React.createElement.
Now, you can use the
CSS prop in any element of your file:
/** @jsx jsx */ import { jsx } from '@emotion/core' import React from "react"; const Header = () => { return ( <header> <h3 css={{ color: 'lightgreen'}}>Hello World!</h3> </header> ) };
A nice feature of the
CSS prop is that we can have access to the theme by default, by using a function that accepts the theme as the
CSS prop:
/** @jsx jsx */ import { jsx } from '@emotion/core' import React from "react"; const Header = () => { return ( <header> <h3 css={theme => ({ color: theme.color.primary}) }>Hello World!</h3> </header> ) };
Style API
A lot of people are using styled-components nowadays, another famous CSS-in-JS library. One of the features that they might miss is the
styled.div style API, that’s why Emotion has a package called
@emotion/styled.
To use this style API, all we have to do is install the
@emotion/styled package using the following command:
yarn add @emotion/styled
And now we can use the style API combined with template literals to create styles very easily:
import styled from '@emotion/styled'; const Button = styled.button` width: 100px; height: 40px; background-color: black; color: white; `;
Theming
Emotion also has support for theming, to work with it all we need to do is install the
emotion-theming package:
yarn add emotion-theming
The
emotion-theming package provides the
ThemeProvider, we should add this provider on the top level of our application and then we can have access to our theme in a styled component using the
props.theme:
import { ThemeProvider } from 'emotion-theming'; const theme = { colors: { primary: 'black', secondary: 'blue' }, breakpoints: { sm: 380, md: 720, } } const App = () => { return ( <ThemeProvider theme={theme}> ... </ThemeProvider> ) }
Media queries
Working with media queries is simple using Emotion. For example, let’s imagine that we have an array of breakpoints:
const breakpoints = [576, 768, 992, 1200];
We can just create a helper function to return the breakpoint that we want, like this:
const mq = (n) => `@media (min-width: ${breakpoints[n]}px)`;
Now, inside our styled-components, we simply use our
mq helper function and pass the media query that we want:
const Text = styled.h3` font-size: 16px; color: black; font-family: Inter; ${mq(1)} { color: green; } ${mq(2)} { color: hotpink; } `;
SSR by default
Server-side rendering is a popular technique and works out of the box with Emotion if you’re using the
@emotion/core and the
@emotion/styled packages.
The default approach is to use the
renderToString from React which will insert a
<style> tag above your element:
import { renderToString } from 'react-dom/server' import App from './App' let html = renderToString(<App />)
The advanced approach is just in case you need to work with
nth child or similar selectors, since the default approach is not the best for it. It requires a few more lines of code, but it works fine.
In your server, put the following code:
import { CacheProvider } from '@emotion/core' import { renderToString } from 'react-dom/server' import createEmotionServer from 'create-emotion-server' import createCache from '@emotion/cache' const cache = createCache() const { extractCritical } = createEmotionServer(cache) let element = ( <CacheProvider value={cache}> <App /> </CacheProvider> ) let { html, css, ids } = extractCritical(renderToString(element)) res .status(200) .header('Content-Type', 'text/html') .send(`<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http- <title>My site</title> <style data-${css}</style> </head> <body> <div id="root">${html}</div> <script src="./bundle.js"></script> </body> </html>`);
Now, on the client-side, all you have to do is the following:
const cache = createCache(); ReactDOM.hydrate( <CacheProvider value={cache}> <App /> </CacheProvider>, document.getElementById('root') );
Should I use Emotion?
Emotion is a really performant and consistent CSS-in-JS library, in comparison with other libraries like styled-components. There’s a lot of content and comparisons between those two libraries, saying that Emotion is 25x faster than styled-components, etc. Even with the release of styled-components v5 last year, Emotion still has a little advantage over styled-components because it has a smaller bundle size and faster runtime. Aside from performance and runtime, both libraries have almost the same functionalities and features.
So, should you use Emotion? There’s not an exact answer to this question, because it really depends on a lot of factors.
If it is your first time using a CSS-in-JS library you may want to start with styled-components. For a better understanding of CSS-in-JS in general, styled-components will work better for you and help to understand the principle concepts of CSS-in-JS and how it can work in real projects. The amount of content available by the community is huge and you can learn about CSS-in-JS really fast.
Have you used a CSS-in-JS library before and are looking for a smaller and faster library? I would go with Emotion. If you’re used to using CSS-in-JS libraries in your projects, you know exactly how and when to use it. Emotion can really help you to get to the next level and build more performative and scalable applications using CSS-in-JS.
Conclusion
In this article, we learned more about Emotion, a powerful and performant CSS-in-JS library that has a lot of nice features. We learned about the core of Emotion, we used the
CSS prop, and learned about theming. Emotion in React appeared first on LogRocket Blog.
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/logrocket/emotion-in-react-1e9c
|
CC-MAIN-2021-10
|
en
|
refinedweb
|
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
UnitC++
UnitC++ is a modern, light weight, single-header c++ library for making unit testing easy. The intention of UnitC++ is to make it really easy to test c++ code in a portable way.
How to use UnitC++
How to get UnitC++
For Users
UnitC++ has a project page on SourceForge which has versioned downloads.
For Developers
UnitC++ is stored in a mercurial repository centrally at bitbucket. The best way to get it is to clone it onto local disk. Like so.
cd ~ hg clone
You can also download/clone it from GitHub at.
How to include UnitC++ in your project
As a single header library this step should be easy to accomplish. The UnitCpp.h header can be copied to your project, or installed and added to the include path.
<UnitCpp.h>. <UnitCpp.h> <UnitCpp.h> TEST(MyString, length_test) { MyString str("This is a string");(""); TEST_TRUE(valid_string.valid()); #ifdef UNITCPP_TEST_THROWS_AVAILABLE TEST_THROWS([&]()<double>(1, some_function()) if you want the values to be compared as
doubless not
ints.
One thing which many people want to do with unit tests is access private members of the class they are testing. This can be done in UnitC++ by use of the
UNITCPP_FRIEND_TEST macro. This is used like so;
class Container { public: ... private: UNITCPP_FRIEND_TEST(Container, internals) int m_member; }; TEST(Container, internals) { Container container; TEST_EQUAL(container.m_member, 5); }
So you declare the specific test a friend of the class you are testing. The macro is called
UNITCPP_FRIEND_TEST so it is declared in the same way as a
friend class.
Note: If you are running many tests in a loop you may want to only print the results which are failures. This is done using the
stop_printing() and
restart_printing() functions. Like this:
TEST(Test, loop) { std::vector<int> ints; stop_printing(); for (int i = 0; i < 1000; ++i) { ints.push_back(i); TEST_EQUAL(ints [i], i); } restart_printing(); TEST_EQUAL(ints.size(), 1000); }
This will only print
Pass: "ints.size() should equal 1000." utest_README.cpp:15
Without an additional 1000 lines of
Pass: "ints [i] should equal i." utest_README.cpp:12
Running the tests with a menu
So you've written a nice set of tests and now you want to run them. This is done with the
TestRegister class. This is a singleton that has registered all of the tests you've declared with the
TEST macro. These are run using the following code.
//============================================================================= int main(int argc, char** argv) { return UnitCpp::TestRegister::test_register().run_tests_interactive( argc, argv ); }
This will produce a menu which looks something like this:
================================================================================ 0) All tests. ================================================================================ 1) Maths 2) "Maths:sqrt_results" 3) "Maths:is_square" 4) "Maths:sqrt_precondition" ================================================================================ 5) MyString 6) "MyString:length_test" 7) "MyString:validity_test"
This gives you the option of running any individual test, any group of tests or all tests.
These numbers can also be give on the command line. e.g.
utest.exe 0 will always run all tests.
Running the tests without a menu
If you don't want the menu or command line options and just want an executable which runs all of the tests the you want a test harness which looks like this:
#include <UnitCpp.h>.
|
https://bitbucket.org/davidcorne/unitcpp
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
a simple iOS app. It will send a single message, and consume that message and log it using print.
In the diagram below, "P" is our producer and "C" is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf of the consumer.
The Objective-C client library
RabbitMQ speaks multiple protocols. This tutorial uses AMQP 0-9-1, which is an open, general-purpose protocol for messaging. There are a number of clients for RabbitMQ in many different languages. We'll use the Objective-C client in this tutorial.
Follow the instructions below to create a new Xcode project.
Now we must add the Objective-C client as a dependency. This is done partly from the command-line. For detailed instructions, visit the client's GitHub page.
Once the client is added as a dependency, build the project with Product -> Build to ensure that it is linked correctly.
To keep things easy for the tutorial, we'll put our send and receive code in the same view controller. The sending code will connect to RabbitMQ and send a single message.
Let's edit ViewController.swift and start adding code.
First, we import the client framework as a module:
import RMQClient
Now we call some send and receive methods from viewDidLoad:
override func viewDidLoad() { super.viewDidLoad() self.send() self.receive() }
The send method begins with a connection to the RabbitMQ broker:
func send() { print("Attempting to connect to local RabbitMQ broker") let conn = RMQConnection(delegate: RMQConnectionDelegateLogger()) conn.start() }
The connection abstracts the socket connection, and takes care of protocol version negotiation and authentication and so on for us. Here we connect to a broker on the local machine with all default settings. A logging delegate is used so we can see any errors in the Xcode console.
If we wanted to connect to a broker on a different machine we'd simply specify its name or IP address using the initWithUri(delegate:) convenience initializer:
let conn = RMQConnection(uri: "amqp://myrabbitserver.com:1234", delegate: RMQConnectionDelegateLogger())
Next we create a channel, which is where most of the API for getting things done resides:
let ch = conn.createChannel()
To send, we must declare a queue for us to send to; then we can publish a message to the queue:
let q = ch.queue("hello") ch.defaultExchange().publish("Hello World!".data(using: .utf8), routingKey: q.name)
Declaring a queue is idempotent - it will only be created if it doesn't exist already.
Lastly, we close the connection:
conn.close()
Here's the whole controller (including receive).
Sending doesn't work!
If this is your first time using RabbitMQ and you get errors logged at this point sending. Our receive method will spin up a consumer that will be pushed messages from RabbitMQ, so unlike send which publishes a single message, it will wait for a message, log it and then quit.
Setting up is the same as send; we open a connection and a channel, and declare the queue from which we're going to consume. Note this matches up with the queue that send publishes to.
func receive() { print("Attempting to connect to local RabbitMQ broker") let conn = RMQConnection(delegate: RMQConnectionDelegateLogger()) conn.start() let ch = conn.createChannel() let q = ch.queue("hello") }
Note that we declare the queue here, as well. Because we might start the receiver before the sender, we want to make sure the queue exists before we try to consume messages from it.
We're about to tell the server to deliver us the messages from the queue. Since it will push messages to us asynchronously, we provide a callback that will be executed when RabbitMQ pushes messages to our consumer. This is what RMQQueue subscribe() does.
print("Waiting for messages.") q.subscribe({(_ message: RMQMessage) -> Void in print("Received \(String(data: message.body, encoding: .utf8))") })
Here's the whole controller again (including send).
Now we can run the app. Hit the big play button, or cmd-R.
receive will log the message it gets from send via RabbitMQ. The receiver will keep running, waiting for messages (Use the Stop button to stop it), so you could try sending messages to the same queue using another client.
If you want to check on the queue, try using rabbitmqctl list_queues.
Hello World!
Time to move on to part 2 and build a simple work queue.
|
https://www.rabbitmq.com/tutorials/tutorial-one-swift.html
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
tag:blogger.com,1999:blog-3877552150457541062018-05-19T10:58:09.063-07:00computed styleChris Zacharias Front-End EngineersWhen I started at YouTube nearly three and a half years ago, there was only one full-time web developer (and one other web developer who, shortly before I started, transitioned into product management). Needless to say, there were plenty of things to work on the moment I walked through the door. In fact, the first order of business was to set to work recruiting our third full-time web developer. <br /><br />By. <br /><br /. <br /><br />Here are my observations on what to look for in potential candidates. These are generalizations based on experiences I have had. Of course there will be plenty of exceptions out there.<br /><br />1.) <b>Good front-end engineers rarely have a computer science degree.</b>.<br /><br />2.) <b>Good front-end engineers cannot be forged from back-end engineers.</b>. <br /><br />3.) <b>Good front-end engineers list Javascript on their resume, not jQuery.</b>: <br /><br /><blockquote. <i>You cannot use jQuery or any other library.</i></blockquote><br /. <br /><br /. <br /><br />4.) <b>Good front-end engineers are artists.</b>.<br /><br />5.) <b>If you want to find good front-end engineers, look to the newspaper and print industry.</b>.<img src="" height="1" width="1" alt=""/>Chris Zacharias From Building a Basic Video Player in HTML5HTML5 browsers that support the <video> tag are required to provide a basic set of controls for watching video on a web page. The built-in controls can be turned on by adding the "controls" attribute to the <video> tag. However, in many cases, you will want to provide your own richer set of playback controls. In this post, I intend to call out some of the hurdles that I have run across working on various HTML5 video players. If you want to see many of these techniques in action, check out the source code for <a href=""></a>.<br /><br />A. <br /><br /><h3>Markup</h3><br /:<br /><code><br /> <button class="play-button"><canvas class="play-icon" height="32" width="32"></button><br /></code><br /:<br /><br />HTML<br /><code><br /><meter id="my-video-rating" class="video-rating" value="4"></meter><br /></code><br />CSS<br /><code><br />.video-rating {<br /> display: block;<br /> width: 100px;<br /> height: 20px;<br />}<br />.video-rating[value=0] { background-image: url(/img/stars-0.png); }<br />.video-rating[value=1] { background-image: url(/img/stars-1.png); }<br />.video-rating[value=2] { background-image: url(/img/stars-2.png); }<br />.video-rating[value=3] { background-image: url(/img/stars-3.png); }<br />.video-rating[value=4] { background-image: url(/img/stars-4.png); }<br />.video-rating[value=5] { background-image: url(/img/stars-5.png); }<br /></code><br />Javascript<br /><code><br />function changeRating(newRating) {<br /> document.getElementById("my-video-rating").value = newRating;<br />}<br /></code><br /><br /><h3>User Interface</h3><br /. <br /><br />One thing that caught me off guard was the nature of volume and muting. For whatever reason, I expected setting <b>muted</b> to true would be reflected in the <b>volume</b> property (e.g. setting the volume to 0). However, the specification explicitly keeps these two values separately, which actually makes life much easier. Just remember to check both values when trying to update your player's volume controls.<br /><br /><h3>Fullscreen</h3><br /:<br /><code><br />.video-player video {<br /> display: block;<br /> width: 640px;<br /> height: 360px;<br />}<br />.video-player.fullscreen video {<br /> display: block;<br /> width: 100%;<br /> height: 100%;<br /> position: absolute;<br /> z-index: 9999;<br /> top: 0;<br /> left: 0;<br />}<br /></code><br />I am still working on getting the controls to layout properly in full-window mode, and will update this post with any insights I uncover.<br /><br /:<br /><code><br /><link rel="stylesheet" type="text/css" media="screen" href="videoplayer.css"><br /><link rel="stylesheet" type="text/css" media="projection, tv" href="videoplayer-full.css"><br /></code><br />Or you could do this in the CSS code:<br /><code><br />@media screen {<br /> /* Do your normal video player styles here */<br />}<br />@media projection, tv {<br /> /* Do your fullscreen styles here */<br />}<br /></code><br />Finally, one hurdle that remains is supporting the ability to show an embedded video in fullscreen on a third-party site. The security puzzle that this introduces is still undergoing heavy debate. Currently, there is no way to accomplish this that I know of.<br /><br /><h3>Embedding</h3><br /:<br /><code><br /><iframe src="" height="360" width="640"></iframe><br /></code><br />.<br /><br /.<br /><br /><h3>Conclusion</h3><br /.<img src="" height="1" width="1" alt=""/>Chris Zacharias Textile to Google App EngineBy default, App Engine includes a copy of Django that it pulls in components from. However, the integration points between App Engine and Django are fairly custom and not well documented. Trying to follow vanilla Django examples for installing Textile will not work in the context of App Engine. To get Textile to work will involve a number of steps.<br /><br />To begin with, you will want to create a lib folder in your App Engine project's home directory.<br /><pre><br />~/Projects/Example$ mkdir lib<br /></pre><br />You will then want to <a href="">download</a> Textile and extract into your newly created lib folder.<br /><pre><br />~/Projects/Example$ cd lib<br />~/Projects/Example/lib$ curl -O<br />~/Projects/Example/lib$ tar xzf textile-2.1.2.tar.gz<br /></pre><br />The Django template library <b>django.contrib.markup</b> will attempt to import from the namespace <b>textile</b>. You need to let Python know to look inside directories in the lib directory for namespaces. To do this, you will need to modify your <b>sys.path</b> to include those directories. The way to do this is to add the following code to the top of the file or files that contain your main functions, such as <b>main.py</b> in some of the App Engine demos.<br /><pre><br />import os<br />import sys<br />import logging<br /><br />DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))<br />LIB_PATH = os.path.join(DIR_PATH, "lib")<br />EXTRA_PATHS = []<br />for path in os.listdir(LIB_PATH):<br /> fullpath = os.path.join(LIB_PATH, path)<br /> if os.path.isdir(fullpath) and not path.startswith("."):<br /> EXTRA_PATHS.append(fullpath)<br />sys.path = sys.path + EXTRA_PATHS<br /></pre><br />This will modify the sys.path and let Python know to look inside of your lib directory for namespaces to import.<br /><br /.<br /><pre><br />def get(self):<br /> template.register_template_library('django.contrib.markup.templatetags.markup')<br /> # Do your template processing here.<br /></pre><br />At this point, you should be able to use the <b>textile</b> template tag in App Engine templates like so.<br /><pre><br /><span>{{someVar|textile}}</span><br /></pre><img src="" height="1" width="1" alt=""/>Chris Zacharias Tag Solution: Simple CSS RatingsThe 4- or 5-star rating has become the default for conveying popularity or relevance across the web. There are many ways to render a rating using stars in HTML and CSS. However, I have not seen a solution that is simultaneously simple, optimized, semantic, and accessible. Therefore, I set to work to uncover my own. The result looks like this: (The image 'none.gif' is a 1x1 transparent gif file)<br /><code><br /><img class="rating" alt="3.5" src="/none.gif" /><br /></code><br /><img style="cursor:pointer; cursor:hand;" src="" border="0" alt=""id="BLOGGER_PHOTO_ID_5185894415459329538" /><br /><br />The initial goal was to start by rendering a rating using only a single HTML tag that both visually displays the rating and retains its numerical value. The tag to use was very obviously the <img> tag. It is meant to display visual information and the 'alt' attribute is the perfect way to convey the numerical value of the rating. For slow-loading webpages, the numerical value of the rating will be displayed until the images load in.<br /><br />The next objective was to make use of image spriting to contain the stars so that only one image has to be loaded and cached for all ratings. There are several different approaches to this. The image sprite I chose to make use of looks like this:<br /><br /><img style="cursor:pointer; cursor:hand;" src="" border="0" alt=""id="BLOGGER_PHOTO_ID_5185888853476681202" /> <br /> <br />The idea is to set the width of the image to be 5-stars wide and then slide this sprite around to get the desired rating. <!-- The following animation demonstrates what is happening behind the scenes.<br /><br /><img src="" alt="Star Animation" />--><br /><br />Building the CSS for this is rather simple. I will demonstrate the intended, but IE6-incompatible approach first. IE6 is the only modern browser that does not support the attribute selector syntax.<br /><code style="white-space: pre;"><br />img.rating {<br /> background: transparent url(stars.gif) no-repeat scroll;<br /> width: 100px;<br /> height: 20px; <br />}<br />img.rating[<br />img.rating {<br /> background: transparent url(stars.gif) no-repeat scroll;<br /> width: 100px;<br /> height: 20px; <br />}<br />img.rating-0\.0 { background-position: -100px 0; }<br />img.rating-0\.5 { background-position: -80px -20px; }<br />img.rating-1\.0 { background-position: -80px 0; }<br />img.rating-1\.5 { background-position: -60px -20px; }<br />img.rating-2\.0 { background-position: -60px 0; }<br />img.rating-2\.5 { background-position: -40px -20px; }<br />img.rating-3\.0 { background-position: -40px 0; }<br />img.rating-3\.5 { background-position: -20px -20px; }<br />img.rating-4\.0 { background-position: -20px 0; }<br />img.rating-4\.5 { background-position: 0 -20px; }<br />img.rating-5\.0 { background-position: 0 0; }<br /></code><br />The modified HTML code would look like:<br /><code><br /><img class="rating rating-3.5" alt="3.5" src="/none.gif" /><br /></code><br />In the end, the result is a simple, semantic rating in one tag and one image. For part 2, I will demonstrate how to turn this into a rating you can pick from.<img src="" height="1" width="1" alt=""/>Chris Zacharias
|
http://feeds.feedburner.com/ComputedStyle
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
.
char *_fcvt( double value, int count, int *dec, int *sign );
value: Number to be converted
count: Number of digits after decimal point
dec : Pointer to stored decimal-point position
sign : Pointer to stored sign indicator
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int decimal, sign;
char *buffer;
double source = 3.1415926535;
buffer = _fcvt( source, 7, &decimal, &sign );
printf( "source: %2.10f buffer: '%s' decimal: %d sign: %d\n",
source, buffer, decimal, sign );
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num=999;
char str[6]; // a 5 character string
sprintf(str, "%d", num);
printf("%s\n", str);
return EXIT_SUCCESS;
}
Notice of the use of %d for integer. Change that to others for double and long.
hongjun
hongjun
|
https://www.experts-exchange.com/questions/20161981/convert-float-double-to-string.html
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
I was given a project to complete:
Help determine how much time someone has left to meet a deadline
- Ask a user to enter the deadline for their project
- Tell them how many days they have to complete the project
- For extra credit, give them the answer as a combination of weeks & days (Hint: you will need some of the math functions from the module
on numeric values)
import datetime
currentday=datetime.date.today()
#set variable to recieve deadline for project
deadLine = 0
deadLine = raw_input('when is the deadline for your project? (dd/mm/YYYY) ')
deadLine=datetime.dateime.strptime(deadLine, '%d/%m/%Y').date()
daysLeft= deadLine-currentday
print 'Number of days left for your project is : '
print daysLeft
when is the deadline for your project? (dd/mm/YYYY) 21/10/2016
Traceback (most recent call last):
File "C:\Users\Oluwaseun Okungbowa\Desktop\Video editing and python programming\projectdeadline.py", line 7, in <module>
deadLine=datetime.dateime.strptime(deadLine, '%d/%m/%Y').date()
AttributeError: 'module' object has no attribute 'dateime'
#import the datetime class
import datetime
#declare and initialize variables
strDeadline = ""
totalNbrDays = 0
nbrWeeks = 0
nbrDays = 0
#Get Today's date
currentDate = datetime.date.today()
#Ask the user for the date of their deadline
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")
deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()
#Calculate number of days between the two dates
totalNbrDays = deadline - currentDate
#For extra credit calculate results in weeks & days
nbrWeeks = totalNbrDays.days / 7
#The modulo will return the remainder of the division
#which will tell us how many days are left
nbrDays = totalNbrDays.days%7
#display the result to the user
print("You have %d weeks" %nbrWeeks + " and %d days " %nbrDays + "until your deadline.")
Please enter the date of your deadline (mm/dd/yyyy): 10/21/2016
Traceback (most recent call last):
File "C:\Users\Oluwaseun Okungbowa\Desktop\Video editing and python programming\projectdeadlineteachers.py", line 16, in <module>
deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()
TypeError: strptime() argument 1 must be string, not int
Install python3 so that you and your tutor are on the same page.
However, if you do decide to stick with python 2.7, this will fix your problem.
Your problem is in this line
#Ask the user for the date of their deadline strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")
Here's an example of what I mean
>>> input() 5 5 >>> input() 10/2 5 >>> input() 10/2/2016 0
python is thinking that your date is arithmetic division of integers. change
input() to
raw_input() to accept the string.
i.e.
strDeadline = raw_input("Please enter the date of your deadline (mm/dd/yyyy): ")
|
https://codedump.io/share/MUfJq5HM4XJh/1/errors-running-python-code-attribute-error-for-datetime-and-strptime-type-error
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
The threading module is built on top of module thread and supplies multithreading functionality in a more usable, higher-level form. The general approach of threading are atomic.
threading provides numerous classes for dealing with threads, including Thread, Condition, Event, RLock, and Semaphore. Besides factory functions for the classes detailed in the following sections, threading supplies the currentThread factory function.
currentThread
currentThread( )
Returns a THRead object for the calling thread. If the calling thread was not created by module threading, currentThread creates and returns a semi-dummy Thread object with limited functionality.
A THRead object t models a thread. You can pass t's main function as an argument when you create t, or you can subclass Thread and override the run method t can be a daemon, meaning that Python can terminate even if t is still active, while a normal (nondaemon) thread keeps Python alive until the thread terminates. Class Thread exposes the following constructor and methods.
Thread
class Thread(name=None,target=None,args=( ),kwargs={ })
Always call THRead with named arguments. The number and order of formal arguments may change in the future, but the names of existing arguments are guaranteed to stay. When you instantiate class Thread itself, you should specify that target: t.run calls target(*args,**kwargs). When you subclass THRead and override run, you normally don't specify target. In either case, execution doesn't begin until you call t.start( ). name is t's name. If name is None, Thread generates a unique name for t. If a subclass T of Thread overrides _ _init_ _, T._ _init_ _ must call Thread._ _init_ _ on self before any other Thread method.
getName, setName
t.getName( ) t.setName(name)
getName returns t's name, and setName rebinds t's name. The name string is arbitrary, and a thread's name need not be unique among threads.
isAlive
t.isAlive( )
Returns TRue if t is active (i.e., if t.start has executed and t.run has not yet terminated). Otherwise, isAlive returns False.
isDaemon, setDaemon
t.isDaemon( ) t.setDaemon(daemonic)
isDaemon returns true if t is a daemon (i.e., Python can terminate the whole process even if t is still active; such a termination also terminates t); otherwise, isDaemon returns False. Initially, t is a daemon if and only if the thread that creates t is a daemon. You can call t.setDaemon only before t.start; it sets t to be a daemon if daemonic is true.
join
t.join(timeout=None)
The calling thread (which must not be t) suspends until t terminates. timeout is covered in "Timeout parameters" on page 346. You can call t.join only after t.start.
run
t.run( )
run is the method that executes t's main function. Subclasses of Thread often override run. Unless overridden, run calls the target callable passed on t's creation. Do not call t.run directly; calling t.run appropriately is the job of t.start!
start
t.start( )
start makes t active and arranges for t.run to execute in a separate thread. You must call t.start only once for any given thread object t.
The tHReading module supplies several synchronization primitives, which are objects that let threads communicate and coordinate. Each primitive has specialized uses. However, as long as you avoid global variables that several threads access, Queue can often provide all the coordination you need. "Threaded Program Architecture" on page 350 shows how to use Queue objects to give your multithreaded programs simple and effective architectures, often without needing any synchronization primitives.
Synchronization primitives Condition and Event supply wait methods that accept an optional timeout argument. A Thread object's join method also accepts an optional timeout argument. A timeout argument can be None (the default) to obtain normal blocking behavior (the calling thread suspends and waits until the desired condition is met). If it is not None, a timeout argument is a floating-point value that indicates an interval of time in seconds (timeout can have a fractional part, so it can indicate any time interval, even a very short one). If timeout seconds elapse, the calling thread becomes ready again, even if the desired condition has not been met. timeout lets you design systems that are able to overcome occasional anomalies in one or a few threads,
and thus are more robust. However, using timeout may also make your program slower.
The Lock objects exposed by module threading are the same as those supplied by module tHRead and covered in "The thread Module" on page 341. RLock objects supply the same methods as Lock objects. The semantics of an RLock object r are, however, often more convenient. An RLock is a "re-entrant" lock, meaning that when r is locked, it keeps track of the owning thread (i.e., the thread that locked it). The owning thread can call r.acquire again without blocking; r just increments an internal count. In a similar situation involving a Lock object, the thread would block forever (until the lock is released by some other thread).
An RLock object r is unlocked only when release has been called as many times as acquire. Only the thread owning r should call r.release. An RLock is useful to ensure exclusive access to an object when the object's methods call each other; each method can acquire at the start, and release at the end, the same RLock instance. TRy/finally (covered in "try/finally" on page 123) is a good way to ensure the lock is indeed released (in Python 2.5, the new with statement, covered in "The with statement" on page 125, is generally at least as good).
A Condition object c wraps a Lock or RLock object L. Class Condition exposes the following constructor and methods.
Condition
class Condition(lock=None)
Condition creates and returns a new Condition object c with the lock L set to lock. If lock is None, L is set to a newly created RLock object.
acquire, release
c.acquire(wait=1) c.release( )
These methods call L's corresponding methods. A thread must never call any other method on c unless the thread holds lock L.
notify, notifyAll
c.notify( ) c.notifyAll( )
notify wakes up one of the threads waiting on c. The calling thread must hold L before it calls c.notify( ), and notify does not release L. The woken-up thread does not become ready until it can acquire L again. Therefore, the calling thread normally calls release after calling notify. notifyAll is like notify, but wakes up all waiting threads, not just one.
wait
c.wait(timeout=None)
wait releases L, then suspends the calling thread until some other thread calls notify or notifyAll on c. The calling thread must hold L before it calls c.wait( ). timeout is covered in "Timeout parameters" on page 346. After a thread wakes up, either by notification or timeout, the thread becomes ready when it acquires L again. When wait returns, the calling thread always holds L again.
In typical use, a Condition object c regulates access to some global state s that is shared between threads. When a thread needs to wait for s to change, the thread loops as follows:
c.acquire( )
while not is_ok_state(s):
c.wait( )
do_some_work_using_state(s)
c.release( )
Meanwhile, each thread that modifies s calls notify (or notifyAll if it needs to wake up all waiting threads, not just one) each time s changes:
c.acquire( )
do_something_that_modifies_state(s)
c.notify( ) # or, c.notifyAll( )
c.release( )
As you can see, you always need to acquire and release c around each use of c's methods, which makes using Condition somewhat error-prone.
Event objects let any number of threads suspend and wait. All threads waiting on Event object e become ready when any other thread calls e.set( ). e has a flag that records whether the event happened; it is initially False when e is created. Event is thus a bit like a simplified Condition. Event objects are useful to signal one-shot changes, but brittle for more general use; in particular, relying on calls to e.clear( ) is error-prone. Class Event exposes the following methods.
Event
class Event( )
Event creates and returns a new Event object e, with e's flag set to False.
clear
e.clear( )
Sets e's flag to False.
isSet
e.isSet( )
Returns the value of e's flag, true or False.
set
e.set( )
Sets e's flag to true. All threads waiting on e, if any, become ready to run.
e.wait(timeout=None)
If e's flag is true, wait returns immediately. Otherwise, wait suspends the calling thread until some other thread calls set. timeout is covered in "Timeout parameters" on page 346.
Semaphores (also known as counting semaphores) are a generalization of locks. The state of a Lock can be seen as true or False; the state of a Semaphore s is a number between 0 and some n set when s is created. Semaphores can be useful to manage a fixed pool of resources (e.g., 4 printers or 20 sockets), although it's often more robust to use Queues for such purposes.
Semaphore
class Semaphore(n=1)
Semaphore creates and returns a semaphore object s with the state set to n. A semaphore object s exposes the following methods.
acquire
s.acquire(wait=TRue)
When s's state is greater than 0, acquire decrements the state by 1 and returns TRue. When s's state is 0 and wait is TRue, acquire suspends the calling thread and waits until some other thread calls s.release. When s's state is 0 and wait is False, acquire immediately returns False.
release
s.release( )
When s's state is > 0 or when the state is 0 but no thread is waiting on s, release increments the state by 1. When s's state is 0 and some thread is waiting on s, release leaves s's state at 0 and wakes up an arbitrary waiting thread. The thread that calls release is not suspended; it remains ready and continues to execute normally.
In Python 2.4, module threading supplies a class local, which threads can use to obtain thread-local storage (TLS), also known as per-thread data. An instance L of local has arbitrary named attributes that you can set and get, and stores them in a dictionary L._ _dict_ _ that you can also access. L is fully thread-safe, meaning there is no problem if multiple threads simultaneously set and get attributes on L. Most important, each thread that accesses L sees a completely disjoint set of attributes, and any changes made in one thread have no effect in other threads. For example:
import threading L = threading.local( )
print 'in main thread, setting zop to 42'
L.zop = 42
def targ( ):
print 'in subthread, setting zop to 23'
L.zop = 23
print 'in subthread, zop is now', L.zop t = threading.Thread(target=targ)
t.start( )
t.join( )
print 'in main thread, zop is now', L.zop
# emits:
# in main thread, setting zop to 42
# in subthread, setting zop to 23
# in subthread, zop is now 23
# in main thread, zop is now 42
TLS makes it easier for you to write code meant to run in multiple threads, since you can use the same namespace (an instance of threading.local) in multiple threads without the separate threads interfering with each other.
|
http://books.gigatux.nl/mirror/pythoninanutshell/0596100469/pythonian-CHP-14-SECT-4.html
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
So my instructor assigned us to create a program that calculates the area and stores that, along with coordinates, in an array. This has to be done for both triangles and squares. He is having us use separate classes for the project; the main Drawer class, parent class, square class, and triangle class. I've got a portion of it done, but I'm honestly not sure where I need to go from here. I can't seem to figure out how to get the information read from the main part of the program into the methods that I have and I don't know if I need to add more methods to accomplish that. I'm also getting errors in what I do have;
Code Java:
public class Drawer { //Declare array for shapes to be stored in public Parent myShape[] = new Parent[10]; /* * Description: This method will allow the items to be entered into the array * and will place them in the first empty location * Precondition: The array must already exist and have been set to null. * Postcondition: The item will reside in the array. */ public double add(double z) { //Use the findFirstEmpty to locate the first null spot int x = findFirstEmpty(); //Take the empty spot and put the item in it if (x >= 0) { myShape[x] = z; } else { //indicates that the array is full System.out.println("The array is at maximum capacity"); } //Return the spot with the shape in it. return z; } /** * Description: This method will search for the first empty spot in the array * Precondition: The array must already exist and there must be at least * one item in the array. * Postcondition: There will now be one less empty spot since an item will * be residing in the formerly empty location. */ public int findFirstEmpty() { /** * Function of this method is to scan the array for the first null * position */ for (int i = 0; i < myShape.length; i++) { /** * Scan the array by using int i to correspond to the position of the * empty spot in the array. */ if (myShape[i] == null) { //Indicates that the scan located a null spot in the array return i; } } //Indicates that the scan produced no null spots in array return -1; } /** * Description: This method is when the bus stops and a child gets off, * freeing up a seat. * Precondition: The bus array must already exist and there must be at least * one child on the bus. * Postcondition: There will be one more empty spot since the child that was * residing in that spot got off at the bus stop. */ public void delete(double z) { for (int x = 0; x < myShape.length; x++) //Take the filled seat and remove the child if (z.equals(myShape[x])) { //Removes a specific person from the bus array myShape[x] = null; } } /* * Description: This class holds the methods and other items that are * inherited by both of the children classes. * Precondition: The array must exist. * Postcondition: The children classes will utilize the methods and items in * this section to recieve desired results */ class Parent { protected double coordx; protected double coordy; /* * Description: This method sets the coordinates for the object. * Precondition: The array must exist and coordinates must have already * been entered in. * Postcondition: The item in the array will have set coordinates. */ public setCoord(double x, double y) { coordx = x; coordy = y; } public void print() { //Print out the array and the position of the item in the array. //Need to print coordx, coordy, side, and area. // for (int x = 0; x < 10; x++) // { // if (names[x] != null) // { // System.out.println(x + " , " + names[x]); // } // } } } public class Square extends Parent { private double side = 0; private double area = 0; //Get side of square and return it public double getSide() { return side; } /** * Description: This method computes the area of the Square. * Precondition: The sides must have already been entered into the array. * Postcondition: There will be a resulting area. */ public double computeArea() { return area = side * 4; } } public class Triangle extends Parent { private double base; private double height; private double area; //Get base of triangle and return it public double getBase() { return base; } //Get height of triangle and return it public double getHeight() { return height; } /** * Description: This method computes the area of the Triangle. * Precondition: The sides must have already been entered into the array. * Postcondition: There will be a resulting area. */ public double computeArea() { return area = .5 * base * height; } } public static void main(String[] args) { Drawer d1 = new Drawer(); /** * Enter in the first shape; Triangle * base = 10 * height = 5.1 * coordinates = (1,2) */ double B = 10; double H = 5.1; double C1 = 1; double C2 = 2; /** * Enter in the second shape; Triangle * base = 3 * height = 7 * coordinates = (3,2) */ /** * Enter in the third shape; Square * size = 5 * coordinates = (7,5) */ //Print the array /** * Enter in the fourth shape; Triangle * base = 20 * height = 30 * coordinates = (20,2) */ //Delete object in array position 1 //Print the array /** * Enter in the fifth shape; Triangle * base = 100 * height = 35 * coordinates = (1,20) */ /** * Enter in the sixth shape; Triangle * base = 25 * height = 50 * coordinates = (1,22) */ //Print the array //Change all of the coordinates to (-1,-1) //Print the array } }
The array at the beginning is giving the error; exporting non-public type through public API. However, that's the method my teacher instructed us to use the array.
I am also getting an error of incompatible types in the add() method (the myShapes[x] = z), and I'm unsure why. It is the same with the delete method, which states that it cannot be dereferenced.
I have the basics of what I need to be doing for this program, I just keep getting stuck. I would appreciate being pointed in the right direction, and I apologize in advanced at the ignorance I have when it comes to some of this stuff(I will likely ask stupid questions). Thank you!
|
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/14289-im-not-sure-what-i-need-do-next-printingthethread.html
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
This seemed like a really big miss, shortcuts are the usual way for people (and certainly beginners to launch applications).
So I set to creating a really simple way of creating shortcuts for Python applications.
Enter shortcut, a X platform (Windows, MacOS, Linux, Raspberry Pi) Python module for automatically creating shortcuts.
pip3 install shortcut shortcut name_of_app
It will find the location of the app and create desktop and menu shortcuts for it.
There is also a Python API which can be used to do the same:
from shortcut import ShortCutter s = ShortCutter() s.create_desktop_shortcut("python") s.create_menu_shortcut("python")
You will find documentation at shortcut.readthedocs.io and code at github.com/martinohanlon/shortcut.
|
http://www.stuffaboutcode.com/
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
NetScape Portable Runtime (NSPR) provides platform independence for non-GUI operating system facilities. These facilities include threads, thread synchronization, normal file and network I/O, interval timing and calendar time, basic memory management (malloc and free) and shared library linking.
History
A good portion of the library's purpose, and perhaps the primary purpose in the Gromit environment, was to provide the underpinnings of the Java VM, more or less mapping the sys layer that Sun defined for the porting of the Java VM to various platforms. NSPR went beyond that requirement in some areas and since it was also the platform independent layer for most of the servers produced by Netscape. It was expected and preferred that existing code be restructured and perhaps even rewritten in order to use the NSPR API. It is not a goal to provide a platform for the porting into Netscape of externally developed code.
At the time of writing the current generation of NSPR was known as NSPR20. The first generation of NSPR was originally conceived just to satisfy the requirements of porting Java to various host environments. NSPR20, an effort started in 1996, built on that original idea, though very little is left of the original code. (The "20" in "NSPR20" does not mean "version 2.0" but rather "second generation".) Many of the concepts have been reformed, expanded, and matured. Today NSPR may still be appropriate as the platform dependent layer under Java, but its primary application is supporting clients written entirely in C or C++.
How It Works
NSPR's goal is to provide uniform service over a wide range of operating system environments. It strives to not export the lowest common denominator, but to exploit the best features of each operating system on which it runs, and still provide a uniform service across a wide range of host offerings.
Threads
Threads are the major feature of NSPR. The industry's offering of threads is quite sundry. NSPR, while far from perfect, does provide a single API to which clients may program and expect reasonably consistent behavior. The operating systems provide everything from no concept of threading at all up to and including sophisticated, scalable and efficient implementations. NSPR makes as much use of what the systems offer as it can. It is a goal of NSPR that NSPR impose as little overhead as possible in accessing those appropriate system features.
Thread synchronization
Thread synchronization is loosely based on Monitors as described by C.A.R. Hoare in Monitors: An operating system structuring concept , Communications of the ACM, 17(10), October 1974 and then formalized by Xerox' Mesa programming language ("Mesa Language Manual", J.G. Mitchell et al, Xerox PARC, CSL-79-3 (Apr 1979)). This mechanism provides the basic mutual exclusion (mutex) and thread notification facilities (condition variables) implemented by NSPR. Additionally, NSPR provides synchronization methods more suited for use by Java. The Java-like facilities include monitor reentrancy, implicit and tightly bound notification capabilities with the ability to associate the synchronization objects dynamically.
I/O
NSPR's I/O is a slightly augmented BSD sockets model that allows arbitrary layering. It was originally intended to export synchronous I/O methods only, relying on threads to provide the concurrency needed for complex applications. That method of operation is preferred though it is possible to configure the network I/O channels as non-blocking in the traditional sense.
Network addresses
Part of NSPR deals with manipulation of network addresses. NSPR defines a network address object that is Internet Protocol (IP) centric. While the object is not declared as opaque, the API provides methods that allow and encourage clients to treat the addresses as polymorphic items. The goal in this area is to provide a migration path between IPv4 and IPv6. To that end it is possible to perform translations of ASCII strings (DNS names) into NSPR's network address structures, with no regard to whether the addressing technology is IPv4 or IPv6.
Time
Timing facilities are available in two forms: interval timing and calendar functions.
Interval timers are based on a free running, 32-bit, platform dependent resolution timer. Such timers are normally used to specify timeouts on I/O, waiting on condition variables and other rudimentary thread scheduling. Since these timers have finite namespace and are free running, they can wrap at any time. NSPR does not provide an epoch , but expects clients to deal with that issue. The granularity of the timers is guaranteed to be between 10 microseconds and 1 millisecond. This allows a minimal timer period in of approximately 12 hours. But in order to deal with the wrap-around issue, only half that namespace may be utilized. Therefore, the minimal usable interval available from the timers is slightly less than six hours.
Calendar times are 64-bit signed numbers with units of microseconds. The epoch for calendar times is midnight, January 1, 1970, Greenwich Mean Time. Negative times extend to times before 1970, and positive numbers forward. Use of 64 bits allows a representation of times approximately in the range of -30000 to the year 30000. There is a structural representation (i.e., exploded view), routines to acquire the current time from the host system, and convert them to and from the 64-bit and structural representation. Additionally there are routines to convert to and from most well-known forms of ASCII into the 64-bit NSPR representation.
Memory management
NSPR provides API to perform the basic malloc, calloc, realloc and free functions. Depending on the platform, the functions may be implemented almost entirely in the NSPR runtime or simply shims that call immediately into the host operating system's offerings.
Linking
Support for linking (shared library loading and unloading) is part of NSPR's feature set. In most cases this is simply a smoothing over of the facilities offered by the various platform providers.
Where It's Headed
NSPR is applicable as a platform on which to write threaded applications that need to be ported to multiple platforms. The current implementation supports Macintosh (PPC), WIN-32 (WinNT, Win9x) and 20 versions of UNIX and is still expanding. The basic API is stable and expected to remain that way.
NSPR is functionally complete and has entered a mode of sustaining engineering. As operating system vendors issue new releases of their operating systems, NSPR will be moved forward to these new releases by interested players.
Original Document Information
- Author: larryh@netscape.com
- Last Updated Date: 2000
- (Portions of the Introduction moved to the history section in 2012)
|
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/About_NSPR?redirectlocale=en-US&redirectslug=About_NSPR
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
Click on the Play button to run the code This blog post was inspired by Mr Rooney's tweet.
fit = input("what is your diet?")— Mr A. Rooney (@arooneycompsci) June 15, 2017
if fit == "beer and kebab":
print ("you fatty")
Ok so I'm not exactly known for my healthy eating, but it is an important part of our lives. So how can we teach children to eat healthy using Python?
Goal
To use Python 3, lists and the random library to teach healthy eating.
Getting started
Using IDLE / Python 3 Editor or in this case Trinket.io, create a new file and call it Healthy-Eating.py.
Importing Libraries
The only library that we need is called random and as its name suggests, it is a collection of classes and functions that offer random elements (choice, shuffle etc) to our code.
import random
Creating two lists
Lists are a Pythonic way of handling data in to a single indexable object. A list in Python is known as an array in other languages.
Lists can contain any datatype (strings, integers, floats, other lists) and each item in a list has an index, a numerical value that identifies its position. The index starts at zero. Lists are mutable, in other words the contents can be changed.
We shall create two lists, healthy and unhealthy. Our healthy list is full of healthy food, saved as strings. Our unhealthy list is full of
tasty awful food that is bad for you.
healthy = ["carrot","apple","mango","pineapple"] unhealthy = ["pizza","burger","kebab","chips"]
Communicating with the user
Our interface with the user starts by welcoming them to the application by using a print function. You will also notice \n at the end of the text. This is Python's way of adding a new line after the print function.
print("Welcome to Healthy Eating with Python\n")
Now the user will enter their favourite food, for this we use a variable called food which will capture the keyboard input from the user.
food = input("What is your favourite food? :")
Check what they are eating
So we now enter into an if...else if...else conditional test. Our first test is to see if the food they are eating is in the healthy list. If it is, then this condition is True and we print a celebratory message to the user. We also suggest they celebrate by eating another, randomly chosen from the healthy list.
if food in healthy: print("Well done you are healthy, celebrate with a "+random.choice(healthy))
Unhealthy eating!
But what if their food is not healthy? Well our else if condition is True. We shuffle the healthy list, to create a pseudo-random list of healthy foods.
elif food in unhealthy: random.shuffle(healthy)
Then we print a message to the user suggesting that they eat something healthy.
print("Oh dear, you should eat some... ")
Now we suggest three alternative foods to the user. We use a for loop to print the first three items in the healthy list. The value i starts at zero, and each time the for loop iterates, the value of i is increased by 1.
for i in range(3): print(healthy[i]+"\n")
But their food isn't in any off the lists!?!
Our final test is else and this is condition is True if the previous tests are False. So in other words if the user enters a food that is not in either list, then the code inside else will be executed.
else:
So we tell the user that we cannot find their food in the "database"" (our two lists). We then shuffle the list of healthy foods.
print("Your food choice is not in my database, but I guess that it is bad so here are some alternatives") random.shuffle(healthy)
Then we use another for loop to print the contents of the healthy list. To print everything in the list we set a range, a set number of times to run the for loop. Our range is set to the len, the length of our list. We then print each item in the list, helping the user to eat better.
for i in range(len(healthy)): print(healthy[i]+"\n")
Complete code listing
import random healthy = ["carrot","apple","mango","pineapple"] unhealthy = ["pizza","burger","kebab","chips"] print("Welcome to Healthy Eating with Python\n") food = input("What is your favourite food? :") if food in healthy: print("Well done you are healthy, celebrate with a "+random.choice(healthy)) elif food in unhealthy: random.shuffle(healthy) print("Oh dear, you should eat some... ") for i in range(3): print(healthy[i]+"\n") else: print("Your food choice is not in my database, but I guess that it is bad so here are some alternatives") random.shuffle(healthy) for i in range(len(healthy)): print(healthy[i]+"\n")
All done!
So there we have it, a simple tool that teaches a little about Python, and encourages healthy eating.
All this talk of food has made me hungry...I'm off to
Greggs to eat a lovely apple. (Bacon, pies etc are ok for you in moderation, but don't eat them everyday, oh and try and go for a walk/run/swim in between bouts of coding.)
|
http://bigl.es/healthy-eating-with-python/
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
BigQuery python library
Project description
bqlib - BigQuery python library
A BigQuery python library. This library is a wrapper for bigquery_client.py.
Requirements
- Python 2.6 or later (not support for 3.x)
Setup
$ pip install bqlib
How to use
Single Query - BQJob
BQJob is a class to start the BigQuery job and fetch result.
You can use either run_sync(synchronous) or run_async(asynchronous) method.
from bqlib import BQJob project_id = 'example_project' query = 'SELECT foo FROM bar' http = authorized_http bqjob = BQJob(project_id=project_id, query=query, http=http) # run synchronously job_result = bqjob.run_sync() # or run asynchronously bqjob.run_async() # ... do other things ... job_result = bqjob.get_result() print job_result # [{u'foo': 10}, {u'foo': 20}, ...]
Multiple Queries - BQJobGroup
BQJobGroup is a class for putting multiple BQJobs into an one group.
Every BQJob in that group are executed concurrently.
from bqlib import BQJob, BQJobGroup bqjob1 = BQJob(project_id=project_id, query=query, http=http) bqjob2 = BQJob(project_id=project_id, query=query, http=http) job_group = BQJobGroup([bqjob1, bqjob2]) # synchronously results = job_group.run_sync() # or asynchronously job_group.run_async() results = job_group.get_results() print results # [[{'foo': 10}, {'foo': 20}], [{'bar': 'test'}]]
Note
- Concurrent Requests to BigQUery
- Concurrent requests to BigQuery is restricted to 20 requests by Quota Policy.
- If you want to set up concurrent requests to 20, you also have to set up at traffic controls in api-console page.
License
This library is disributed as MIT license.
History
2013-10-22 bqlib 0.0.1
- First release
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/bqlib/0.0.1/
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
full implemented class for user_interaction based on callback functions. More...
#include <user_interaction.hpp>
Inherits libdar::user_interaction.
Inherited by shell_interaction.
full implemented class for user_interaction based on callback functions.
this class is an inherited class of user_interaction it is used by dar command line programs, but you can use it if you wish.
Definition at line 338 of file user_interaction.hpp.
constructor which receive the callback functions.
You can set a listing callback thanks to this method.
If set, when file listing will this callback function will be used instead of the x_warning_callback given as argument of the constructor.
Definition at line 406 of file user_interaction.hpp.
References libdar::user_interaction::set_use_listing().
|
http://dar.linux.free.fr/doc/html/classlibdar_1_1user__interaction__callback.html
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
Much better I used Collections.sort with a boxed integer array - that beats 50% - your solution is surely better and simple. in fact this one is fine too. Value of k is always guaranteed to be in range so you can ignore those checks.
public class Solution { public int findKthLargest(int[] nums, int k) { if (nums == null || nums.length == 0) return -1; Arrays.sort(nums); return nums[nums.length-k]; }}
|
https://discuss.leetcode.com/user/kzvikzvi1
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
- NAME
- SYNOPSIS
- DESCRIPTION
- WEB SITE
- DOCUMENTS
- ATTRIBUTES
- METHODS
- available_datatype
- available_typename
- assign_clause
- column
- connect
- create_model
- dbh
- delete
- delete_all
- each_column
- each_table
- execute
- get_column_info
- get_table_info
- insert
- include_model
- like_value
- mapper
- merge_param
- model
- mycolumn
- new
- not_exists
- order
- q
- register_filter
- type_rule
- update
- update_all
- show_datatype
- show_tables
- show_typename
- values_clause
- where
- create_result EXPERIMENTAL
- ENVIRONMENTAL VARIABLES
- DEPRECATED FUNCTIONALITY
- BACKWARDS COMPATIBILITY POLICY
- BUGS
- AUTHOR
NAME
DBIx::Custom - DBI extension to execute insert, update, delete, and select easily
SYNOPSIS
use DBIx::Custom; # Connect my $dbi = DBIx::Custom->connect( "dbi:mysql:database=dbname", 'ken', '!LFKD%$&', {mysql_enable_utf8 => 1} ); # Create'}); # Select, more complex # select book.title as book.title, # book.author as book.author, # comnapy.name as company.name # form book # left outer join company on book.company_id = company.id # where book.author = ? # order by id limit 0, 5 my $result = $dbi->model('book')->select( [ {book => [qw/title author/]}, {company => ['name']} ], where => {'book.author' => 'Ken'}, join => ['left outer join company on book.company_id = company.id'], append => 'order by id limit 0, 5' ); # Get all rows or only one row my $rows = $result->all; my $row = $result->one; # Execute SQL with named place holder my $result = $dbi->execute( "select id from book where author = :author and title like :title", {author => 'ken', title => '%Perl%'} );
DESCRIPTION
DBIx::Custom is DBI wrapper module to execute SQL easily. This module have the following features.
Execute
insert,
update,
delete, or
selectstatement easily
Create
whereclause flexibly
Named place holder support
Model support
Connection manager support
Choice your favorite relational database management system,
MySQL,
SQLite,
PostgreSQL,
Oracle,
Microsoft SQL Server,
Microsoft Access,
DB2or anything,
Filtering by data type or column name
Create
order byclause flexibly
WEB SITE
DBIx::Custom - Perl O/R Mapper
DOCUMENTS
DBIx::Custom API reference
ATTRIBUTES
connector
my $connector = $dbi->connector; $dbi = $dbi->connector($connector);
Connection manager object. if
connector is set, you can get
dbh through connection manager. Conection manager object must have
dbh method.
This is DBIx::Connector example. Please pass
default_option to DBIx::Connector
new method.
my $connector = DBIx::Connector->new( "dbi:mysql:database=$database", $user, $password, DBIx::Custom->new->default_option ); my $dbi = DBIx::Custom->connect(connector => $connector);
If
connector is set to 1 when connect method is called, DBIx::Connector is automatically set to
connector
my $dbi = DBIx::Custom->connect( dsn => $dsn, user => $user, password => $password, connector => 1); my $connector = $dbi->connector; # DBIx::Connector
Note that DBIx::Connector must be installed.
dsn
my $dsn = $dbi->dsn; $dbi = $dbi->dsn("DBI:mysql:database=dbname");
Data source name, used when
connect method is executed.
default_option
my $default_option = $dbi->default_option; $dbi = $dbi->default_option($default_option);
DBI default option, used when
connect method is executed, default to the following values.
{ RaiseError => 1, PrintError => 0, AutoCommit => 1, }
exclude_table
my $exclude_table = $dbi->exclude_table; $dbi = $dbi->exclude_table(qr/pg_/);
Excluded table regex.
each_column,
each_table,
type_rule
filters
my $filters = $dbi->filters; $dbi = $dbi->filters(\%filters);
Filters, registered by
register_filter method.
last_sql
my $last_sql = $dbi->last_sql; $dbi = $dbi->last_sql($last_sql);
Get last succeeded SQL executed by
execute method.
now
my $now = $dbi->now; $dbi = $dbi->now($now);
Code reference which return current time, default to the following code reference.
sub { my ($sec, $min, $hour, $mday, $mon, $year) = localtime; $mon++; $year += 1900; return sprintf("%04d-%02d-%02d %02d:%02d:%02d"); }
This return the time like
2011-10-14 05:05:27.
This is used by
insert method's
ctime option and
mtime option, and
update method's
mtime option.
models
my $models = $dbi->models; $dbi = $dbi->models(\%models);
Models, included by
include_model method.
mytable_symbol
Symbol to specify own columns in select method column option, default to '__MY__'.
$dbi->table('book')->select({__MY__ => '*'});
option
my $option = $dbi->option; $dbi = $dbi->option($option);
DBI option, used when
connect method is executed. Each value in option override the value of
default_option.
my $password = $dbi->password; $dbi = $dbi->password('lkj&le`@s');
Password, used when
connect method is executed.
quote
my quote = $dbi->quote; $dbi = $dbi->quote('"');
Reserved word quote. Default to double quote '"' except for mysql. In mysql, default to back quote '`'
You can set quote pair.
$dbi->quote('[]');
result_class
my $result_class = $dbi->result_class; $dbi = $dbi->result_class('DBIx::Custom::Result');
Result class, default to DBIx::Custom::Result.
safety_character
my $safety_character = $dbi->safety_character; $dbi = $dbi->safety_character($character);
Regex of safety character for table and column name, default to 'a-zA-Z_'. Note that you don't have to specify like '[a-zA-Z_]'.
separator
my $separator = $dbi->separator; $dbi = $dbi->separator('-');
Separator which join table name and column name. This have effect to
column and
mycolumn method, and
select method's column option.
Default to
..
user
my $user = $dbi->user; $dbi = $dbi->user('Ken');
User name, used when
connect method is executed.
user_column_info
my $user_column_info = $dbi->user_column_info; $dbi = $dbi->user_column_info($user_column_info);
You can set the date like the following one.
[ {table => 'book', column => 'title', info => {...}}, {table => 'author', column => 'name', info => {...}} ]
Usually, you set return value of
get_column_info.
my $user_column_info = $dbi->get_column_info(exclude_table => qr/^system/); $dbi->user_column_info($user_column_info);
If
user_column_info is set,
each_column use
user_column_info to find column info. this is very fast.
user_table_info
my $user_table_info = $dbi->user_table_info; $dbi = $dbi->user_table_info($user_table_info);
You can set the following data.
[ {table => 'book', info => {...}}, {table => 'author', info => {...}} ]
Usually, you can set return value of
get_table_info.
my $user_table_info = $dbi->get_table_info(exclude => qr/^system/); $dbi->user_table_info($user_table_info);
If
user_table_info is set,
each_table use
user_table_info to find table info.
METHODS
DBIx::Custom inherits all methods from Object::Simple and use all methods of DBI and implements the following new ones.
available_datatype
print $dbi->available_datatype;
Get available data types. You can use these data types in
type rule's
from1 and
from2 section.
available_typename
print $dbi->available_typename;
Get available type names. You can use these type names in
type_rule's
into1 and
into2 section.
assign_clause
my $assign_clause = $dbi->assign_clause({title => 'a', age => 2});
Create assign clause
title = :title, author = :author
This is used to create update clause.
"update book set " . $dbi->assign_clause({title => 'a', age => 2});
column
my $column = $dbi->column(book => ['author', 'title']);
Create column clause. The following column clause is created.
book.author as "book.author", book.title as "book.title"
You can change separator by
separator attribute.
# Separator is hyphen $dbi->separator('-'); book.author as "book-author", book.title as "book-title"
connect
# DBI compatible arguments my $dbi = DBIx::Custom->connect( "dbi:mysql:database=dbname", 'ken', '!LFKD%$&', {mysql_enable_utf8 => 1} ); # pass DBIx::Custom attributes my $dbi = DBIx::Custom->connect( dsn => "dbi:mysql:database=dbname", user => 'ken', password => '!LFKD%$&', option => {mysql_enable_utf8 => 1} );
Connect to the database and create a new DBIx::Custom object.
DBIx::Custom is a wrapper of DBI.
AutoCommit and
RaiseError options are true, and
PrintError option is false by default.
create_model
$dbi->create_model('book'); $dbi->create_model( 'book', join => [ 'inner join company on book.comparny_id = company.id' ] ); $dbi->create_model( table => 'book', join => [ 'inner join company on book.comparny_id = company.id' ], );
Create DBIx::Custom::Model object and initialize model. Model columns attribute is automatically set. You can use this model by using
model method.
$dbi->model('book')->select(...);
You can use model name which different from table name
$dbi->create_model(name => 'book1', table => 'book'); $dbi->model('book1')->select(...);
dbh
my $dbh = $dbi->dbh;
Get DBI database handle. if
connector is set, you can get database handle through
connector object.
delete
$dbi->delete(table => 'book', where => {title => 'Perl'});
Execute delete statement.
The following options are available.
OPTIONS
delete method use all of
execute method's options, and use the following new ones.
- prefix
prefix => 'some'
prefix before table name section.
delete some from book
- table
table => 'book'
Table name.
- where
Same as
selectmethod's
whereoption.
delete_all
$dbi->delete_all(table => $table);
Execute delete statement for all rows. Options is same as
delete.
each_column
$dbi->each_column( sub { my ($dbi, $table, $column, $column_info) = @_; my $type = $column_info->{TYPE_NAME}; if ($type eq 'DATE') { # ... } } );
Iterate all column informations in database. Argument is callback which is executed when one column is found. Callback receive four arguments.
DBIx::Custom object,
table name,
column name, and
column information.
If
user_column_info is set,
each_column method use
user_column_info information, you can improve the performance of
each_column in the following way.
my $column_infos = $dbi->get_column_info(exclude_table => qr/^system_/); $dbi->user_column_info($column_info); $dbi->each_column(sub { ... });
each_table
$dbi->each_table( sub { my ($dbi, $table, $table_info) = @_; my $table_name = $table_info->{TABLE_NAME}; } );
Iterate all table information from in database. Argument is callback which is executed when one table is found. Callback receive three arguments,
DBIx::Custom object,
table name,
table information.
If
user_table_info is set,
each_table method use
user_table_info information, you can improve the performance of
each_table in the following way.
my $table_infos = $dbi->get_table_info(exclude => qr/^system_/); $dbi->user_table_info($table_info); $dbi->each_table(sub { ... });
execute
my $result = $dbi->execute( "select * from book where title = :title and author like :author", {title => 'Perl', author => '%Ken%'} ); my $result = $dbi->execute( "select * from book where title = :book.title and author like :book.author", {'book.title' => 'Perl', 'book.author' => '%Ken%'} );
Execute SQL. SQL can contain column parameter such as :author and :title. You can append table name to column name such as :book.title and :book.author. Second argument is data, embedded into column parameter. Return value is DBIx::Custom::Result object when select statement is executed, or the count of affected rows when insert, update, delete statement is executed.
Named placeholder such as
:title is replaced by placeholder
?.
# Original select * from book where title = :title and author like :author # Replaced select * from where title = ? and author like ?;
You can specify operator with named placeholder by
name{operator} syntax.
# Original select * from book where :title{=} and :author{like} # Replaced select * from where title = ? and author like ?;
Note that colons in time format such as 12:13:15 is an exception, it is not parsed as named placeholder. If you want to use colon generally, you must escape it by
\\
select * from where title = "aa\\:bb";
OPTIONS
The following options are available.
- after_build_sql
You can filter sql after the sql is build.
after_build_sql => $code_ref
The following one is one example.
$dbi->select( table => 'book', column => 'distinct(name)', after_build_sql => sub { "select count(*) from ($_[0]) as t1" } );
The following SQL is executed.
select count(*) from (select distinct(name) from book) as t1;
- append
append => 'order by name'
Append some statement after SQL.
- bind_type
Specify database bind data type.
bind_type => {image => DBI::SQL_BLOB} bind_type => [image => DBI::SQL_BLOB] bind_type => [[qw/image audio/] => DBI::SQL_BLOB]
This is used to bind parameter by
bind_paramof statement handle.
$sth->bind_param($pos, $value, DBI::SQL_BLOB);
- filter
filter => { title => sub { uc $_[0] } author => sub { uc $_[0] } } # Filter name filter => { title => 'upper_case', author => 'upper_case' } # At once filter => [ [qw/title author/] => sub { uc $_[0] } ]
Filter. You can set subroutine or filter name registered by
register_filter. This filter is executed before data is saved into database. and before type rule filter is executed.
- reuse
reuse => $hash_ref
Reuse query object if the hash reference variable is set.
my $queries = {}; $dbi->execute($sql, $param, reuse => $queries);
This will improved performance when you want to execute same query repeatedly because generally creating query object is slow.
- table
table => 'author'
If you want to omit table name in column name and enable
into1and
into2type filter, You must set
tableoption.
$dbi->execute("select * from book where title = :title and author = :author", {title => 'Perl', author => 'Ken', table => 'book'); # Same $dbi->execute( "select * from book where title = :book.title and author = :book.author", {title => 'Perl', author => 'Ken');
- table_alias
table_alias => {worker => 'user'} # {ALIAS => TABLE}
Table alias. Key is alias table name, value is real table name, . If you set
table_alias, you can enable
into1and
into2type rule on alias table name.
- type_rule_off
type_rule_off => 1
Turn
into1and
into2type rule off.
- type_rule1_off
type_rule1_off => 1
Turn
into1type rule off.
- type_rule2_off
type_rule2_off => 1
Turn
into2type rule off.
- prepare_attr EXPERIMENTAL
prepare_attr => {mysql_use_result => 1}
Statemend handle attributes, this is DBI's
preparemethod second argument.
- query EXPERIMENTAL
query => 1
If you want to get SQL information only except execution, You can get DBIx::Custom::Query object by this option.
my $query = $dbi->execute( "insert into book (id, name) values (:id, :name)", {id => 1, name => 'Perl'}, query => 1 );
DBIx::Custom::Query have the following information
my $sql = $query->sql; my $param = $query->param; my $columns $query->columns;
You can get bind values and the types by the following way.
# Build bind values and types $query->build; # Get bind values my $bind_values = $query->bind_values; # Get bind types my $bind_value_types = $query->bind_value_types;
You can prepare sql and execute SQL by DBI directry.
my $sth = $dbi->dbh->prepare($sql); $sth->execute($sql, @$bind_values);
If you know parameters have no duplicate column name, have no filter, you get bind values in the following fastest way.
my $bind_values = [map { $param->{$_} } @columns]
get_column_info
my $column_infos = $dbi->get_column_info(exclude_table => qr/^system_/);
get column information except for one which match
exclude_table pattern.
[ {table => 'book', column => 'title', info => {...}}, {table => 'author', column => 'name' info => {...}} ]
get_table_info
my $table_infos = $dbi->get_table_info(exclude => qr/^system_/);
get table information except for one which match
exclude pattern.
[ {table => 'book', info => {...}}, {table => 'author', info => {...}} ]
You can set this value to
user_table_info.
insert
$dbi->insert({title => 'Perl', author => 'Ken'}, table => 'book');
Execute insert statement. First argument is row data. Return value is affected row count.
If you want to set constant value to row data, use scalar reference as parameter value.
{date => \"NOW()"}
You can pass multiple parameters, this is very fast.
$dbi->insert( [ {title => 'Perl', author => 'Ken'}, {title => 'Ruby', author => 'Tom'} ], table => 'book' );
In multiple insert, you can't use
id option. and only first parameter is used to create sql.
options
insert method use all of
execute method's options, and use the following new ones.
- bulk_insert
bulk_insert => 1
bulk insert is executed if database support bulk insert and multiple parameters is passed to
insert. The SQL like the following one is executed.
insert into book (id, title) values (?, ?), (?, ?);
- ctime
ctime => 'created_time'
Created time column name. time when row is created is set to the column. default time format is "YYYY-mm-dd HH:MM:SS", which can be changed by
nowattribute.
- prefix
prefix => 'or replace'
prefix before table name section
insert or replace into book
- table
table => 'book'
Table name.
- mtime
This option is same as
updatemethod
mtimeoption.
- wrap
wrap => {price => sub { "max($_[0])" }}
placeholder wrapped string.
If the following statement
$dbi->insert({price => 100}, table => 'book', {price => sub { "$_[0] + 5" }});
is executed, the following SQL is executed.
insert into book price values ( ? + 5 );
include_model
$dbi->include_model('MyModel');
Include models from specified namespace, the following layout is needed to include models.
lib / MyModel.pm / MyModel / book.pm / company.pm
Name space module, extending DBIx::Custom::Model.
MyModel.pm
package MyModel; use DBIx::Custom::Model -base; 1;
Model modules, extending name space module.
MyModel/book.pm
package MyModel::book; use MyModel -base; 1;
MyModel/company.pm
package MyModel::company; use MyModel -base; 1;
MyModel::book and MyModel::company is included by
include_model.
You can get model object by
model.
my $book_model = $dbi->model('book'); my $company_model = $dbi->model('company');
You can include full-qualified table name like
main.book
lib / MyModel.pm / MyModel / main / book.pm / company.pm my $main_book = $self->model('main.book');
See DBIx::Custom::Model to know model features.
like_value
my $like_value = $dbi->like_value
Code reference which return a value for the like value.
sub { "%$_[0]%" }
mapper
my $mapper = $dbi->mapper(param => $param);
Create a new DBIx::Custom::Mapper object.
merge_param
my $param = $dbi->merge_param({key1 => 1}, {key1 => 1, key2 => 2});
Merge parameters. The following new parameter is created.
{key1 => [1, 1], key2 => 2}
If same keys contains, the value is converted to array reference.
model
my $model = $dbi->model('book');
Get a DBIx::Custom::Model object create by
create_model or
include_model
mycolumn
my $column = $dbi->mycolumn(book => ['author', 'title']);
Create column clause for myself. The following column clause is created.
book.author as author, book.title as title
new
my $dbi = DBIx::Custom->new( dsn => "dbi:mysql:database=dbname", user => 'ken', password => '!LFKD%$&', option => {mysql_enable_utf8 => 1} );
Create a new DBIx::Custom object.
not_exists
my $not_exists = $dbi->not_exists;
DBIx::Custom::NotExists object, indicating the column is not exists. This is used in
param of DBIx::Custom::Where .
order
my $order = $dbi->order;
Create a new DBIx::Custom::Order object.
q
my $quooted = $dbi->q("title");
Quote string by value of
quote.
register_filter
$dbi->register_filter( # Time::Piece object to database DATE format tp_to_date => sub { my $tp = shift; return $tp->strftime('%Y-%m-%d'); }, # database DATE format to Time::Piece object date_to_tp => sub { my $date = shift; return Time::Piece->strptime($date, '%Y-%m-%d'); } );
Register filters, used by
filter option of many methods.
my $result = $dbi->select( column => ['author', 'title'], table => 'book', where => {author => 'Ken'}, );
Execute select statement.
You can pass odd number arguments. first argument is
column.
my $result = $dbi->select(['author', 'title'], table => 'book');
OPTIONS
select method use all of
execute method's options, and use the following new ones.
- column
column => 'author' column => ['author', 'title']
Column clause.
if
columnis not specified, '*' is set.
column => '*'
You can specify hash of array reference.
column => [ {book => [qw/author title/]}, {person => [qw/name age/]} ]
This is expanded to the following one by using
colomnmethod.
book.author as "book.author", book.title as "book.title", person.name as "person.name", person.age as "person.age"
You can specify own column by
__MY__.
column => [ {__MY__ => [qw/author title/]}, ]
This is expanded to the following one by using
mycolomnmethod.
book.author as "author", book.title as "title",
__MY__can be changed by
mytable_symbolattribute.
- param
param => {'table2.key3' => 5}
Parameter shown before where clause.
For example, if you want to contain named placeholder in join clause, you can pass parameter by
paramoption.
join => ['inner join (select * from table2 where table2.key3 = :table2.key3)' . ' as table2 on table1.key1 = table2.key1']
- prefix
prefix => 'SQL_CALC_FOUND_ROWS'
Prefix of column clause
select SQL_CALC_FOUND_ROWS title, author from book;
- join
join => [ 'left outer join company on book.company_id = company_id', 'left outer join location on company.location_id = location.id' ]
Join clause. If column clause or where clause contain table name like "company.name", join clauses needed when SQL is created is used automatically.
$dbi->select( table => 'book', column => ['company.location_id as location_id'], where => {'company.name' => 'Orange'}, join => [ 'left outer join company on book.company_id = company.id', 'left outer join location on company.location_id = location.id' ] );
In above select, column and where clause contain "company" table, the following SQL is created
select company.location_id as location_id from book left outer join company on book.company_id = company.id where company.name = ?;
You can specify two table by yourself. This is useful when join parser can't parse the join clause correctly.
$dbi->select( table => 'book', column => ['company.location_id as location_id'], where => {'company.name' => 'Orange'}, join => [ { clause => 'left outer join location on company.location_id = location.id', table => ['company', 'location'] } ] );
- table
table => 'book'
Table name.
- where
# (1) Hash reference where => {author => 'Ken', 'title' => ['Perl', 'Ruby']} # -> where author = 'Ken' and title in ('Perl', 'Ruby') # (2) DBIx::Custom::Where object where => $dbi->where( clause => ['and', ':author{=}', ':title{like}'], param => {author => 'Ken', title => '%Perl%'} ) # -> where author = 'Ken' and title like '%Perl%' # (3) Array reference[Array refenrece, Hash reference] where => [ ['and', ':author{=}', ':title{like}'], {author => 'Ken', title => '%Perl%'} ] # -> where author = 'Ken' and title like '%Perl%' # (4) Array reference[String, Hash reference] where => [ ':author{=} and :title{like}', {author => 'Ken', title => '%Perl%'} ] # -> where author = 'Ken' and title like '%Perl%' # (5) String where => 'title is null' # -> where title is null
Where clause. See also DBIx::Custom::Where to know how to create where clause.
type_rule
$dbi->type_rule( into1 => { date => sub { ... }, datetime => sub { ... } }, into2 => { date => sub { ... }, datetime => sub { ... } }, from1 => { # DATE 9 => sub { ... }, # DATETIME or TIMESTAMP 11 => sub { ... }, } from2 => { # DATE 9 => sub { ... }, # DATETIME or TIMESTAMP 11 => sub { ... }, } );
Filtering rule when data is send into and get from database. This has a little complex problem.
In
into1 and
into2 you can specify type name as same as type name defined by create table, such as
DATETIME or
DATE.
Note that type name and data type don't contain upper case. If these contain upper case character, you convert it to lower case.
into2 is executed after
into1.
Type rule of
into1 and
into2 is enabled on the following column name.
- 1. column name
issue_date issue_datetime
This need
tableoption in each method.
- 2. table name and column name, separator is dot
book.issue_date book.issue_datetime
You get all type name used in database by
available_typename.
print $dbi->available_typename;
In
from1 and
from2 you specify data type, not type name.
from2 is executed after
from1. You get all data type by
available_datatype.
print $dbi->available_datatype;
You can also specify multiple types at once.
$dbi->type_rule( into1 => [ [qw/DATE DATETIME/] => sub { ... }, ], );
update
$dbi->update({title => 'Perl'}, table => 'book', where => {id => 4});
Execute update statement. First argument is update row data.
If you want to set constant value to row data, use scalar reference as parameter value.
{date => \"NOW()"}
OPTIONS
update method use all of
execute method's options, and use the following new ones.
- prefix
prefix => 'or replace'
prefix before table name section
update or replace book
- table
table => 'book'
Table name.
- where
Same as
selectmethod's
whereoption.
- wrap
wrap => {price => sub { "max($_[0])" }}
placeholder wrapped string.
If the following statement
$dbi->update({price => 100}, table => 'book', {price => sub { "$_[0] + 5" }});
is executed, the following SQL is executed.
update book set price = ? + 5;
- mtime
mtime => 'modified_time'
Modified time column name. time row is updated is set to the column. default time format is
YYYY-mm-dd HH:MM:SS, which can be changed by
nowattribute.
update_all
$dbi->update_all({title => 'Perl'}, table => 'book', );
Execute update statement for all rows. Options is same as
update method.
- option
option => { select => { append => '...' }, insert => { prefix => '...' }, update => { filter => {} } }
If you want to pass option to each method, you can use
optionoption.
- select_option
select_option => {append => 'for update'}
select method option, select method is used to check the row is already exists.
show_datatype
$dbi->show_datatype($table);
Show data type of the columns of specified table.
book title: 5 issue_date: 91
This data type is used in
type_rule's
from1 and
from2.
show_tables
$dbi->show_tables;
Show tables.
show_typename
$dbi->show_typename($table);
Show type name of the columns of specified table.
book title: varchar issue_date: date
This type name is used in
type_rule's
into1 and
into2.
values_clause
my $values_clause = $dbi->values_clause({title => 'a', age => 2});
Create values clause.
(title, author) values (title = :title, age = :age);
You can use this in insert statement.
my $insert_sql = "insert into book $values_clause";
where
my $where = $dbi->where; $where->clause(['and', 'title = :title', 'author = :author']); $where->param({title => 'Perl', author => 'Ken'}); $where->join(['left join author on book.author = author.id]);
Create a new DBIx::Custom::Where object. See DBIx::Custom::Where to know how to create where clause.
create_result EXPERIMENTAL
my $result = $dbi->create_result($sth);
Create DBIx::Custom::Result object.
ENVIRONMENTAL VARIABLES
DBIX_CUSTOM_DEBUG
If environment variable
DBIX_CUSTOM_DEBUG is set to true, executed SQL and bind values are printed to STDERR.
DBIX_CUSTOM_DEBUG_ENCODING
DEBUG output encoding. Default to UTF-8.
DBIX_CUSTOM_SUPPRESS_DEPRECATION
$ENV{DBIX_CUSTOM_SUPPRESS_DEPRECATION} = '0.25';
Suppress deprecation warnings before specified version.
DEPRECATED FUNCTIONALITY
# Methods DBIx::Custom AUTOLOAD feature # will be removed at 2022/5/1 DBIx::Custom::helper method # will be removed at 2022/5/1 DBIx::Custom::update_or_insert method is DEPRECATED! # will be removed at 2022/5/1 DBIx::Custom::count method # will be removed at 2022/5/1 DBIx::Custom::select,update,delete method's primary_key option is DEPRECATED! # will be removed at 2022/5/1 DBIx::Custom::select,update,delete method's id option is DEPRECATED! # will be removed at 2022/5/1 DBIx::Custom::setup method is DEPRECATED! # will be removed at 2022/5/1
# Options kv method's multi option (from 0.28) # will be removed at 2018/3/1
DBIx::Custom::Model AUTOLOAD feature # will be removed at 2022/5/1 DBIx::Custom::Model::helper method is DEPRECATED! # will be removed at 2022/5/1 DBIx::Custom::Model::update_or_insert method is DEPRECATED! # will be removed at 2022/5/1 DBIx::Custom::Model::count method # will be removed at 2022/5/1 DBIx::Custom::Model::primary_key attribute is DEPRECATED! # will be removed at 2022/5/1
BACKWARDS COMPATIBILITY POLICY
DBIX_CUSTOM_SUPPRESS_DEPRECATION environment variable.
EXPERIMENTAL features will be changed or deleted without warnings.
BUGS
Please tell me bugs if you find bug.
<kimoto.yuki at gmail.com>
AUTHOR
Yuki Kimoto,
<kimoto.yuki at gmail.com>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2 POD Errors
The following errors were encountered while parsing the POD:
- Around line 2382:
You forgot a '=back' before '=head2'
- Around line 2856:
You forgot a '=back' before '=head2'
You forgot a '=back' before '=head2'
|
https://metacpan.org/pod/DBIx::Custom
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
Most interacts.
Locale setting is normally performed across the board for all relevant categories of cultural conventions. This wide-spectrum setting is denoted by the constant attribute LC_ALL of module locale. However, the cultural conventions handled by module locale are grouped into categories, and, in some cases, a program can choose to mix and match categories to build up a synthetic composite locale. The categories are identified by the following constant attributes of module locale:
LC_COLLATE
String sorting; affects functions strcoll and strxfrm in locale
LC_CTYPE
Character types; affects aspects of module string (and string methods) that have to do with lowercase and uppercase letters
LC_MESSAGES
Messages; may affect messages displayed by the operating systemfor example, function os.strerror and module gettext
LC_MONETARY
Formatting of currency values; affects function locale.localeconv
LC_NUMERIC
Formatting of numbers; affects functions atoi, atof, format, localeconv, and str in locale
LC_TIME
Formatting of times and dates; affects function time.strftime
The settings of some categories (denoted by the constants LC_CTYPE, LC_TIME, and LC_MESSAGES) affect behavior in other modules (string, time, os, and gettext, as indicated). The settings of other categories (denoted by the constants LC_COLLATE, LC_MONETARY, and LC_NUMERIC) affect only some functions of locale itself.
Module locale supplies functions to query, change, and manipulate locales, as well as functions that implement the cultural conventions of locale categories LC_COLLATE, LC_MONETARY, and LC_NUMERIC.
atof
atof(s)
Converts string s to a floating-point number using the current LC_NUMERIC setting.
atoi
atoi(s)
Converts string s to an integer number using the current LC_NUMERIC setting.
format
format(fmt, num, grouping=False)
Returns the string obtained by formatting number num according to the format string fmt and the LC_NUMERIC setting. Except for cultural convention issues, the result is like fmt%num. If grouping is true, format also groups digits in the result string according to the LC_NUMERIC setting. For example:
>>> locale.setlocale(locale.LC_NUMERIC, 'en')
'English_United States.1252'
>>> locale.format('%s', 1000*1000)
'1000000'
>>> locale.format('%s', 1000*1000, True)
'1,000,000'
When the numeric locale is U.S. English and argument grouping is true, format supports the convention of grouping digits by threes with commas.
getdefaultlocale
getdefaultlocale(envvars=['LANGUAGE', 'LC_ALL', 'LC_TYPE', 'LANG'])
Checks the environment variables whose names are specified by envvars, in order. The first one found in the environment determines the default locale. getdefaultlocale returns a pair of strings (lang, encoding) compliant with RFC 1766 (except for the 'C' locale), such as ['en_US', 'ISO8859-1']. Each item of the pair may be None if gedefaultlocale is unable to discover what value the item should have.
getlocale
getlocale(category=LC_CTYPE)
Returns a pair of strings (lang, encoding) with the current setting for the given category. The category cannot be LC_ALL.
localeconv
localeconv( )
Returns a dict d with the cultural conventions specified by categories LC_NUMERIC and LC_MONETARY of the current locale. While LC_NUMERIC is best used indirectly, via other functions of module locale, the details of LC_MONETARY are accessible only through d. Currency formatting is different for local and international use. The U.S. currency symbol, for example, is '$' for local use only. '$' is ambiguous in international use, since the same symbol is also used for other currencies called "dollars" (Canadian, Australian, Hong Kong, etc.). In international use, therefore, the U.S. currency symbol is the unambiguous string 'USD'. The keys into d to use for currency formatting are the following strings:
'currency_symbol'
Currency symbol to use locally.
'frac_digits'
Number of fractional digits to use locally.
'int_curr_symbol'
Currency symbol to use internationally.
'int_frac_digits'
Number of fractional digits to use internationally.
'mon_decimal_point'
String to use as the "decimal point" for monetary values.
'mon_grouping'
List of digit-grouping numbers for monetary values.
'mon_thousands_sep'
String to use as digit-groups separator for monetary values.
'negative_sign'
'positive_sign'
Strings to use as the sign symbol for negative (positive) monetary values.
'n_cs_precedes'
'p_cs_precedes'
True if the currency symbol comes before negative (positive) monetary values.
'n_sep_by_space'
'p_sep_by_space'
True if a space goes between sign and negative (positive) monetary values.
'n_sign_posn'
'p_sign_posn'
Numeric codes to use to format negative (positive) monetary values:
0
The value and the currency symbol are placed inside parentheses.
1
The sign is placed before the value and the currency symbol.
2
The sign is placed after the value and the currency symbol.
3
The sign is placed immediately before the value.
4
The sign is placed immediately after the value.
CHAR_MAX
The current locale does not specify any convention for this formatting.
d['mon_grouping'] is a list of numbers of digits to group when formatting a monetary value. When d['mon_grouping'][-1] is 0, there is no further grouping beyond the indicated numbers of digits. When d['mon_grouping'][-1] is locale.CHAR_MAX, grouping continues indefinitely, as if d['mon_grouping'][-2] were endlessly repeated. locale.CHAR_MAX is a constant used as the value for all entries in d for which the current locale does not specify any convention.
normalize
normalize(localename)
Returns a string, suitable as an argument to setlocale, that is the normalized equivalent to localename. If normalize cannot normalize string localename, then normalize returns localename unchanged.
resetlocale
resetlocale(category=LC_ALL)
Sets the locale for category to the default given by getdefaultlocale.
setlocale
setlocale(category, locale=None)
Sets the locale for category to the given locale, if not None, and returns the setting (the existing one when locale is None; otherwise, the new one). locale can be a string or a pair of strings (lang, encoding). The lang string is normally a language code based on ISO 639 two-letter codes ('en' for English, 'nl' for Dutch, and so on). When locale is the empty string '', setlocale sets the user's default locale.
str
str(num)
Like locale.format('%f', num).
strcoll
strcoll(str1, str2)
Like cmp(str1, str2), but according to the LC_COLLATE setting.
strxfrm
strxfrm(s)
Returns a string sx such that the built-in comparison (e.g., by cmp) of strings so transformed is equivalent to calling locale.strcoll on the original strings. strxfrm lets you use the decorate-sort-undecorate (DSU) idiom for sorts that involve locale-conformant string comparisons. However, if all you need is to sort a list of strings in a locale-conformant way, strcoll's simplicity can make it faster. The following example shows two ways of performing such a sort; in this case, the simple variant is often faster than the DSU one, by about 10 percent for a list of a thousand words:
import locale
# simpler and often faster def locale_sort_simple(list_of_strings):
list_of_strings.sort(locale.strcoll)
# less simple and often slower def locale_sort_DSU(list_of_strings):
auxiliary_list = [(locale.strxfrm(s), s) for s in list_of_strings]
auxiliary_list.sort( )
list_of_strings[:] = [s for junk, s in auxiliary_list]
In Python 2.4, the key= argument to the sort method offers both simplicity and speed:
# simplest and fastest, but 2.4-only:
def locale_sort_2_4(list_of_strings):
list_of_strings.sort(key=locale.strxfrm)
A key issue in internationalization is the ability to use text in different natural languages, a task also known as localization. Python supports localization via module gettext, which was inspired by GNU gettext. Module gettext is optionally able to use the latter's infrastructure and APIs, but is simpler and more general. You do not need to install or study GNU gettext to use Python's gettext effectively.
gettext does not deal with automatic translation between natural languages. Rather, gettext helps you extract, organize, and access the text messages that your program uses. Pass each string literal subject to translation, also known as a message, to a function named _ (underscore) rather than using it directly. gettext normally installs a function named _ in the _ _builtin_ _ module. To ensure that your program runs with or without gettext, conditionally define a do-nothing function, named _, that just returns its argument unchanged. Then you can safely use _('message') wherever you would normally use a literal 'message' that should be translated. The following example shows how to start a module for conditional use of gettext:
try: _
except NameError:
def _(s): return s def greet( ): print _('Hello world')
If some other module has installed gettext before you run this example code, function greet outputs a properly localized greeting. Otherwise, greet outputs the string 'Hello world' unchanged.
Edit your source, decorating message literals with function _. Then use any of various tools to extract messages into a text file (normally named messages.pot) and distribute the file to the people who translate messages into the various natural languages your application must support. Python supplies a script pygettext.py (in directory Tools/i18n in the Python source distribution) to perform message extraction on your Python sources.
Each translator edits messages.pot to produce a text file of translated messages with extension .po. Compile the .po files into binary files with extension .mo, suitable for fast searching, using any of various tools. Python supplies script Tools/i18n/msgfmt.py for this purpose. Finally, install each .mo file with a suitable name in a suitable directory.
Conventions about which directories and names are suitable differ among platforms and applications. gettext's default is subdirectory share/locale/<lang>/LC_MESSAGES/ of directory sys.prefix, where <lang> is the language's code (two letters). Each file is named <name>.mo, where <name> is the name of your application or package.
Once you have prepared and installed your .mo files, you normally execute, at the time your application starts up, some code such as the following:
import os, gettext os.environ.setdefault('LANG', 'en') # application-default language gettext.install('your_application_name')
This ensures that calls such as _('message') return the appropriate translated strings. You can choose different ways to access gettext functionality in your programfor example, if you also need to localize C-coded extensions, or to switch back and forth between languages during a run. Another important consideration is whether you're localizing a whole application or just a package that is distributed separately.
Module gettext supplies many functions; the most often used ones are the following.
install
install(domain, localedir=None, unicode=False)
Installs in Python's built-in namespace a function named _ to perform translations given in file <lang>/LC_MESSAGES/<domain>.mo in directory localedir, with language code <lang> as per getdefaultlocale. When localedir is None, install uses directory os.path.join(sys.prefix, 'share', 'locale'). When unicode is true, function _ accepts and returns Unicode strings, not plain strings.
translation
TRanslation(domain, localedir=None, languages=None)
Searches for a .mo file similarly to function install. When languages is None, translation looks in the environment for the lang to use, like install. It examines, in order, environment variables LANGUAGE, LC_ALL, LC_MESSAGES, LANG; the first nonempty one is split on ':' to give a list of language names (for example, 'de:en' is split into ['de', 'en']). When not None, languages must be a list of one or more language names (for example, ['de', 'en']). TRanslation uses the first language name in the list for which it finds a .mo file. Function TRanslation returns an instance object that supplies methods gettext (to translate a plain string), ugettext (to translate a Unicode string), and install (to install either gettext or ugettext under name _ into Python's built-in namespace).
Function translation offers more detailed control than install, which is like translation(domain,localedir).install(unicode). With translation, you can localize a single package without affecting the built-in namespace by binding name _ on a per-module basisfor example, with:
_ = translation(domain).ugettext
TRanslation also lets you switch globally between several languages, since you can pass an explicit languages argument, keep the resulting instance, and call the install method of the appropriate language as needed:
import gettext translators = {}
def switch_to_language(lang, domain='my_app', use_unicode=True):
if not translators.has_key(lang):
translators[lang] = gettext.translation(domain, languages=[lang])
translators[lang].install(use_unicode)
Internationalization is a very large topic. For general introductions and useful resources,
see and. One of the best packages of code and information for internationalization is ICU (), which also includes the Unicode Consortium's excellent Common Locale Data Repository (CLDR) database of locale conventions and code to access the CLDR. Unfortunately, at the time of this writing, ICU supports only Java, C, and C++, not (directly) Python. You can easily use the Java version of ICU with Jython (see "Importing Java Packages in Jython" on page 656 for more information about using Java classes from Jython code); with more effort, you can wrap the C/C++ version of ICU with tools such as SWIG or SIP (covered in Chapter 25) to access ICU functionality from Classic Python.
|
http://books.gigatux.nl/mirror/pythoninanutshell/0596100469/pythonian-CHP-10-SECT-12.html
|
CC-MAIN-2018-22
|
en
|
refinedweb
|
XML Schema is an alternative to XML DTDs. It defines the document organization, like DTD, but it also provides data typing of element content and additional features. XML Schema provides many built-in datatypes such as scalar, real, date and time, URIs, and encoded binary data. User-defined datatypes can be build from these primitive datatypes through extension or restriction.
XML Schema is still beta. This version implements the May 2001 W3C Recommendation. This beta implementation is incomplete at present; not all schema features are implemented.
This chapter describes the following section:
The sequence of calls to the processor is
schemaInitialize(),
schemaValidate(), ... ,
schemaValidate(),
schemaTerminate(). The
initialize() call is invoked once at the beginning of a session; it returns a Schema context that is used throughout the session.
The validation process is go/no-go. Either the document is valid with respect to the schemas or it is invalid. When it is valid, a zero error code is returned. When it is invalid, a nonzero.
The instance document to be validated is first parsed with the XML parser. The root element for the instance is then passed to the Schema validate function, along with an optional Schema URL. If optimal schema is provided, it will be loaded and become the default schema. More documents may then be processed using the same Schema context. When the session is over, the
schemaTerminate() function is called, which releases all memory allocated by the loaded Schemas.
Note: The contents of
xsdctx and
xsd are private (opaque) and must not be accessed by users.
Initializes the XML Schema processor; must be called before any Schema validation can take place. The same context may be used repeatedly for validating multiple documents. Returns a pointer to the allocated context; otherwise returns
NULL.
xsdctx *schemaInitialize( xmlctx *ctx, uword *err);
Loads Schema and returns the error code, or
0 for success.
To indicate that "nsp" is not provided, specify
NULL; to indicate that it's not in any target namespace, specify an empty string, ""; otherwise, provide a namespace URI such as "". If "nsp" is provided, then the following must be all true:
targetNamespace[attribute] of imported schema.
targetNamespace[attribute].
uword schemaLoad( xsdctx *scctx, oratext *uri, oratext *nsp, xsd **schema);
Returns target namespace URI for schema.
oratext *schemaTarget( xsd *schema);
Tears down the Schema processor, releasing all allocated memory. The context may not be used again.
void schemaTerminate( xsdctx *scctx);
Validates an instance document against a Schema. If the default Schema is provided, the named schema is loaded and will become the default. Returns
0 on success (the document is structurally valid and all datatypes check out), or an error code on failure.
uword schemaValidate( xsdctx *scctx, xmlnode *root, xsd *schema);
|
http://docs.oracle.com/cd/A97630_01/appdev.920/a96616/arxml15.htm
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
This document is also available in these non-normative formats: PDF version and XHTML Diff markup to publication from 31 October 2007.
Copyright © 2008 "Best Practices for XML Internationalization". This document was developed by the Internationalization Tag Set (ITS) Working Group, part of the W3C Internationalization Activity. complement to the W3C Recommendation Internationalization Tag Set (ITS) Version 1.0 [ITS]. However, not all internationalization-related issues can be resolved by the special markup described in ITS. The best practices in this document therefore go beyond application of ITS markup to address a number of problems that can be avoided by correctly designing the XML format, and by applying a few additional guidelines when developing content.
This document and Internationalization Tag Set (ITS) Version 1.0 [ITS] implement requirements formulated in Internationalization and Localization Markup Requirements [ITS REQ].
This set of best practices does not cover all topics about internationalization for XML. Other useful reference material includes: Character Model for the World Wide Web 1.0: Fundamentals [CharMod], and Unicode in XML and other Markup Languages [Unicode in XML].
This document is divided into two main sections:
The first one is intended for the designers and developers of XML applications (also referred to here as 'schemas' or 'formats').
The second is intended for the XML content authors. This includes users modifying the original content, such as translators.
Section 2: When Designing an XML Application provides a list of some of the important design choices you should make in order to ensure the internationalization of your format.
Section 4: Generic Techniques provides additional generic techniques such as writing ITS rules or adding an attribute to a schema. Such techniques apply to many of the best practices.
Section 5: ITS Applied to Existing Formats provides a set of concrete examples on how to apply ITS to existing XML based formats. This section illustrates many of the guidelines in this document.
Section 3: When Authoring XML Content provides a number of guidelines on how to create content with internationalization in mind. Many of these best practices are relevant regardless of whether or not your XML format was developed especially for internationalization.
Section 4.1: Writing ITS Rules provides practical guidelines on how to write ITS rules. Such techniques may be useful when applying some of the more advanced authoring best practices.
Designers and developers of XML applications should take into account the following best practices:
Where it says "How to implement this as a new feature", this section describes how to create new schemas or add new features to existing schemas. When doing this you may need to take into account the following:
Think twice before creating your own schema. Seriously consider using existing formats such as DITA, DocBook, Open Document Format, Office Open XML, XML User Interface Language, Universal Business Language, etc. Those formats have many useful insights already built in.
Check carefully whether an existing format comes with a built-in capability for modification. DocBook and DITA, for example, come with their own set of features for adapting their format to special needs.
The modification mechanisms available will depend on the schema language (DTD, XML Schema, RELAX NG, etc.) For example, namespace-based modularization of schemas is difficult to achieve with DTDs.
NVDL is an example of a meta-schema language was designed especially to allow integration of several existing vocabularies into a single XML vocabulary without the need to know the details of source schemas. This means that with NVDL you can usually create a schema for compound documents more easily than with other schema technologies.
Each schema language provides different ways of extending or modifying existing schemas. Some examples are the include, import or redefine mechanisms in XML Schema.
Some processors do not implement support for all schema language constructs, due to erroneous implementations or differences in conformance profiles (e.g. see the conformance requirements to XML Schema part 1). Therefore a schema which works in one environment may not work in a different one.
What is possible also depends on the features of the schema which the modification is targeting. For example:
An XML Schema
redefine is only possible if the modified schema has been created with named types.
If you are working with XML Schema, you can only apply the technique of 'chameleon' or 'proxy' schemas (see) if the 'chameleon' schemas have no namespace. For example, the XML Schema document for ITS XML Schema document for ITS has a target namespace and therefore cannot be a 'chameleon' schema.
Note: The considerations above are only a portion of what you need to take into account. You need to know a lot more when diving into schema modularization.
The XML namespace provides the
xml:lang attribute and the ITS Language Information data category provides the
its:langRule element to address this requirement.
How to implement this as a new feature
Make sure the
xml:lang attribute is defined for the root element of your document, and for any element where a change of language may occur.
For examples of how to add attributes in your existing schema see Section 4.2: Example of adding an attribute to an existing schema.
Some XML documents may be designed to store data without natural language content. In these cases, there is no need for the
xml:lang attribute.
The scope of the
xml:lang attribute applies to both the attributes and the content of the element where it appears, therefore one cannot specify different languages for an attribute and the element content. ITS does not provide a remedy for this. Instead, it is recommended that you avoid translatable attributes.
Make sure that the definition of the
xml:lang attribute allows for empty values. That is:
In a DTD you must not use
NMTOKEN as the data type, instead use
CDATA.
In XML Schema the built-in data type
language does not allow empty values. However, the declaration for
xml:lang in the XML Schema document for the XML namespace at does allow for empty values and therefore can be used.
It is not recommended to use your own attribute or element to specify the language of the content. The
xml:lang attribute is supported by various XML technologies such as XPath and XSLT (e.g. the
lang() function). Using something different would diminish the interoperability of your documents and reduce your ability to take advantage of some XML applications.
Note: If you need to specify language as data or meta-data about something external to the document, do it with an attribute different from
xml:lang. For more information see the article xml:lang in XML document schemas.
In XHTML the language of a file linked with the
a element is indicated with a
hreflang attribute because it does not apply to the content of the
a element.
<a xml:Click here for German</a>
If you have different languages in the attribute values and content of an element, consider nesting elements, if possible. See Handling attribute values and element content in different languages.
Handling markup not in the ITS namespace
If you are working with an existing schema where there is a way to specify content language that uses something other than the
text element. The
langcode element has no inheritance behavior equivalent to the one of
xml:lang.
Note: This example is a multilingual document, which has its own set of issues (see Best Practice 12: Working with multilingual documents).
<myRes> <messages> <msg id="1"> <langcode>en</langcode> <text>Cannot find file.</text> </msg> <msg id="2"> <langcode>fr</langcode> <text>Fichier non trouvé.</text> </msg> </messages> </myRes>
The corresponding ITS Rules document contains an
its:langRule element that specifies that the
langcode element holds the same values as the
xml:lang attribute and applies to the
text element.
<its:rules xmlns: <its:langRule </its:rules>
Why do this
Information about the language of content can be very important for correctly rendering or styling text in some scripts, applying spell-checkers during content authoring, appropriate selection of voice for text-to-speech systems, script-based processing, and numerous other reasons. You must provide a standard way to specify the language for the document as a whole, but also for parts of the document where the language changes.
In scripts such as Arabic and Hebrew characters may run from both left to right and right to left when displayed. Directional markup allows you to manage the flow of characters. For an example of how directional markup is used see Creating (X)HTML Pages in Arabic & Hebrew.
The ITS Directionality data category provides the
its:dir attribute and the
its:dirRule element to address this requirement.
How to implement this as a new feature
Make sure the
its:dir attribute is defined for the root element of your document, and for any element that has text content.
For examples of how to add attributes in your existing schema see Section 4.2: Example of adding an attribute to an existing schema.
Handling markup not in the ITS namespace
If you are working with an existing schema where there is a way to specify text directionality that is not implemented using the
its:dir attribute, you should provide an ITS Rules document where you use the
its:dirRule element to associate the different directionality indicators with their equivalents].
The corresponding ITS Rules document contains a set of
its:dirRule elements that specifies the relationships between the
textdir attribute do this
Generally the Unicode bidirectional algorithm will produce the correct ordering of mixed directionality text in scripts such as Arabic and Hebrew. Sometimes, however, additional help is needed. For instance, in the sentence of Example 4 the 'W3C' and the comma should appear to the left side of the quotation. This cannot be achieved using the bidirectional algorithm alone.
The following will display Hebrew text. If your browser supports bidirectional display, the following should appear correctly, since directional markup has been added to the element surrounding the quote:
The title says "פעילות הבינאום, W3C" in Hebrew.
The desired effect can be achieved using Unicode control characters, but this is not recommended (See Unicode in XML and other Markup Languages [Unicode in XML]). Markup is needed to establish the default directionality of a document, and to change that where appropriate by creating nested embedding levels.
Markup is also occasionally needed to disable the effects of the bidirectional algorithm for a specified range of text.
How to implement this as a new feature
Make sure you store all translatable text as element content, not as attribute values.
It is bad design to use the 6: Providing
information related to text segmentation.
Handling markup not in the ITS namespace
If you are working with an existing schema where there are attributes with translatable values, you should provide an ITS Rules document where you use the
its:translateRule element to specify what attributes are translatable. See Best Practice 4: Indicating which elements and attributes should be translated for more information about how to do this.
Why do this
There are a number of issues related to storing translatable text in attribute values. Some of them are:
The language identification mechanism (i.e.
xml:lang) applies to both the content and to the attribute values of the element where it is declared. If the text of an attribute is in a different language than the text of the element content, one cannot set the language for both correctly.
It may be necessary to apply some language-related properties, such as directionality and language identification, to only part of the text in an attribute value. This requires the use of a
span-like element, but elements cannot be used within an attribute value.
It is difficult to apply meta-information, such as no-translate flags, author's notes, etc., to the text of an attribute value
The difficulty of attaching unique identifiers to translatable attribute text makes it more complicated to use ID-based leveraging tools.
It can be problematic to prepare translatable attributes.
The ITS Translate data category provides the
its:translateRule element to address this requirement.
How to do this
Provide an ITS Rules document where you use
its:translateRule elements to indicate which elements have non-translatable content.
If you are working with a schema where there are translatable attributes (something that is not recommended), you should also use
its:translateRule to specify these translatable attributes.
Note: Where the language of content is given as
xml:lang="zxx", where
zxx indicates content that is not in a language, the element in question is probably not to be translated. You should provide a rule for this.
In the following document, the content of the
head element should not be translated, and the value of the
alt attribute should be translated. In addition, the content of the
del element should not be translated.
<myDoc xml: <head> <id xml:H4-A3-F8-A1</id> <author>Robert Griphook</author> <rev>v13 2007-10-27</rev> </head> <par>To start click <ins>the <ui>Start</ui> button</ins><del>green icon</del> and fill the form labeled by the following icon: <ref file="vat.png" alt="Value Added Tax Form"/></par> </myDoc>
The following rules specify exceptions from the default ITS behavior for documents like the one above.
<its:rules xmlns: <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule </its:rules>
First
translateRule: The content of
head in
myDoc is not translatable. By inheritance, the child elements of
head are also assumed not translatable.
Second
translateRule: All the
alt attributes are translatable.
Third
translateRule: The content of
del is not translatable.
Fourth
translateRule: The non-translatability of
del applies also to any attribute that may have been set as translatable by a prior rule (i.e. the second rule).
Fifth
translateRule: Any element or attribute with their language set to
zxx is not translatable.
Why do this
By default, ITS assumes that the content of all elements is translatable and that all attributes have non-translatable values. If your XML document type does not correspond to this default assumption it is important to indicate what are the exceptions. Doing so can significantly improve translation throughput.
The ITS Translate data category provides the
its:translate attribute and the
its:translateRule element to address this requirement.
How to implement this as a new feature
Make sure the
its:translate attribute is defined for the root element of your documents, and for any element that has text content.
For examples of how to add attributes in your existing schema see Section 4.2: Example of adding an attribute to an existing schema.
It is also recommended that you define the
its:rules element in your schema, for example in a header if there is one, and within that the
its:translateRule element. Content authors can then use these elements to globally change the default translate rules for specific elements and attributes.
Handling markup not in the ITS namespace
If you are working with a schema where there is a way to override translate information that is not
its:translate, the authors of the documents should use it. In addition, you should provide an ITS Rules document where you use the
its:translateRule element to associate this mechanism with the ITS Translate data category.
For example, DITA offers a
translate attribute, and Glade provides a
translatable attribute. Both have the same semantics as
its:translate, ie. the translation information applies to element content, including child elements, but excluding attribute values.
The following rules indicate how to associate the DITA
translate attribute with the ITS Translate data category. The order in which the rules are listed is important:
First
translateRule: Indicates that the content of any element with a
translate attribute set to
no is not translatable.
Second
translateRule: Indicates that any attribute value of any element with a
translate attribute set to
no is not translatable. This is needed because some attributes are translatable in DITA and we need to make sure they are not translated when
translate="no" is used in the elements where they are.
Third
translateRule: Indicates that the content of any element with a
translate attribute set to
yes is translatable. This takes care of the cases where
translate="yes" is used to override a prior
translate="no".
<its:rules xmlns: <its:translateRule <its:translateRule <its:translateRule </its:rules>
You can find a more complete example of how DITA markup is associated with ITS in Section 5.4.2: Associating existing DITA markup with ITS.
Why do this
In some cases, the author of a document may need to change the translatability property on parts of the content, overriding ITS default behavior, or the general rules for the schema that you have specified when applying Best Practice 4: Indicating which elements and attributes should be translated.
Segmentation refers to how text is broken down, from a linguistic viewpoint, into units that can be handled by processes such as translation.
The ITS Element Within Text data category provides the
its:withinTextRule element to address this requirement.
How to do this
Whether you are creating a new schema or documenting legacy markup, provide an ITS Rules document where you use
its:withinTextRule elements to indicate which elements should be treated as either part of their parents, or as a nested but independent run of text. By default, element boundaries are assumed to correspond to segmentation boundaries.
In the following DITA document:
The elements
term and
b should be treated as part of their parent.
The element
fn should be treated as an independent run of text.
three elements, all other elements are assumed to have the value
its:withinText="no":
First
withinTextRule: The elements
term and
b are defined as part of the text flow.
Second
withinTextRule: The element
fn is defined as a separate bit of content nested inside its parent element.
<its:rules xmlns: <its:withinTextRule <its:withinTextRule </its:rules>
These rules applied to the DITA document above will result do this
Many applications that process content for linguistic-related tasks need to be able to perform a basic segmentation of the text content. They need to be able to do this without knowing the semantics of the elements.
While in many cases it is possible to detect mixed content automatically, there are some situations where the structure of an element makes it impossible for tools to know for sure where appropriate segmentation boundaries fall. For example, the boundaries of some inline elements, such as emphasis, do not typically correspond to segmentation boundaries; on the other hand, some inline elements embedded in a parent element, such as footnotes or quotations, may define segments that should be handled separately from the text in which they are embedded.
Intelligent segmentation is particularly important in translation to successfully match source text against translation-memory databases.
Ruby text is used to provide a short annotation of an associated base text. It is most often used to provide a reading (pronunciation) guide.
The ITS Ruby data category provides the elements
its:ruby and
its:rubyRule and their children to address this requirement. The definition of this data category is compliant with the specification of Ruby in [Ruby Annotation].
How to implement this as a new feature
Make sure the
its:ruby element and its children are defined for all elements where there is text content.
Handling markup not in the ITS namespace
If you are working with an existing schema where there is a way to specify ruby text that has the same semantics as the ITS Ruby data category (for example the Ruby Annotation [Ruby Annotation]), you should provide an ITS Rules document where you use the
its:rubyRule element to associate your ruby markup with its equivalent in ITS.
In this document, the
rubyBlock element has the same functionality as
its:ruby,
rBase as
its:rb,
rParen as
its:rp, and
rText as
its:rt.
<text> <para>この本は <rubyBlock> <rBase>慶応義塾大学</rBase> <rParen>(</rParen> <rText>けいおうぎじゅくだいがく</rText> <rParen>)</rParen> </rubyBlock>の歴史を説明するものです。</para> </text>
This
its:rubyRule element indicates that the
rBase element has the same functionality as
its:rb and that the elements
its:ruby,
its:rt and
its:rt have equivalent elements as well.
<its:rules xmlns: <its:rubyRule </its:rules>
Why do this
Ruby is a type of annotation for text. It can be used with any language, but is very commonly used with East Asian scripts to provide phonetic transcriptions of characters that are likely to be unfamiliar to a, even if your original documents are to be developed into a language that does not use such markup.
The ITS Localization Note data category provides the attributes
its:locNote,
its:locNoteType and
its:locNoteRef, as well as the
its:locNoteRule element to address this requirement.
How to implement this as a new feature
Make sure the attributes
its:locNote,
its:locNoteType and
its:locNoteRef are defined
its:locNoteRule element and its related markup. Content authors can use this markup to specify localization-related notes. Within the
its:locNoteRule element, notes can be stored in the
its:locNote element.
The
its:locNoteRule element also allows you to specify notes in the current flags markup not in the ITS namespace
If you are working with an existing schema where there is a way to provide notes to the localizers that is not implemented using ITS, you should provide an ITS Rules document where you use the
its:locNoteRule element to associate your notes markup with its equivalent in ITS.
In this document the
comment element is a note for its sibling
text element.
<messages> <msg id="ERR_NOFILE"> <text>The file '{0}' could not be found.</text> <comment>The variable {0} is the name of a file.</comment> </msg> </messages>
The
its:locNoteRule element specifies that the
text elements have an associated localization description in their sibling
comment elements.
<its:rules xmlns: <its:locNoteRule </its:rules>
Why do this
To assist the translator to achieve a correct translation, authors may need to provide information about the text that they have written. For example, the author may want to do the following:
Tell the translator how to translate part of the content (e.g. "Leave text in uppercase").
Expand on the meaning or contextual usage of a particular element, such as what a variable refers to or how a string will be used on the UI.
Clarify ambiguity and show relationships between items sufficiently to allow correct translation (e.g. in many languages it is impossible to translate the word 'enabled' in isolation without knowing the gender, number and case of the thing it refers to.)
Explain why text is not to be translated, point to text reuse, or describe the use of conditional text.
Indicate why a piece of text is emphasized (important, sarcastic, etc.)
How to do this
Make sure identifiers are most useful when their values are globally unique (i.e. unique across any documents) and persistent (i.e. ones which do not change over time).
Why do this
In order to most effectively reuse translated text where content is reused (for example across updates) it is necessary to have a unique and persistent identifier associated with the element.
This identifier allows the translation tools to correctly track an item from one version or location to the next. After ensuring that this is the same item, the content can be examined for changes, and if no change has taken place the potential for reuse of the previous translation is very high.
Change analysis of this kind constitutes an extremely powerful productivity tool for translation when compared to typical source matching techniques (a.k.a. translation memory). These techniques simply look for similar source text in a multilingual database without, most of the time, being able to tell whether the context of its use is the same.
Identifiers can also be helpful to track displayed text back to its underlying source. For example, when reviewing a translated user interface, the identifiers can be used as temporary prefixes to the text so that any correction can be efficiently done on the proper strings.
The ITS Terminology data category provides the
its:termRule element to address this requirement.
How to do this
Provide an ITS Rules document where you use
its:termRule elements to indicate which elements are terms and information related to them (e.g. definitions).
Note: The information identified through the
its:termInfoRef can be of any type (e.g. human-readable or machine-specific). It is up to the application processing the data to make the distinction.
In this document, the elements
term and
dt, as well as any element with a
syn attribute, denote terms. In addition, they can all have associated information.
<myDoc> <body> <p>A <term def="d001" syn="#alterego">doppelgänger</term> is basically <def xml:the counterpart of a person</def>. It is almost the same as an <emph syn="#alterego">alter ego</emph>, but with a more sinister connotation. Sometimes the word <emph syn="#alterego">fetch</emph> is also used.</p> </body> <definitions> <entry xml: <dt>alter ego</dt> <dd>A second self. Figurative sense: trusted friend.</dd> <origin>Latin, literally: "second I"</origin> </entry> </definitions> </myDoc>
The set of ITS rules below indicates:
First
termRule: The
term element is a term and its associated information can be accessed in the node that has the identifier corresponding to the value in its
def attribute.
Second
termRule: Any element with a
syn attribute is considered a term and the
syn attribute contains a URI location where some associated information can be found.
Third
termRule: The
dt element is a term and its associated information is in its sibling element
dd.
<its:rules xmlns: <its:termRule <its:termRule <its:termRule </its:rules>
Why do this
The capability of specifying terms within the source content is important for terminology management and beneficial to translation and localization quality. For example, term identification facilitates the creation of glossaries and allows the validation of terminology usage in the source and translated documents.
Term identification is also useful for change management and to ensure source language quality.
Terms may require various associated information, such as part of speech, gender, number, term types, definitions, notes on usage, etc. To avoid associated information to be repeated throughout a document, it should be possible for identified terms to link to externalized attribute data, such as glossary documents and terminology database.
The ITS Terminology data category provides the attributes
its:term and
its:termInfoRef, as well as the
its:termRule element to address this requirement.
How to do this
Make sure the
its:term and the
its:termInfoRef attributes are defined for any element that has text content.
For examples of how to add attributes in your existing schema see Section 4.2: Example of adding an attribute to an existing schema.
It is also recommended to define the
its:rules element in your schema, for example in a header if there is one. The
its:rules element provides access to the
its:termRule element which can be used to override terminology-related information globally.
Why do this
In some cases, the author of a document may need to change the information indicating what is a term or how to point to term information, overriding the general rules for the schema that you have specified when applying Best Practice 10: Identifying terminology-related elements.
This a separate document.
This is an example of bad design. It shows a single document that contains multiple translations of the same content:
<messages> <msg xml: <text xml:File not found.</text> <text xml:Fichier non trouvé.</text> </msg> </messages>
Instead, use one document for each language. Here one in English, and the other one in French. Other languages would go in similar separate documents.
<messages xml: <msg xml: <text>File not found.</text> </msg> </messages>
<messages xml: <msg xml: <text>Fichier non trouvé.</text> </msg> </messages>
Note: It is admissible to store multilingual copies of a content in a single document before the document to send to localization, or after all localization tasks are done. For example, a final resource file could be constructed by collating the different language entries.
Note: It is admissible to provide the localizer with multilingual documents in XML formats that are specifically designed for localization, and are industry standards, like the XML Localisation Interchange File Format [XLIFF 1.2].
Why do this
There are two main reasons to avoid sending documents for localization if the source material is located in parallel with the different translations in the same document:
It is difficult to manage concurrent translations in all languages. It is very likely that each translation will be done by a different translator, in a different location. To facilitate this, the document will have to be broken down into separate parts and reconstructed later on. This adds processing time, increases cost and provides more opportunities for the introduction of errors.
Depending on the point in the document's lifecycle, such a document may already contain translations, some up-to-date and some outdated (because the source material may have changed). In is an example of bad design. The element
b is used for several purposes.
<doc> <p>To run the application, click the <b>Start</b> button.</p> <p><b>Make sure to enter your username</b>, and then press <b>OK</b>.</p> </doc>
Instead, define different elements based on their functions rather than a pre-supposed rendering.
<doc> <p>To run the application, click the <ui>Start</ui> button.</p> <p><emph>Make sure to enter your username</emph>, and then press <ui>OK</ui>.</p> </doc>
Also, if possible, avoid element names which do not follow a fixed naming scheme (for example, element names that serve also as identifiers).
This is an example, or accessibility.
Using documents where elements or attributes do not follow a predictable naming pattern may cause problems when using XSLT-driven processes. It may also be an issue for translation tools. This is especially true if not all parts of the document are to be translated, since it would be more difficult to specify rules to distinguish the translatable nodes from the non-translatable ones.
A
span-like element is an element that can be used to mark authors to associate arbitrary content with properties such as directionality, language information, etc.
If your schema does not already provide such an element, you could provide the
its:span element.
The definition of the
its:span element in the ITS Specification lists a set of ITS attributes that should be allowed on a span-like element.
Why do this
Some properties of content are applied using attributes. Directionality, terminology, localization notes, translate information, and language identification are examples of such properties. There is a need for a neutral element to delimit the run of text to which such attributes apply, since the appropriate boundaries are sometimes not delimited by other markup that is present, or perhaps those attributes are not permitted on other markup that is present.
How to do this
Make sure you document the internationalization and localization aspects of your schema by providing a set of relevant ITS rules in a single standalone ITS Rules document.
Your ITS Rules document should include the following information, when applicable:
The correspondence between any proprietary mechanism you have to specify the language of content and
xml:lang (see Best Practice 1: Defining markup for natural language labelling).
The correspondence between any proprietary mechanism you have to indicate text directionality and
its:dir (see Best Practice 2: Defining markup to specify text direction).
What markup has translate rules different from the default expectation that elements are to be translated and attributes are not (see Best Practice 4: Indicating which elements and attributes should be translated).
The correspondence between any proprietary mechanism you have to override translatability information and
its:translate (see Best Practice 5: Defining markup to override translate information).
The list of elements that should be treated as "nested" or "within text" from a segmentation viewpoint (see Best Practice 6: Providing information related to text segmentation).
The correspondence between any proprietary mechanism you have to mark up ruby text and
its:ruby (See Best Practice 7: Defining markup for ruby text).
What part of your markup holds notes for the localizers (see Best Practice 8: Defining markup for notes to localizers).
What part of your markup denotes terms and term-related information (see Best Practice 10: Identifying terminology-related elements).
You can find some examples of ITS Rules documents for existing XML formats in Section 5: ITS Applied to Existing Formats.
Why do this
Although some XML vocabularies are easy to understand or process, it is often helpful or necessary to provide explicit information about a given vocabulary. If such a vocabulary is to be used in a multilingual context, it is of high importance to provide information, such as which elements contain translatable content, because general information on purpose, general structure, and node types very often are not sufficient. In a way, this need for explicit information is related to the general good practice of documenting source code.
In XML it should come naturally to use a well-defined, structured format to capture such information. For information related to internationalization and translation, ITS Rules documents are a good choice for the following reasons:
They are designed to take into account many important aspects of internationalization and translation.
They capture information precisely (for example, selectors identify to which nodes a data category pertains).
They can be processed by ITS-aware applications.
They can be easily combined with additional structured information (e.g. related to version control, as shown in the example below).
An ITS processor should still be able to process a file as an external ITS rules file if the format of the file contains your own customized information in addition to the ITS rules. The following is an example of that.
>
Authors of XML content should consider the following best practices:
A number of these practices can be followed only when the XML application has been internationalized properly using the design guidelines in Section 2: When Designing an XML Application.
Your schema should provide the
xml:lang attribute (or an equivalent mechanism) for specifying the language of content. See Best Practice 1: Defining. Attribute values are deemed to be in the same language as the element where they are declared.
Make sure the values of
xml:lang conform to Tags for Identifying Languages [BCP 47]. For a brief introduction to how to form language values using BCP 47 see Language tags in HTML and XML.
In this example, the main content of the document is in English, while a short citation in the
q element is identified as French using
xml:lang set to
<document xml: <para>The motto of Québec is the short phrase: <q xml:Je me souviens</q>. It is chiseled on the front of the Parliament Building.</para> </document>
If the schema you are using does not provide an
xml:lang attribute, use the equivalent attribute.
In this example, the schema for this document type uses a non-standard way to specify language: a
code attribute. Authors should use that mechanism, not
xml:lang, because the developer of the
stringList document type should provide, along with the schema, an ITS Rules document (shown below) that declares
code to be equivalent to
xml:lang when used with the
lang element.
<stringList> <msg id="connected"> <lang code="cs">Jste připojeni k Internetu.</lang> <lang code="de">Sie sind an das Netz angeschlossen.</lang> <lang code="fr">Vouz êtes connecté à la Toile.</lang> <lang code="it">Sei connesso al Web.</lang> <lang code="ja">インターネットに接続しました。</lang> <lang code="ko">웹에 연결되었습니다.</lang> <lang code="ru">Вы подключены к Интернету.</lang> </msg> </stringList>
Note: This example is a multilingual document, which has its own set of issues as described in Best Practice 12: Working with multilingual documents.
The developer of the
stringList document type should provide an ITS Rules document in compliance with Best Practice 1: Defining markup for natural language labelling for existing schemas. Here the
its:langRule element defines the
code attribute of the
lang element to be equivalent to
xml:lang.
<its:rules xmlns: <its:langRule </its:rules>
Note: In some cases, a change in language has implications for translation. For example, content in a different language may have to remain untranslated, or require specific handling. Such information could be provided to the localizer using
its:translate or
its:locNote (or their equivalents in your schema). For more details, see Best Practice 18: Overriding information about what should be translated and Best Practice 21: Providing notes for localizers.
Why do this
Knowing the language of the content is very important in many situations. These 2: Defining markup to specify text direction.
How to do this
By default the text directionality in an XML document is assumed to be left-to-right. Use
its:dir (or its equivalent in your schema) on the root element of any document where the text runs predominantly from right-to-left, and on elements where the Unicode bidirectional algorithm needs help to achieve proper display of bidirectional text.
You can get additional guidance.
In this example, the attribute
its:dir is used to specify the directionality of a right-to-left text run in a document that is by default left-to-right.
<text xmlns: <body> <par>In Hebrew, the title <quote xml:פעילות הבינאום, W3C</quote> means <quote>Internationalization Activity, W3C</quote>.</par> </body> </text>
Without the markup, the Hebrew title will display incorrectly. The text 'W3C' and the comma will be to the right of the quoted Hebrew text, rather than to its left. The markup provides the contextual information that tells the user agent that the comma and 'W3C' text are part of a right-to-left flow of]., situations commonly arise where higher level contextual information is needed to achieve the desired layout of bid.
Note: Directionality information cannot be deduced from language markup: markup are not necessarily aligned with the values of markup about the language. For example, a part of a document might be declared as having right-to-left directionality, but there might be only a general language declaration for a left-to-right script language available, like
Markup used to indicate directionality has values that indicate that the normal directionality should be overridden; it is not possible to indicate that using language related values.
Your schema should provide
its:translate (or an equivalent mechanism) to allow you to override defaults. See Best Practice 5: Defining the last
par should not be translated.
Note that the author does not need to specify that the
head element should not be translated, because this is defined for all documents of type
myDoc by the ITS Rules document provided by the developer of the
myDoc schema (see just below).
<myDoc xmlns: <head> <lastRev>2007-10-23 041254Z</lastRev> <docID>1A454AE4-7EB8-4ed2-A58E-1EC7F75BB0D5</docID> </head> >
This is the ITS Rules document created by the developer of the
myDoc document type (implementing Best Practice 4: Indicating which elements and attributes should be translated). These rules override the ITS default that all element content should be translated, but attribute values should not.
<its:rules xmlns: <its:translateRule <its:translateRule </its:rules>
This is what the rules mean:
First
translateRule: The
head element and its children should not be translated.
Second
translateRule: The
alt attribute of any
img element should be translated.
To override translate information for attributes, you have to use an
its:translateRule element in your
alt attributes should be translated. This is done at the top of the document, using
its:translateRule.
<myDoc xmlns: <head> <lastRev>2007-11-12 234503Z</lastRev> <docID>D1EA7453-DC53-488a-B950-137BE0EF5253</docID> <its:rules> to remain the same>
It may, however, be useful to the translator to mark up loan-words or any special words in this example as terms, as described in the section Best Practice 23: Identifying terms.
Why do this
Although the set of ITS rules provided with the schema should specify any exceptions to the default ITS translation rules for a given schema (see Best Practice 4: allow you to assign unique identifiers to elements. See Best Practice 9: Defining markup for unique identifiers.
Segmentation refers to how text is broken down, from a linguistic viewpoint, into units that can be stored separately and handled by processes such as translation. The schema author ought to create a list of these elements where they differ from the ITS defaults (see Best Practice 6: Providing information related to text segmentation).
How to do this
Use unique identifiers in the way provided by your schema on each element that constitutes a segmentation boundary.
Note: Often, ids are automatically assigned by authoring or content management applications. Thus, authors may not have to worry about them in some cases.
If possible use globally unique and persistent values as identifier values.
Why do this
Providing unique identifiers can be very useful for change analysis, text tracking, and various other tasks often utilized during the authoring and the localization of documents.
This is explained in more detail in Best Practice 9: Defining markup.
This is an example of bad design. In this document, part of the content is in a CDATA section. It is no longer possible to mark up that content for language changes, terms, text direction, translate information, or any of the other things that may be needed to facilitate localization.
<myData> <item course="12" page="2"> <title>Accessing the R&D facilities</title> <body><![CDATA[The R&D facilities are located in the South wing of Building 12-W, in the East quarter of the section Q. IMPORTANT ==> These facilities are accessible only to personal with Class Omega-45Q1 clearance.]]></body> </item> </myData>
Instead, use normal XML for your content. This allows you to tag the content as needed. For instance, here the author has added some terminology markup.
<myData xmlns: <item course="12" page="2"> <title>Accessing the R&D facilities</title> <body>The R&D facilities are located in the South wing of Building 12-W, in the East quarter of the section Q. IMPORTANT ==> These facilities are accessible only to personal with <span its:Class Omega-45-Q1</span> clearance.</body> </item> </myData>
If the CDATA section encloses a large, self-contained block of data, such as a script or an XML example, you may be able to replace the section by some inclusion mechanism such as XInclude or XLink.
In SVG you can place a script directly into an SVG document, in which case you usually use CDATA sections to avoid having to escape characters in the script's code.
<?xml version="1.0" encoding="utf-8"?> <svg width="6cm" height="5cm" viewBox="0 0 600 500" xmlns="" version="1.1"> <!-- Script is inlined and enclosed in CDATA section --> <script type="text/ecmascript"> <![CDATA[ function circle_click(evt) { var circle = evt.target; var currentRadius = circle.getAttribute("r"); if (currentRadius < 100) circle.setAttribute("r", currentRadius*2); else circle.setAttribute("r", currentRadius*0.5); } ]]> </script> >
Instead, you could use XLink to store the script in a separate file and reference it from the SVG document.
<?xml version="1.0" encoding="utf-8"?> <svg width="6cm" height="5cm" viewBox="0 0 600 500" xmlns="" version="1.1" xmlns: <!-- Script is included from external file --> <script type="text/ecmascript" xlink: >
It is quite common to use CDATA sections to put examples of source code into XML documents. The following example shows how to do this using DocBook.
<?xml version="1.0" encoding="utf-8"?> <example xmlns=""> <title>Skeleton of XHTML page</title> <programlisting><![CDATA[<html xmlns="" xml: <head> <title>… page title goes here …</title> </head> <body> … page content goes here … </body> </html>]]></programlisting> </example>
Instead, you could use XInclude to store the example code in a separate file and include it during at processing time. Note that you have to use
parse="text" to treat the included file as plain text rather than markup.
<?xml version="1.0" encoding="utf-8"?> <example xmlns="" xmlns: <title>Skeleton of XHTML page</title> <programlisting><xi:include</programlisting> </example>
If you must use CDATA sections:
Document the type of content (for example with an attribute set to the appropriate MIME-type). This may help tools to use an appropriate parser to process the content.
Aim to produce well-formed content. This will allow parsers to process the content more easily.
Note: CDATA is often used to store textual content containing HTML or XML tags. This is not recommended. See Best Practice 24: Storing markup from another format for more details.
Note: Using CDATA does.
Numeric character references and entity references are not supported in CDATA sections either. This could lead to a possible loss of data if the document is converted from one encoding to another, or when translating.
Mixing content in CDATA sections and content not in CDATA sections in the same document causes more work when doing some tasks with non-XML-aware tools. For example, when searching for the text "R&D" the user has to search both for
R&D (for the CDATA sections) and
R&D (for the normal content).
Your schema should provide
its:locNote,
its:locNoteType, and
its:locNoteRef (or equivalent mechanisms) to allow you to communicate with those who will localize your content. See Best Practice 8: Defining markup for notes to localizers.
How to do this
Use
its:locNote,
its:locNoteType and
its:locNoteRef (or their equivalents in your schema) to provide notes to the localizer.
This is especially important for content with inserted text where the translator will need context to translate more accurately.
In this document two ITS local attributes are used to annotate an XSLT template:
its:locNoteRef is used to point to an explanation of the acronym RFID.
its:locNote is used to indicate what kind of value the element
<xsl:value-of corresponds to.
Note: When working with XSLT, you need to decide whether the ITS markup should be in the output or not, and may have to use different markup accordingly. In this example, the ITS attributes do not appear in the output.
<?xml version="1.0"?> <xsl:stylesheet <xsl:template <xsl:variable <xsl:variable <html xmlns="" xml: <head> <meta http- <title>Login</title> </head> <body> <p>Login Into Queztal-Systems</p> <form method="POST"> <table border="0" id="table2"> <tr><td>First, place your pass card in front of the reader to scan your <xsl:text its:RFID</xsl:text>. When the light turns green, enter your password in the box below, and click Submit.</td></tr> <tr><td><input type="password" name="pword" size="25"/></td></tr> </table> <p><input type="submit" value="Submit" name="go"/></p> </form> <p>If you have difficulties login in, please call <xsl:value-of, or send an email to <a href="mailto:{$EMail}"><xsl:value-of</a>.</p> </body> </html> </xsl:template> </xsl:stylesheet>
Why do this
There are many reasons to provide information to localizers. You may want to:
Expand on the meaning or contextual usage of a particular element, such as what a variable refers to or how a string will be used in the user interface.
Clarify ambiguity and show relationships between items sufficiently to allow correct translation. For example, in many languages it is impossible to translate the word "enabled" in isolation without knowing the gender, number and case of the thing it refers to.
Explain why text is not translated, point to text reuse, or describe the use of conditional text.
Indicate why a piece of text is emphasized (important, sarcastic, etc.)
Using XML comments for doing this may not be enough as they may get stripped out or ignored during the localization process.
Inserted text refers to any text that is marked by a placeholder in the source XML document and automatically inserted within text content when the document is processed.
Types of inserted text include:
Boilerplate text reused in different contexts.
Various parts of a sentence composed by bringing]).
How to do this
Use inserted text only when the text is self-contained and does not affect its surrounding context. For example, titles and quotations are inserted text that, usually, would not cause problems.
Avoid using inserted text that has any effect or dependence on the context where it is inserted. 21: Providing notes for localizers and Best Practice 23: Identifying terms.
In this example, in the first message, the element
var is used to insert the name of a printer. In the second example, it is used to insert a filename. The
its:locNote attribute is utilized to provide a description of what the variables represent. This may help in deciding how to translate each message.
<strings xmlns: <msg id="pmAdded">The printer <var arg="0" its: has been added to the list.</msg> <msg id="fmAdded">The file <var arg="0" its: has been added to the list.</msg> </strings>
This is a French translation of the document shown above. The context provided allowed to disambiguate the variable and to get a more accurate translation.
<strings xmlns: <msg id="pmAdded">L'imprimante <var arg="0" its: a été ajoutée à la liste.</msg> <msg id="fmAdded"><var arg="0" its: a été ajouté à la liste.</msg> </strings>
Why do lift'.
<p>Using a <term conref="termbase.xml#t123"/>, raise the vehicle from the ground.</p>
At a first glance the example above seems to work fine in English. However, such a construction has several problems:
You should not separate the article from the noun. If "hydraulic lift" is independently replaced in the future by some other term, you may need to change the article to 'an' or remove."
What constitutes a term depends on many factors specific to each organization and project. Terms may include for example names of features, programs, services, and so forth. They also may include words or expressions that are specific to the domain to which the content pertains, such as technical terms, or legal terms, and they may include terms that simply occur often and should be translated consistently.
How to do this
Use
its:term and
its:termInfoRef (or their equivalent in your schema) to mark terms and supply term-related information.
Your schema should provide
its:term and
its:termInfoRef (or equivalent mechanisms). See Best Practice 11: Defining markup for specifying or overriding terminology-related information.
You should also override default terminology rules as needed.
In this document, terms are normally denoted with a
term element. Following Best Practice 10: Identifying terminology-related elements, the developer of the schema has provided an ITS Rules document that defines such property for
term.
However, in this specific document, the author wants to indicate the following:
The content of any
ui element should be seen as a term.
The text
Vector Files in the title is a term.
In the first case, the author uses a
its:termRule element in the header of the document to indicate that any
ui element in this document is a term. This is more efficient than adding an attribute for each instance of
ui in the body of the document.
In the second case, because the schema does not allow the element
term to be used in
title (an oversight of the developer), the author uses a simple
span element with
its:term and
its:termInfoRef to associate
Vector Files with its corresponding term information.
<myManual xmlns: <head> <its:rules> <its:termRule </its:rules> <title>Generating <span its:Vector Files</span></title> </head> <body> <par>Select the command <ui>Build Output Files</ui> from the <ui>Tasks</ui> menu to generate the final <term ref="vFile">vector files</term>.</par> </body> <extra> <terms> <termDef xml:A <emph>vector file</emph> is a binary document that contains the complete set of vectors needed to draw the background layer of a map.</termDef> </terms> </extra> </myManual>
This ITS Rules document is the one created by the developer of the
myManual document type (in implementing Best Practice 10: Identifying terminology-related elements). It provides one
termRule element indicating that any
term element is a term and its associated information is located in the element that is identified with the value stored in the
ref attribute of
term.
<its:rules xmlns: <its:termRule </its:rules>
Why do this
If you do not indicate what words are terms of interest in the content, the translators will not know that these terms need to be translated consistently. Often, multiple translators are working on different files in a given project, and the way they choose to translate specific words can be inconsistent with the way that other translators have translated them. If important terms are marked in the content, they can extract these terms from the content before the content is translated, and pre-translate them in the form of a shared electronic dictionary. This ensures consistency of translation of important terms.
While markup denoting terms for a given schema level should be specified in a set of ITS rules provided with the schema (See Best Practice 10: Identifying terminology-related elements), there are cases where these general rules need to be overridden or complemented for specific elements, in specific documents. It is up to the author of the content to provide such overriding markup.
How to do this
If possible, use the XML namespace mechanism to store different vocabularies inside a single XML document.
In this document, the elements
top and
body both contain HTML markup coded as text. There is no easy way to make the distinction between the HTML markup and the HTML text content.
<pages> <row> <key>ENConvClasses</key> <top><span class="h1">Elibur Library</span> - Conversation Groups</top> <body><![CDATA[<p>These small discussion groups meet <b>weekly</b> and are for people learning English. Each group is led by a volunteer who is a native speaker of American English. Groups converse about books, articles, and other materials.</p> <p>Space is limited. Ask for availability to <a href="mailto:enconv@elibur-lib.com"> enconv@elibur-lib.com</a>.</p>]]></body> </row> </pages>
Instead, use the XML namespace mechanism. Here the content of
top and
body is now a mix of text and XHTML elements. This avoid any confusion between text and HTML tags.
<pages xmlns: <row> <key>ENConvClasses</key> <top><h:spanElibur Library</h:span> - Conversation Groups</top> <body><h:p>These small discussion groups meet <h:b>weekly</h:b> and are for people learning English. Each group is led by a volunteer who is a native speaker of American English. Groups converse about books, articles, and other materials.</h:p> <h:p>Space is limited. Ask for availability to <h:aenconv@elibur-lib.com</h:a>.</h:p></body> </row> </pages>
Another alternative to using markup as text is to store it externally and include it into the document using a mechanism such as XInclude or XLink.
If you must include markup as text content:
Make sure to document the type of content, for example with an attribute set to the appropriate MIME-type. This may help tools to use a more appropriate parser to process the given content.
Aim at having the content well-formed. This will allow parsers to process it more easily.
Why do not a problem. The issue is only for large volume of XML/HTML data contained in another XML document.
Storing such XML data inside XML elements as text content (i.e. with its markup tags escaped), has several drawbacks:
Any handling of such content is made difficult by the impossibility to separate text from markup without extra processing.
Often, such content is put in CDATA sections, which has its own set of issues. See Best Practice 20: Avoiding CDATA sections.
The escaped markup cannot be validated.
If there is a process turning markup into escaping, there is the danger of double escaping.
This section provides a set of generic techniques that are applicable to various guidelines; for example, how to add ITS attributes to different types of schemas, or how to optimize XPath expressions for the ITS
selector attribute.
Whether they are external or embedded, there are a few things you should take into consideration when writing ITS rules.
Try to keep the number of nodes to be overridden to a minimum. This improves performance. For example, if most of a document should not be translated, it is better to set the root element to be non-translatable than to set all elements. The inheritance mechanism will have the same effect for a much lower computing cost.
Because a rule has precedence over the ones before, you should start with the most general rules first and progressively override them as needed. Some rules may be more complex if they need to take into account all the aspects of inheritance.
ITS 1.0 defines the precedence of ITS information for data categories. The precedence order for selection is as follows (starting with the highest precedence) and will be explained using the ITS Translate data category:
ITS local attributes on a specific element, for example the
its:translate attribute, have the highest precedence.
Next are global rules, for example a set of
its:translateRule elements for the ITS Translate data category. Individual rules in an
its:rules element have an inherent precedence which depends on their position in the
its:rules element: the rules at the bottom have a higher precedence than rules at the top. In addition, the rules inside a given
its:rules element have a higher precedence than the rules linked via an
xlink:href attribute in that same
its:rules element.
Inherited ITS information constitutes the third level of precedence. The kind of inheritance is data category specific. For example, if an element has been labelled as "do not translate" using one of the means described via 1) or 2) above, this information is inherited by its child elements, but not by attributes.
ITS information which originates in data category specific defaults is the one with the lowest precedence. For example, the default for the ITS Translate data category is that element content is to be translated and attribute values are not to be translated.
The following example shows the usage of local and global ITS markup and how the precedence described above comes into play.
In this document, all child elements within the
<text> element are set as to 'do not translate' by the first
its:translateRule element. However, the second and last
its:translateRule element has higher precedence than the one before, so it can be used to describe an exception: all
<p> elements are still to be translated. This shows the interplay between different rules and demonstrates that the last one always "wins".
Another exception to the first
its:translateRule element is expressed with the local
its:translate attribute on the
<notes> element. It specifies that the content of this element should be translated. Without the
its:translate attribute, the information from the first
its:translateRule element would be inherited, and this
<notes> element would not be translatable.
Finally, the content of the
<documentation> element within the
<head> element is also translatable, but not the content of any attributes in the document. This demonstrates the role of defaults for the ITS>
When writing rules for documents that use XML namespaces you must make sure that you declare the namespaces,>
ITS uses XPath expressions in several contexts to identify nodes. The most prominent contexts are selectors, and pointer attributes like those shown in the following rules:
<its:translateRule
or
<its:locNoteRule
When writing ITS-related XPath expressions like the ones above, the following should be considered:
ITS XPath expressions pertain to XPath 1.0 or its successor
The values of ITS selector attributes are XPath absolute location paths
The values of ITS pointer attributes are XPath relative location paths. The ITS pointer attributes are:
locNotePointer,
locNoteRefPointer,
its:termInfoPointer,
its:termInfoRefPointer,
its:rubyPointer,
its:rtPointer,
its:rpPointer,
its:rbcPointer,
its:rtcPointer,
its:rbspanPointer, and
its:langPointer.
In environments where XSLT is used to process ITS-related XPath expressions, it is important to know about the subset of XPath which is termed 'XSLT best practices related to writing XPath expressions (see for example the XPath tutorial).
This example shows how to add an attribute (here
xml:lang) to an existing document type. We will add the attribute to an element called
para.
Note that this example only shows a few ways of adding attributes. There are many others, depending on the schema language and the modularization techniques used in the existing schema.
xml:langin XML Schema
To include the
xml:lang attribute in your XML Schema document, import the W3C xml.xsd schema into your own schema using the
xs:import element.
<xs:schema xmlns: <!-- Import for xml:lang and xml:space --> <xs:import ...
Once the xml.xsd schema is imported, you can use the reference to
xml:lang in any of your element declarations.
xml:langin RELAX NG
Declare
xml:lang directly in your schema. There is no existing declaration of, or standardized schema fragment defining, the
xml:lang attribute in RELAX NG. You have to declare
xml:lang directly in your schema and specify the choice of values to be either the XML Schema
language datatype or an empty value., for XHTML it promotes and its values should be applied to.
The following XML vocabularies are discussed:
Section 5.1: ITS and XHTML 1.0
Section 5.3: ITS and XML Spec
Section 5.4: ITS and DITA
Section 5.5: ITS and GladeXML
Section 5.6: ITS and DocBook
XHTML [XHTML 1.0] is a reformulation of the three HTML 4 document types as applications of XML 1.0. HTML is an SGML (Standard Generalized Markup Language) application, widely regarded as the standard publishing language of the World Wide Web.
In XHTML 1.0, the XHTML namespace may be used with other XML namespaces as per Namespaces in XML [XML Names], but such documents are no longer strictly conformant XHTML 1.0.
Here is an example of a document containing ITS rules which is a non-conformant XHTML 1.0 document.
<html xmlns="" xmlns: <head> <meta http- <meta name="keywords" content="ITS example, XHTML translation" /> <its:rules <its:translateRule <its:termRule </its:rules> <title>ITS Working Group</title> </head> <body> <h1>Test of ITS on <span class="term">XHTML</span></h1> <p>Some text to translate.</p> <p its:Some text not to translate.</p> </body> </html>
There are three ways to use ITS with XHTML and keep the XHTML document conformant:
Use XHTML Modularization [XHTMLMod1.1]. See Section 5.1.2: Using XHTML Modularization 1.1 for the Definition of ITS for details.
Use external ITS global rules, as shown in the following example. Even local information within the document that would be handled by ITS attributes can be set indirectly.
These rules illustrate some of the ITS data categories you can <its:translateRule <its:translateRule <its:termRule </its:rules>
The corresponding document:
> XML Schema format..10 2008/02/12 04:55:09>
This schema conforms to Conformance Type 1 of the ITS specification.
The schema adds the following ITS element to the existing schemas. An NVDL schema can be used in the same way as schemas written in other languages, such as DTDs, RELAX NG or XML Schema. You can then use such a schema to validate your document instances or so that an XML editor can guide you while you are editing documents. The NVDL.org site provides additional information about the language. You can also find there a list of applications which support the NVDL language.
Adding ITS to XHTML involves allowing the
its:rules element
inside the
head element and allowing the ITS local
attributes to appear on every existing XHTML element.
<?xml version="1.0" encoding="UTF-8"?> <rules xmlns="" startMode="xhtml"> <!-- Validation starts here --> <mode name="xhtml"> <!-- XHTML elements are validated against XHTML schema --> <namespace ns=""> <validate schema="../xhtml-schemas/xhtml11.xsd"> <!-- Inside head element its:rules element is allowed --> <context path="head" useMode="its-rules"/> </validate> </namespace> <!-- ITS attributes are validated against separate schema --> <namespace ns="" match="attributes"> <validate schema="its-attributes-for-xhtml.rng"/> </namespace> </mode> <!-- Handling of ITS markup in head is different because its:rules should be allowed --> <mode name="its-rules"> <namespace ns=""> <validate schema="its-rules.rng"/> </namespace> <namespace ns="" match="attributes"> <validate schema="its-attributes-for-xhtml.rng"/> </namespace> </mode> </rules>
The NVDL script references three schemas. One for XHTML and two supplementary ones for ITS. The first supplementary schema defines local attributes which are needed for XHTML.
<?xml version="1.0" encoding="UTF-8"?> <grammar xmlns=""> <!-- Include schema with all ITS building blocks --> <include href="its.rng"/> <!-- Pull out only definitions of ITS attributes which are useful for XHTML --> <start> <group> <ref name="its-att.translate.attributes"/> <ref name="its-att.locNote.attributes"/> <ref name="its-att.term.attributes"/> <optional> <ref name="its-att.version.attributes"/> </optional> </group> </start> </grammar>
The second supplementary schema defines the
its:rules element.
<?xml version="1.0" encoding="UTF-8"?> <grammar xmlns=""> <!-- Include schema with all ITS building blocks --> <include href="its.rng"/> <!-- Pull out only definition of its:rules element --> <start> <ref name="its-rules"/> </start> </grammar>
This schema conforms to Conformance Type 1 of the ITS specification.
The schema adds the following ITS element to the XHTML schema:
The schema adds the following local ITS attributes to the XHTML schema:
A number of XHTML constructs implement the same semantics as some of the ITS data categories. In addition, some of the attributes in XHTML need to be translated, which is not the default for XML documents according to the default translate settings in ITS. These attributes need to be identified as needing translation.
An external ITS rules element can summarize these relationships.:
The
script and
style elements may contain text that needs translation, but their content needs to be parsed with, respectively, a script filter and a CSS filter. Depending on the capabilities of your translation tools you may want to leave these elements as needing translation.
The
value attribute of the
input element may or may not need translation, depending on the way the element is used. The decision as to whether the value of this attribute needs translation or not will depend on its use in a given instance. Note, however, that it can often be undesirable to translate these values, since they are commonly used by scripts as identifiers: change the value of the attribute and the script will often fail. The values of the
value attribute are not usually seen by a user of a web page.
The
del element indicates removed text and therefore, most often, its content would not be translated. Because ITS rules for elements are not inherited by attributes, and because this element may contain elements with attributes that need translation, such as
img with an
alt attribute, you need to: a) define this rule after defining how translation applies to attribute values, and b) use rules such as
selector="//h:del/descendant-or-self::*/@*" to override any possibility of translation being applied to an attribute within a
del element or any of its descendants.
The
dt element is defined by HTML as a "definition term" and can therefore be seen as a candidate to be associated with the ITS Terminology data category. However, for historical reasons, this element has been used for many other purposes. Whether or not
dt is associated with the ITS term data category will depend on its use in a given instance.
The Text Encoding Initiative [TEI] is intended for literary and linguistic material, and is most often used for digital editions of existing printed material. It is also suitable, however, for general purpose writing. The P5 release of TEI consists of 23 modules which can be combined together as needed.
TEI is maintained as a single ODD document, and customizations of it are also written as ODD documents. ODD (One Document Does it all) is a literate programming language of the Text Encoding Initiative for writing XML schemas. These documents are processed using XSLT style .
This schema conforms to Conformance Type 1 text below takes version 2.10 of XML Spec as an example and shows how you would integrate ITS into it. This version is available in DTD, XML Schema and RELAX NG formats.
Note: Within the W3C Internationalization Activity, a modified version of the XML Spec 2.9 DTD is used for document creation. This version has been updated with ITS markup declarations.
The integration of ITS into the XML Spec DTD uses the files xmlspec-its.dtd (the XML Spec schema) and its.dtd (the ITS schema). To achieve the integration, the following modifications to the XML Spec DTD have been made:
External ITS definitions are integrated via the new entity
<!ENTITY % its SYSTEM "its.dtd"> and the entity call
%its;.
The existing XML Spec entity
%local.common.att; has been modified. It now includes the declarations
'%its.att.local.with-ns.attributes; and
xmlns:its CDATA "". The former allows the use of ITS local attributes, the latter is necessary to permit the use of the ITS namespace in the DTD.
The XML Spec entity
%header.mdl; contains the content model of the
header element. The ITS
its:rules element has been added as the last element to this content model. In this way,
its:rules can be used inside an XML Spec document.
The ITS elements
its:ruby and
its:span have been added to the XML Spec entity
%p.pcd.mix;. In this way it is possible to use them as inline elements.
The integration of ITS into the XML Spec RELAX NG schema uses the files xmlspec-its.rnc (the XML Spec schema) and its.rnc (the ITS schema). The modifications to the RELAX NG schema have the same motivations like for the DTD described above. The:
External ITS definitions are integrated via an
<xs:import> statement.
The attribute group
its-att.local.with-ns.attributes is added to the attribute group
common.att.
The element declaration
its:rules is added to the element group
header.mdl.
The element declarations
its:ruby and
its:span are added to the element group
p.pcd.mix.
The following example shows an XML Spec document conforming to the XML Spec+ITS schemas. The its:translateRule element is used to indicate that elements for code, keywords and examples should not be translated. The
w3c-doctype element is also marked as non-translatable using local ITS markup.
< conform to Conformance Type 1 of the ITS specification.
The following ITS elements are added:
The following local ITS attributes are added:
A number of XML Spec constructs implement the same semantics as some of the ITS data categories. In addition, some of the XML Spec attribute values need to be translated, which is not the default for XML documents according to the ITS default settings for translatability. These attributes need to be identified as needing translation, and some elements need to be identified as not needing translation.
Note: When you have the choice of using an XML Spec construct or an ITS construct to express the same semantics, make sure you use the XML Spec construct to ensure that XML Spec processing tools work properly. Use ITS local markup only if XML Spec does not provide an equivalent.
An external ITS
its:rules element can
summarize these relationships. The rules defined here are just examples and may need further
tailoring for specific use.
<its:rules xmlns: <!-- Translatable attributes --> <its:translateRule <!-- Non-translatable elements/attributes --> <its:translateRule <!-- Possible terms --> <its:termRule <!-- Elements within text --> <its:withinTextRule <its:withinTextRule </its:rules>"?> <!-- declaration for the specialized wrapper and alternate element --> <!ENTITY % its "its"> <!-- definition for the specialized wrapper and alternate element --> <!ELEMENT its ((%its-rules;) | (%its-ruby;)) > <!ATTLIST its %global-atts; class CDATA "+ topic/foreign its-d/its ">
Then you can adapt the
concept.dtd file to take into account the new domain.
Include the ITS domain entities at the end of the Domain Entity Declarations section:
<!ENTITY % its-d-dec SYSTEM "itsDomain.ent" > %its-d-dec;
Include the ITS document type and namespace:
<!ENTITY % its-def SYSTEM "its.dtd" > %its-def; <!ENTITY % its-d-namespace "xmlns:its CDATA #FIXED ''"> <!ENTITY % props-attribute-extensions "" > <!ENTITY % base-attribute-extensions "%its-d-namespace; %att.version.attributes; %att.locNote.attributes;" >
Define the extension element at the end of the Domain Extension section:
<!ENTITY % foreign "foreign | %its-d-foreign;" >
Modify the list of included domains in the included-domains entity:
<!ENTITY included-domains "&ui-d-att; &hi-d-att; &pr-d-att; &sw-d-att; &ut-d-att; &indexing-d-att; &its-d-att;" >
Include the ITS domain module at the end of the Domain Element Integration section:
<!ENTITY % its-d-def SYSTEM "itsDomain.mod" > %its-d-def;
All these changes allow you to include a new
its>
This schema conforms to Conformance Type 1 of the ITS specification.
The schema adds the following ITS element to the DITA DTD:
The schema adds the following local ITS attributes to the DITA DTD:
There are several ITS data categories that are already implemented in DITA. For example, DITA offers a
translate attribute that provides the same functionality as
its:translate.
In the same way as for other formats, these existing features can be associated with ITS data categories, so ITS-enabled tools can process seamlessly DITA source documents.
Note: When you have the choice of using a DITA construct or an ITS construct to express the same thing, use the DITA construct to ensure that DITA processors work properly. Use ITS local markup only if DITA does not provide an equivalent.
<?xml version="1.0"?> <!-- Possible default ITS rules for DITA --> <its:rules xmlns: <!-- Translatable attribute (some are deprecated) --> <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <!-- Non-translatable elements --> <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <its:translateRule <!-- Translatability flags --> <its:translateRule <its:translateRule [Glade] is a user interface builder system for GTK+ and Gnome. It uses XML files (GladeXML) to store the user-interface components. The library has been ported to different platforms and offers bindings in different programming languages.
<?xml version="1.0" standalone="no"?><!--*- mode: xml -*--> ="Open"> <property name="visible">True</property> <property name="label">gtk-open</property> <property name="use_stock">True</property> <signal name="activate" handler="on_Open_activate"/> <XML files are mostly composed of data that should not be translated: user-interface widgets properties. Text content is limited to titles, labels and a few various other types of strings.
GladeXML does offer support for some of the ITS features, but not all of them. While it would be technically feasible to allow the use of additional ITS markup directly in your GladeXML resources, there is little point doing it here because these resources are closely tied to the Glade's editors and compilers which would have to be modified as well.
GladeXML offers a
translatable attribute that provides the same functionality as
its:translate. The
Like for other formats, existing features of GladeXML can be associated with ITS data categories using global rules, so ITS-enabled tools can seamlessly process GladeXML>
DocBook is a general purpose XML schema particularly well suited to books and papers about computer hardware and software (though it is by no means limited to these applications). DocBook is maintained by the DocBook Technical Committee of OASIS.
DocBook
its:ruby as inline element almost everywhere where plain text could be.
# This schema integrates ITS markup () # into DocBook schema () # # This schema conforms to Conformance Type 1 defined in # # # Schema adds the following ITS elements into DocBook schema: # * rules # * ruby # # Schema adds the following local ITS attributes into DocBook schema: # * translate # * locNote # * locNoteType # * locNoteRef # * term # * termInfoRef # Namespace declarations for DocBook, ITS and HTML # (HTML is used internally in DocBook schema) namespace db = "" namespace its = "" namespace html = "" # Include base DocBook schema include "docbook.rnc" { # Exclude ITS markup from "wildcard" element db._any = element * - (db:* | html:* | its:*) { (attribute * { text } | text | db._any)* } } # Include base ITS schema include "its.rnc" # Define pattern for local ITS attributes db.its.attributes = its-att.translate.attributes? & its-att.locNote.attributes? & its-att.term.attributes? & its-att.version.attributes? # Add local ITS attributes to all DocBook elements db.common.base.attributes &= db.its.attributes # Allow its:rules inside info element db.info.extension |= its-rules # Allow Ruby markup almost everywhere db.ubiq.inlines |= its-ruby
For your convenience there is also available a “flattened” schema stored inside one file.
dbits.rnc (RELAX NG compact syntax schema in one file)
dbits.rng (RELAX NG schema in one file) the
function element) should not be
translated. The first paragraph is also marked as not to be translated
using local ITS markup.
<?xml version="1.0" encoding="UTF-8"?> <article xmlns="" xmlns: <info> <title>Sample article</title> <its:rules <its:translateRule </its:rules> </info> <para its:Non-translatable content</para> <section> <title>Sample section</title> <para>You can delete file using <function>unlink()</function> function.</para> </section> </article>
This schema conforms to Conformance Type 1, which is not the default for XML documents according to the ITS default settings. These attributes need to be identified as needing translation. which may need further
tailoring for specific use.
<its:rules xmlns: <!-- Translatable attributes --> <its:translateRule <its:translateRule <its:translateRule <its:translateRule <!-- Non-translatable elements/attributes --> <its:translateRule <its:translateRule <its:translateRule <!-- Possible terms --> <its:termRule <its:termRule <its:termRule <its:termRule <!-- Bidirectional information --> <its:dirRule <its:dirRule <its:dirRule <its:dirRule <!-- Elements within text --> <its:withinTextRule <its:withinTextRule </its:rules>
This document has been developed with important contributions from past and present member of the Working Group: Bartosz Bogacki (W3C Invited Expert), Martin Dürst (W3C Invited Expert), Tim Foster, Richard Ishida (W3C/ERCIM), Masaki Itagaki, Jirka Kosek (W3C Invited Expert), Christian Lieske (SAP AG), Sebastian Rahtz (W3C Invited Expert), Felix Sasaki (W3C/Keio), Yves Savourel (ENLASO Corporation), Diane Stoick (The Boeing Company), Najib Tounsi (Ecole Mohammadia d'Ingenieurs Rabat (EMI)), and)).
|
https://www.w3.org/TR/xml-i18n-bp/
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
Created on 2004-02-15 21:33 by tlynn, last changed 2004-03-02 04:49 by brett.cannon. This issue is now closed.
On Win2k:
Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> import time
>>> time.strftime("%a",(1900,1,1, 13,0,0, -3,0,-1))
Python dumps core. Is that (ever) expected behaviour?
Logged In: YES
user_id=80475
It is expected. Well, now that I've confirmed it on Py2.3.3
and Py2.4, yes ;-)
Is it desirable? Heck no.
Brett, can you take a look at this?
Logged In: YES
user_id=31435
I assume this is specific to Python on Windows using
Microsoft's C, since this workalike plain C program also dies
with a memory error while in the bowels of MS's strftime():
#include <stdio.h>
#include <time.h>
void main() {
struct tm t;
char buf[256];
size_t i;
t.tm_year = 1900 - 1900;
t.tm_mon = 1 - 1;
t.tm_mday = 1;
t.tm_hour = 13;
t.tm_min = 0;
t.tm_sec = 0;
t.tm_wday = -3;
t.tm_yday = 0;
t.tm_isdst = -1;
printf("calling strftime\n");
i = strftime(buf, sizeof(buf), "%a", &t);
printf("i: %d\n", i);
}
The problem is the negative value for tm_wday. MS strftime
isn't defensive, and uses the negative tm_wday to index into
nonsense memory. Ironically, if C had defined the % operator
in the sane way (meaning Python's way <wink>), a negative
tm_wday wouldn't have survived for the C library function to
see.
Logged In: YES
user_id=304464
Also, please have a look at:
at the same time.
Logged In: YES
user_id=304464
On my linux system does:
>>> import time
>>> time.strftime("%a",(1900,1,1, 13,0,0, -3,0,-1))
'\x0e'
Python 2.3.3c1 (#2, Dec 6 2003, 16:44:56)
[GCC 3.3.3 20031203 (prerelease) (Debian)] on linux2
Logged In: YES
user_id=304464
On WinXP Home does:
>>> import time
>>> time.strftime("%a",(1900,1,1, 13,0,0, -3,0,-1))
'\xfcI\xc1w\xf8I\xc1w\xf4I\xc1w\xf0I\xc1w\xecI\xc1w\xe8I\xc1w\xe4I\xc1w\xdcI\xc1w\xd4I\xc1w\xccI\xc1w\xc0I\xc1w\xb4I\xc1w\xacI\xc1w\xa0I\xc1w\x9cI\xc1w\x98I\xc1w\x94I\xc1w\x90I\xc1w\x8cI\xc1w\x88I\xc1w\x84I\xc1w\x80I\xc1w|I\xc1wxI\xc1wtI\xc1wpI\xc1whI\xc1w\\I\xc1wTI\xc1wLI\xc1w\x8cI\xc1wDI\xc1w<I\xc1w4I\xc1w(I\xc1wI\xc1w\x14I\xc1w\x08I\xc1w\x04I\xc1w'
ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on
Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit
(Intel)] on win32
Logged In: YES
user_id=357491
Should be able to deal with this cleanly by modifying gettmarg() to do
some sanity checks on the values before returning and letting
time_strftime() at the struct tm that gettmarg() created.
First have to check the ISO C standard, though, to make sure I don't
overstep my bounds on the sanity checks (or I could just follow our own
specs, but that would be too easy =).
Logged In: YES
user_id=357491
OK, have a solution coded up, just waiting to hear from Tim on whether a
change to datetime is okay with him.
Logged In: YES
user_id=263764
Not sure if it's helpful, but here's another data point. I
get the buggy behaviour on 2.3.3 on Gentoo Linux:
ratchet% python
Python 2.3.3 (#1, Jan 6 2004, 09:44:50)
[GCC 3.3.2 20031022 (Gentoo Linux 3.3.2-r2, propolice)] on
linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> import time
>>> time.strftime("%a",(1900,1,1, 13,0,0, -3,0,-1))
Segmentation fault
Logged In: YES
user_id=357491
OK, fixed in Python 2.4 with rev. #2.140 for Modules/timemodule.c
(along with changes to Doc/lib/libtime.tex as rev. 1.63,
datetimemodule.c as rev. 1.70, Lib/test/test_time.py as rev. 1.16, and
Lib/test/test_strftime.py as rev. 1.28).
This will break some code that does not use 1 or higher for fields in the
time tuple that are supposed to be set to that (month, day, and day of
year), but it was felt it was better to do a complete check on all values
then on only certain values so as to make it consistent.
Since it breaks code it will not be backported.
And yes, ashtong, more data points are always helpful.
|
http://bugs.python.org/issue897625
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
Le samedi 7 mai 2011 05:24:56 Eric W. Biederman, vous avez écrit :> Pieces of this puzzle can also be solved by instead of> coming up with a general purpose system call coming up> with targed system calls perhaps socketat that solve> a subset of the larger problem. Overall that appears> to be more work for less reward.socketat() is still required for multithreaded namespace-aware userspace, I believe.-- Rémi Denis-Courmont unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
http://lkml.org/lkml/2011/5/7/48
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
How to Display Something on Screen with the C Programming puts() Function
When you’re programming in C, you may want your computer to display something on the screen. The puts() function sends a stream of text to the standard output device.
What the heck does that mean?
For now, consider that the puts() function displays text on the screen on a line by itself. Here’s the format:
#include <stdio.h> int puts(const char *s);
Because that official format looks confusing, you can also use this unofficial format:
puts("text");
The text part is a string of text — basically, anything sandwiched between the double quotes. It can also be a variable.
The puts() function requires that the source code include the stdio.h header file. That header file contains the function’s prototype. Header files are added to the source code by the use of the #include directive, as just shown.
The C language handles text in streams, which is probably different from the way you think computers normally handle text.
The standard output device is usually the computer’s display. Output can be redirected at the operating system level; for example, to a file or another device, such as a printer. That’s why the technical definition of the puts() function refers to standard output and not to the display.
|
http://www.dummies.com/how-to/content/how-to-display-something-on-screen-with-the-c-prog.html
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
java.lang.Object
org.apache.myfaces.dateformat.SimpleDateFormatterorg.apache.myfaces.dateformat.SimpleDateFormatter
public class SimpleDateFormatter
A reimplementation of the java.text.SimpleDateFormat class.
This class has been created for use with the tomahawk InputCalendar component. It exists for the following reasons:
This implementation does extend the SimpleDateFormat class by adding the JODA "xxxx" yearOfWeekYear format option, as this is missing in the standard SimpleDateFormat class.
The parse methods also return null on error rather than throw an exception.
The code here was originally written in javascript (date.js), and has been ported to java.
At the current time, the following format options are NOT supported:
DFkKSzZ.
ISO standard ISO-8601 defines a calendaring system based not upon year/month/day_in_month but instead year/week/day_in_week. This is particularly popular in embedded systems as date arithmetic is much simpler; there are no irregular month lengths to handle.
The only tricky part is mapping to and from year/month/day formats. Unfortunately, while java.text.SimpleDateFormat does support a "ww" week format character, it has a number of flaws.
Weeks are always complete and discrete, ie week yyyy-ww always has 7 days in it, and never "shares" days with yyyy-(ww+1). However to achieve this, the last week of a year might include a few days of the next year, or the last few days of a year might be counted as part of the first week of the following year. The decision is made depending on which year the "majority" of days in that week belong to.
With ISO-8601, a week always starts on a monday. However many countries use a different convention, starting weeks on saturday, sunday or monday. This class supports setting the firstDayOfWeek.
public SimpleDateFormatter(String pattern, DateFormatSymbols symbols, int firstDayOfWeek)
firstDayOfWeek- uses java.util.Date convention, ie 0=sun, 1=mon, 6=sat.
public SimpleDateFormatter(String pattern, DateFormatSymbols symbols)
public static WeekDate getIsoWeekDate(Date date)
public static WeekDate getWeekDate(Date date, int firstDayOfWeek)
This is exactly like getIsoWeekNumber, except that a firstDayOfWeek can be specified; ISO-8601 hard-wires "monday" as first day of week.
TODO: support minimumDaysInWeek property. Currently, assumes this is set to 4 (the ISO standard).
firstDayOfWeek- is: 0=sunday, 1=monday, 6=sat. This is the convention used by java.util.Date. NOTE: java.util.Calendar uses 1=sunday, 2=monday, 7=saturday.
public void setFirstDayOfWeek(int dow)
public Date parse(String dateStr)
public String format(Date date)
public WeekDate getWeekDate(Date date)
public Date getDateForWeekDate(WeekDate wdate)
|
http://myfaces.apache.org/tomahawk-project/tomahawk/apidocs/org/apache/myfaces/dateformat/SimpleDateFormatter.html
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
class Link { public int iData; public Link next; // Constructor public Link ( int item ) { iData = item; next = null; } // Print contents public String toString () { String str = "( " + iData + " ) "; return str; } } class CircularList { private Link head; // Constructor public CircularList () { head = null; } // Insert an element in the list public void insert ( int item ) { //new temp object made every time called Link temp = head; Link newLink = new Link(item); if( head != null) { while(temp.next != head) { temp = temp.next; newLink.next = head; temp.next = newLink; head = newLink; } } if ( head == null) { head = newLink; newLink.next = head; } } // Find the link with the given key NOT FINISHED public Link find ( int key ) { Link current = head; while ( current.iData != key ) { if ( current.next == null ) return null; else current = current.next; } return current; } // Delete a link with a given key public Link delete ( int key ) { Link current = head; Link previous = head; Link tail = current; while ( current.iData != key) { if ( current.next == null) return null; else { previous = current; current = current.next; } } if ( current == head ) head = head.next; else previous.next = current.next; if ( current != null) { if (current.next == current) { current = null; return current; } if (current.next != current) { while(tail.next != current) { tail = tail.next; } current = current.next; tail.next = current; } } return current; } // Delete the nth link starting from the Link start // Return the next link from the deleted Link public Link deleteAfter ( Link start, int n ) { } // Return a string representation of a Circular List public String toString () { StringBuffer buf = new StringBuffer(); int count = 0; Link current = head; while ( current != null ) { if ( count == 4 ) { buf.append ( current.toString() + "\n" ); count = 0; } else { buf.append ( current.toString() + " " ); count++; } current = current.next; } return buf.toString(); } } public class Josephus { // program will read in the number of soldiers, the elimination number n, and the soldier from whom the counting starts. //havent done this yet }
[b]I am not sure if my logic is correct for a circular link list in my delete, insert, find and toString method. I am also slightly confused as to what should be done in delete after?! should i just call the delete method? delete the key and print the new link?
|
http://www.dreamincode.net/forums/topic/48674-josephus-problem-with-circular-link-lists/
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
VertexShader - Parameter / Matrix Issues.lars Aug 23, 2011 5:34 AM
I'm trying to implement a simple mask-shader for my 2D engine and I'm having multiple issues getting it to work.
Basically the shader takes two images and two matrices and tries to map back the vertex position of the sprites vertex back to the local mask space position and then calculate the local uv-coordinates for the mask, but I'm stuck with some basic calculations here.
Bug 1: Divisions in the material-vertex kernel don't work at all. That's why I have to put invertedMaskSize (which is 1.0 / 128.0) into the shader (but we already know that )
Bug 2: interpolated vars have to be float4, float2 is not possible (That's a pretty old bug as well)
I tried the following changes in the shader. The shader posted here, just tries to display the resulting uv-coordinates. No textures are used.
Case 1:
interpolatedMaskUV = float4((vertexPos.x + halfMaskSize.x) * invertedMaskSize.x, (vertexPoss.y + halfMaskSize.y) * invertedMaskSize.y, 0.0, 0.0);
The output is this: Just like you expect! Perfect, let's proceed.
Case 2:
Change the halfMaskSize and invertedMaskSize to float2 and set set the parameters as two vectors of length two of course in AS. The output:
Case 3:
Masking Test, matrix multiplication. First calculating the world space position of the vertex:
float4 worldSpacePos = float4(vertexPos.x, vertexPos.y, 0.0, 1.0) * objectToClipSpaceTransform;
Then mapping it back to the local space of the mask:
float4 localMaskSpacePos = worldSpacePos * maskObjectToClipSpaceTransform;
And calculating the uv-coords:
interpolatedMaskUV = float4((localMaskSpacePos.x + halfMaskSize.x) * invertedMaskSize.x, (localMaskSpacePos.y + halfMaskSize.y) * invertedMaskSize.y, 0.0, 0.0);
For testing, I set the maskObjectToClipSpaceTransform to the inverse of the objectToClipSpaceTransform. In theory and on paper, this should work.
But, I think, something gets out of order and maybe the maskObjectToClipSpaceTransform is screwed up in the shader, just like when I set the halfMaskSize and invertedMaskSize to float2. The result is this: and I have no idea how to fix this...
<languageVersion : 1.0;>
material kernel texture
<
namespace : "ND2D_Shader";
vendor : "nulldesign";
version : 1;
>
{
input vertex float2 uvCoord
<
id : "PB3D_UV";
>;
input vertex float2 vertexPos
<
id : "PB3D_POSITION";
>;
parameter float2 uvOffset;
parameter float4x4 objectToClipSpaceTransform;
parameter float4x4 maskObjectToClipSpaceTransform;
// if set to float2, strange things happen
parameter float4 halfMaskSize;
parameter float4 invertedMaskSize;
interpolated float4 interpolatedUV;
interpolated float4 interpolatedMaskUV;
void evaluateVertex()
{
// not used in the current test ...
interpolatedUV = float4(uvCoord.x + uvOffset.x, uvCoord.y + uvOffset.y, 0.0, 0.0);
float4 worldSpacePos = float4(vertexPos.x, vertexPos.y, 0.0, 1.0) * objectToClipSpaceTransform;
// doesn't work as expected
float4 localMaskSpacePos = worldSpacePos * maskObjectToClipSpaceTransform;
interpolatedMaskUV = float4((localMaskSpacePos.x + halfMaskSize.x) * invertedMaskSize.x,
(localMaskSpacePos.y + halfMaskSize.y) * invertedMaskSize.y,
0.0, 0.0);
}
input image4 textureImage;
input image4 textureMaskImage;
parameter float4 color;
output float4 result;
void evaluateFragment()
{
// just visualize the uv-coords
result = float4(interpolatedMaskUV.x, interpolatedMaskUV.y, 0.0, 1.0);
/*
float4 texel = sample(textureImage, float2(interpolatedUV.x, interpolatedUV.y), PB3D_2D | PB3D_MIPNEAREST | PB3D_CLAMP);
float4 texel2 = sample(textureMaskImage, float2(interpolatedMaskUV.x, interpolatedMaskUV.y), PB3D_2D | PB3D_MIPNEAREST | PB3D_CLAMP);
result = float4(texel.r * color.r,
texel.g * color.g,
texel.b * color.b,
texel.a * color.a * texel2.a);
*/
}
}
I know that we're working with a four month old version of pb3d and I hope that a new version will be out soon and maybe all these bugs I encountered are already solved, but if not.... here's another shader to fix
1. Re: VertexShader - Parameter / Matrix IssuesAIF Bob Aug 24, 2011 11:09 AM (in response to .lars)1 person found this helpful
First of all, thank you for posting such an informative description of your problem. Having this much detail helps us to track down what's going on. We have fixes for some of the bugs you've encountered, and we're working on the other bugs. We'll make sure this gets added to our test suite.
We're working on a new release which we plan to have out soon (weeks rather than months).
Bob
2. Re: VertexShader - Parameter / Matrix Issues.lars Aug 25, 2011 6:34 AM (in response to AIF Bob)
Thanks Bob for the quick reply. I'm really curious about the next drop
One more thing that came into my mind: I tried to implement geometry batching with pixelbender and had two issues:
1. I can declare something like this in a vertex / fragment shader:
parameter float4x4 objectToClipSpaceTransform[8];
But during runtime, I get this error, even if the array size is very small:
[Fault] exception, information=Error: Register allocator has run out of registers.
2. And as far as I know, there's no way to fill the arrays with the vertexBufferHelper class:
parameterBufferHelper.setMatrixParameterByName(Context3DProgramType.VERTEX, "objectToClipSpaceTransform", clipSpaceMatrix, true);
I had to use setProgramConstantsFromMatrix, which is a bit inconsistent...
Are these issues, that have already been adressed? I'd really like to speed up rendering by doing proper batch rendering..
Cheers,
Lars
3. Re: VertexShader - Parameter / Matrix IssuesAIF Bob Aug 25, 2011 10:42 AM (in response to .lars)
One of the problems we have is that PB3D is built on top of Molehill which has severe hardware restrictions, particularly around the number of registers that are available for use. Once you start using float4x4, particularly in conjunction with arrays you run out of registers almost immediately (there are only 8 temporary registers available - since a float4x4 uses of 4 of them you can see that we're squeezed really tight).
This means we haven't been focussing on array handling, so you're probably stuck with a clunky method of getting values into arrays for the next release.
Bob
4. Re: VertexShader - Parameter / Matrix IssuesAIF Bob Sep 1, 2011 10:25 AM (in response to .lars)
I just discovered one more issue when I was working through your example. If you have a parameter that's used by the vertex kernel, and a parameter that's used by the evaluateVertex function of the material kernel they must have different names, even if they are supposed to be the same value. The particular parameter that gave me trouble is objectToClipSpaceTransform. I'm using it in my standard vertex kernel, but it's also used in your example as an input to the evaluateVertex function.
We haven't yet worked out what the right way to deal with this situation is, for the time being, the work around is to make sure that the parameters have two different names.
Bob
5. Re: VertexShader - Parameter / Matrix Issues.lars Sep 2, 2011 1:52 AM (in response to AIF Bob)
Ah that's interesting. I thought after compiling the three shaders with pixelbender, the two vertex kernels are merged and I can use the same parameters. This would mean, I have to push objectToClipSpaceTransform twice (with a different name)? So I would to waste four registers
Here is the AGAL version of the shader, it's working as expected:
vertex:
m44 vt0, va0, vc0 // vertex * clipspace
m44 vt1, vt0, vc4 // clipsace to local pos in mask
add vt1.xy, vt1.xy, vc8.xy // add half masksize to local pos
div vt1.xy, vt1.xy, vc8.zw // local pos / masksize
mov v0, va1 // copy uv
mov v1, vt1 // copy mask uv
mov op, vt0 // output position
fragment:
mov ft0, v0 // get interpolated uv coords
tex ft1, ft0, fs0 <2d,clamp,linear,nomip> // sample texture
mul ft1, ft1, fc0 // mult with color
mov ft2, v1 // get interpolated uv coords for mask
tex ft3, ft2, fs1 <2d,clamp,linear,nomip> // sample mask
mul ft1, ft1, ft3 // mult mask color with tex color
mov oc, ft1 // output color
The full source code here: skMaterial.as
I'll try it with a different parameter name now. Thanks
6. Re: VertexShader - Parameter / Matrix IssuesAsterLUXman Aug 24, 2013 7:22 PM (in response to .lars)
This may not be the answer to .lars' issue, and may be totally obvious to some, but for readers who, like me, were stuck wondering why offset UVs weren't working when the offset was applied within the evaluateVertex() function of the material kernel ( as opposed to the evaluateVertex() of the vertex kernel ):
You need to pass the UV offset parameter ( aka. constant register ) to the VERTEX shader, NOT to the FRAGMENT shader, even though you are targeting the evaluateVertex() of the material kernel.
In other words, use:
com.adobe.pixelBender3D.utils.ProgramConstantsHelper::setNumberParameterByName( Context3DProgramType.VERTEX, "myUVOffset", Vector.<Number>( [ value1, value2 ] ) );
P.S. My question to Adobe: did we really need to split the vertex shader in two: on portion in the vertex kernel and the other in the material kernel? .. It seems like a really odd choice, making things unnecessarily more complicated.
|
https://forums.adobe.com/thread/894332?tstart=0
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
C to Go
Go!
Thanks to Ivan Krasin, Carlos Cobo, Karl Magdsick, Michael Gehring, and Bob Appleyard for suggestions.
CAUTION
I wrote these notes long ago while I was learning Go, so they are likely outdated.
Nowadays I spend most of my energy on Haskell. Go is a natural intermediate step between C and Haskell.
Go’s (:=) operator does type inference. Haskell’s type inference is so powerful that we can write entire complex programs without a single type declaration (though leaving some in is usually preferred for clarity).
Go has channels and goroutines. Haskell has equivalents, along with other powerful constructs for concurrency such as Software Transactional Memory.
Go has interfaces. Haskell has type classes, which can be viewed as generalized Go interfaces. Type classes easily solve one of Go’s biggest problems: lack of generics.
Go has anonymous functions. Haskell has lambdas, currying, type parameters, and type inference which together yield elegant notation for manipulating functions.
Go has numeric constants. Haskell also has numeric literals, but thanks to type classes, we can use constants with user-defined types rather than a specific subset of built-in types.
Go has garbage collection. Haskell does too, but since data is typically immutable (due to purity), garbage collection can be extremely simple and fast.
import Control.Monad import System.Environment main = getArgs >>= forever . putStrLn . f where f [] = "y" f xs = unwords xs
|
http://crypto.stanford.edu/~blynn/c2go/index.html
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
template< typename Sequence , typename T > struct push_front { typedef unspecified type; };
push_front performs an insertion at the beginning of the sequence with guaranteed O(1) complexity.
#include <boost/mpl/push_front.hpp>
For any Front Extensible Sequence s and arbitrary type x:
typedef push_front<s,x>::type r;
Amortized constant time.
typedef vector_c<int,1,2,3,5,8,13,21> v; BOOST_MPL_ASSERT_RELATION( size<v>::value, ==, 7 ); typedef push_front< v,integral_c<int,1> >::type fibonacci; BOOST_MPL_ASSERT_RELATION( size<fibonacci>::value, ==, 8 ); BOOST_MPL_ASSERT(( equal< fibonacci , vector_c<int,1,1,2,3,5,8,13,21> , equal_to<_,_> > ));
|
http://www.boost.org/doc/libs/1_53_0/libs/mpl/doc/refmanual/push-front.html
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
In this simple tutorial we will see how to implement multiple file upload in a Spring 3 MVC based application.
The requirement is simple. We have a form which displays file input component. User selects a file and upload it. Also its possible to add more file input components using Add button. Once the files are selected and uploaded, the file names are displayed on success page.
1. Maven Dependencies / Required JAR files
If you using Maven in your project for dependency management, you’ll need to add dependencies for Apache Common File upload and Apache Common IO libraries. The spring’s
CommonsMultipartResolver class internal uses these library to handle uploaded content.
Add following dependencies in your maven based project to add File upload feature.
<dependencies> <!-- Spring 3 MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.1.2.RELEASE</version> </dependency> <!-- Apache Commons file upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- Apache Commons IO --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!-- JSTL for c: tag --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
If you have a simple web application, add following JAR files in WEB-INF/lib folder. You can download all these JARs with source code at the end of this tutorial.
2..
FileUploadForm.java
package net.viralpatel.spring3.form; import java.util.List; import org.springframework.web.multipart.MultipartFile; public class FileUploadForm { private List<MultipartFile> files; //Getter and setter methods }
3. Controller – Spring Controller
Create a Spring 3 MVC based controller which handles file upload. There are two methods in this controller:
displayForm– Is a used to show input form to user. It simply forwards to the page file_upload_form.jsp
save– Fetches the form using
@ModelAttributeannotation and get the File content from it. It creates a list of filenames of files being uploaded and pass this list to success page.
FileUploadController.java
package net.viralpatel.spring3.controller; import java.util.ArrayList; import java.util.List; import net.viralpatel.spring3.form.FileUploadForm; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { @RequestMapping(value = "/show", method = RequestMethod.GET) public String displayForm() { return "file_upload_form"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String save( @ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map) { List<MultipartFile> files = uploadForm.getFiles(); List<String> fileNames = new ArrayList<String>(); if(null != files && files.size() > 0) { for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); fileNames.add(fileName); //Handle file content - multipartFile.getInputStream() } } map.addAttribute("files", fileNames); return "file_upload_success"; } }
4. View – JSP views
Now create the view pages for this application. We will need two JSPs, one to display file upload form and another to show result on successful upload.
The file_upload_form.jsp displays a form with file input. Apart from this we have added small jquery snippet onclick of Add button. This will add a new file input component at the end of form. This allows user to upload as many files as they want (subjected to file size limit ofcourse).
Note that we have set enctype=”multipart/form-data” attribute of our <form> tag.
file_upload_form.jsp
<[email protected]</script> <script> $(document).ready(function() { //add more file components if Add is clicked $('#addFile').click(function() { var fileIndex = $('#fileTable tr').children().length - 1; $('#fileTable').append( '<tr><td>'+ ' <input type="file" name="files['+ fileIndex +']" />'+ '</td></tr>'); }); }); </script> </head> <body> <h1>Spring Multiple File Upload example</h1> <form:form <p>Select files to upload. Press Add button to add more file inputs.</p> <input id="addFile" type="button" value="Add File" /> <table id="fileTable"> <tr> <td><input name="files[0]" type="file" /></td> </tr> <tr> <td><input name="files[1]" type="file" /></td> </tr> </table> <br/><input type="submit" value="Upload" /> </form:form> </body> </html>
Note that we defined the file input name as files[0], files[1] etc. This will map the submitted files to the List
I would suggest you to go through this tutorial to understand how Spring maps multiple entries from form to bean: Multiple Row Form Submit using List of Beans
Second view page is to display filename of uploaded file. It simply loops through filename list and display the names.
file_upload_success.jsp
<[email protected] <li>${file}</li> </c:forEach> </ol> </body> </html>
5. Spring Configuration
In Spring configuration (spring-servlet.xml) we define several important configurations. Note how we defined bean multipartResolver. This will make sure Spring handles the file upload correctly using
CommonsMultipartResolver class.
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <context:annotation-config /> <context:component-scan <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipart>
6. Output
Execute the project in Eclipse. Open following URL in browser to see file upload form.
URL:
Select files through file dialog and press Upload button to upload. Following page will displayed with list of files being uploaded.
We have added a small Javascript snippet for Add button. This will add more file upload components to the page. Use this if you want to upload more files.
Download Source Code
SpringMVC_Multi_File_Upload_example.zip (3.6 MB)
Hi Viral! A great tutorial! How do we restrict the file types being uploaded. Use case being i want the user to upload only .pdf file or .xls files.
You can use a validator, first register your validator
Then you apply that validator to uploaded file
I hope this helps
Hi Creg,
In your reply said :
First register your validator, then apply, can you please show us where to register and where to apply, and where to create the validator, do we need a configuration somewhere ?
Thanks
Hello there, nice tutorial. Just one warn, when I run your example after download it from here and I get the following exception stacktrace:
You shoul change the line of code:
for this one:
doing so, it wont duplicate the same last index when select the “Add File” button
Regards!
Very good tutorial, thanks.
this is very good to learn java, keep exist with this site such we can to be java expert hahahahaha., thanks viralpatel.,
Thanks for this example. Its easy to understand, I have downloaded the source code, but i am not able to run the project.
i am getting 404 error. what is missing?.
Spring Multiple File Upload example
Following files are uploaded successfully.
CreateDB.sql
Where is place uploaded files ?
I want to using ajax(not submit form), read the selected file in input file. You can help me…
Hi,
I need to send a similar form but using AJAX. Any solution?
Thanks a lot!
hai all
can you help me now?
For some of my homework (one of many problems)
“how to uploading file xls with asp mvc 3 to database? ”
share with me please, simple sample
programming ASP MVC3
Database SQL SERVER
example databases name_DB = db_school, name_table = tbl_student, Field = – id, name
Thanks for detailed explanation. Before visiting to this page I didn’t knew anything about file upload, Now i can write file upload code easily..
Regards
sid
I was not sure where the files were uploaded…
So,I just got your code a little modified with d help of some other example:
And here is the full running code:
1.Just Create D:\Test\Upload directory structure or whatever.
2.Copy this code to FileUploadController.java
when I copied your updated controller, the file is getting uploaded into the location. But, I’m getting this error. Please clarify.
java.io.IOException: Destination file [C:\Temp\Upload] already exists and could not be deleted
org.springframework.web.multipart.commons.CommonsMultipartFile.transferTo(CommonsMultipartFile.java:130)
I got the solution for the above exception. I just added a condition like this and added the files in the last step. Please see the code below:
Hi Sathya,
How to get a path and path will store mysqldatabase with the help of hibernate.please send me a [email protected]
thankyou soo muucch for ur valuable and timesaving concept :)
Thanks much Sathya :)
This was helpful :)
cool machi…yenga tale viral-kku oru ooooooo podu…
Hi viral could you please rectify this following exception
This really helped me. Struggled lot of time to get this done before seeing this tutorial/topic
Thankyou.
very nice tutorial for beginners.
Really a great tutorial. I am getting file name as null in controller. here is my controller code.
Please help me
Check if you have added
in spring-servlet.xml
Hi,
Thanks for sharing. Nice one .
Hi, dynamically added file type not working. when I click on add file and upload three files then also I get only default two file. Dynamically added file object are not available in controller.
Please help..!!.
I am getting the java.io.IOException: Destination file [C:\TEMP] already exists and could not be deleted.
However the file is getting uploaded and updated.
Please see my code below :
i want to show the image after upload image so can u help me to get that code in .jsp and also controller?
Hi viral, Really this examples helps me a lot, But plz do one help for me, plz develop a applicaiton to select two files from browser ( txt1, txt2) and display it on to the browser and while clicking on save button it will ask the location on harddisk to save the files.
And plz send me these application on to the my id – [email protected]
and if possible then give me ur number also into my id.
Thanking you
==========
Devesh Anand
How many changes are require to convert this to Ajax based file upload?
I have repository class where I want to store the image that is coming from MultipartFile to webapp/resources/images directory before adding the product details to the repository ?
my repository class is ResourceLoaderAware. I am getting fileNotFoundException, “imagesDesert.jpg” is the image I am trying to upload
Hi Viral,
Do you have any idea for sending Email with multiple attachments???? actually i refereed bellow link its working fine for single attachment….
please if u have any idea share us…
Thank you
hey i want to remove attach files…
plz give me code as early as possible.
function confirmation()
{
alert(“Please check your mail and attachment”);
}
$(document).ready(function() {
//add more file components if Add is clicked
$(‘#addFile’).click(function() {
var fileIndex = $(‘#fileTable tr’).children().length;
if(fileIndex==0){
fileIndex=fileIndex;
}
else if(fileIndex==2){
fileIndex=fileIndex-1;
}
else{
var i=fileIndex/2-1;
fileIndex=i+1;
}
$(‘#fileTable’).append(
‘
‘);
});
$(‘#delfile’).live(‘click’, function() {
$(this).parent().parent().html(“”);
return false;
});
});
java code————————
thank you…..
Getting this error when i try to execute this code
java.lang.IllegalArgumentException: Document base C:\Documents and Settings\temp\My Documents\NetBeansProjects\WebRatan\build\web does not exist or is not a readable directory
viralupload
FileUploadController
FileUploadController
com.FileUploadController
FileUploadController
/FileUploadController
spring
org.springframework.web.servlet.DispatcherServlet
1
contextConfigLocation
/WEB-INF/spring-servlet.xml
org.springframework.web.context.ContextLoaderListener
spring
*.html
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
Hi viral, I have learnt so many things from ur blog….
Can you help me out for doing file uploading using angularjs and spring??
hey, viralpatel! I was wondering how one can store and retrieve an image (or a list of images) to and from a database, say, mysql. I’m really struggling with this for days now.
Thank you!
I followed Your code i want to save the file in data base can you specify the code in controller method like
dao.save();
And what to write in the Dao class
hi i got this error..please give me solution
type Exception report
message An exception occurred processing JSP page /index.jsp at line 1
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 1
1:
How can i see the uploaded files can you please help me ..
Hi am getting null value in @ModelAttribute(“uploadForm”) FileUploadForm uploadForm
|
http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
The limitations of JSON
By bblfish on Jul 13, 2007...
You continue to provide a very useful service by explaining semantic Web concepts in ways that mere mortals (me!) can understand.
Thanks, and please continue to take the time to provide these helpful pieces.
Mike
Posted by Mike Bergman on July 13, 2007 at 01:42 PM CEST #
Posted by Nico on July 13, 2007 at 04:54 PM CEST #
Posted by guest on July 14, 2007 at 01:34 AM CEST #
anonymous coward: The english definition of foaf:Person as being the set of what we would consider a person is a perfectly good explanation of the concept. Concepts can be vague, as long as they are useful. And I think we all have very good intuitions as to what a person is. What the semantic web allows us to do is to give this concept a URL, so that if later someone wants to come up with another concept of a person, perhaps a more ethically oriented one, or one that would allow them to say that companies are persons, then they can do that too, by giving their concept a URL. It is then possible to distinguish the two uses, and relate them in various ways. The proof that it is useful is in the pudding. It is widely used and well understood.
I don't agree that JSON has no pretensions to have any semantics. In fact my argument is that it has the semantics imparted to it by JavaScript, which is exactly what makes it easier to read and understand. These semantics are good for client server communication, when the person writing the client is mostly also the person writing the server, or if not, the code in the client is very closely tied to one particular server. To break out of this one needs something more general, which is what RDF provides. (And btw, RDF is not RDF/XML. RDF is a syntax free semantics, bizaarely enough. Learn N3, it is much easier to understand)
Posted by guest on July 14, 2007 at 03:05 PM CEST #
Posted by Henry Story on July 14, 2007 at 03:22 PM CEST #
Hey look, that's me, with the subject lasso around my neck!
I think the great thing about JSON is that it's very close to the data structures we use in our programs all the time -- lists, maps, scalars. Getting some data from my software out into JSON is trivial, and getting it back into a data structure is just as easy. This isn't about Javascript really, it's about the impedance mismatch. Going from objects to JSON is simpler than going from objects to XML or RDF, no matter what programming language you use. JSON is great for client/server style data exchange, I use it extensively, and it has pretty much replaced XML for me.
So, what are the strengths of RDF over JSON? I don't think the explicit semantics and inferencing in RDF are such a big deal; they are just icing on the cake.
RDF's strength is the hyperlink. You can build a Web of Data with RDF. You can't do that with JSON, because JSON doesn't have hyperlinks. There's no way to say, “and more data about that thing is found over there”. You have to ship everything in one JSON file, or specify out-of-band how a client can find other pieces of data. Imagine HTML without hyperlinks (but with the ability to embed Javascript that updates document.location in response to user actions). That's what JSON looks like to RDF people.
But if you don't need Web of Data features, e.g. when you're building client/server-style apps, then JSON is quite fine.
Posted by Richard Cyganiak on July 15, 2007 at 07:28 AM CEST #
Posted by Patrick Mueller on July 15, 2007 at 12:07 PM CEST #
JSON is different from XML. XML comes with namespaces, so you can tell from the namespace of an xml element how it is to be interpreted. Namespaces are URIs, so you have a unique identifier for that. The xhtml namespace is <code></code> for example. When you then find the xhtml:a anchor element you know to interpret its href attribute as a URL.
In JSON you don't have anything like this. You would only be able to determine the meaning of particular JSON document by using mime types, and if you did that you would have a non extensible format, like html, since there would be no way to distinguish between different extensions for the meaning of the JSON elements. So when you say: you are right. The point is that either
In both cases you have a format that is extensible only through a centralized process. With RDF you can decentralize meaning. You can mix and match different vocabularies written out around the web without risking name clashes and whilst keeping very clear rules semantic rules, so much so that an agent can work confidently even when he only understand parts of the words in the document. The Semantic Web also allows robots to automatically discover the meaning of unknown "words", by fetching documents describing them (also known as ontologies) at the location of the word itself (since words are URIs).
- "the other side" has to be a particular server, and the client has to know the particular intention of that server for this to work. And we all agree that at least for that case, JSON makes more sense than XML because it is a lot easier to write and parse, and in fact in those circumstances has a clear semantics, the one imparted on it by the server and the javascript interpreters of JSON.
- or the JSON has to be served up with a special mime type, and then it no longer is extensible (a bit like RSS 2.0) without going through a centralized agreement process
These are some quite stupendous advantages, derived from some very very simple elements. It is definitively worth learning, because once you know it, some very new horizons will start opening up. If you do learn RDF go for N3, section A is really all you need to learn to get going. cwm will help you convert most of the rdf/xml documents into this easier to read format.
Posted by Henry Story on July 15, 2007 at 10:56 PM CEST #
Both of those will disappear in due course. It would of course be great if browsers built in better RDF support. But don't forget, the browser is not the only user agent possible. As every application becomes web enabled, publishing your data in RDF will open up the possibility of many other types of applications.
Posted by Henry Story on July 15, 2007 at 11:34 PM CEST #
Posted by Richard Cyganiak on July 16, 2007 at 01:55 AM CEST #
Posted by Alexander Pohoyda on July 16, 2007 at 03:04 AM CEST #
Posted by Alexander Pohoyda on July 16, 2007 at 04:18 AM CEST #
Alexander said: “one can define namespaces semantics and store it using JSON syntax (same way it is done in XML)”
That's misleading. With XML, the namespace semantics are standardized and universally supported by the tools. With JSON, you have to roll your own, and everybody who wants to use your namespace mechanism has to code from scratch. That makes all the difference.
“Some commentators compare RDF (a model) with JSON (a syntax). This does not make any sense!”
JSON and RDF are both formats for data exchange. Why shouldn't we compare them?
Posted by Richard Cyganiak on July 16, 2007 at 04:29 AM CEST #
Well, I do point out that using URIs in JSON is possible, just like writing C programs that use unicode strings. It is just not something that comes naturally. In fact I give as example the "Serializing SPARQL Query Results with JSON" spec as one that does use URIs and has a clear mapping to an XML format. It is worth noticing the difference between the XML and the JSON versions though. Notice again that in order to make sense of the resulting JSON document described in the above spec, the client has to know that it is receiving a SPARQL result back in JSON format. So the message is still very closely tied to the server, because there is no standard way in JSON to give the words "head", "vars","results","binding","type","value", etc... a unique name. All these strings could appear in many different contexts with different meanings, even though all of them may be perfectly legitimate JSON documents. Compare that to the XML documents it is derived from. There all the elements and attributes are relative to the "" namespace. XML provides a standard to namespace elements and attributes, JSON does not. JSON probably could, but you'd think that a syntax that defines booleans and numbers, as primary types, would have done something special for URIs, if it had really wanted to distinguish itself as a web language! And for a language so closely derived from Java, why no package naming, which would have been a step in the right direction? I would never criticise a language's lack of power because it could only describe relational data, now that I understand the semantic web. Every data structure can be built out of relations: lists, trees, tables, graphs. Lisp is not the simplest language: lists can be specified by using two relations :first and :rest and the :null final element. The simplest data structure is the relation: or in other terminology .
Posted by Henry Story on July 16, 2007 at 04:48 AM CEST #
Posted by Tony Hammond on July 16, 2007 at 05:09 AM CEST #
Posted by Alexander Pohoyda on July 16, 2007 at 05:10 AM CEST #
Posted by Alexander Pohoyda on July 16, 2007 at 05:21 AM CEST #
One answer is that strings in RDF can be thought of as URIs that refer to themselves. URIs usually refer to other things than themselves, so it is better not to say the above, but rather to say that literals uniquely identify themselves. Semantically what you have to imagine is an arrow going from the person John (wherever he happens to be) to a string "John". Imagine further that the arrow has a little tag "foaf:firstName" attached to it, which you can click on to find out what it means. "John" does not refer to John (the real person) directly, but indirectly via the unique foaf:firstName relationship. Note that many other people can have a similar relationship to the string "John", which is why on the web you cannot uniquely identify a person by their first name. Imagine here that you are looking at the "John" string and you look at all the foaf:firstName relations pointing to it. You will find a lot of other people at the other end of those arrows. It is also true that things other than people can have relationships other than foaf:name to the string "John". For example the class of christian names has the :contains relationship to that string. The nameplate John wears at his Javascript conference, has the "xxx:inscribedOn" relation to it too, etc... So again looking at this universal string John, you will find a lot of other types of arrows pointing to it too. Another point you could be making is that foaf:firstName is an (unstable) foaf term which relates a person to his name. Since people can have different names in different languages, it is true that it may be better to write .
The same arguments hold for the contact:city relation. But here your point that it should perhaps be a URL is even more powerful. The contact:city relation does not say what the range of the relation should be. Since cities are indifividuals, I could very well understand someone who argued that it should be an ObjectProperty. contact:city has clearly had less work on it than the foaf vocabulary. A quick:will show that it is very underspecified. Underspecified is not a problem: things can be specified later... But yes the code here to parse this may have to be very open to the type of thing it relates to... Mind you there are really only two choices I think: an object defined by a URI or a string. Given those two options it is quite easy to see how to interpret them.
Posted by Henry Story on July 16, 2007 at 05:30 AM CEST #
Posted by Alexander Pohoyda on July 16, 2007 at 06:22 AM CEST #
Posted by Henry Story on July 16, 2007 at 07:13 AM CEST #
Posted by Alexander Pohoyda on July 16, 2007 at 07:25 AM CEST #
Now let me also agree with you that one could indeed create some object that spanned the name over time, such asThis may be very useful in some areas of research. The foaf ontology does not specify such a precise ontology because their use cases are more mundane: connecting people in an easy to understand way. But the two are not exclusive. This name group could even provide some extra relations to relate foaf:Person-s to name:Name-s: Now one could write your foaf file out using both ways of doing things: And one could probably write rules in forms of SPARQL queries to infer the one relation from the other. Perhaps something like: Alexander, I think this discussion has really helped reveal the power of the semantic web. Just try to imagine the endless fights that people discussing such an issue would have had if working with a language that did not allow them to make fine distinctions of meaning such as that between name:name and foaf:name, or speak about the implications of statements in a clear and precise way. I have seen this so often. Everyone would be out there discussing the "real" meaning of the string "name". Each side would have understood something different, there would have been no way to clearly distinguish the meanings, so the conversation would have lasted forever as people kept misunderstandings each other. There would be huge fights on newsgroups and on the blogosphere. All quite entertaining for a while, especially during a bust no doubt, when time is cheap and people need to let of steam. But certainly a huge waste of time. All these relations exist! You just have to distinguish them. And the best way to do that is to use URIs.
Posted by Henry Story on July 16, 2007 at 08:37 AM CEST #
Posted by Valentin on July 16, 2007 at 04:10 PM CEST #
Posted by Alexander Pohoyda on July 17, 2007 at 03:51 AM CEST #
Which relation is useful cannot be decided in the abstract. It depends on what the person consuming the information is doing, or needs the information for. The foaf ontology is clearly very useful. I have not yet been in a position where I wondered if someone had two first names or if they were translations of each other. And I doubt that many people have yet been in that position. But who knows. If it turns out to be very useful, it will be easy to add new relations to foaf for those cases, or for people to add relations such as the name:firstName relation to the name:Name class.
Let natural selection do its work here too.
Posted by Henry Story on July 17, 2007 at 04:45 AM CEST #
JSON on the other hand comes with syntactic structures for things called numbers and booleans, but without namespaces. And there is no well established way of adding namespaces to it. Will it be able to grow such a thing in the clean way XML did?
If you look at N3 on the other hand you will see that it is built on URIs. This is clearest by looking at the NTriples subset of N3, which is just lines of three URIs or 2 URIs and a string. In fact you can think of N3 (or rather the Turtle subset of N3) as just syntactic sugar for NTriples. This makes me think that N3 mat be the best language long term for data interchange on the web.
Posted by Henry Story on July 17, 2007 at 05:24 AM CEST #
YAML,,, is a superset of JSON. YAML has much the same purpose as JSON, exchanging or storing state information, with a bit more emphasis on human readability:
"YAML ... is a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages such as Perl and Python. YAML is optimized for data serialization, configuration settings, log files, Internet messaging and filtering."
YAML has a feature, tags, that can be used much as you would use XML namespace names to disambiguate you vocabulary (set of type names). And yes, you can use an URI as a tag (the 'tag' URI scheme is preferred).
Now, if the state that you want to serialize looks like a bunch of RDF statements, you will obviously be better off using some convenient RDF serialization format. But quite a lot of state information has no natural fit to triples and no intrinsic value in being Web-enabled.
Here is an interesting comparison of textual (serialization) formats for the Web:
<XML/> without the X - the return of {{Textual}} markup
Posted by Peter Ring on July 17, 2007 at 06:10 PM CEST #
The idea of using whitespace as a bracketing mechanism is really not a good idea. That makes it impossible to use in emails for example when chatting in newsgroups. The Yahoo groups munges whitespaces for breakfast, as you can see on the mail I wrote that lead to this blog. I had written out the Turtle example there with nice indentation to make it easy to read, but Yahoo decided to remove them all. Now with Turtle the result is a document that still makes sense, if perhaps more difficult to read. Do that to a YAML document and you have killed it.Thanks for pointing that out. It seems tagged on though, so to speak. The simplest form of Turtle, NTriples, is just URIs. There it is the core of the language. Could you give me an example of some state information that does not fit well into triples? People don't realise that this is the basic data format. Even objects are really just a bunch of relations with methods attached, as so(m)mer demonstrates.
Thanks for the pointer to the presenation on textual markup languages. That is really good.
Posted by Henry Story on July 18, 2007 at 03:50 AM CEST #
I just came across a cool Turtle to JSON translator. I placed the Turtle from the article above into the top box, pressed the "Turtle to JSON" button and got the following:Cute! Well apart from the bug that it misreads the closing "]" of the address object as a new relation... Anyway, if the user agent parsing the fixed translation could guess the origin of the JSON, it would be able to deal with it as another encoding of RDF.
That site also provides a link to Jim Ley's Javascript parser. I wonder if one could do for Javascript what so(m)mer is setting out to do for Java...
Posted by Henry Story on July 18, 2007 at 04:27 PM CEST #
Using whitespace for bracketing works fine for Python. Just try it. Anyway, in YAML, there is also flow-style bracketing, much like in most computer languages.
Should the fact that any data structure could be expressed in terms of s-expressions (or triples, with a bit of effort) imply that you would want to transmit it using an RDF serialization? The simple answer is, it depends! It depends on the nature of the information and why you want to transmit it.
I am somewhat confused about what the subject of the discussion is: information modeling or serialization formats? Anyway, I'll try to describe a few examples from my own experience in which XML and/or RDF would do more harm than good.
I used to work as a consultant in the metalworking industry, implementing data transmission between CAD/CAM systems and CNC mills and lathes. A product model in a CAD system comprise a geometrical description of surfaces and volumes. This geometrical description is transformed into a CNC program, a sequence of tool changes and movements for the CNC mill. CNC programs are usually encoded in simple formats, similar to HPGL. The geometry model can usually be exchanged in an XML-based form, but you wouldn't gain anything from expressing the geometry model in terms of triples -- except starting the discipline of geometry modeling all over again. And you wouldn't gain anything from expressing the CNC tool's trajectory along a double curvature, i.e. a loooong list of X,Y,Z coordinates, as triples -- except a larger CNC program.
I used to work in telecom instrumentation as a tech writer. To set up connections and otherwise do the business of a telecom system, a number of signaling protocols are employed. These protocols are usually described and encoded in terms of ASN.1. Using XML and/or RDF would only add enormous cost. Of course, you occasionally want to "see source", but you can't do that real-time at 140 Mbit/s, so you need recording and decoding instrumentation anyway.
Oh, but this is not really exchange of state info like I think of it, this is nothing like exchange of documents and forms on the Web, you might say. Well, there are worlds of exchange that barely touches the Web.
It's not that space-time, signals, programs, event logs etc. can't be described and serialized in useful ways using triples. But if you just want to consume the information, and you don't want to compose it with other information resources on the Web, why bother?
Oh, but someone might someday want to do interesting and fantastic things. Well, let's cross that bridge when we get to it.
I should add that I now work in legal publishing and do find RDF and SPARQL extremely useful ;)
Posted by Peter Ring on July 18, 2007 at 05:13 PM CEST #
IMHO, the binary syntax/semantic distinction is too blunt an instrument for the current discussion. The three level stack [syntax / data structure / semantics] is better: JSON is a a serialization of a particular variety of mathematical object (aka data structure): a tree with labeled edges that has literals as leaves - an array being a node with integers as edge-labels. Labeled trees can in turn be used to represent all kinds of things - the semantics being defined by the application (and I don't mean to restrict attention to the semantic web here - any useful data carries a meaning defined by the application that manipulates it)
The data model underlying RDF is a graph whose edges and non-literal nodes are labeled by URIs. It is an easy exercise to encode graphs as trees. JDIL (Json Data Integration Layer) defines a particular way of doing this - one that includes XML-style namespaces for concise expression of URIs This yields the four level stack: [JSON syntax/Labeled Tree/URI Graph/Semantics].
So, JSON can easily be used to encode RDF - all that's needed is the short hop from tree to graph. What are the merits of this encoding relative to the alternatives? This is a practical matter unrelated to the philosphical debates at the semantic levels: I have a well-defined data structure (a URI graph) that I want to store or transport - what's the best way of doing this? The criteria are: compactness, computational efficiency of generation and parsing, availability of tools for parsing and generation, and legibility. JSON is compact compared to any of the XML representations (though not compared to Turtle - it is about the same). JSON has excellent parser support not just in the JavaScript environment, but in all of the major Web programming environments:PHP,Python,Perl,Ruby, ActionScript.... JSON is all over the web now - it's not just a client-side technology. Finally, the legibility of JSON is good.
Granting the feasibility of the tree-to-graph hop, JSON is a practical candidate for serializing RDF. And, to repeat: the relevant issues are not philosphical but of the ordinary software engineering variety - what's fast, what's easy, what's supported.
Posted by Chris Goad on July 27, 2007 at 09:42 AM CEST #
I am not sure you get much out of your syntax, data structure, semantics distinction. JSON like XML is defined primarily syntactically. In fact all well defined artificial languages require that. N3 has it too. But JSON does not come with a default semantics, other than that it is easily parsed by a JavaScript process, and as I explain therefore is usually seen to have a behavioral semantics. Usually pieces of JSON have the semantics of the program that is meant to interpret them, which means they are very closely tied together, which as I pointed out keeps the technology in the client-server realm.
But nothing stops one from doing as JDIL does, add namespaces to JSON. This would if adopted help JSON break out of the client server realm. If this is going to be obvious to interpreting programs, then it had better be served with a special mime type though, perhaps "application/json+rdf" or "application/jdil", otherwise there would be no reliable way to know that it was meant to be interpreted in that way rather than any other way. JDIL looks like an interesting attempt therefore to give an open semantics to JSON, by tying it to RDF via URIs. My guess is that there is still a lot of work to be done there to make sure it ties in cleanly, and to define precisely the semantics of JDIL. Anyway, it will be interesting to see how it catches on. Is the namespace piece going to help it be correctly interpreted by JSON evals? Or will an intermediate layer need to be set up to make sure the namespaces get interpreted correctly? Will the JSON VM force certain interpretations on the code that are counterproductive otherwise? Lots of questions... Thanks for pointing this out.
You may also want to follow the thread on another attempt at a JSONesque view of RDF: RDFON.
I myself currently am very happy with N3. It is built as a stack on simpler languages such as NTriples and Turtle, and shows the way forward to a rule based language. The syntax is simple and readable, and it has a lot of work behind it, and it interacts very well with SPARQL.
Posted by Henry Story on July 27, 2007 at 11:11 AM CEST #
Hello Henry,
>But JSON does not come with a default semantics, other than that it is easily parsed by a JavaScript process, and as I explain therefore is usually seen to have a behavioral semantics.
I don't quite agree. JSON has its origins in JavaScript, and has an operational definition in the JavaScript parser. But the JavaScript/ECMA 262 spec is clear enough on the data structure denoted by the object syntax and in this sense already provides denotational semantics. Then, Doug Crawford performed the very valuable service of separating out the object notation from its original JavaScript context, giving it a name, and writing down it's denotational semantics clearly and concisely at JSON.ORG. There are compatible implementations of parsers in a dozen languages, showing that the structure denoted by JSON is clear in practice as well as theory. By now, JSON's special connection to JavaScript is only historical.
>Is the namespace piece going to help it be correctly interpreted by JSON evals? Or will an intermediate layer need to be set up to make sure the namespaces get interpreted correctly?
The latter: to go from the JSON tree data structure with namespaces to the JDIL URI graph, an algorithm is needed. I have implementations in the languages that are involved in our own projects: JavaScript and PHP. I need to spiff these up and publish them on the JDIL site. Also, although I think that the tree-to-graph mapping is adequately specified on the JDIL page, I agree with you that the section about RDF needs elaboration and additional formality. I also agree with your point about mime types - and will think about the best course in this regard.
Meanwhile, Alistair Miles has implemented RDFOO, of which he says: "RDFOO is (more or less) an implementation of JDIL, using Jena and the Java classes for JSON from json.org."
I like Turtle too, but JSON is becoming the new XML, with very widespread support - giving it practical advantages for slinging object graphs around.
Posted by guest on July 30, 2007 at 11:21 AM CEST #
This aside, check out the response Tim Berners Lee just wrote to the RDFON proposal on the Semantic Web mailing list. There are some very interesting points he brings up there.
Posted by Henry Story on July 31, 2007 at 01:25 PM CEST #
Hello Henry,
I didn't mean anything fancy by "denotational semantics" - nothing as complex as the model theories of various logics (such as OWL's Description logic). I only meant "denotational" in the sense that JSON syntax encodes or denotes a mathematical object/data structure rather than an "operational" computation. (In the doc: "JSON is built on two structures: a collection of name/value pairs ... and an ordered list of values" - a labeled tree in other words with an option for consecutive integer labels) Call this an "encoding" rather than a "semantics" if you like, but either way JSON strings denote something quite definite; JSON is not only a collection of rules defining the notion of a well-formed string.
In the email about RDFON that you reference, TBL expresses the same view:
The tree data structure that JSON encodes can in turn encode a URI graph - the same data structure encoded by RDF/XML, Turtle, triples, RDFON, and various other syntaxes. Building a model theory/semantics for the URI graph is where things get interesting. The encoding levels below are just plumbing. But good plumbing is nice to have! My original point: JSON works as plumbing, and has a few practical things going for it.
Posted by Chris Goad on August 05, 2007 at 05:28 PM CEST #
hi all, i may be late to the show but MAYBE this gives me an edge in getting the last word.
ok, put it simply: i think most of the above post and commentaries are fundamentally wrong wherever they miss the point that both JSON and XML/RDF are, fundamentally, nothing but series of octets that we visualize as strings of characters. they are absolutely identical in this respect when they go over the wire. this is their common ‘extensional’ ontology.
second, JSON and XML are very similar in that they are intended to represent possibly nested data structures of name/value pairs—both are extremely similar with respect to their ‘intentional’ ontology.
observe i am not talking here yet about what you can express with JSON or XML; i am talking about the foundations.
i guess that any structure that can be molded as XML is also expressable with JSON, and vice versa. this is a bit similar to programming languages: once a language is turing-complete, you can already express ‘anything’ in it, which makes all languages similar in that whatever facilities or syntactics one language boasts over another is, in the end, just a matter of surface appearance. that appearance \*does\* matter a lot as anyone who has ever compared say python to cobol will underwrite.
it is funny how many people lose sight of the simple fact that namespaces in XML and the structure of RDF are nothing but a convention how to structure names and values. that’s it. no meaning here.
much recent ontological discussions and some heavy but almost empty books suffer from people not realizing that putting on another metalayer onto their data and label it semantic doesn’t mean they have ultimately attained meaning. no, they just did this: they hung a label next to the road sign "HOBOKEN 4 MILES" saying {type:"roadsign", placename:"HOBOKEN", distance: { value:4, unit: "us-miles" }}. it’s nothing but more letters for fewer letters, period.
then, some people claim that something fundamentally changes when you say ‘’ for ‘HOBOKEN’. but nothing has changed fundamentally. the data has just gained a little more fitness to be passed around within a larger audience. we still need a lot of external knowledge to get to the meaning.
over the years, i have gained the impression that XML has some pretty lousy characteristics that make it less than optimally suited for delivering structured data, and that some people are a little benumbed by all the hype that surrounds it.
one of the reasons you can do more with less in JSON as when compared to XML is that at least you have fundamental datatypes such as numbers and booleans clearly expressed in the language, and also that a data structure is always a hash or a list (i wished there were more, like sets and so on, but well).
the next reason JSON is superior to XML is that it painlessly switches between being a data object inside your virtual machine and a string that goes into a text file or over the wire. and this while almost completely eliminating the considerable overhead that XML processing entails.
Posted by loveEncounterFlow on February 14, 2008 at 11:00 AM CET #
This is something that is completely wrong, since Douglas was not the creator of JSON, because in fact JSON is originally described in the ECMA-262 specification as Literal Javascript. The other fact is that, Douglas JSON spec. is incomplete the way he specifies it. ECMA-262 specification for Literal javascript is the way all browsers javascript engines work. So it is not based on a subset of the Javascript programming language, it was stolen from Javascript itself.Why do we need to clarify this? Because if we already have the standarization problem between browser javascript implementation, we are going to have more incompatibilities in the future with a new pretended stolen standard.
We need a better understanding of ECMA-262 in its Literal scripting concept, because in fact, the Javascript programing language creator (a real genius) designed javascript, not only as a programing language for streaming, otherwise you will be always confused by JSON. Same thing happens these days with closures, which nobody really understands, because the closures disclosure is that in fact they are enclosures.
Posted by jose gomez on March 21, 2008 at 03:06 AM CET #
I need to correct some of Jose's comments. I have never claimed to have invented JSON. I only claim to have discovered it. I do not claim to be the first to have discovered it. I give JSON a name and a description and a little web site. Jose intends that credit go to someone else, but he chose not to name that person. That is an odd way of giving credit. The man behind JavaScript is Brendan Eich. Jose did get one thing right: Brendan is in fact a really smart guy.
Posted by Douglas Crockford on July 09, 2008 at 06:43 PM CEST #
Ha what a hot place:-)
Seems you mix syntax and semantics.
I facing this problem now when handle new ON.
I think Henry Story() have proved this problem.
JSON self no namespaces, BUT JSON post-process tool can do namespaces things.
Yes, post-process can much more things than pre-precess.
So can say so:
JSON not need namespaces, but JSON namespaces tool needed.:)
Posted by qinxian on March 27, 2009 at 11:23 PM CET #
|
https://blogs.oracle.com/bblfish/entry/the_limitations_of_json
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
RMI Section Index | Page 12
How can I log my remote server calls?
If you start the server with the java.rmi.server.logCalls system property set to true (java -Djava.rmi.server.logCalls=true Server), you'll be able to monitor server activity.
How do I send a ResultSet back to a client using RMI?
java.sql.ResultSet is not serializable, so it cannot be sent over an RMI connection. You will need to extract the data from the ResultSet and encapsulate it in a serializable object to send back ...more?
Say I have a remote interface: public interface Hello extends Remote { public String sayHello() throws RemoteException; } and an implementation like: public class HelloImpl extends Unicast...more
Is there a mailing list for RMI discussions?
Yes, Sun's RMI-USERS mailing list. To subscribe, send an email to listserv@java.sun.com which contains the message: subscribe RMI-USERS Note that the archives of the mailing list are here....more
Is there another RMI FAQ that I can look at?
Yes, check out: Sun's RMI FAQ.
How does Java RMI differ from Jini?
Java RMI Jini RMI clients use the class Naming.Lookup() for locating the requested RMI Service Jini clients use the discovery process to locate Jini Lookup services. Dis...more
What's new in RMI under Java 2?
Java 2 SDK adds significant enhancements to the RMI implementation found within JDK 1.1. The most important changes are: Under JDK 1.1, RMI servers have to be up and running all the time, and co...more
What is the purpose of the java.rmi.server.useCodebaseOnly property?
When the property java.rmi.server.useCodebaseOnly is set to true, then the JRE will load classes only from either a location specified by the CLASSPATH environment variable or...more
When would I use the java.rmi.server.codebase property?
The property java.rmi.server.codebase is used to specify a URL. This URL points to a file:, ftp:, or http: location which supplies classes for objects that are sent from this ...more
What are the different RMI system configurations possible?
What are the different RMI system configurations possible?
Why is that my remote objects can bind themselves only with a rmiregistry running on the same host?
Although an RMI application can perform a lookup on any host, it can bind, rebind or unbind remote object references only with a registry running on the same host. This is mainly for security rea...more
I get the exception "java.net.SocketException: Address already in use" whenever I try to run rmiregistry. Why?
The exception means that there is already an rmiregistry process running on the default port 1099 on that machine. You can either choose to kill it and restart rmiregistry, or start it up on a dif...more
Is there a servlet implementation of the java-rmi.cgi script for enabling call forwarding when using RMI across firewalls?
Is there a servlet implementation of the java-rmi.cgi script for enabling call forwarding when using RMI across firewalls?
What's the cleanest way to have a client terminate a RMI server that is no longer needed?
The cleanest way to exit is to convert your remote object into an activatable remote object and then a client can invoke the Activatable.unexportObject() method to get rid of it. Things are a lit...more
|
http://www.jguru.com/faq/server-side-development/rmi?page=12
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
Licensing:OpenAudioLicense - Revision history 2016-05-24T13:59:17Z Revision history for this page on the wiki MediaWiki 1.19.24 Wikibot: Licensing/OpenAudioLicense moved to Licensing:OpenAudioLicense: Moving Legal/Licensing Pages to appropriate namespaces 2008-12-21T03:34:11Z <p><a href="/wiki/Licensing/OpenAudioLicense" class="mw-redirect" title="Licensing/OpenAudioLicense">Licensing/OpenAudioLicense</a> moved to <a href="/wiki/Licensing:OpenAudioLicense" title="Licensing:OpenAudioLicense">Licensing:OpenAudioLicense<:34, 21 December 2008</td> </tr></table> Wikibot Spot: New page: This used to be on the EFF website, but has since been taken down. Note that v2 of this license... 2008-09-15T19:27:04Z <p>New page: This used to be on the EFF website, but has since been taken down. Note that v2 of this license...</p> <p><b>New page</b></p><div>This used to be on the EFF website, but has since been taken down.<br /><br /> <br /> Note that v2 of this license is simply Creative Commons Attribution-ShareAlike (CC-BY-SA):<br /><br /> <br /> New content should generally not be produced using this license, as it is considered obsolete by the EFF.<br /> <br /> <pre><br /> EFF Open Audio License:<br /> Version 1.0.1<br /> <br /> Changes from ver. 1.0[.0]: Typo corrections; no substantive changes.<br /> <br /> 1. Preamble<br /> 2. Terms of Use<br /> 3. How to Use this License<br /> <br /> I. PREAMBLE<br /> Principles<br /> <br /> Digital technology and the Internet can empower artists to reach a worldwide audience and to build upon <br /> each other's ideas and imagination with extremely low production and distribution costs. Many software <br /> developers, through both the open source software initiative and the free software movement, have long <br /> taken advantage of these facts to create a vibrant community of shared software that benefits creators <br /> and the public.<br /> <br /> EFF's Open Audio License provides a legal tool that borrows from both movements providing freedom and <br /> openness to use music and other expressive works in new ways. It allows artists to grant the public <br /> permission to copy, distribute, adapt, and publicly perform their works royalty-free as long as credit <br /> is given to the creator as the Original Author.<br /> <br /> As in the software communities, this license is intended to help foster a community of creators and <br /> performers who are free to share and build on each others' work. This also frees their audience to <br /> share works that they enjoy with others, all for the purpose of creating a rich and vibrant public <br /> commons.<br /> <br /> More specifically, this license is designed to serve as a tool of freedom for artists who wish to reach <br /> one another and new fans with their original works. It allows musicians to collaborate in creating a <br /> pool of "open audio" that can be freely modified, exchanged, and utilized in new ways. Artists can use <br /> this license to promote themselves and take advantage of the new possibilities for empowerment and <br /> independence that technology provides. It also allows the public to experience new music, and connect <br /> directly with artists, as well as enable "super distribution" where the public is encouraged to copy <br /> and distribute a work, adding value to the artist's reputation while experiencing a world of new music <br /> never before available.<br /> <br /> Why is the EFF advocating a license?<br /> <br /> Because, despite the fact that we are uneasy with the licensing, as opposed to sale, of both music and <br /> software, we see this particular license as a tool of freedom. Our goal is to use the tools of copyright <br /> to free artists and audiences from the portion of current copyright law that seems, to us, to be getting <br /> in the way of copyright's original purpose -- the creation of a vibrant public commons of music that we <br /> all can enjoy and that artists can build upon. As part of it, we hope to demonstrate some of what we <br /> believe should be the best practices in licenses, including respect for the rights and limitations of <br /> copyright law including fair use, first sale rights, as well as consumer protection laws and of course <br /> freedom of speech. The aim of this license is to use copyright tools to achieve copyright's stated <br /> objectives of spreading knowledge and culture while preserving incentives for the author.<br /> <br /> For legal purposes, this document is the official license under which Open Audio is made available for <br /> public use. The original version of this document may be found at:<br /><br /> <br /> Specific terms and conditions for accessing, copying, distribution, adaptation, public performance, and <br /> attribution follow.<br /> <br /> II. TERMS AND CONDITIONS FOR USE:<br /> Access, Copying, Distribution, Public Performance, Adaptation, and Attribution<br /> <br /> This license applies to any work offered by the Original Author(s) with a notice indicating that it is <br /> released under the terms of the EFF Open Audio License, "(O)". If used in conjunction with a sound <br /> recording (whether in digital or analog form), this license encompasses the copyright in both the sound <br /> recording (the "master" rights) and the underlying musical composition (the "songwriter" rights).<br /> <br /> The Original Author retains the copyrights to works released under this license, but grants the worldwide <br /> public permission to use the work in the ways authorized herein. Activities other than those specifically <br /> addressed below are outside the scope of this license.<br /> <br /> 1. Access, Reproduction, Distribution, Modification, and Performance Rights. Subject to the terms and <br /> conditions of this license, the Original Author irrevocably and perpetually grants to the public <br /> authorization to freely access, copy, distribute, modify, create derivative works from, and <br /> publicly perform the work released under this license in any medium or format, provided that <br /> Original Author attribution be included with any copies distributed or public performances of the <br /> work, as well as any derivative works based on the work, as further described below.<br /> 2. Original Author Attribution Requirement. Original Author attribution is generally defined as a <br /> method in the regular course of dealing that reasonably conveys to the recipient of a copy or <br /> performance the following information: (1) The notice "(O)" that indicates the work is released <br /> under the EFF Open Audio license; (2) the identity of the Original Author; (3) the title of the <br /> work (at Original Author's option); and (4) how the first listed Original Author may be contacted <br /> (at Original Author's option).<br /> <br /> Where a common, widely-adopted method for attribution is available (such as ID3 tagging for MP3 <br /> files), Original Author attribution should be implemented using the common, widely-adopted method. <br /> In other circumstances, Original Author attribution may be implemented in any reasonable fashion, <br /> such as by including attribution in the public performance, or affixing it to the physical media, <br /> or embedding it in the digital file. See the Suggested Guidelines for general attribution <br /> requirements for giving proper credit to the work's Original Author in differing circumstances.<br /> 3. Agree Not to Limit Others' Use. Any new work that in whole or in part contains or is derived from a<br /> work (or part thereof) made available under this license, must itself be licensed as a whole under <br /> the terms of this license.<br /> <br /> Notwithstanding the foregoing, mere aggregation on a volume of a storage or distribution medium of <br /> an independently created work with one that is made available under this license does not bring the <br /> other work under the scope of this license. It is not the intent of this section to contest the <br /> rights of others in works created entirely by them; rather, the intent is to exercise the right to <br /> control the distribution of derivative or collective works based upon a work subject to this <br /> license.<br /> 4. Acceptance of Terms. Because you have not signed this license, you cannot be required to accept it. <br /> But nothing besides this license grants you authorization to copy, distribute, adapt, or publicly <br /> perform royalty-free the copyrighted works released under it. These activities are prohibited by <br /> law without a license or other contractual right granted by the copyright owner. By exercising one <br /> of the rights granted herein you indicate your acceptance of this license and agree to be bound by <br /> all its terms and conditions.<br /> 5. License Version. This license is Version 1.0. New versions of this license will be published from <br /> time to time at:<br /><br /> Anyone who releases a work under the license without specifying a version number allows the <br /> recipient to use the work subject to the then-current version of this license.<br /> 6. Civil Liberties Unrestricted. Nothing in this license is intended to reduce, limit, or restrict any <br /> fair use, the first sale doctrine, or the public side of the copyright bargain under copyright law, <br /> or to in any other way limit any rights bestowed under consumer protection or other applicable laws.<br /> 7. Warranty. By offering an original work for public release under this license, the Original Author <br /> warrants that (i) s/he has the power and authority to grant the rights conveyed herein, and (ii) <br /> use of the work within the scope of this license will not infringe the copyright of any third party.<br /> <br /> III. HOW TO USE THIS LICENSE<br /> <br /> If you are a musician, band, or other artist and you want your creative works to be experienced by the <br /> widest audience possible and touch the hearts and minds of the greatest number of people around the world,<br /> the EFF Open Audio License allows your fans and supporters to market and distribute your work through <br /> viral marketing that creates attention and adds value to your identity. You can also help build a common <br /> pool of creative expression that can be accessed and improved upon by all of society.<br /> <br /> To do so, convey or affix the following information to or about the copy or performance of the work:<br /> <br /> The designation "(O)", representing "open" which indicates that the Original Author(s) have released <br /> the work subject to the terms and conditions of this public license;<br /> <br /> Name of work's Original Author(s) (both the performer and the song writer);<br /> <br /> Name or title of work (at option of author);<br /> <br /> First Original Author's specified contact means usually an email or Internet address (at option of <br /> author);<br /> <br /> notice, year created; and license version number.<br /> <br /> Examples:<br /> <br /> (O) Future Tribe "Gaian Smile" 2001 V.1.0<br /> <br /> or<br /> <br /> (O) Future Tribe "Imitatio Mundi" future@virtualrecordings.com 2001 V.1.0 <br /> <br /> This license is designed to provide artists with a mechanism to promote their creative talents and <br /> identity to millions of people through releasing certain recordings to the public. It is also designed <br /> to serve as a tool to allow musicians to experiment with new business models that do not depend solely <br /> on a payment of fee-per-copy. Changing times require artists be creative in devising new business models <br /> for assuring payment and adequate compensation for their important contributions to society.<br /> </pre></div> Spot
|
https://fedoraproject.org/w/index.php?title=Licensing:OpenAudioLicense&feed=atom&action=history
|
CC-MAIN-2016-22
|
en
|
refinedweb
|
How to Raise Funds for Your Nonprofit through Direct Mail
If you think you want to try large-scale direct mail fundraising at your nonprofit organization, consider hiring clear understanding of what you want to accomplish with a mail campaign (perhaps to reach out to new donors or raise a large number of modest contributions that may be upgraded in the future)
A compelling, well-presented letter that makes its reader care about a cause and believe that the nonprofit described can make a difference
A well-chosen mailing list, usually purchased from a list broker
Nonprofit bulk-rate postage, which can save you a significant amount over commercial mailing rates
Easy, clear ways your letter readers can respond to the request by using a return envelope, response card, or web service
Testing your letter and list at a modest scale before sending the letter to hundreds of thousands of names
A direct mail schedule through which you solicit donors several times each year
When writing a fundraising letter, remember that many potential donors will read your letter’s P.S. before the body of the letter, so include any compelling information there.
Raising money through the mail depends on development of a loyal cadre of donors who respond by mail. Less than 1 percent of the people you mail to initially may send contributions, but after they give, add them to your donor list. You can send mail to these folks in the future and expect a higher rate of return (6 recover only half of your cost.
That’s why direct mail may not be appropriate for a small or start-up organization: the financial risk is high. You need to be able to cover significant upfront costs and not expect a strong return on that investment for several years.
If your organization is newly established, locally focused, too technical for general understanding, or lacking the resources to invest in mailing hundreds of thousands of letters, it still can use letters — both sent through the post office and electronically — to invite people to contribute. You can increase your mail response rates by having your staff and board members write to people they know personally.
|
http://www.dummies.com/how-to/content/how-to-raise-funds-for-your-nonprofit-through-dire.html
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Create and return Akx subclass instances. More...
#include <BelosAkxFactory.hpp>
Create and return Akx subclass instances.
This factory knows how to create various types of matrix powers kernel bases, all of which implement the Belos::Akx interface. As new matrix powers kernel implementations are added to Trilinos, this factory class will help you instantiate them and use them in solvers.
Definition at line 70 of file BelosAkxFactory.hpp.
Type of the matrix powers kernel abstract interface.
Definition at line 75 of file BelosAkxFactory.hpp.
Constructor.
It doesn't do anything exciting.
Definition at line 150 of file BelosAkxFactory.hpp.
Make an OpAkx<Scalar, MV, OP> subclass instance.
OpAkx implements the matrix powers kernel using straightforward applications of the operator A (and the left and/or right preconditioner, if applicable). It's a good default choice for (Flexible) CA-GMRES, especially with reasonably long restart cycles (so that the main benefit of CA-GMRES would likely come from TSQR and Block Gram-Schmidt, not from the matrix powers kernel).
Definition at line 167 of file BelosAkxFactory.hpp.
Return the default matrix powers kernel parameter list.
Definition at line 222 of file BelosAkxFactory.hpp.
Return name of the matrix powers kernel parameter list.
This method is useful if you are looking for parameters for the matrix powers kernel as a sublist of a solver's parameter list.
Definition at line 119 of file BelosAkxFactory.hpp.
|
http://trilinos.sandia.gov/packages/docs/r11.0/packages/belos/doc/html/classBelos_1_1AkxFactory.html
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
This section demonstrates you how to delete a non empty directory.
It is easy to delete a directory if it is empty by simply calling the built in function delete(). But if the directory is not empty then this method will not delete subdirectories and files of that directory. So it is necessary to recursively delete all the files and subdirectories that are available in the directory.
You can see in the given example, we have created a recursive function deleteDir() that will remove all the files and subdirectories of the given directory. We have called this method in the main function.
Here is the code:
import java.io.*; public class DeleteNonEmptyDirectory { public static void main(String[] argv) throws Exception { deleteDir(new File("c:/Hello")); } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } }
Through the above code, you can delete any non empty directory.
|
http://www.roseindia.net/tutorial/java/core/files/deletenonemptydirectory.html
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Introduction
A hallmark of good solution architecture is the degree of low-coupling between the components comprising an application. One design strategy first postulated by Robert C. Martin for decoupling components within object-oriented systems is the Dependency Inversion Principle. This article provides an introduction to this principle, considers its relationship to other software patterns and practices, and reflects on the merits of adhering to this principle.
Overview
The Dependency Inversion Principle is defined as follows:
A. High-level modules should not depend upon low-level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
In conventional architecture, higher-level components depend upon lower-level components as depicted in the following diagram:
In this diagram, component A depends upon component B, which in turn depends upon component C. Due to these dependencies, each of the higher-level components is coupled with the lower-level components.
The goal of the Dependency Inversion Principle is to decouple higher-level components from their dependency upon lower-level components. This may be achieved by creating interfaces as part of the higher-level component package which define the component’s external needs. This allows the component to be isolated from any particular implementation of the provided interface, thus increasing the component’s portability. The following diagram illustrates this relationship:
In this diagram, component A provides an interface which defines the services it needs. Component B satisfies this dependency by implementing the interface. The same relationship is additionally shown for components B and C. Take special note that the interfaces are packaged together with the higher-level components and are defined in terms of the higher-level component’s needs, not the lower-level component’s behavior. It is this association of the interface with the client component which logically inverts the conventional dependency flow.
In some cases, multiple higher-level components existing in separate packages share similar external dependency needs which would best be satisfied by a single lower-level component. In this case, the Dependency Inversion Principle requires that clients agree upon the desired interface which is then published in a separate package. The following diagram illustrates this relationship:
In this diagram, components A and B share a dependency upon a single package containing the common client interface. Component C implements this interface, thus satisfying the dependency of both higher-level components. Note again that the interface here is defined according to the shared needs of the higher-level components rather than according to the behavior provided by the lower-level component. According to the Dependency Inversion Principle, the higher-level components share the ownership of the separate interface package. While in some situations this will arguably be a nominal distinction to make, especially when all of the components are to be maintained by the same development group, this distinction logically maintains the guideline that higher-level components shouldn’t depend upon lower-level components. When the components are maintained by separate groups, this distinction may have implications on which groups are consulted if changes to the interface become necessary. Additionally, the association of the interface with the higher-level component(s) may in some cases impact the style and naming conventions used in the creation of the interface. However, when all components are maintained by the same group, this can indeed become a distinction without a difference.
The second, seemingly more peculiar aspect of the Dependency Inversion Principle is the stipulation that abstractions should not depend upon details, but rather that details should depend upon abstractions. To fully understand the motivation behind this portion of the principle, it is helpful to understand from wince this principle was derived.
The Dependency Inversion Principle was first conceived within the context of C++ development. In the C++ language, classes are typically defined using both a declaration source file and a definition source file. The declaration source files are referred to as header files and are primarily used for including the necessary class declarations required by other components at compile time. While header files provide a measured form of abstraction in C++, their purpose is not to provide separation of interface from implementation. Header files define all the public and private member functions for a class definition, as well as any member variables used by the class. Due to the fact that header files contain implementation details about the class definition, header files (i.e. the abstraction) are dependent upon the source files (i.e. the detail).
While the C++ language does not define an interface type as a first class entity (as is the case in languages such as Java and C#), it does support the notion of a pure abstract class. A pure abstract class is one which contains only abstract methods and which is devoid of any data. Through the use of pure abstract classes, interfaces can be defined to enforce contracts between components. It is the contrast between the use of header files and the use of pure abstract classes (i.e. interfaces) that is in view when the Dependency Inversion Principle advises that abstractions should not depend upon details, but that details should depend upon abstractions.
The next sections will discuss several other associated patterns and practices related to achieving low coupling between components to further aid in the understanding of the Dependency Inversion Principle.
Dependency Inversion and Plain Ole Interfaces
One practice often confused with the Dependency Inversion Principle is the fundamental practice of programming to interfaces rather than implementations.
A fairly common description of the Dependency Inversion Principle establishes a base line example demonstrating components which are tightly coupled as
in the following diagram:
A second example is then typically shown with the introduction of an interface to decouple the dependency between the components as in the following diagram:
While programming to interfaces rather than implementations represents good design practice, the Dependency Inversion Principle is not merely concerned with the use of interfaces, but the decoupling of high-level components from dependency packages. All that has been demonstrated in the above example is the introduction of an abstraction to the dependency. If this abstraction is contained within the dependency package, the high-level component is still coupled to the low-level component’s package. While the conventional use of interfaces adhere to the guideline that abstractions should not depend upon details (a somewhat vestigial guideline from the perspective of languages such as Java and C#), inversion of the conventional dependency relationship is not achieved unless the high-level component defines its own interface whose implementations are defined in separate packages.
Simply stated, every case of programming to interfaces rather than implementations are not examples of the Dependency Inversion Principle.
Dependency Inversion and the Separated Interface Pattern
The Separated Interface Pattern, defined in the book Patterns of Enterprise Application Architecture, sets forth an approach for decoupling components from the implementation details of their dependencies. This is accomplished by defining the interface of the dependency in a separate package from its implementation. One illustration given in the book for how this might be achieved places the interface within the client component package as depicted in the following diagram:
An alternate approach of storing the interface in its own package is also presented, and is recommended when the dependency is used by multiple clients. The following diagram depicts this organization:
As one might observe, these diagrams bear a striking resemblance to the structures advocated by the Dependency Inversion Principle. This similarity has led some to consider the two to be synonymous, and to a large extent they are. However, while the organization of the components set forth by each is nearly identical, slight nuances exists between the advocacy and description set forth by each approach.
First, while both have in view the decoupling of components from the implementation details of their dependencies, the Dependency Inversion Principle achieves this by assigning ownership of the interface to the higher-level component, whereas the Separated Interface pattern achieves this by separating the interface from the implementation … irrespective of any assumed package ownership.
The distinction is the level of emphasis placed by the Dependency Inversion Principle on the value in reusing higher-level components over that of lower-level components. While such an approach is facilitated by the Separated Interface pattern, no such value assignments are assumed.
Additionally, because the Dependency Inversion Principle assigns ownership of the interface to the higher-level component, it considers interfaces more closely aligned with their clients than with their implementations. The Separated Interface pattern makes no assumption on who should own the interface. In fact, the book Patterns of Enterprise Application Architecture sets forth that one reason for separating an interface into a separate package is when there is a desire for emphasizing that the development of the interface isn’t the responsibility of the client developers.
The Separated Interface pattern does set forth the option of packaging the interface with the client, especially when there is only one client, or all the clients are maintained in the same package, but this is more a matter of pragmatism than principle. In similar fashion, the Dependency Inversion Principle acknowledges situations where there may be no particular owner to an interface. This, however, is set forth more as a special case than the general prescription.
Another nuance is the level of applicability advocated by each approach. The Dependency Inversion Principle declares that higher-level components should never depend upon lower-level components. In contrast, the Separated Interface pattern advocates a more conservative approach, even advising against introducing the complexity of separating interface from implementation prematurely, favoring rather to keep interface and implementation together until a specialized need arises.
While both the Dependency Inversion Principle and the Separated Interface pattern result in nearly identical arrangements of the components involved, each approach the same problem with slightly different perspectives and advocate different levels of applicability.
Dependency Inversion and Dependency Injection
Another practice often associated with the Dependency Inversion Principle is Dependency Injection. Dependency Injection encompasses a set of techniques for assigning the responsibility of provisioning dependencies for a component to an external source. The goal of Dependency Injection is to separate the concerns of how a dependency is obtained from the core concerns of a component.
One dependency injection technique, referred to as constructor injection, defines the dependencies of a component within its constructor which are supplied at the time of the component’s creation. A simple demonstration of this technique can be seen in the following code example where an instance of an Automobile class is obtained which has a dependency upon an Engine class:
public class Application { public void CreateAutomobile() { var automobile = new Automobile(new Engine()); } } public class Automobile { Engine _engine; public Automobile(Engine engine) { _engine = engine; } // ... } public class Engine { // ... }
In this example, an instance of Automobile is created by passing an instance of a newly created Engine to the Automobile class constructor. This decouples how the Engine is created from the core concerns of the Automobile class. Dependency injection is typically accompanied by the use of interfaces to decouple the dependency from its implementation and is generally facilitated through an Inversion of Control framework to construct complex object graphs. The use of interfaces has been omitted here for clarity, but also to help emphasis that dependency injection is concerned with decoupling how dependencies are obtained, not the abstraction of dependencies.
The practice of dependency injection is often discussed alongside the Dependency Inversion Principle as a facilitating pattern for supplying implementations of the client interface to the client component at run time. While other patterns such as Service Locator and Plug-in can be used to facilitate the Dependency Inversion Principle, Inversion of Control in the more common solution due to its ability to decouple components from how their dependencies are obtained.
One potential stumbling block newcomers to these design approaches face is in the similarity of terms used in describing these approaches. For instance, taken at face value, the phrase “Dependency Inversion” might conjure up the idea that dependency requirements are being inverted (as in turned inside out) rather than the inversion of dependency (as in reversal) between higher-level components and lower-level components. While the former is an adequate understanding of what dependency injection is, it doesn’t describe the goal of the Dependency Inversion Principle. While certainly complimentary, how dependency implementations are obtained is orthogonal to the module dependency concerns set forth by the Dependency Inversion Principle.
Benefits and Consequences
The approach advocated by the Dependency Inversion Principle provides a useful option for decoupling components from their external dependencies. By following the guideline that higher-level components shouldn’t depend upon lower-level components, core functionality within an application can be more easily used in different contexts.
While applying the Dependency Inversion Principle enables higher-level components to be used in a different context, it unfortunately negatively impacts the ability to reuse lower-level components. While this may at times be an optimal compromise, it is not always the case that higher-level components possess the greatest need for decoupling.
The core business components within an application often encapsulate a rich set of behavior tailored to a specific context. While such components may be of tremendous benefit to applications requiring the same behavior, it is their specificity that tends to limit the context where reuse is possible. In contrast, lower-level components often encapsulate more generic functionality which is applicable across a wider range of contexts.
Consider for example the development of a custom logging component. Logging is generally a concern shared by many components across all applications within an enterprise. In following the Dependency Inversion Principle, the logging component would be developed to depend upon a client-owned interface package to allow higher-level components to remain decoupled from the specific logging implementation. While this enables a higher-level component to be reused without requiring the specific logging implementation, it doesn’t allow the logging component to be easily used by other applications.
While the Dependency Inversion Principle does account for the reuse of lower-level components by maintaining the client interface in a separate package, assigning ownership of this package to one or more consumers of a lower-level component can itself be problematic. In doing so, this creates a form of associative coupling between clients which may have diverging interests that affect the agreement upon, or stability of the interface contract. Additionally, the resulting contract, naming conventions, and deployment strategy may lack the objectively and elegance that might follow more naturally from assigning the ownership of the interface package to the lower-level component.
An Alternate Approach
In considering the logging example further, an alternate approach to coupling either component package to the other is the combination of the Separated Interface pattern with the Adapter pattern to allow both higher-level and lower-level components to exist independently.
Through this approach, an interface to the dependency is maintained within the high-level component package (or in a separate package shared among two or more high-level components), but an additional adapter package is created to adapt the interface of the high-level component to that of the low-level component.
The following diagram illustrates this organization:
By using a logging adapter to implement the client-owned interface, both the high-level client components and the logging component are able to remain free from dependency upon one another. While this approach dispenses with the notion of dependency inversion from the low-level component point of view, it achieves the Dependency Inversion principle’s goal of decoupling without affecting the potential reuse of lower-level components. Though this level of decoupling is certainly not necessary in every case, this technique offers a more flexible option for those wishing to maximize the level of decoupling between application and infrastructure components.
|
http://lostechies.com/derekgreer/2008/12/28/examining-dependency-inversion/
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
String.Split Method (Char[], Int32)
Assembly: mscorlib (in mscorlib.dll)
Parameters
- separator
An array of Unicode characters that delimit the substrings in this instance, an empty array that contains no delimiters, or a null reference (Nothing in Visual Basic).
- count
The maximum number of substrings to return.
Return Value a null reference (Nothing in Visual Basic) or contains no characters, white-space characters are assumed to be the delimiters. If count is zero, an empty array is.). code example demonstrates how count affects the number of strings returned by Split.
using System; public class StringSplit2 { public static void Main() {} ..............", x); foreach (string s in split) { Console.WriteLine("-{0}-", s); } } } }
import System.*; public class StringSplit2 { public static void main(String[] args) {} ..............", System.Convert.ToString(x)); for (int iCtr = 0; iCtr < split.get_Length(); iCtr++) { String s = split[iCtr]; Console.WriteLine("-{0}-", s); } } } //main } //StringSplit.
|
http://msdn.microsoft.com/en-us/library/windows/apps/c1bs0eda(v=vs.85)
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
19 November 2009 19:32 [Source: ICIS news]
HOUSTON (ICIS news)--A French court on Thursday cleared a Total subsidiary and the former director of AZF of wrongdoing in a 2001 fertilizer plant explosion that killed 31 people, according to several media reports.
A court in ?xml:namespace>
Biechlin and Grande Paroisse were accused of involuntary homicide.
The fertilizer plant explosion also injured thousands.
The blast occurred
|
http://www.icis.com/Articles/2009/11/19/9265684/french-court-clears-total-in-2001-azf-explosion.html
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Jan Van der Haegen
One of the biggest advantages LightSwitch has over conventional RAD environments I have experimented with is that the generated application isn’t a closed box. Using a virtually unlimited number of extension points, you can take control of almost any element you want. After a year of working with LightSwitch, I still haven’t hit any brick walls, that is, challenges I couldn’t surmount because of limitations imposed by LightSwitch.
For example, in the first Leading LightSwitch article I wrote, I completely replaced the LightSwitch client with a Windows Phone 7 client. After looking at the LightSwitch metadata-driven MVVM model, I wrapped the outer tier with an ASP.NET Web site to allow users to log in with their social media credentials.
Before diving in to the LightSwitch architecture and playing with the server implementation, which I’ll do over the next couple months, I wanted to bring you one more Leading LightSwitch article about advanced client-side customizations you might not be aware of. In this “micro-novel,” you’ll find four tales that prove to me that with LightSwitch, if you can imagine something, you’re just minutes away from creating it.
I’ll be honest: my SQL Server skills are currently a bit rusty. Who could blame me for turning to LightSwitch given its visually stunning query designer that accommodates all my query needs? Bob, the IT manager for a large retailer with chains of stores in numerous countries, requested software to help him manage the backend of the company’s business. Specifically, he wanted a screen that would let him browse work tickets from various angles.
Here’s what Bob told me: “A work ticket comes from a particular shop that belongs to a particular chain, located in a particular city or region. It is made for a particular customer, by a particular employee, on a particular date and time, and it contains sales records of particular articles, paid with particular payment types. Only rarely are our employees interested in querying the tickets solely based on properties such as start date or total value. But we have use cases for filtering the tickets by each category I just mentioned.”
Stories like this usually mean the customer doesn’t really have a particular use case in mind but still wants an application that does whatever he wants, whenever he wants it. Given that the customer is always right, I started thinking about a mega-query that could address Bob’s needs.
I can create an extremely large query within the LightSwitch query designer without much effort, but I oversimplified the required query because a more realistic version of it wouldn’t fit on a single screen, or in Figure 1, and I wouldn’t be able to show you the entire query.
Figure 1 An advanced LightSwitch query
Figure 2 shows a screen generated from the query in Figure 1. In the command bar, I clicked Add Screen and then selected a new Search Data screen. By default, LightSwitch creates a screen and opens it in the screen designer.
Figure 2 A screen generated on the query in Figure 1
At run time, Bob can now search tickets on any combination of the optional parameters shown in Figure 3: ID, Shop, Customer, Value (minimum or maximum), Started time and Finished time.
Figure 3 Search screen with filter criteria
Bob probably hasn’t memorized the ID of each shop, so that search field isn’t very useful as is. He needs to be able to select a shop by name instead of having to enter the shopId manually.
Like all things LightSwitch, we’re just a couple clicks away from modifying this application to give Bob what he wants. In the screen designer, I clicked the Add Data Item button in the command bar, and in the Add Data Item dialog box, I added a new Local Property of the type Shop (Entity), as shown in Figure 4.
Figure 4 Add Data Item dialog box
From the left-hand side of the screen designer, I dragged this Shop(Entity) onto the screen in the center and removed the Ticket Shop Id control since it’s no longer needed. I can change the control that’s being used to an Auto Complete Box or a Modal Window Picker, whatever fits in a particular solution. Figure 5 shows the result of these modifications to the visual tree.
Figure 5 Rebinding the query argument in the screen designer
That takes care of the controls, but in the ViewModel (at the left-hand side of the screen designer), notice that the query parameter ShopId is still bound to the local screen property TicketShopId, which no longer appears on the screen. To correct this, I selected ShopId and in the properties panel, changed the value of Parameter Binding to Shop.Id, as in Figure 5. When I next launch the application, the filter criteria section of the screen now has a Shop Modal Window Picker (or an Auto Complete Box if I had wanted one) where the Ticket Shop Id text box once was, as shown in Figure 6.
Figure 6 Improved search screen
When the ... (ellipses) at the right of the Shop box is clicked, the modal window Select Shop shown in Figure 7 opens. From there, Bob and his employees can select the particular shop they want to review.
Figure 7 Select Shop modal window
Bob wants to have every possible use case he can think of implemented for this one screen (not something I recommend because creating a screen around each separate business process or use case is more effective). That’s what Bob wanted, however, so that he can rinse and repeat this process for such parameters as employee, chain, region, payment, customer, workstation, article, classification and possible other categories that might come up.
I love it when my clients are a bit IT-minded. However, during an initial talk with Hank, who asked me to create a small CRM (customer relationship management) application for him, I found out that there’s a big difference between being IT-minded and having some IT buzzwords in your mind.
Three days after the first phone call, Hank and I sat down to discuss some details of the application he wanted, and I showed him a proof of concept I had put together the night before. Hank was wildly enthusiastic about what I had prepared, and talking about his needs in more detail was helpful for both of us. During this initial talk with a client, I often take advantage of the built-in LightSwitch run-time screen editor to tailor the application as we’re discussing it.
Hank and I chatted for hours, and my respect for him grew as we spoke. He was right there with me as we considered how to make this application fit his business processes. Unfortunately, near the end of our meeting, Hank said, “So far the app looks great—but where’s the Metro?” I stared at him, part of me wondering if he was asking about the subway system running through the city or if he wanted an extra module that shows live subway information. Then I noticed that his laptop was open to the Windows 8 start page. I said, “If you’re referring to the Metro design guidelines, the Cosmopolitan theme we’re using adheres to those.” Hank replied, “But there are no squares.”
I knew he was referring to the tiles found in many Metro applications, so I started creating a new screen. Not all screens in LightSwitch have to be based on data. For example, to create the new List and Details screen in Figure 8, I didn’t even have to select anything in the Screen Data combo box.
Figure 8 A screen created without screen data
After I clicked OK in the Add New Screen dialog box, LightSwitch generated an empty screen and opened it in the screen designer. Then from the command bar, I clicked the Add Data Item button and in the Add Data Item dialog box, added a new method named OpenPeopleScreen, as shown in Figure 9.
Figure 9 Adding a new method as a data item to the screen
I edited the code for this new method so that it opened a particular screen in my application by right-clicking on it in the screen designer and selecting Edit Execute Code. I then replaced the code with the following:
namespace LightSwitchApplication
{
public partial class DashBoard
{
partial void OpenPeopleScreen_Execute()
{
// LightSwitch generates this method if you create a screen
// called CustomersListDetail
this.Application.ShowCustomersListDetail();
}
}
}
Next I dragged the method in the screen designer onto the screen, changed the control from a button to a link, added a static image, and with the help of some layout controls, created the screen in Figure 10.
Figure 10 A really small dashboard screen in the screen designer
After making the preceding adjustments, I fired up the application and showed Hank how easy it was to add some squares to his application, as in Figure 11.
Figure 11 The dashboard screen at run time
But the conversation went downhill from there. When I phoned Hank the next day, he told me the deal was off, saying, “This application has to be a state-of-the-art, gigantic and completely modern CRM. How can I trust a developer who doesn’t even know what Metro is?”
I didn’t argue with Hank. In hindsight, I’m relieved I didn’t commit to this project. What Hank, with his smattering of knowledge about Metro, didn’t understand is that the presence or absence of tiles isn’t what makes an application adhere to or violate the Metro design guidelines—although I must admit the “squares” do provide a beautiful, modern finish for the new LightSwitch default look and feel (the Cosmopolitan theme), as you can see in Figure 12.
Figure 12 Finished version of a dashboard screen
Of all my customers, I like working with Nancy the most. She runs a small but lucrative online shop from a small office downtown, where she works with her husband and five employees. Nancy wants everything in her company to work smoothly and to be optimized for her business processes, so she is closely involved in the application development process. She is the opposite of Hank—that is, she doesn’t pretend to be an IT expert. Yet when I showed her how a LightSwitch app works, she immediately grasped how an OData-based backend would help align all the applications she uses.
Over the six weeks I worked with Nancy and her team, I spent many days coding on-site so I could question her and her staff when I needed to. I also wanted Nancy to learn enough about LightSwitch that she could modify the app herself in the future.
One day, Jean-Paul passed by while Nancy and I were working on the main customer screen. Besides being young, “fashion-aware” (his own words) and unafraid of saying something the second it crosses his mind, Jean-Paul will be one of the principal users of the application. Because Nancy’s company is so small, Jean-Paul is not only in charge of CRM, but also the head of shipping and human resources as well as the financial department. He stopped and said, “Nice to see you have found out what a default customer looks like.”
Let me explain the context for Jean-Paul’s comment. When I first presented a proof of concept for the application, Jean-Paul immediately asked me to change the customer List and Detail screen since the look and feel offended his visual sensibilities. By default, the list contains the summary property of the entity, which results in the screen shown in Figure 13.
Figure 13 A default List and Details screen
I explained to Jean-Paul that at design time (or using the runtime screen editor), you can easily change the look of this “item template.” Jean-Paul was much happier when I changed the list part of the screen to look like Figure 14.
Figure 14 Modified list from Figure 13
I altered the list part of the original screen in the screen designer by changing the control in the List from a Summary control (label) to a Picture and Text control. Figure 15 shows where I made these modifications.
Figure 15 Modifying through the screen designer
Nancy’s customers get “store credit points” if they complete an online profile. Not all her customers choose to upload a picture of themselves, so a lot of blanks are left in the list on the screen—a flaw I discovered in my test data when I realized I didn’t have any pictures of my cats Muppet and Munchkin. Jean-Paul asked me to add a default image in these cases so that the screen wouldn’t look so empty.
LightSwitch doesn’t support a picture control with a default image, but as I wrote in this article’s introduction, if you can imagine it, you’re minutes away from creating it. The trick here is to create a simple Silverlight user control. I just added a new Silverlight class library to my solution and then added a new user control named CustomImageControl to it. From the screen designer, I then replaced the default Image Viewer with Custom Control, as shown in Figure 16.
Figure 16 Changing from the Image Viewer to Custom Control in the LightSwitch screen designer
When I clicked Custom Control in the screen designer, LightSwitch started a wizard I used to sequentially add a reference to the Silverlight class library and to select the CustomImageControl as the control to use. To make this control work, however, I needed to know that when I create a custom control, LightSwitch binds an IContentItem as the datacontext. This interface belongs to the ViewModelMetaData layer I talked about in my April 2012 Leading LightSwitch article.
This interface has a property named Screen that is a reference to the IScreenObject, also known as the ViewModel of the screen, visible on the left side of the screen designer, and a property named Value. Obviously, in this case I wanted to bind directly to that Value property from the XAML, as shown in Figure 17.
<UserControl x:Class="CustomControls.CustomImageControl"
xmlns=""
xmlns:x=""
xmlns:d=""
xmlns:mc=""
xmlns:local="clr-namespace:CustomControls"
mc:Ignorable="d"
d:
<UserControl.Resources>
<ResourceDictionary>
<local:ImageToVisibleConverter
x:
<local:ImageToCollapsedConverter
x:
<local:LightSwitchImageToSilverLightImageSourceConverter
x:
</ResourceDictionary>
</UserControl.Resources>
<Grid x:
<Image Source="Customer.png"
Visibility="{Binding Value,
Converter={StaticResource ImageToCollapsedConverter}}"
Stretch="UniformToFill"
Height="100" Width="100"/>
<Image Source="{Binding Value,
Converter={StaticResource LSImageToSLImageSourceConverter}}"
Visibility="{Binding Value,
Converter={StaticResource ImageToVisibleConverter}}"
Stretch="UniformToFill"
Height="100" Width="100"/>
</Grid>
</UserControl>
Figure 17 XAML for the CustomImageControl
Because in LightSwitch an image is kept in memory as an array of bytes, I needed to convert this array to Visible, Collapsed or a MediaSource, depending on the type of property I wanted to bind to the image. This heavy lifting is done in IValueConverter implementations, as shown in Figure 18.
using System;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Microsoft.LightSwitch.Presentation;
namespace CustomControls
{
public class LightSwitchImageToSilverLightImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
var contentItem = value as IContentItem;
var theValue =
contentItem == null ? value : contentItem.Value;
byte[] byteArray = theValue as byte[];
var bitMapImage = new BitmapImage();
if (byteArray != null && byteArray.Length > 0)
{
MemoryStream stream = new MemoryStream(byteArray);
bitMapImage.SetSource(stream);
}
return bitMapImage;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Figure 18 IValueConverter implementation that converts a byte[] into a BitmapImage
There is no code behind since LightSwitch binds the IContentItem as the DataContext, which means I can do everything from XAML with a little help from the converters. So the XAML is straightforward.
There is a grid with two Image controls. If the customer has uploaded a picture, that picture will be bound to the second Image control—the first one will be hidden. If no picture has been uploaded, only the first Image control, the one showing a default picture, will be visible, as illustrated in Figure 19.
Figure 19 Control that doesn’t show blanks
When Jean-Paul saw the finished screen, he joked, “I didn’t realize our default customer is a tie-wearing, round-headed bald guy.” Even Matthew had to laugh.
Matthew is Nancy’s husband and partner in the company. The first time I met Nancy and Matthew, Nancy welcomed me and we chatted about her company’s software needs and how I could help her. Before Nancy introduced me to the rest of her crew, who would all attend the demo of my proof of concept, she warned me about Matthew. “He’s such a sweet and funny man, but you’ll need lots of icebreaking before he’ll warm up to you. Do you know any good jokes?”
She was right about Matthew. I sensed that uncomfortable “I don’t know you so I don’t trust you” feeling from him throughout the demo. He asked me one difficult question after another. Near the end of the demo, he seemed to be the only person who wasn’t completely sold. His last remark to me was, “Not as bad as I thought, but I need the icons on top of the window, not in that banner at the bottom.”
I could understand his comment. Before the Metro hype hit, Microsoft was implementing ribbons in every piece of software it could. Ribbons are traditionally located at the top of the screen, and some people don’t think they belong anywhere else. I already had experience creating a shell extension on-site in around 15 minutes, so I replied to Matthew with, “I’ll take that challenge, sir.” He objected, saying not to bother, but before he had a chance to stop me, I was adding a custom shell to the solution.
A lot of people who use LightSwitch stay away from creating custom shells or themes even though it isn’t that difficult. One perceived obstacle is that custom shells and themes can be developed only in a LightSwitch Extensions project, not in the LightSwitch application. LightSwitch Extensions projects can be really annoying to debug. Because several of my customers have wanted a shell, or at least a theme tailored to their trademark, I created an extension that removes this restriction: ExtensionsMadeEasy.
With ExtensionsMadeEasy, I can create shells and themes directly from the LightSwitch client, which is much easier to develop and debug than an extension project. I can still create the shell or theme in a separate Silverlight class library and compile it into a reusable LightSwitch extension later. Here’s how it works: First download, install and activate ExtensionsMadeEasy in the LightSwitch project. Next, from Solution Explorer, change the LightSwitch application from Logical View to File View. Right-click on the client project, and select Add New Item. A shell is nothing more than a very complex LightSwitch user control, so just add a new user control named MyShell, as demonstrated in Figure 20.
Figure 20 Adding a new shell directly to a LightSwitch client project
The XAML of the user code can be replaced with anything you want, but since I was coding on-site with Nancy, Matthew and their five employees watching me, I reused the Cosmopolitan shell in my control and simply applied a PlaneProjection to it, as shown in Figure 21.
<UserControl x:Class="LightSwitchApplication.MyShell"
xmlns=""
xmlns:x=""
xmlns:d=""
xmlns:mc=""
xmlns:cosmo="clr-namespace:Microsoft.LightSwitch.Cosmopolitan.Presentation.Shells;assembly=Microsoft.LightSwitch.Cosmopolitan.Client"
mc:Ignorable="d"
d:
<UserControl.Projection>
<PlaneProjection RotationX="180" />
</UserControl.Projection>
<cosmo:CosmopolitanShell />
</UserControl>
Figure 21 XAML that defines the visual part of the shell
From the LightSwitch application designer, I changed the shell used from the LightSwitch Cosmopolitan Shell to EasyShell, as shown in Figure 22.
Figure 22 Using EasyShell to bridge LightSwitch and a user control
EasyShell comes with ExtensionsMadeEasy and does all the hard work, such as integrating with the LightSwitch IDE. At run time, EasyShell tries to discover the custom user control and use that as the shell.
My final task was to make the user control discoverable by EasyShell. I just added a small class to the LightSwitch client project. You can’t do this from a separate class library—you have to add the class to the LightSwitch client project because of the way a LightSwitch client uses Managed Extensibility Framework (MEF) to discover all the different parts. To save time, I just appended the class to the code-behind file of the user control, as shown in Figure 23.
using System;
using System.Windows.Controls;
using Microsoft.LightSwitch.Runtime.Shell;
namespace LightSwitchApplication
{
public partial class MyShell : UserControl
{
public MyShell()
{
InitializeComponent();
}
}
public class MyShellExporter : ExtensionsMadeEasy.ClientAPI.Shell.EasyShellExporter
<MyShellExporter>, IShell
{
public string Name
{
get { return "MyShell"; }
}
public Uri ShellUri
{
get
{
var uri = new Uri(
string.Format(@"/{0};component/MyShell.xaml",
this.GetType().Assembly.FullName.Split(',')[0])
, UriKind.Relative);
return uri;
}
}
}
}
Figure 23 Code behind the user control with an added Exporter class
When the LightSwitch application is launched, LightSwitch uses EasyShell as the shell implementation. The shell implementation in turn uses MEF to discover an IShellExporter, which is implemented by the EasyShellExporter base class. This exporter class exports the URI of the actual user control (MyShell.xaml) to EasyShell.
If you’re unfamiliar with PlaneProjections, the result might not be what you expect, as you can see in Figure 24.
Figure 24 User control mirroring the Cosmopolitan shell
I typed Annys in the search control and executed the query. The shell might be mirrored across two axes, but it’s still usable and responsive. Once the data was on the screen, I looked Matthew straight in the eye and, with my best poker face, told him, “Here you go; icons are back on top.”
He stared at me in disbelief. And then I noticed him cracking a small smile. That smile turned into laughter. He got up, shook my hand, and said, “Welcome to the family, son. If you can pull this off, you can make anything work.”
I want to thank Syncfusion for their free Metro Studio, in which I created each of the icons in this article’s screenshots.
The four tales in this article are based on actual technical details, but names have been changed throughout to protect the innocent.
Tale 1, the mega-filter, is a technique Beth Massi mailed me when she was reviewing my eBook. Although it was too late in the process to update the book with a completely new chapter that would include this tip, I didn’t want to keep it to myself either.
Tale 2, where’s the metro, is based on one of Paul Patterson’s latest blog posts: Microsoft LightSwitch - Simply Beautiful Applications. Figure 12, featured on his site, is used in this article with his permission.
Tale 3, what a default customer looks like, is based on actual experiences. Nancy, Matthew and Jean-Paul (not their real names), you are the best clients anyone could wish for.
Tale 4, turning Cosmopolitan upside down, was good for laugh but has a few flaws other than the obvious. For example, a lot of the elements in a LightSwitch application (e.g., modal windows, validation tooltips and drop-down menus) are not under the shell’s control and thus are not subjected to the PlaneProjection. If you want to read more about modal windows, I have an extra tale about Nancy on my blog that explains how to create reusable modal windows in the LightSwitch screen designer.
Jan Van der Haegen is a green geek who turns coffee into software. He’s a loving husband, he’s proud to be part of an international team at Centric Belgium, and he’s so addicted to learning about any .NET technology – Visual Studio LightSwitch in particular – that he maintains a blog on his coding experiments. You can find his latest adventures at.
Thanks to the following technical expert for reviewing this article: community rock star Michael Washington ().
Thanks for your article will help us to go ahead
Hi Jan This is really a useful article. Thank You
More MSDN Magazine Blog entries >
Browse All MSDN Magazines
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
|
http://msdn.microsoft.com/en-us/magazine/jj159885.aspx
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Getting Further with Spring RCP
Creating a Table
Let's now display our data in a table.
First, we create the table, using the Spring RCP "AbstractObjectTable" class. This is a convenience class provided by Spring RCP, with some handy methods for setting up our table in an intuitive manner, providing a simple layer between our domain and our view.
Then we add the related messages to the messages.properties file.
And, finally, we add the table to the CustomerView.
So, let's start by creating a new class called "CustomerTable", with this content:
package simple;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;
import domain.CustomerDataStore;
import org.springframework.richclient.table.support.AbstractObjectTable;
public class CustomerTable extends AbstractObjectTable {
private CustomerDataStore dataStore;
public CustomerTable(CustomerDataStore dataStore) {
super("customers", new String[]{
"address.street",
"address.city",
"address.state",
"address.zip"});
this.dataStore = dataStore;
}
@Override
protected void configureTable(JTable table) {
TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(0).setPreferredWidth(100);
tcm.getColumn(1).setPreferredWidth(100);
tcm.getColumn(2).setPreferredWidth(200);
tcm.getColumn(3).setPreferredWidth(50);
tcm.getColumn(4).setPreferredWidth(10);
tcm.getColumn(5).setPreferredWidth(50);
}
@Override
protected Object[] getDefaultInitialData() {
return dataStore.getAllCustomers();
}
}
Next, add the strings referred to above to the messages.properties file, with values that will be displayed as the labels of the columns in the table:
firstName.label=First Name
lastName.label=Last Name
address.street.label=Street
address.city.label=City
address.state.label=State
address.zip.label=Zip
And then we display the table in our CustomerView, the same CustomerView that we had at the end of the 2nd part of "Getting Started with Spring RCP". We first need a getter and a setter for the data store that we registered in the richclient-application-context.xml and then we need to override AbstractView.createControl() to return a JComponent that consists of our AbstractObjectTable within a JPanel:
package simple;
import domain.CustomerDataStore;
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.springframework.richclient.application.support.AbstractView;
public class CustomerView extends AbstractView {
private CustomerDataStore customerDataStore;
private CustomerTable customerTable;
protected CustomerDataStore getCustomerDataStore() {
return customerDataStore;
}
public void setCustomerDataStore(CustomerDataStore customerDataStore) {
this.customerDataStore = customerDataStore;
}
@Override
protected JComponent createControl() {
customerTable = new customerTableFactory().createCustomerTable();
JPanel view = new JPanel(new BorderLayout());
JScrollPane sp = getComponentFactory().createScrollPane(customerTable.getControl());
view.add(sp, BorderLayout.CENTER);
return view;
}
private class customerTableFactory {
public CustomerTable createCustomerTable() {
CustomerTable customerTable = new CustomerTable(customerDataStore);
return customerTable;
}
}
}
Now deployment will result in our table being displayed in the CustomerView:
|
http://java.dzone.com/news/getting-further-with-spring-rc?page=0,2
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
20 April 2012 06:06 [Source: ICIS news]
SHANGHAI (ICIS)--?xml:namespace>
The plant at Tobolsk in Tyumen Oblast,
The facility will mainly supply to
He explained that
Thus the scale of Russian’s polymer market is relatively small and polymer consumption level is lower as well, the source added.
Tobolsk-Polymer is a subsidiary of SIBUR, a leading petrochemical
|
http://www.icis.com/Articles/2012/04/20/9552099/chinaplas-12tobolsk-polymer-plans-pp-production-for-2013.html
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Post your Comment
Create an Empty DOM Document
Create an Empty DOM Document
This Example shows how to create an empty DOM Document
. JAXP... documents. Here the Document BuilderFactory is used to create new DOM
parsers
The Document Object Model (DOM) APIs
The Document Object Model (DOM) APIs
...
document using the DOM parser:
... of DocumentBuilder. Through DocumentBuilder it
produces a Document (a DOM
DOM
DOM hello,
What is DOM?
hii,
DOM is stands for Document object Model.
DOM is an interface-oriented Application Programming Interface. We can use it for navigation of the entire document
DOM
DOM package name for Document class?
Hi Friend,
The package is known as dom api.
For more information, visit the following links:
Thanks
Adding an Attribute in DOM Document
Adding an Attribute in DOM Document
This Example shows you how to adds an attribute in a
DOM...
parsing of xml documents. Here the Document BuilderFactory is used to create new
Document Object Model(DOM)
Document Object Model(DOM)
The Document Object Model (DOM)
is a an standard object model... to use DOM in order to
render an HTML document. However, JavaScript scripts
Example for getElementsByTagName() method in DOM Document.
Example for getElementsByTagName()
in DOM Document
In this section ,we... of the child in the xml
document. The method getElementsByTagName... level.
We use DocumentBuilderFactory
to create the DocumentBuilder ,then we
DOM to SAX and SAX to DOM - XML
Java DOM to SAX and SAX to DOM Simple API for XML and Document Object Model
Creating Blank DOM Document
Creating Blank DOM Document
This tutorial shows you how to create blank DOM
document. JAXP (Java... of the class DocumentBuilder is
used to create a blank document. The newDocument
Dom in java
Create XML using DOM
import java.io.*;
import org.w3c.dom.*;
import...Dom in java Exception in thread "main" org.w3c.dom.DOMException... =documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument
DOM - XML
DOM Hello....
I'm creating an xml file from java using DOM...*;
public class CreateXML{
public static void createXmlFile(Document doc,String... = builderFactory.newDocumentBuilder();
Document doc
Array Empty
document. write print an
Array is empty. An array object hold the various element... Array Empty
... to
understand in an Array Empty. For this example we are using Java Scripting
DOM Parser Example to Parse A DOM Document
DOM Parser Example to Parse A DOM Document
In this tutorial, we will discuss about how to parse(retrieve data) DOM
Document.
The XML DOM views an XML... to create a DOM object.Get a list of
Employee elements from the DOM and count
Java DOM Tutorial
This section shows you how to create the blank DOM document.
...;
This tutorial is complete guide
to DOM processing.
What is DOM?
Document Object Model....
The DOM is an interface that exposes an XML document as a tree structure
Java dom from string
Java dom from string Hi,
How to create dom tree from string data? I am trying to search the example for java dom from string.
Thanks
... ) );
Document d = builder.parse( is );
}
catch( Exception ex
DOM API - Java Beginners
DOM API How can i go through each and every node of an xml file Each...();
Document doc = build.parse(str);
Node node...);
}
}
}
----------------------------------------------
Read for more information.
Normalize All of the Text in a Document
of the
Text in a DOM document. Methods which are used for Normalizing the text node in
the DOM Document are described below :-
Element root = doc.getDocumentElement():-allows direct
access to the root of the DOM document.
root.getNodeName
Listing nodes used in a document
documents.
Here the Document BuilderFactory is used to create new DOM...
Listing nodes used in a document
This Example shows you the Lists of nodes used in a DOM document
DOM Parser Tutorial
DOM Parser Tutorial
Introduction
Dom stands for Document Object Model.... It presents in DOM only when an entity present in source document. It
can not used... the ordered list of children of each node of the
DOM
Document
Create - XML File (Document)
Create - XML File (Document)
In this section, you will learn to create a XML
document using the DOM APIs. This XML document uses 1.0 version
and UTF-8
XML DOM Tutorial
XML DOM Tutorial
W3C provides a standard called DOM (Document Object Model) for HTML & XML
documents. DOM is also used as an interface for accessing and manipulating HTML
& XML
XML Error checker and locater (DOM)
and locate
(line and column number) an error in your XML document using the DOM
APIs. The XML document follows some rules to check its syntax. ... XML Error checker and locater (DOM)
XML DOM error - Java Beginners
XML DOM error import org.w3c.dom.*;
import javax.xml.parsers.... = DocumentBuilderFactory.newInstance();
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse(xmlFile
Creating DOM Child Elements
tree. We will first create a blank DOM document and add the
root element... DocumentBuilder
object and the create a blank DOM document. The following code creates a blank
document.
//Create blank DOM Document
Document doc
Creates a New DOM Parse Tree
Creates a New DOM Parse Tree
This Example describes a method to create a new DOM
tree .Methods...():-allows direct
access to the root of the DOM document.
Xml code for the program
Post your Comment
|
http://www.roseindia.net/discussion/21801-Create-an-Empty-DOM-Document.html
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Patent application title: SYSTEM AND METHOD FOR PROVIDING AUTOMATED METER MANAGEMENT LAYER INTELLIGENCE TO A POWER LINE COMMUNICATIONS SYSTEM
Inventors:
Shmuel Goldfisher (Petach-Tikva, IL)
Rami Refaeli (Kfar-Saba, IL)
Assignees:
Main.Net Communications Ltd.
IPC8 Class: AG08C1506FI
USPC Class:
34087002
Class name: Communications: electrical continuously variable indicating (e.g., telemetering) with meter reading
Publication date: 2010-03-25
Patent application number: 20100073192
Abstract:
A system and method are provided to enable automated broadband AMR,
optionally in real time. The system may include an Automated Meter
Management Server and an Automated Meter Reading Converter, wherein the
Automated Meter Management Server utilizes data generated by a Poller
Converter and a Name Server, to enable automated data collaboration
between Automated Meter Reading meters and a Power Line Communications
System.
Claims:
1. A system for enabling automated correlating of AMR data in a broadband
PLC system, comprisinga Poller
Converter, to provide said CNAME and Meter information data to said AMM
Server.
2. The system of claim 1, wherein said name Server includes a service application and a Name Protocol Stack.
3. The system of claim 1, wherein said Poller Converter includes a Poller application associated with a NSRV Connection Stack and an AMR Connection Stack.
4. The system of claim 1, wherein said Poller Converter includes a Poller application associated with a logger unit and a Name database.
5. The system of claim 1, wherein said automated correlation occurs substantially in real time.
6. The system of claim 1, wherein said automated correlation is executed substantially simultaneously for multiple AMR clients.
7. A method for enabling automated correlation of AMR data in a broadband PLC system, comprising:implementing an automated registration process to associate a Converter with an AMR client;using a Name Server (NSRV) to keep an updated list of Converter Name-to-IP data;correlating a Converter Name and Serial ID (SID) for each client; andobtaining client AMR data to be provided to the PLC system.
8. The method of claim 7, comprising authenticating a meter state before obtaining client AMR data.
9. The method of claim 7, wherein said registration process comprises:receiving IP Configuration data from a DHCP process, by a Converter;using a Name Server (NSRV) to get an NSRV address for an AMR client, by said Converter;sending a name registration message to said NSRV, with a unique identifying Converter Name (CNAME);updating a Poller Converter (PoCo) with said CNAME for each client; andstarting a meter discovery process, by said PoCo, by accessing said Converter.
10. The method of claim 7, wherein said obtaining client AMR data comprises:sending a query to a PoCo asking for the CNAME correlated with said SID;using said CNAME, by said AMM Server, to access said Converter; andusing said CNAME to IP process to connect between said AMM Server and said Converter.
11. The method of claim 8, wherein an authentication process precedes said read action invoked by said AMM Server.
12. A process to enable automated AMR management in a broadband PLC system, comprising:automatically registering an AMR client on the PLC system; said registering being handled by a Poller Converter (PoCo) unit coupled to a Name Server; andaccessing said AMR client in real time, by an AMM Server, to provide broadband AMR management.
Description:
CROSS REFERENCE TO RELATED APPLICATIONS
[0001]This application claims priority from U.S. Provisional Patent Application No. 60/870,616, filed Dec. 19, 2006, entitled "System and method for providing automatic meter reading layer intelligence to a power line communications network", which is incorporated in its entirety herein by reference.
FIELD OF THE INVENTION
[0002]The present invention relates to methods and devices useful in providing automatic meter management layer functionality in a power line communications system.
BACKGROUND OF THE INVENTION
[0003]Automatic Meter Reading (AMR) generally refers to technologies for automatically collecting data from metering devices (e.g. water, gas, electric) and transferring that data to a central database for billing and/or analyzing. AMR aims to enable billing that can be based on actual consumption rather than on an estimate based on previous consumption, and giving customers better control of their consumption.
[0004]In general, AMR in power line communication (PLC) networks enables electronic data to be transmitted over power lines back to the substation, then relayed to a central computer in the utility's main office. This would be considered a type of fixed network system--the network being the distribution network which the utility has built and maintains to deliver electric power. However, in most cases the native PLC system does not typically handle application layer implementations, and the PLC system devices may not be familiar with the different end devices and languages. For example, different meters may be connected to a PLC system, for example, via Ethernet ports using external serial-to-IP Converters, or via internal Converters. In many cases the correlation between the AMR world and the PLC and Internet Protocol (IP) world are very limited or non-existent.
[0005]It would be highly advantageous to have an electric meter reading system or advance metering infrastructure that may be automatically correlated with the PLC system, to enable, for example, automated updates following device setup, changes, and developments.
SUMMARY OF THE INVENTION
[0006]There is provided, in accordance with an embodiment of the present invention, an apparatus, system, and method for providing Automated Broadband AMR management in real time. Embodiments of the present invention may form at least a part of an Automated Meter Management (AMM) or Advanced Metering Infrastructure (AMI) system, which may enable transforming automated meter reading (AMR) data collected from metering devices (e.g., electric, gas, and water meters) in a Power Line Communications (PLC) system into an intelligent manageable system.
[0007]According to some embodiments, a PLC system management system may be able to automatically detect, validate and collaborate with AMR devices that are added to a Power line network. A variety of client meter devices and types may be used. According to some embodiments broadband meters or clients may be used to create a real time broadband AM network.
[0008]According to some embodiments a method for automatically registering a new AMR meter or client may include getting, by a Converter, an IP Configuration and a Name Server (NSRV) address from DHCP; sending, by the Converter, a name registration message to the NSRV with a unique identifying Converter Name (CNAME); updating, by the NSRV, a Poller Converter (PoCo), either by notifying it, or by the PoCo initiating a continuous update check procedure; and starting, by the PoCo, a meter discovery process by accessing the Converter.
[0009]According to some embodiments a method for automatically accessing of the Converter, to implement real time collaboration with an AMR meter or client, may include sending, by an AMM Server, a query to the PoCo asking for the
[0010]CNAME correlated with the Identification Number, for example, the Serial ID (SID) of the AMR meter; with the resulting CNAME, accessing the Converter, by the AMM Server, using the NAME protocol, and optionally sending a query to the NSRV, by the Converter; connecting the CNAME to the IP, thereby enabling the AMM Server to connect to the relevant Converter. In some embodiments read actions invoked by the AMM Server may have authentication processes before the actions are implemented. In some embodiments, by using CNAME instead of IP, the system may not need to keep an updated IP map for each device in the network; rather updates may be made using a standard protocol to a centralized Server.
[0011]According to some embodiments a system for enabling automated correlating of AMR data in a broadband PLC system is provided, including: a Poller Converter, to provide the
[0012]CNAME and Meter information data to the AMM Server. In some embodiments the name Server includes a service application and a Name Protocol Stack. In some embodiments the Poller Converter includes a Poller application associated with a NSRV Connection Stack and an AMR Connection Stack. In further embodiments the Poller Converter includes a Poller application associated with a logger unit and a Name database. In still further embodiments the automated correlation occurs substantially in real time. In additional embodiments the automated correlation is executed substantially simultaneously for multiple AMR clients.
[0013]According to some embodiments a method for enabling automated correlation of AMR data in a broadband PLC system is provided, including: implementing an automated registration process to associate a meter Converter with an AMR client; using a Name Server (NSRV) to keep an updated list of Converter Name-to-IP data; correlating the Converter Name and Serial ID (SID) for each client; and obtaining client AMR data to be provided to the PLC system. In some embodiments the step of authenticating a meter state may be executed before obtaining client AMR data. In further embodiments the registration process may include receiving IP Configuration data from a DHCP process, by a Converter; using a Name Server (NSRV) to get an NSRV address for an AMR client, by the Converter; sending a name registration message to the NSRV, with a unique identifying Converter Name (CNAME); updating a Poller Converter (PoCo) with the CNAME for each client; and starting a meter discovery process, by the PoCo, by accessing the Converter. In additional embodiments the obtaining client AMR data may include: sending a query to a PoCo asking for the CNAME correlated with the SID; using said CNAME, by the AMM Server, to access the Converter; and using the CNAME to IP process to connect between said AMM Server and the Converter. In a further embodiment an authentication process may precedes a read action invoked by the AMM Server.
[0014]According to some embodiments a Poller Converter process may be provided to enable automated AMR management in a broadband PLC system. The Poller Converter process may be include automatically registering an AMR client on the PLC system; such registering being handled by a Poller Converter (PoCo) unit coupled to a Name Server; and accessing the AMR client in real time, by an AMM Server, to provide broadband AMR management.
BRIEF DESCRIPTION OF THE DRAWINGS
[0015]The principles and operation of the system, apparatus, and method according to the present invention may be better understood with reference to the drawings, and the following description, it being understood that these drawings are given for illustrative purposes only and are not meant to be limiting, wherein:
[0016]FIG. 1 is a schematic diagram illustrating a Converter registration process, according to some embodiments;
[0017]FIG. 2 is a schematic diagram illustrating a process of an AMM Server accessing a Converter, according to some embodiments;
[0018]FIG. 3 is a schematic illustration of aspects of the PoCo and NSRV general architecture, according to some embodiments;
[0019]FIG. 4 is a flow chart illustrating an example of an Automatic Meter Rules Implementation, according to some embodiments; and
[0020]FIG. 5 is a flow chart illustrating an example of an automated meter detection Implementation, according to some embodiments.
[0021
[0022.
[0023]In the following detailed description, numerous specific details are set forth in order to provide a thorough understanding of the present invention. However, it will be understood by those skilled in the art that the present invention may be practiced without these specific details.
[0024]The term "Automated Meter Reading" or the word "AMR" as used herein may encompass various automated meter reading applications, apparatus, devices and services, including meters for electricity, gas, water or other utilities. The term "Automated Meter Management" or the word "AMM" as used herein may encompass a variety of metering management systems, including Advanced Metering Infrastructure (AMI) applications, devices and services. The term "real time" as used herein may encompass data communications that occur substantially immediately, in general in an automated fashion and not requiring manual intervention.
[0025]Embodiments of the present invention enable provision of AMR layer intelligence to a power line communications (PLC) network, for example, to provide Broadband Automated Meter Management (AMM) Layer services in real time. According to some embodiments, an AMM system may be able to automatically detect and collaborate with AMR devices that are added to a Power line network. A variety of client meter devices and types may be used. According to some embodiments broadband meters or clients may be used to create a real time broadband AM system.
[0026]In particular, in some embodiments, a Poller Converter (PoCo) element may be used to handle the application layer of an AMM system. Since the native PLC system does not typically handle the application layer, the PLC system devices may not be familiar with the different end-devices and languages (which, in this case, may refer to the different meters which are connected to a PLC system, for example, via an Ethernet port using external serial-to-IP Converter, or via an internal Converter). Amongst the PoCo's main tasks is to correlate between the AMR world and Internet Protocol (IP) world, over the PLC system. For example, the PoCo may be used to add automation for the correlation between the Metering world and the IP Management world.
[0027]In the "AMR world", a key element typically used for detecting a meter is the meter's serial ID (SID). The SID is generally used as the unique identifier of a client. In the "IP/PLC world", each Converter that is connected to the AMM system may be marked with its Ethernet MAC address and IP address. In order to create an easy representation of these Converters, and in order to remove the need for IP addresses and MAC addresses, a naming method may be used. For this purpose, a Name Server (NSRV) may be in charge of keeping the name-to-IP entries updated using a registration process from modems or Converters associated with AMR units (i.e. AMRplus, from MainNet Communications of Ra'anana, Israel).
[0028]According to some embodiments, such a NSRV may correlate the Converter NAME to IP, and the PoCo may correlate between CNAME and SID. PoCo's other tasks may include, for example, Automatic discovery of meter type and protocol; Log activity in terms of meters' connections, replacing, lost, etc. In some embodiments, NSRV may be implemented as a service on the PoCo machine.
[0029]Since the connection between an Internal and External Converter to a meter generally uses a serial protocol, which does not implement connection state discovery, the Converter may not know anything regarding the state of the meter, for example, whether it is connected, disconnected, needing replacing, etc. Due to that, before performing each reading from a meter an authentication process may be included before obtaining the client data.
[0030]NSRV is an entity that may be dedicated to the AMM system. Even though it may use standard protocols for this purpose, the NSRV may be used for the AMM system solely. Examples for protocols that may be used for NSRV are DNS, WINS and NETBIOS.
[0031]According to some embodiments, the AMM system's installation base may be varied, meaning that the system should be able to grow beyond its basic support level (i.e. adding more meters types), hence, configurability and easy maintenance of meters' protocol stacks is important.
[0032]According to some embodiments, as can be seen with reference to the operational flow chart illustrated in FIG. 1, AMM system 100 elements may cooperate to implement a Converter registration process, to automatically convert meter or client data for usage by a PLC system, prior to implementing AMR with a client. Accordingly, for example, a Converter 110 (e.g., an IP to Serial Converter), which may be coupled to a meter 115 or client, may convert data from meter 115 to an IP protocol. Meter 115 may have an interface that may transmit using serial, wireless (e.g. Zigbee, Bluetooth, WiFi etc.), RF, parallel, and any other suitable or available communication method. Converter 110 may get its Internet Protocol (IP) related configuration (e.g., IP address) and Name Server (NSRV) address via a Dynamic Host Configuration Protocol (DHCP) process. Converter 110 may obtain its IP and NSRV addresses manually using a predefined configuration. At stage 1, Converter 110 may send a name registration message to the NSRV 120 with a unique identifying Converter Name (CNAME). Name Server (NSRV) 120 may enable correlation of the CNAME and the Converter IP address. At stage 2, the NSRV may update PoCo 130, either by notifying it, or by the PoCo 130 initiating a continuous update check procedure. At stage 3, PoCo 130 may start a meter discovery process by accessing the Converter 110 (e.g., using IP via NAME access protocol). In stage 3, PoCo 130 may discover the Serial ID (SID) of the relevant AMR meter or client 115.
[0033]According to some embodiments, an AMM Server 205 may access the Converter in real time, as can be seen with reference to FIG. 2. At stage 1, the AMM Server 205, which may be an AMR management tool or system to enable management of multiple AMR units or clients in a PLC system, may send a query to the PoCo 230, asking for the CNAME correlated with the SID. AMM Server 205 may also request further information from PoCo 230, for example, meter type, protocol information etc. PoCo 230 may send meter connection information data, which may include, for example, CNAME, meter type, protocol information etc. to AMM Server 205. The AMM Server 205 may, at stage 3, access the Converter 210 using the NAME protocol, thereby accessing the relevant meter data. Converter 210 may be coupled to an AMR meter or client 215. Optionally, at stage 2, the Converter 210 may send a query to the NSRV, for example, if the PoCo did not provide the IP identification. The CNAME to IP process may connect between the AMM Server 205 and Converter 210. This process may be optimized using the AMM Server cache, however, each read action invoked by the AMM Server 205 should optionally have an authentication process before it (e.g., in order to assure that no meter had been replaced on the Converter level since the last update). By using CNAME instead of IP, the system does not need to keep an updated IP map for each device in the network; rather updates may be made using a standard protocol to a centralized Server.
[0034]According to some embodiments, in order to summarize different system elements knowledge range and relations between them, a relations tables may be maintained, for example, to include a general structure to store each network element's table structure (e.g., in terms of main fields). For example, where a unit with an internal Converter had been registered in the system, the unit's Ethernet MAC Address may be 00-03-6A-01-02-03, its IP address may be 192.168.10.1, and its derived name may be 101020302. A meter from type 02 may be connected to this unit, the meter's SID being 012345.
[0035]After the unit had registered itself to the NSRV, the NSRV may maintain the following SRV table:
TABLE-US-00001 CNAME IP address I01020302 192.168.10.1
[0036]PoCo may either poll the NSRV for new entries or use signals to get updates from it. After detecting that a new CNAME exists, it may perform polling in order to detect whether there is a Meter connected to the new name, if so, what type of meter it is, and what its SID is. After the query has ended, the PoCo Table may include, for example:
TABLE-US-00002 CNAME SID Type I01020302 012345 02
[0037]When the AMM Server attempts to connect to Meter 012345, it may send a query to PoCo asking what the relevant CNAME is. PoCo may search for SID, and return (if found) the CNAME. From this point, the AMM Server may perform its query and IP connection directly to the meter itself (e.g., using CNAME query standard protocols).
[0038]Since PoCo is a service entity, it may provide several interfaces for notification and query, and it may also use external interfaces to perform updates and to notify other system elements about actions taken.
[0039]In one embodiment an AMM Server->PoCo Query interface may provide translations of SID to CNAME. The AMM Server may use this interface to make a query for a SID, in which case PoCo may return the relevant CNAME which will be used to access this SID.
[0040]In one embodiment a PoCo->AMM Server Notification interface may be provided. Whenever PoCo has detected a table inaccuracy (i.e. new/modified/deleted CNAME), it may notify the AMM Server of this new information.
[0041]In one embodiment a PoCo->NSRV Query interface may be provided, which may be able to read NSRV tables (e.g., including updated CNAME lists). In some embodiments the PoCo->NSRV Query interface may be used to enable a "pull mode" by which PoCo may pull or retrieve NSRV data from the NSRV.
[0042]In one embodiment a NSRV->PoCo Notification interface may be implemented. Whenever NSRV encounters a new CNAME or had aged out and deleted a CNAME from its list, it may notify PoCo regarding this update. In some embodiments the NSRV->PoCo Notification interface may be used to enable a "push mode" by which the NSRV may push or update the PoCo about changes to the NSRV data.
[0043]In one embodiment a PoCo->Meters Query interface may be provided. This interface may use a Meters stack (configurable and updatable), via IP protocol. PoCo may update its database information regarding SID to CNAME by querying new CNAMEs and verifying already added CNAMEs.
[0044]According to some embodiments, the PoCo System general architecture may include, for example, the components depicted in FIG. 3. As can be seen in FIG. 3, an implementation of an intelligent AMM system, sometimes referred to as "AmrPlus Poller system" built from two major components: Poller Converter (PoCo) 310 and NAME Server (NSRV) 350.
[0045]In this example, PoCo 310 and NSRV 350 are interconnected using PoCo's
[0046]NSRV Connection Stack 315. PoCo 310 may include one of more of the following sub-components: Poller Application 320, for initialization and run-time activity (i.e. validation of database entries); Meter Protocol Discovery Interface 325, for running the process to connect to Meters, wherein the interface "speaks" meter language (over IP protocol) and is used to connect to a Meter (using the IP Converter), and enable meter type detection, status and SID querying, etc.; NSRV Connection stack 315, to provide an interface on which PoCo 310 may get the list of registered names from NSRV 350, and use this list to invoke queries to detect new meters and update meters' status. In addition, this interface can be used for the NSRV 350 to proactively update the PoCo 310 about changes in its database; AMM Server Connection stack 330, which may be an interface between PoCo 310 and AMM Server, may be used by the AMM Server to invoke queries toward PoCo 310 (i.e. which NAME belongs to which SID) and to get a response. Additionally, this interface may be used in order to proactively update PoCo 310 in cases where meter information inaccuracy was detected; Database 335, which may contain the information of the meters, meter detection rules, etc.; Logger 340 , which may contain the activity which PoCo 310 handled (i.e. AMM Server queries, meters' status changes, user activity, etc.); and GUI 345, which is a user interface for manual update and information retrieval.
[0047]NSRV 350, according to some embodiments, may include one or more of the following sub-components: Service application 355, which may responsible to control the NSRV activities (i.e. registration, queries, delete of old entries); a Database 360, which may contain information about the NAMEs (i.e. IP address, registration time stamp), and optionally may contain additional data; and a Name Protocol Stack 365, which is an interface for interconnecting with IF devices for registration and queries using the NSRV defined protocol.
[0048]According to some embodiments, since the PLC system may not intrinsically "understand" the AMR serial world, the PLC system may act as a pipe connecting all the system elements together. In order for the PoCo to obtain the SID for each meter, it should have the capability to "speak" in the meter "language". Since there may be several types of meters in the same system (which is the most common installation case), it should be able to discover the relevant meter languages. Further, since installation is scalable in its nature, an integrated configuration method may be supported. For example, a method may be provided to enable manual adding and configuration of a new protocol and/or type of meter, and/or by providing an option to configure and define sets of rules and actions to automatically detect the type of the meter(s) and the language it(they) speak(s).
[0049]There may be multiple methods to implement such processes. Using Manual Configuration (for example, with small scale installations), each CNAME entry (which may be known, since the modem or Converter connected to the meter can be registered during the installation process) on the PoCo database may contain a manual protocol ID with the relevant protocol (derived from the meter type). When the PoCo discovers such a unit to be connected, it may access the unit using the configured protocol only.
[0050]Using Automatic discovery, each new CNAME may invoke an automatic discovery process in order to detect which meter type is connected to it (and what its SID is). Rules may be defined on a rules manager module. Rules may use the CNAME structure in order to provide some clues about the meter type.
[0051]Other type of rules that may be applied may be proactive rules, for example, where the PoCo will try to send some meter commands to the Converter, and according to return replies (or no answer) it can detect the meter type. Rules may be fully configurable (e.g., with customer level tools) in order to support extension of the meter brands, types and languages in the field. During run-time, the auto discovery process may be invoked again, for example, in case a meter had stopped responding. For example, such a discovery process may be important in order to support cases where a meter had been replaced with a meter from another brand or type.
[0052]In another embodiment automatic discovery with manual override may be used, for example, to solve conflicts in special cases by optionally manually overriding both the meter language (protocol ID) or the SID connected to the Converter, when the automatic discovery is active and all other Converters should be supported.
[0053]According to some examples of this discovery mechanism, for example in a case where three types of Meters are installed in the system, a First Meter type may be deduced from the CNAME structure which the AMR modem or Converter creates. The other two types have the same CNAME structure; consider 3 CNAMEs for this example: X010101; I010102; I010103. Consider 3 possible languages which the PoCo supports: Language 1; Language 2; and Language 3. We know that all `X` prefix CNAMEs use Language 1, so the automatic procedure should search for "X" as a prefix, and allocate the type--Language 1, to it.
[0054]The two other types may be detected using a proactive test--we may send a command which only Language 2 answers to it, if the CNAME will answer with a legal reply (that fits language 2 rules)--it may be tagged as a Language 2 type. There may be two different languages that use the same command but use the reply structure to differentiate between them. If there is no answer, it doesn't necessarily show that the CNAME is Language 3 type--it may be a disconnected Meter, so verification rules to Language 3 type should be defined as well. In this example, there may be two constant "types" for the cases of DISCONNECTION and UNKNOWNTYPE (where a reply was received, however it doesn't match any of the defined rules). Proactive messages may be different from each other not only by their payload structure, but also in their infrastructure (i.e. UDP/TCP, ports numbers etc.).
[0055]According to one example, in order to simulate a Meter language, the Meter may have two ways of installation, for example, using external Converters (e.g., which may use UDP with port 1000 to access), and using internal Converters (e.g., which may use UDP with port 2000).
[0056]From the reply message in can be deduced which type of Meter answered the request. In addition, the PoCo may obtain its SID using the Customer Number field. In order to access a Meter in this scheme (e.g., only a single Meter type, but have different UDP port to access), a trial-and-error method may be used, or the CNAME structure may be used, which may be different (for instance, External Converters names will begin with `X` while internal Converters will begin with T). In some embodiments the rules structure should support (in general) the Trial-and-Error detection rules and CNAME parsing rules.
[0057]An example for Automatic Meter Rules Implementation is described in FIG. 4. In this example an Automatic Meter Rules implementation or Automatic Discovery, may be operated for each new CNAME (Converter Name) detected on the NSRV database. Each query stage/property is represented by a separate box. In the example illustrated, CNAMEPatternRule is a set of inner rules which use the CNAME structure in order to define a smaller list of rules, i.e. different prefix character may imply that the Converter serves a specific meter type, hence, simplify the process for detecting a meter type. Inside this Rule, the following rules exist: Id--specific rules to an ID (i.e. manual configuration for a CNAME); Prefix--analyze the beginning of the CNAME string and define the relevant set of rules that match it; Postfix--analyze the end of the CNAME string and define the relevant set of rules that match it; Rule--based on CNAMEPatternRule, the sets of rules which are being implemented on a CNAME.
[0058]Each Rule may be built from the following definitions: MeterType--unique ID for a Meter type language; Protocol--transport protocol over IP (i.e. UDP, TCP); PortDetails--either defined PortNumber, or a range of port numbers--PortNumberRange--limited by "From" and "To"; GetSerialNumberCommand--define the command which will be sent using the IP transport protocol, this command can be text based (using TextCommand) or binary (using BinaryCommand). This command will be sent toward the meter, and if reply that matches the protocol will receive--the meter type is detected; MeterSerialIdentification--analyze the reply message (if received) and get the Meter SID from it using either Location (on textual based reply between "startIndex" and "endIndex") or by using Expression that may translate binary response to a SID value; TimeOut--definition for time to wait between sending the SerialNumberCommand until MeterSerialIdentification reply is being received. This setting is useful for the trial-and-error process wait time. Inner parameters define times to open connection (createConnectionTimeout--relevant for connection oriented protocols i.e. TCP) and time to wait for a response (replyTimeout); and Cname-ref--defines manual override rules.
[0059]An implementation example which uses Windows Internet Naming Service (WINS) as its NSRV protocol, and covers substantially the full process of meter auto detection, meter query and the database relationship, can be seen with reference to FIG. 5.
[0060]A CNAME Table may be provided to hold the updated CNAME and the most recent information. Past information may be deleted (since the logger module should hold it), for example:
TABLE-US-00003 Field name Field type Notes CNAME STRING Used to keep the CNAME value of the meter, which is its IP connectivity address. TYPE_INT INTEGER Type of Meter which will be define (according to field requirement and its installation base) the meter protocol which should be used to communicate with the Meter. SID STRING Serial ID of the meter. May contain letters and digits. CONNECTION_DATE DATE_TIME Initial type on which the CNAME had been added to the table. Kept for fast tracking. CONNECTION_IP_LAST DATE_TIME Last type of meter to which the CNAME had responded using an IP based transmission (i.e. PING). CONNECTION_SR_LAST DATE_TIME Last type of meter which the CNAME had responded to using a Serial based transmission - which shows that the meter was connected at this time.
[0061]TYPE_INT value may correspond with the Meter Types Table which may correlate between INT value and STRING, which may hold a textual reference to the Meter type. Its value may be set by the application either by the automatic detection mechanism, or using the manual configuration table.
[0062]A Meter Types Table may be used to store the correlation between TYPE Integer value and the textual reference describing it.
TABLE-US-00004 Field name Field type Notes TYPE_INT INTEGER Type of Meter which will define (according to field requirement and its installation base) the meter protocol which should be used to communicate with the Meter. TYPE_TEXT STRING Textual reference of the Meter TYPE.
[0063]This table may be set by the user while defining the required meter types that the PoCo should support. It may have a close relationship with the Automatic Detection mechanism, which may return the TYPE_INT value when the Meter type has been detected.
[0064]A Manual Configuration Table may be provided, which may hold manual configuration data (and which may override options in case the user wants to manually configure a special Meter with a different value). This may be set by the user. Every new CNAME may try to first search on the Manual configuration table for matching entries that specify the meter Type and SID, and only if this is not found--it will start the Automatic Detection mechanism.
[0065]The table may hold the following fields:
TABLE-US-00005 Field name Field type Notes CNAME STRING Use to keep the CNAME value of the meter, which is its IP connectivity address. TYPE_INT INTEGER Type of Meter which will define (according to field requirement and its installation base) the meter protocol which should be used to communicate with the Meter. SID STRING Serial ID of the meter. May contain letters and digits.
[0066]The NSRV Connection stack, including the NSRV (Name Server) may be implemented as a service within the PoCo application. However, due to the fact that it may optionally be separated to a different machine, a standard interface may be used in order to interconnect between the PoCo entity and the NSRV entity.
[0067]The AMM Server may use the PoCo as a knowledgebase entity for accessing SIDs over IP. It may use queries in order to get the CNAME of each requested SID. After receiving a successful response with the corresponding CNAME to the requested SID, the AMM Server may perform its actual data connection mechanism--for example, after performing its verification procedure in order to ensure that the information it received from the PoCo is up to date (for instance, there might be several cases in which a meter had been replaced or switched between Converters and PoCo did not made an update round yet on the relevant CNAMEs). In addition, the PoCo may return other answers in the case where the SID was not found, or when SID existed in the database, yet when the CNAME is marked as disconnected.
[0068]When the AMM Server detects an inaccuracy in the information it received from the PoCo it may be able to notify and alert the PoCo in order that the PoCo will be able to update its tables. The PoCo may also use this notification to accelerate the relevant CNAME's to make updates (i.e. if a SID that was found by the AMM Server is registered on the PoCo tables under another CNAME, it may verify or modify this CNAME too).
[0069]To summarize, a PoCo query protocol may be provided, which may be used by the AMM Server in order to obtain requested CNAME's to given SID. Answers may include one or more of: CNAME String; Not found answer; Disconnected answer; and PoCo notification protocol--the protocol which AMM Server uses in order to warn the PoCo about inconsistency it found in its tables.
[0070]Other possible interfaces that may be defined (if needed) are: AMM Server notification protocol--in case the PoCo will work on push mode and will notify the AMM Server about new CNAMEs and SIDs and about changes in its tables); PoCo authentication protocol--in case the system will define that every change that PoCo had found needs to be authorized first by the AMM Server before making it active (e.g., in order to "catch" intrusions, unauthorized installation modifications and breaks into the system); and a Poller Application, to maintain SID to CNAME Accuracy.
[0071]Due to the fact that PoCo should give accurate information regarding the relevant Meter SID corresponding CNAME string, it may maintain, beside the new unit handling procedure (which was described in the previous chapter) a run-time mechanism which may perform accuracy constant checks to find, for example, disconnections of Meters, Meter replacements and Meter reinstallations etc.
[0072]In summary, the New name tracking and detection mechanism may be implemented to constantly check for changes (e.g., running on every known CNAME and performing validation to see if the meter is connected and that the meter data as maintained by the PoCo is accurate and/or updated), to track deleted names (e.g., in case a CNAME was aged out), and track name changes (e.g., since a customer may cause a change in internal configuration which might affect the CNAME sting). In cases of CNAME string changes, such changes may be supported (e.g., extension for CNAME deleted and CNAME added cases).
[0073]The PoCo application may therefore be able to implement NSRV Database polling and PoCo Database polling. The NSRV Database polling task may include polling the NSRV Database in order to locate changes on the Name Server side which have effect on the PoCo information. Changes like IP address replacement may not interest the PoCo since it may work on the NAME access layer. However, new CNAMEs added to the NSRV database, deleted CNAMEs, and possibly CNAME structures that had been changed (TBD) may cause the PoCo to start polling to the new/altered CNAME and to change states to a deleted CNAME.
[0074]The PoCo Database polling task may pass over all CNAMEs in the database, so that each CNAME may be checked at every CHECK_INTERVAL (a parameter that needs to be set). Since every CNAME check may require a time interval to be completed, in accordance with the meter type, for example, a CNAME check may require up to 30 seconds each, or any other suitable time interval (e.g., due to the fact that meters may use serial interfaces with relatively slow transmission rates), this mechanism may work with multiple threads in order to complete a plurality of tests in parallel.
[0075]The polling task's goal may include tracking databases changes, CNAMEs which have been disconnected, switches between Meters, replaced Meters, disconnected Meters, etc. In order to check that a Converter is connected to the IP backbone (whether no Meter may be connected to it, or is connected, but is not working etc.), the Application may use, for example, ICMP protocol. When a Meter (SID) does not respond, the PoCo may try to PING it. If the Meter did not respond, but the CNAME had PING responses, it may mean that, for example, the Converter is connected, but the Meter is either disconnected or malfunctioning.
[0076]Glossary
TABLE-US-00006 PoCo Poller-Converter, AMM system element, correlating between SID and Converter NAME. NSRV Name Server, correlating between NAME of device to its IP address. May use WINS, SAMBA, or other standard naming protocol. SID Serial ID - identifier of a meter. Correlates between customer and a meter. CNAME Converter Name - a name created by the AmrPLUS units, in order to notify the NSRV about an internal or external Converter connected to them. PLC Power Line Communication AmrPLUS Automatic Meter Reading capable PLC units WINS (Windows Internet Naming Service) Name resolution software from Microsoft that runs in Windows NT and 2000 servers. It converts NetBIOS names to IP addresses. DNS (Domain Name System) A system for converting host names and domain names into IP addresses on the Internet or on local networks that use the TCP/IP protocol. NETBIOS The original networking protocol for DOS and Windows PCs. Today, NetBIOS is used to support legacy NetBIOS applications but is also widely used for NetBIOS name resolution. GUI Graphic User Interface ICMP RFC 792, Internet Control Message Protocol SAMBA Samba is a free software implementation of Microsoft's networking system released under the GNU General Public License
[00 Rami Refaeli, Kfar-Saba IL
Patent applications by Main.Net Communications Ltd.
Patent applications in class With meter reading
Patent applications in all subclasses With meter reading
User Contributions:
Comment about this patent or add new information about this topic:
|
http://www.faqs.org/patents/app/20100073192
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
User Tag List
Results 1 to 2 of 2
How to show popup only once through cookies
I want to show popup only once, and I have already written code for it but it is not working.
I want to execute did_you_know_slide_in() function only once.
Can anyone guide me what i am doing wrong.
HTML Code:
function get_cookie(Name) { var search = Name + "=" var returnvalue = ""; if (document.cookie.length > 0) { offset = document.cookie.indexOf(search) if (offset != -1) { // if cookie exists offset += search.length end = document.cookie.indexOf(";", offset); if (end == -1) end = document.cookie.length; returnvalue=unescape(document.cookie.substring(offset, end)) } } return returnvalue; } function loadornot(){ if (get_cookie('hasSeen')==''){ document.cookie="hasSeen=yes" did_you_know_slide_in(); } } loadornot();
- Join Date
- Sep 2006
- 731
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Your code works so something else must be wrong.
Any console errors?
Are you sure you're deleting all cookies for the domain?
A useful bookmarklet is javascript:alert(document.cookie);
Your cookie reader doesn't check that the matched name is a whole word, so in a cookie string like peanuts=2;nuts=1 it would pick up the value of 'peanuts' when searching for 'nuts'.
Code:
function get_cookie(Name) { var cString; return ( ( cString = document.cookie.match( "(^|;|\\s)" + Name + "=([^;$]+)" ) ) ) ? decodeURIComponent( cString[ 2 ] ) : ""; }Tab-indentation is a crime against humanity.
Bookmarks
|
http://www.sitepoint.com/forums/showthread.php?707035-How-to-show-popup-only-once-through-cookies
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
I am currently preparing my developer track talks for the local Big>Days 2005 road show and - oh what a surprise - the key topic for the dev-track will of course be a lap around important new things in Visual Studio 2005 and .NET 2.0.Well and currently I am thinking about a useful demo for Generics ... and guess what ... I don't want to tell the people that they should create their own generic collections. That's not only boring, I think Generics exist that people don't have to write their own collections anymore because they already exist in the framework and, due to the fact they are generic, they can be used in any different situation. Okay, so when writing my own collection for my "Person" class or what so ever is over, what are some other additional usecases.
I mean I have found several really cool blog entries and articles for this topic:
Wow, just a huge repertoire of information. But what the hack do all these things tell me for real world line-of-business applications? Nothing! A Stack is not a problem I want to solve while creating business-applications! And a binary tree is something I don't want to create in a business application as well! These are just things that should exist in the framework. Most, oh, no, all of these examples always write about utility classes or base-framework classes – something that you might use in LOB-applications but don’t write yourself. Honestly I don't believe that my SuperBestGenericList class will be better than the one implemented in the framework. So why are we all talking about generics if just a minority will really find them useful? I mean the generic collections are definitely great but from the "value"-standpoint I think it's not the huge improvement, isn't it?
So what are line-of-business use cases? Where are real advantages of generics for LOB applications that are more than just "self-evident"? When started thinking about that I had the following idea: generic inheritance if you want to create a base-class with “façade-functionality” - another thing that makes life just easier. Just think about a simple example: you have a distributed application and you middle-tier consists of a couple of business classes implementing a typical CRUD pattern. I just want to ensure that in every of the methods a security-checks are performed before the actual operation takes place. This check may not be forgotten accidentally: therefore the base class calls them automatically in the CreateDocument, ReadDocument, DeleteDocument and UpdateDocument and afterwards it calls a CreateDocumentInternal, ReadDocumentInternal,… which must be implemented by the derived classes. With the current version of .NET I’d implement this as follows:
public abstract class BusinessBase{ public object CreateDocument() { if (CheckSecurity("Create")) { return CreateDocumentInternal(); } else { throw new System.Security.SecurityException("..."); } }
public object ReadDocument(object key) { if (CheckSecurity("Read")) { return ReadDocumentInternal(key); } else { throw new System.Security.SecurityException("..."); } }
public void UpdateDocument(object document) { /*...*/ } public void DeleteDocument(object key) { /*...*/ }
public bool CheckSecurity(string opCode) { // Your logic goes here... return false; }
public abstract object CreateDocumentInternal(); public abstract object ReadDocumentInternal(object key); public abstract void UpdateDocumentInternal(object document); public abstract void DeleteDocumentInternal(object key);}
What I don’t like with that are many type-checks and type-casts in both – the inherited classes as well as the classes using this object model. It leads to unreadable code and adds potential type-mistakes to your code. As soon as it comes to concrete implementations I don’t want to have things like this:
public class MyCustomerService : BusinessBase{ public override object CreateDocumentInternal() { /* ... */ } public override object ReadDocumentInternal(object key) { /* ... */ } public override void DeleteDocumentInternal(object key) { /* ... */ }
public override void UpdateDocumentInternal(object document) {
// Argh!! Type checks and casts more and more... if (document is MyCustomer) { MyCustomer customer = (MyCustomer)document; // ... } else { throw new ArgumentException("Invalid business document!"); } }}
Oh yeah, of course the same applies to the usage of this MyCustomerService class. And if you pass the wrong type you don’t get a compiler-error but your application will result in a runtime error. With generics you actually can solve this problem quite nice – with having both: the advantage of type-safe code and of a generic base class that automatically calls a security check function so that this cannot be forgotten accidentally:
/// <summary>/// Business service base class/// </summary>/// <typeparam name="D">Document type</typeparam>/// <typeparam name="K">Document-identifier type</typeparam>public abstract class BusinessBase<D, K>{ public D CreateDocument() { if (CheckSecurity("Create"))
{ return CreateDocumentInternal(); } else { throw new System.Security.SecurityException("..."); } } public D ReadDocument(K key) { if (CheckSecurity("Read")) { return ReadDocumentInternal(key); } else { throw new System.Security.SecurityException("..."); } } public void UpdateDocument(D document) { /*...*/ } public void DeleteDocument(K key) { /*...*/ } public bool CheckSecurity(string opCode) { // Your logic goes here... return true; } public abstract D CreateDocumentInternal(); public abstract D ReadDocumentInternal(K key); public abstract void UpdateDocumentInternal(D document); public abstract void DeleteDocumentInternal(K key);} public class MyCustomerService : BusinessBase<MyCustomer, string>{ public override MyCustomer CreateDocumentInternal() { /* ... */ } public override MyCustomer ReadDocumentInternal(string key) { /* ... */ } public override void DeleteDocumentInternal(string key) { /* ... */ }
public override void UpdateDocumentInternal(MyCustomer document)
{ // Cool, no type-checks and casts // Now the compiler is doing that for me // Hey, that means no runtime errors anymore :) string id = document.Id; // Do something... }}
I think this is a useful use case even for LOB applications. But my problem is – I think this is too complicated for a road show with the title “lap around Visual Studio 2005”. If anyone out there has some other useful use cases (and I am not talking about Stack, Tree or something like that so please don’t bother me with them, I can’t here that anymore) feel free posting them here... I am really happy for any suggestion. Oh well, and if you have a similar useful use case for anonymous methods as well, tell me so... Thanks a lot ;-)
|
http://blogs.msdn.com/b/mszcool/archive/2005/05/09/415718.aspx
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Walkthrough: Developing and Using a Custom Server Control @ Register directive on each page that uses the custom control, as in the following example:
, directory you created for source files in the first procedure of this walkthrough..
Embedding an Icon in the Control Assembly
A visual designer such as Visual Studio 2005.. namespace includes statement completion in a script block as well as property browser support when a page developer clicks the control's tag.. more information, see ASP.NET Web Server Controls and Browser Capabilities.
|
http://msdn.microsoft.com/en-us/library/yhzc935f(v=vs.85).aspx?cs-save-lang=1&cs-lang=jscript
|
CC-MAIN-2013-48
|
en
|
refinedweb
|
Deploy a Phoenix app with Docker stack
Ivan Iraci
・6 min read
The mandatory introductions
Hi everybody, this is my very first post on DEV and I want it to be as short as possible, so that anyone could be able to go straight to the point, if deploying a Phoenix app on docker is the problem at hand.
We will take advantage of the new "mix release" feature released with Elixir 1.9.
I will assume your app needs a Postgres DB. If your architecture is more complex than this (Redis, Mongo, whatever) the deployment strategy for any other piece of software included in your architecture is beyond the scope of this article.
Ok, let's go!
Releasing locally...
... first without docker
In the following examples, our app's name is Demo (so replace any occurrence of "demo" with your app's real name).
First of all we have to make sure our app will "mix release" locally with a production environment setup.
Run the following command in you console, at the root of your project:
mix release.init
Then create a releases.exs file inside your project's /config dir:
import Config secret_key_base = System.fetch_env!("SECRET_KEY_BASE") app_port = System.fetch_env!("APP_PORT") app_hostname = System.fetch_env!("APP_HOSTNAME") db_user = System.fetch_env!("DB_USER") db_password = System.fetch_env!("DB_PASSWORD") db_host = System.fetch_env!("DB_HOST") config :demo, DemoWeb.Endpoint, http: [:inet6, port: String.to_integer(app_port)], secret_key_base: secret_key_base config :demo, app_port: app_port config :demo, app_hostname: app_hostname # Configure your database config :demo, Demo.Repo, username: db_user, password: db_password, database: "demo_prod", hostname: db_host, pool_size: 10
We are going to keep all of our production "secrets" in an .env file in the root of our project:
APP_PORT=4000 APP_HOSTNAME=localhost DB_USER=postgres DB_PASSWORD=pass DB_HOST=localhost SECRET_KEY_BASE=Y0uRvErYsecr3TANDL0ngStr1ng
The APP_HOSTNAME will be localhost for testing your app locally but later it will need to be set to your real domain name (e.g.: myverycoolapp.com), as you see in the comments of /config/prod.exs which needs to be edited as follows, in order to get host and port from our .env file. Make sure to uncomment the last line and to remove the "import_config "prod.secret.exs" from the file (since our "secrets" are in .env):
use Mix.Config # Don't forget to configure the url host to something meaningful, # Phoenix uses this information when generating URLs. config :demo, DemoWeb.Endpoint, load_from_system_env: true, url: [host: Application.get_env(:demo, :app_hostname), port: Application.get_env(:demo, :app_port)], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # Which server to start per endpoint: # config :demo, DemoWeb.Endpoint, server: true
Remember to edit init/2 in /lib/demo_web/endpoint.ex:
@doc """ Callback invoked for dynamically configuring the endpoint. It receives the endpoint configuration and checks if configuration should be loaded from the system environment. """ def init(_key, config) do if config[:load_from_system_env] do port = Application.get_env(:demo, :app_port) || raise "expected the PORT environment variable to be set" {:ok, Keyword.put(config, :http, [:inet6, port: port])} else {:ok, config} end end
To be able to manage our migrations in the released app, we need to create a /lib/demo/release.ex:
defmodule Demo.Release do @app :demo
Ok, we are ready to try to release our app locally.
All you have to do is execute the following commands in your console:
mix phx.digest MIX_ENV=prod mix release
If nothing went wrong, you will be welcomed with the following instructions:
* assembling demo-0.1.0 on MIX_ENV=prod * using config/releases.exs to configure the release at runtime * skipping elixir.bat for windows (bin/elixir.bat not found in the Elixir installation) * skipping iex.bat for windows (bin/iex.bat not found in the Elixir installation) Release created at _build/prod/rel/demo! # To start your system _build/prod/rel/demo/bin/demo start Once the release is running: # To connect to it remotely _build/prod/rel/demo/bin/demo remote # To stop it gracefully (you may also send SIGINT/SIGTERM) _build/prod/rel/demo/bin/demo stop To list all commands: _build/prod/rel/demo/bin/demo
But before we can start and try our released app, we need to migrate our database, typing the following command in our console:
source .env _build/prod/rel/demo/bin/demo eval Demo.Release.migrate
Then, you can start your app as suggested above:
_build/prod/rel/demo/bin/demo start
Is your app working as intended? I hope so. If yes we can move on.
... and then with docker
We want our app to be as light as it can be, so we are going to use two docker images based on elixir:alpine and, of course, alpine.
We are going to have a multistage Dockerfile. In the first stage we are going to build our release, in the second one we are going to deploy our released app and a postgres client (that we will use to know if the database is ready to accept connections and to run our migrations).
This is our Dockerfile and I suggest you to read it very carefully:
# ---- Build Stage ---- FROM elixir:alpine AS app_builder # Set environment variables for building the application ENV MIX_ENV=prod \ TEST=1 \ LANG=C.UTF-8 RUN apk add --update git && \ mix.exs . COPY mix.lock . # Fetch the application dependencies and build the application RUN mix deps.get RUN mix deps.compile"]
Create an entrypoint.sh (and make it executable) at the root of your project:
#!/bin/sh # Docker entrypoint script. # Wait until Postgres is ready while ! pg_isready -q -h $DB_HOST -p 5432 -U $DB_USER do echo "$(date) - waiting for database to start" sleep 2 done ./prod/rel/demo/bin/demo eval Demo.Release.migrate ./prod/rel/demo/bin/demo start
Now we can build our image:
docker build -t demo-app .
Since we need to have a postgres instance running, here is a docker-compose.yml that will take care of both our app and a database:
version: '3.1' services: database: image: postgres restart: always environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_DB: demo_prod web: image: demo-app restart: always ports: - ${APP_PORT}:${APP_PORT} environment: APP_PORT: ${APP_PORT} DB_USER: ${DB_USER} DB_PASSWORD: ${DB_PASSWORD} DB_HOST: ${DB_HOST} SECRET_KEY_BASE: ${SECRET_KEY_BASE} depends_on: - database
Now you need to edit your .env and change at least the DB_HOST (you can leave the db credentials unchanged, the database container will take care of creating the user and db for you):
APP_PORT=4000 APP_HOSTNAME=localhost DB_USER=postgres DB_PASSWORD=pass DB_HOST=database SECRET_KEY_BASE=Y0uRvErYsecr3TANDL0ngStr1ng
Now you can start your containers:
docker-compose -f docker-compose.yml up
If all is well, you can point your browser to and your application will be there waiting for you.
Now we are ready to write our docker-stack.yml, so that we can deploy our app in production (in a DigitalOcean droplet, on AWS, on your own server, ...):
version: '3.1' services: database: image: postgres deploy: restart_policy: condition: on-failure environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_DB: demo_prod networks: - backend web: image: foobar/demo-app:latest deploy: restart_policy: condition: on-failure ports: - ${APP_PORT}:${APP_PORT} environment: APP_PORT: ${APP_PORT} APP_HOSTNAME: ${APP_HOSTNAME} DB_USER: ${DB_USER} DB_PASSWORD: ${DB_PASSWORD} DB_HOST: ${DB_HOST} SECRET_KEY_BASE: ${SECRET_KEY_BASE} depends_on: - database_migrator networks: - backend networks: backend:
Before deploying, we need to publish our application to the docker-hub of our choice (in the example above it is published as a fictional foobar/demo-app:latest). Publishing an image to a docker-hub is out of the scope of this article, but if you are here I am positive that you already know how to do it...
Now we have to create an .env-stack for our deploy:
APP_PORT=4000 APP_HOSTNAME=mycoolapp.com DB_USER=postgres DB_PASSWORD=pass DB_HOST=database SECRET_KEY_BASE=Y0uRvErYsecr3TANDL0ngStr1ng
Finally, after you set up you swarm and connect to it (out of this scope, see the docs on docs.docker.com), you can deploy your app as follows:
source .env-stack docker stack deploy -c docker-stack.yml demo-app
Given that your swarm is configured to respond to the hostname mycoolapp.com, point your browser to and that's all!
Easy, uh? :-)
I'm looking forward for all your constructive (but not only) criticisms and suggestions.
Thanks and to the next.
🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained
In the next post we are going to explore CSS @apply to supercharge what we talk about here....
Hello, i can't make it run. I've got the following error when trying to run
evallocally:
My
endpoint.exand
release.exare updated with you fragments and application name is changed to mine. Postgres is running on port 5432. Have you got any idea why is that ?
Ecto.Migrator.with_repo/2 was introduced in ecto_sql v3.1.2, maybe you have an older version.
Take a look at your mix.lock.
I am using those dependencies:
defp deps do
[
{:phoenix, "~> 1.3.4"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:plug_cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:bcrypt_elixir, "~> 1.0"},
{:guardian, "~> 1.0"},
{:number, "~> 1.0.1"}
]
end
And the error is occurring too.
Any idea?
ecto_sql version has to be at least 3.1.2, eg:
Yes that was a problem. Thank you
Using bash, during local migrate, I got this error
In bash the line
must be translated to
I am posting this to save time to someone who might stumble upon this problem.
Thanks for this!
Cool! Thank you!
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/ilsanto/deploy-a-phoenix-app-with-docker-stack-1j9c
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
.
§.HttpFilters import play.filters.hosts.AllowedHostsFilter class Filters @Inject() (allowedHostsFilter: AllowedHostsFilter) extends HttpFilters { def filters = Seq(allowedHostsFilter) }
- Java
import play.mvc.EssentialFilter; import play.filters.hosts.AllowedHostsFilter; import play.http.HttpFilters; import javax.inject.Inject; public class Filters implements HttpFilters { @Inject AllowedHostsFilter allowedHostsFilter; public EssentialFilter[] filters() { return new EssentialFilter[] { allowedHostsFilter.asJava() }; } }"] }
Next: Extending Play with modules
|
https://www.playframework.com/documentation/tr/2.5.3/AllowedHostsFilter
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
Installing CUDA and cuDNN on windows 10
This is an how-to guide for someone who is trying to figure our, how to install CUDA and cuDNN on windows to be used with tensorflow.
It should be noted that at the time of writing this, tensor flow is supporting only upto CUDA version 9.0 and corresponding cuDNN libraries so please don’t download CUDA 9.2.
Installing CUDA 9.0 on windows.
Pre requisites :
- NVIDIA GPU with compute capability of > 2.0 . Check your GPU here
- Download CUDA version 9.0
Please note if your connection permits, please download the
local version. That saves you from sitting around waiting for download to finish at the installation time.
The download should be ~ 1.4 G. Once the download finishes, launch the installer and follow the defaults. It takes around 10–15 mins for installation to finish. Pleasy verify the files at the default install location after the installation finishes:
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0
Installing cuDNN from NVIDIA
First of all, register yourself at NVIDIA Developer site. Its an free registration and takes only a couple of mins. From there, the installation is a breeze Once registered, goto the download page and accept the terms and conditions. POst this download cuDNN v7.1.4 for CUDA 9.0
Once the files are downloaded locally, unzip them. Installing cuDNN is pretty straight forward. You just have to copy three files from the unzipped directory to CUDA 9.0 install location. For reference, NVIDIA team has put them in their own directory. So all you have to do is to copy file from :
{unzipped dir}/bin/–>
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin
{unzipped dir}/include/–>
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\include
{unzipped dir}/lib/–>
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\lib
That’s it.
Testing it with tensor flow
Install
tensorflow-gpu using
pip3 install tensorflow-gpu. Once that is done, fire up a python console do a
from tensorflow import *. If you don’t see any errors, we are good.
Another way you know that your GPU is being used by executing a keras model and having it use tensorflow as its backend. So at the runtime, you should see a message like this :
2018-08-05 23:43:32.091733: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2018-08-05 23:43:33.288310: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1392] Found device 0 with properties:
name: GeForce GTX 1050 Ti major: 6 minor: 1 memoryClockRate(GHz): 1.62
pciBusID: 0000:01:00.0
totalMemory: 4.00GiB freeMemory: 3.29GiB
2018-08-05 23:43:33.289799: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1471] Adding visible gpu devices: 0
2018-08-05 23:43:35.537890: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:952] Device interconnect StreamExecutor with strength 1 edge matrix:
2018-08-05 23:43:35.538772: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:958] 0
2018-08-05 23:43:35.539309: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0: N
2018-08-05 23:43:35.540537: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1084] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 3020 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
Happy coding
I am a Devops Expert and Machine Learning enthusiast. Please find my original blog post at An Average Joe
Akshay
Source: Deep Learning on Medium
|
https://mc.ai/installing-cuda-and-cudnn-on-windows-10/
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
This the third part in a four part series about how to use Python for heart rate analysis. In this part you will learn about how to improve peak detection using a dynamic threshold, signal filtering, and outlier detection.
>
- Part 1: Opening the data, detecting the first peaks and calculating the BPM;
- Part 2: Extracting complex measures from the heart rate signal;
- Part 3: Signal filtering, improving detection with a dynamic threshold;
- anyway. The data was collected with a simple data logger based on an ATTiny45, as described in another post.
Some Theory and Background
So far we’ve been over how to analyze a heart rate signal and extract the most widely used time domain and frequency domain measures from it. However, the signal we used was ideal. Now consider this signal:
A challenge! This is the other extreme of the signal qualities you will run into. To be honest I cheated and generated this signal by measuring while I was attaching the sensor to my finger (between 0 and about 4000). Immediately after this the blood vessels in the finger need to adapt to being compressed by the sensor (at about 4000-5000), after which the signal becomes stable. At about 7500, 9000 and 12000 I forcefully moved the sensor over my finger to create extra noise. I was surprised at how well the sensor suppresses noise by itself, so well done guys at pulsesensor.com.
Although this signal is manually ‘destroyed’ at points, in practice it
can will happen that parts of your data contain noise or artefacts. The sensor might move which creates noise, it might not be correctly attached or become detached during the measurement, the participant might sneeze, move, or any other noise inducing factor might interfere.
We will see how to deal with this in a few stages:
- Getting started, evaluate the result of passing this signal to our algorithm from part two;
- Careful: Sampling Frequency;
- Filter the signal to remove unwanted frequencies (noise);
- Improving detection accuracy with a dynamic threshold;
- Detecting incorrectly detected / missed peaks;
- Removing errors and reconstructing the R-R signal to be error-free.
Getting Started
First let’s see how our algorithm from part 2 handles this signal. Download the dataset here.
(...) line 37, in detect_peaks maximum = max(window) ValueError: max() arg is an empty sequence
Great, it doesn’t. What is happening?
Some may have noticed it before, our detect_peaks() function will break in one eventuality: when the heart rate signal goes from being smaller than the moving average, to becoming equal to it without moving above it for at least two data points in a row. The most likely case of this happening is if the signal drops to zero for a period of time. The function will then skip to the else statement and try to detect peaks in the ROI, but no ROI has been marked because the signal never rose above the moving average, so max(window) throws the error because an empty list has no maximum. This happens
If you didn’t notice this in the code before, don’t worry, neither did I at first. Now to update the detect_peaks() function:
def detect_peaks(dataset): window = [] peaklist = [] listpos = 0 for datapoint in dataset.hart: rollingmean = dataset.hart_rolling]
For now also comment out line 19, we will get to this later on.
def rolmean(dataset, hrw, fs): mov_avg = pd.rolling_mean(dataset.hart, window=(hrw*fs)) avg_hr = (np.mean(dataset.hart)) mov_avg = [avg_hr if math.isnan(x) else x for x in mov_avg] #mov_avg = [x*1.2 for x in mov_avg] dataset['hart_rollingmean'] = mov_avg
And plot again, this time with peak detection:
The module is not throwing errors anymore and is detecting peaks, but it is hardly the result we’re looking for. Let’s start by looking at noise reduction to see if we can improve the signal.
Sampling Frequency
Before getting to signal filtering let’s determine the sample rate of our file. The file from the previous two parts was 100Hz, what about this one? In practice the actual recording frequency may vary with different devices or systems. It can also be (slightly) different than what the devices are rated for. The accuracy of all the calculated measures is dependent on accurately knowing the sample rate, so this is important to check. Even a difference of 100Hz and 101Hz can lead to significantly different results if you combine data from various sources. I usually log either ‘world time’ or ‘time since start of recording’ with every data line for the purpose of calculating and verifying sample rate afterwards.
With this it is straightforward to calculate the sampling rate:
#Simple way to get sample rate sampletimer = [x for x in dataset.timer] #dataset.timer is a ms counter with start of recording at '0' measures['fs'] = ((len(sampletimer) / sampletimer[-1])*1000) #Divide total length of dataset by last timer entry. This is in ms, so multiply by 1000 to get Hz value #If your timer is a date time string, convert to UNIX timestamp to more easily calculate with, use something like this: unix_time = [] for x in dataset.datetime: dt = datetime.datetime.strptime(Datum, "%Y-%m-%d %H:%M:%S.%f") unix_time.append(time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)) measures['fs'] = (len(unix_time) / (unix_time[-1] - unix_time[0]))
The sample rate of the file provided here is actually 117Hz! The measures can now be calculated automatically using the determined sample rate.
Note that this is not the whole story, apart from sample rate you should also check your data for sampling spread; are all samples spaced evenly apart, e.g. are there no ‘gaps’ or ‘skips’ in the datastream? If your data contains gaps and skips, provided they are only a few samples long at maximum, consider interpolating the missing values before processing. If your sampling rate varies much over time you’re in trouble, use a different datalogging device.
Now that we know the sampling frequency more accurately, we can move on to signal filtering.
Signal Filtering
The first thing you should do when encountering artefacts or noisy signals is try to filter your signal. Why? Because in any real-life measuring situation your signal, whatever it may be, will consist of a signal part and an error part. This is because the perfect sensor does not exist, so it will always pick up interference from sources other than the one you are trying to measure. An example of common interference is power line noise. The AC power from the wall contacts in most countries has a frequency of 50Hz (some, such as the U.S., use 60Hz). This noise is present in many raw ECG-measurements as well.
An often used filter to reduce noise is the Butterworth Filter, which is characterized by a very even response to frequencies within the specified range. It acts as a ‘frequency gate’; suppressing frequencies beyond the specified cutoff range, more so as the frequencies move further away from it. This cutoff point is not a hard line. What I mean is that if you set the cutoff frequency at for example 5Hz, a signal of 5.1Hz will still be let through the filter, it will just be slightly reduced in amplitude (or ‘volume’, if that makes more sense). A signal of 10Hz on the other hand will only get through very weakly, if at all. This is also dependent on the filter order, as is illustrated nicely here.
Still difficult to understand? Think about it like this: you’re at a party and two people are talking to you simultaneously, leading to a situation where you cannot understand either of them. Now place a filter between you and the two others. The filter will reduce the speaking volume of person 1 without altering the volume of person 2. Now you can understand person 2 just fine. This is what the filter does except with frequencies.
Anyway, let’s get to coding and see if the signal can benefit from filtering. First download and open the dataset if you have not done it yet, define the filter using scipy.signal, filter and finally plot the signal. Assuming you’re working with the code from the previous part, define the filter and plot as such:
from scipy.signal import butter, lfilter #Import the extra module required #Define the filter def butter_lowpass(cutoff, fs, order=5): nyq = 0.5 * fs #Nyquist frequeny is half the sampling frequency normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a def butter_lowpass_filter(data, cutoff, fs, order): b, a = butter_lowpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y dataset = get_data('data2.csv') dataset = dataset[6000:12000].reset_index(drop=True) #For visibility take a subselection of the entire signal from samples 6000 - 12000 (00:01:00 - 00:02:00) filtered = butter_lowpass_filter(dataset.hart, 2.5, 100.0, 5)#filter the signal with a cutoff at 2.5Hz and a 5th order Butterworth filter #Plot it plt.subplot(211) plt.plot(dataset.hart, color='Blue', alpha=0.5, label='Original Signal') plt.legend(loc=4) plt.subplot(212) plt.plot(filtered, color='Red', label='Filtered Signal') plt.ylim(200,800) #limit filtered signal to have same y-axis as original (filter response starts at 0 so otherwise the plot will be scaled) plt.legend(loc=4) plt.show()
Now there doesn’t seem to be much improvement in this signal. If you look closely the lines are a little smoother, but there wasn’t a lot of high-amplitude, high-frequency noise there to begin with. It could even be argued that filtering slightly worsens the parts with the lower frequency noise, because there it suppresses the R-peaks a little as well. This is a good example of why you should always plot your signal when you decide to filter it. Filtering the signal changes it, and it is up to you to decide whether this change is for the better.
An example of where a Butterworth Filter was very useful, is this noisy signal I worked with in another project:
No question this improved the signal enough to process it further.
Improving Detection Accuracy With a Dynamic Threshold
The first and maybe most obvious way to reduce the incorrect labeling of the secondary peaks is to raise the moving average we use as a threshold. But raise to what level? This will be different for many different signals. We need measures to help determine which threshold level is probably the most accurate.
A few simple measures can help, we can:
- Look at signal length and count how many peaks there are vs how many we would expect;
- Determine and use the standard deviation of RR intervals (let’s call it RRSD).
The amount of detected peaks holds valuable information but only works to reject obvious incorrect thresholds. Depending on your application (most of mine are with people sitting still), we can reject unlikely bpm values. For example I reject thresholds resulting in average bpm of <30bpm and >130bpm. In other situations (physical excercise) the threshold can be different.
The RRSD tells us something about how spread out the differences between all RR-intervals are. Generally if there is not too much noise, the detection that has both the lowest RRSD that is not zero and also a believable BPM value will be the best fit. RRSD must not be zero because that means there is no heart rate variability, which is a strong indication of mistakes in the detection of R-peaks.
This simple approach works because missing a beat will lead to an RR interval that is about twice as big as the average RR interval, while incorrectly labeling a beat will lead to an RR interval that is at most about half as big as the average RR interval, but generally smaller. Both situations lead to an increased RRSD. In essence we exploit the fact that the heart rate signal contains a fairly stable, recurring pattern.
To illustrate let’s plot four peak detection rounds in a subselection of the dataset, with the moving average raised by 0%, 10%, 25% and 35% (top to bottom):
In the second-to-last plot all R-peaks are detected correctly and nothing has been marked as an R-peak incorrectly. Note that, although the BPM on its own could be valid for all four plots (none of them is an absolute mess), the RRSD strongly points to the plot which is most correct. I say ‘most correct’ because there are situations where some errors will remain no matter how you position the threshold, more on this later. Also note how the missing of a single peak in the last plot already causes the RRSD to increase quite a bit compared to the third one.
Now how to implement this? We cannot simply run 10.000 variations, each with a slightly more raised moving average. Apart from that this would cost us severely in overall performance of the algorithm, it would also be very redundant because many iterations would yield the same correct result (and many others the same incorrect result!). A possible solution is to check with intervals, and afterwards evaluate the most likely RRSD and BPM pair, like this:
def detect_peaks(dataset, ma_perc, fs): #Change the function to accept a moving average percentage 'ma_perc' argument rolmean = [(x+((x/100)*ma_perc)) for x in dataset.hart_rollingmean] #Raise moving average with passed ma_perc window = [] peaklist = [] listpos = 0 for datapoint in dataset.hart: rollingmean = rol] measures['rolmean'] = rolmean calc_RR(dataset, fs) measures['rrsd'] = np.std(measures['RR_list']) def fit_peaks(dataset, fs): ma_perc_list = [5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 150, 200, 300] #List with moving average raise percentages, make as detailed as you like but keep an eye on speed rrsd = [] valid_ma = [] for x in ma_perc_list: #Detect peaks with all percentages, append results to list 'rrsd' detect_peaks(dataset, x, fs) bpm = ((len(measures['peaklist'])/(len(dataset.hart)/fs))*60) rrsd.append([measures['rrsd'], bpm, x]) for x,y,z in rrsd: #Test list entries and select valid measures if ((x > 1) and ((y > 30) and (y < 130))): valid_ma.append([x, z]) measures['best'] = min(valid_ma, key = lambda t: t[0])[1] #Save the ma_perc for plotting purposes later on (not needed) detect_peaks(dataset, min(valid_ma, key = lambda t: t[0])[1], fs) #Detect peaks with 'ma_perc' that goes with lowest rrsd
Now run and plot on the dataset (timed the entire algorithm so far including loading and preprocessing at about 151ms, single core performance on an i7-4790, so it’s still still pretty quick. Multithreading will speed this up a lot):
That is already a lot better. It’s not dropping any correct R-peaks, but there are still a few incorrect detections remaining, and there is also the part from 0 to about 5000 which contains little to no heart rate signal. We will come back to this noisy segment and see how to detect and exclude segments of noise in part 4.
For now let’s take out the noisy part at the beginning and see how we can detect and reject outliers.
Finding Incorrectly Detected Peaks
The last thing to look at is how to detect and reject abnormal peak positions. One way to do this is to make use of the fact that the heart rate changes gradually rather than abruptly. Your bpm for example will not skip from 60bpm to 120bpm in a single beat or vice versa, so let’s make use of that.
Again this means returning to RR-intervals. Remember that if a peak is skipped in the detection, or two peaks are marked in stead of one, the resulting RR-interval will be a lot larger or smaller than the average interval. We can set a threshold and mark intervals that exceed it, similar to how we detected the peaks. For the data I collect this is enough.
There is, however, one potential complication. If you analyze a very long signal at once, wherein the heart rate changes a lot over time, this can lead to incorrect rejections. Imagine a signal with a gradually increasing heart rate, starting from 60 bpm and ending at 180bpm. This means a steady trend of decreasing RR-intervals, which is indicative of the speeding up of the heart rate rather than mistakes in the detection of R-peaks. By using just thresholds based on the mean RR-interval, this will result in a rejection of the first and last portion of the signal. If this happens in your data you could detrend RR_list first. Using scipy.signal, this is easy:
from scipy import signal RR_list = measures['RR_list'] #First retrieve list from dictionary RR_list_detrended = signal.detrend(RR_list, type='linear')
However, if your signal contains a period of large increases followed by similarly large decreases in heart rate, you will need to employ other methods. The solution is beyond the scope of this tutorial series, but if you have this problem you may want to use a high pass filter with a very low cutoff frequency. Another way could be to split the signal in to smaller portions (so that the increase and decrease trends are separated), detrend linearly and average the measures. If the smaller portions are not of equal length, be sure to weight the measures before averaging.
Naturally, do not calculate any measures with the detrended RR-signal, only use it for the detection of errors in peak marking.
Back to outlier rejection. For the thresholds, in practice I’ve found a threshold level of the mean of RR-differences with a band of 250-300ms on both ends works well. Using the previous code and limiting the dataset to [5000:15000] (to exclude the noisy beginning for now), implement like so:
RR_list = measures['RR_list'] #Get measures peaklist = measures['peaklist'] ybeat = measures['ybeat'] upper_threshold = (np.mean(RR_list) + 300) #Set thresholds lower_threshold = (np.mean(RR_list) - 300) #detect outliers cnt = 0 removed_beats = [] removed_beats_y = [] RR2 = [] while cnt < len(RR_list): if (RR_list[cnt] < upper_threshold) and (RR_list[cnt] > lower_threshold): RR2.append(RR_list[cnt]) cnt += 1 else: removed_beats.append(peaklist[cnt]) removed_beats_y.append(ybeat[cnt]) cnt += 1 measures['RR_list_cor'] = RR2 #Append corrected RR-list to dictionary plt.subplot(211) plt.title('Marked Uncertain Peaks') plt.plot(dataset.hart, color='blue', alpha=0.6, label='heart rate signal') plt.plot(measures['rolmean'], color='green') plt.scatter(measures['peaklist'], measures['ybeat'], color='green') plt.scatter(removed_beats, removed_beats_y, color='red', label='Detection uncertain') plt.legend(framealpha=0.6, loc=4) plt.subplot(212) plt.title("RR-intervals with thresholds") plt.plot(RR_list) plt.axhline(y=upper_threshold, color='red') plt.axhline(y=lower_threshold, color='red') plt.show()
Resulting in:
It seems we got all the little buggers. The result is a plot with all correctly detected R-peaks marked green. The incorrect ones are marked red. The generated list measures[‘RR_list_cor’] has the RR-list without those belonging to incorrect peaks in it.
In part 4 we will look into how to mark and exclude noise segments and a few other optimizations.
Rounding up
Now tidy up all code, and also update some functions to accept new variables and insert the peak rejection function.
44 Comments
RobinJuly 17, 2017
Hi Paul,
Thank you for great tutorial. I have a question about filtering. I have a heart rate data in bmp. But there are unreasonably low and high values of 30 bmp and 200 bmp. Would you please suggest the appropriate filter to get rid of such values.
Paul van GentJuly 21, 2017
Hi Robin. Do you have more information about the data? Is it just BPM values? Or do you have raw data that you converted to BPM?
WadaaneJuly 21, 2017
Hello,
I’m a biomedical engineering student, and I’ve been following this tutorial.
I wanted to know if you abandoned the project and that you won’t publish the part 4.
Or if you posted it in another website.
Thank you, you’ve been so helpful.
Paul van GentJuly 21, 2017
Hi Wadaane. Definitely not abandoned! Please keep an eye on the project’s github:.
Once I’m past the present deadline drama at work (until about first week of august), I’ll finish the to-do list there first, then publish the tutorial shortly after.
BeckySeptember 7, 2017
I’m getting all ‘nan’ values back from the lfilter- will look into this in other places too but any idea on why that might be? It appears that the a and b values I’m getting back from butter are at least floats not ‘nan’s.
I also wondered about the message about pd.rolling_mean being deprecated – any reason not to move away from that?
Looking forward to part 4!!
Paul van GentSeptember 7, 2017
Hi Becky.
– Does your data passing through the filter contain NaN’s? I’m not 100% sure but I believe the filter does not tolerate it
– You can also check for filter instability
As fas ar the deprecation goes: once you feel you understand the code take a loot at the github implementation. I dropped all pandas dependencies for that. You can find a moving average function there.
BeckySeptember 11, 2017
Okay great, thank you!
AlexSeptember 16, 2017
Hi Paul,
Can I use the code provided in the blog post to extract feature from ECG signal? I have processed/downsampled ECG signal and all I want to do is to extract features. Could it be possible with code discussed?
Paul van GentSeptember 19, 2017
What are you referring to as “features”? You mean peak locations? Or something else?
AlexSeptember 19, 2017
rmssd, sdnn, sdsd etc.
Paul van GentSeptember 22, 2017
That is the main purpose of the algorithm.
RorySeptember 21, 2017
Hi Paul
Your tutorials have been a great help to me. I have recently come across a data set that has very high P waves. This causes lots of false positives. How would you suggest I approach this problem?
Paul van GentSeptember 22, 2017
Hi Rory. That depends. If the P-waves are (almost) as high as the R-waves, you might have a problem. If they’re smaller, however, a simple preprocessing ‘trick’ might be to cube the signal first (or use a higher power) to exaggerate the differences between the higher and less high waves.
Do you need all the features the algorithm extracts? A simple FFT of the signal might suffice if you need only the BPM.
RorySeptember 27, 2017
Yeah the P-waves are about just as high as the R-waves, so squaring does not really help me.
Also I have tried FFTs before, but I have a signal sampled at 1000Hz and at least 30min in length (we actually want to work with 24 hour data sets). That is just too much data and my computer freezes.
So at the moment I am looking at some non linear methods, like wavelet transforms.
Thanks for your input. I appreciate it.
Also in your algorithm. After you do the peak rejection. I think you should recalculate the RR-intervals, because at the moment you are just throwing away those portions of the data and if you have many rejected peaks, your overall data set length is reduced.
Paul van GentSeptember 27, 2017
You could also think about splitting your data: do FFT’s on smaller portions of data at a time and get the average for the 24 hour period. Wavelet transforms might also definitely be worth checking out, yes!
As for the peak rejection: the measures are calculated based on intervals between adjacent R-R pairs (so without rejected peak in between), which is not dependent on data set length. Recalculating the RR intervals would not affect this. However, if there are many rejected peaks, there is a chance that there is more error present in the calculated terms (after all, if in the end 50% of the peaks is used, that means 50% of the variance is not taken into account, which is risky especially for shorter time spans). An estimated quality measure for both the raw signal, as well as for the confidence of the calculated measures, will be implemented in the near future on the github.
And in part 4, if I ever get around to that….
RorySeptember 27, 2017
Hmmm yeah a windowed FFT. I’ll try that.
Okay I understand. Something you might want to do in part 4 is a kind of validation for your algorithm, where you can use annotated data sets from the PhysioNet database to check the performance of your algorithm.
Once again thanks for your input and I look forward to see what you do in part 4 if you ever get to it.
Paul van GentSeptember 27, 2017
Thanks, I’ve sent you a mail as well.
AlexSeptember 22, 2017
I am waiting for your respone
amulyaOctober 11, 2017
hi im trying to detect ecg from an eeg signal does the same hold good
Paul van GentOctober 12, 2017
Hi Amulya. As long as you can get a good signal-to-noise ratio, then sure! It doesn’t really matter where on the body you measure the ECG, as long as you separate a decent signal from the background noise.
EEG is relatively high frequency compared to normal resting heart rate, with maybe the exception of the Delta waves, which can cross into heart rate frequencies. As long as you have the EEG from an awake and alert individual you should be fine, and can likely filter the EEG frequencies (>4 Hz) out.
Let me know if you run into trouble.
-Paul
amulyaOctober 23, 2017
thanks paul
AleNovember 26, 2017
Hey, very cool tutorial! Are you planning to write the last section soon?
Paul van GentDecember 4, 2017
Hi Ale. I get this question a lot. Part 4 is actually written mostly. However, as part of my current PhD project I’m writing a paper about the finished algorithm (including an embedded C implementation). As soon as this is published, early 2018 I hope, everything goes online here as well as on Github!
AbhishekFebruary 27, 2018
Hi Paul. Great job on your project. Really helpful. I am currently doing a research project on a similar topic and have a small doubt. While calculating Time Domain features from the ECG data, should the time duration of the signal be the same or the number of peak points considered be the same? Any help from your side would be great.
Thanks!
Paul van GentFebruary 28, 2018
Hi Abhishek. Nice to hear from you. I’m not sure I understand the question completely, could you elaborate a little bit?
Also, what kind of project are you performing? I might have some extra tips :).
– Paul
AbhishekMarch 1, 2018
My project is regarding the association of HRV in Diabetic patients and its importance in Indian Traditional Medicine.
My question: I want to compare results (features) from 2 different devices (same sampling frequency) on 2 different datasets. For feature extraction (both time and frequency domain), should the time duration of the original signal (say 5 minutes ECG recording) be the same or the number of RR intervals (say 500 values) be the same?
Thanks for replying. Appreciate your help!
Paul van GentMarch 1, 2018
Hi Abhishek. That sounds super interesting, good luck!
I understand the question now, thanks. In this case I would compare signals of comparable time length, but make sure that if there is noise in one of the signals, you’re not comparing very few vs a lot R-R intervals. Some discrepancy there is fine, but as soon as for example you start to compare 25 RR vs 300 RR you’re in trouble.
To be honest I don’t think it matters an awful lot though. Are the heart rate signals time dependent (for example measured simultaneously with the two devices), or is it important to measure for N minutes after a treatment intervention? If not, you can get away with comparing reasonably similar signal lengths in stead of exactly similar.
Edit: Regarding frequency domain measures, make sure you use the version from my github. It has some improved stability fixes and speed-ups.
– Paul
AbhishekMarch 1, 2018
Okay. It’s a silly doubt but thanks for clarifying. I am using parametric PSD estimation. Let’s see how it goes. Thank you!
Paul van GentMarch 1, 2018
Keep me updated.
No worries, in data science silly doubts often make the difference! Good to think things through completely.
NITESH SINGH NITESH SINGHApril 15, 2018
sir can u please tell me how to take timer in data sheet
Paul van GentApril 23, 2018
I’m not sure what you mean. Do you have more details?
ParisMay 16, 2018
Dear Paul,
thank you for your tutorial, it really helped a lot.
A question: would you consider 145 an acceptable value for rmssd?
I am looking at hrv through ppg in my experiments, I have cubed the raw ppg signal to emphasise peaks, and i’ve increased the moving average by 10%. Still, for a few participants the hrv is around 120-150. The rest vary between 35 and 85 (which are considered acceptable, i think).
I’ve noticed that in participants for which I get these outliers, often i detect parts of their raw ppg signal where primary peaks and secondary peaks are not too far from eachother.
I’ve tried to power up the raw signal to even pow(rawSignal, 50), but that messes up the “reliable” participants.
Since the experiment has 2 conditions (stressful/non-stressful) maybe the outliers can help me detect the non-stressful conditions (where hrv should be higher).
What do you think?
Thanks again,
Paris
Paul van GentMay 17, 2018
Dear Paris,
You’re welcome! Take a look at the Github as well as it contains some more tweaks and fixes.
145 should not be a normal RMSSD value, from the top of my head I would not expect it to exceed 90-100. Are you seeing a lot of false positives in this case (non-peaks marked as peaks)? If you’re willing, please share a sample of your anomalous data with me so I can have a look: info@paulvangent.com
Before using the seemingly anomalous measures as deciding factors in your experiment, let’s have a look at it together to see nothing strange is going on :).
Cheers,
Paul
Carlo RafaelSeptember 15, 2018
Dear Paul,
Is it possible to “predict” bpm?
palkabSeptember 16, 2018
Hi Carlo. Yes and no. You need to give a little more context. What are you trying to achieve?
Carlo RafaelSeptember 22, 2018
can you create a model for predicting heart rate based on the past data?
palkabSeptember 22, 2018
Yes you can, but it will not be accurate. For example if I’m sitting on the couch and start running, how will the model know this? I’d say there are too many variables.
What are you trying to do it for?
Carlo RafaelSeptember 23, 2018
Nothing im just wondering
palkabSeptember 28, 2018
Alright. Well the answer is that you can predict almost anything, but you need to capture the relevant variance in order to do so. To make it less abstract: for heart rate you would for example probably also like to measure physical activity, maybe with an accelerometer, and use that as input for your model as well.
In a practical example: If I’m sitting on the couch and don’t move much then my heart rate is relatively stable, but as soon as I get up and start walking muy HR will increase as well. If you want to predict that, you need a way to capture me getting up and waking around as well so you can predict the HR increase.
Hope that answers your question.
– Paul
Carlo RafaelSeptember 29, 2018
Oh I see. Thanks paul. Uhm when will you release the part 4 of the tutorial paul ? I think it will really help me for my project thanks
palkabOctober 2, 2018
Hi Carlo. It depends on when publication of the papers I’ve written happens. I expect official approval within 10 days, so somewhere then it will come online. Most of part 4 is already written.
– Paul
Kevin JoseApril 9, 2019
Hi, I’m interested in your work. May I know whether is it possible to find blood pressure and oxygen saturation from heart rate values. If possible could you provide me with the mathematical relation between them or the code to find them?
palkabApril 17, 2019
Hi Kevin,
Yes there are ways to extract this from the PPG signal. Take a look at the paper here:
Cheers
Paul
ShaneJune 21, 2019
Dear Paul,
Thank you so much for what you’ve done, it’s a really useful tutorial for a new guy who’s going to learn DSP using Python. I’ve went through all three toturial and got the results like your image. But now I encourte a tough problem, when I use another group of data, I couldn’t fix it.
The problems I concluded such as 1. The new data is 250 Hz, which influence the choice of window size. Can I ask how to choose a suitable window size based on the frequency of a new group of data? 2. The new data has more noise and baseline drift, I tried use Butterworth bandpass filter ([0.5 Hz, 45Hz], order =(2,6)) to clean my data, but it looks like it didn’t work. Can I ask how to properly design a digital filter to remove baseline and noise? 3.The peak detection seems miss sereral point even these point above the moving average value, which imfluence the RR list colection and outlier rejection. I think the previous two problem highly influence the third problem.
I am looking forward to your reply.
Thank you for your time!
Best regards,
Shane
|
http://www.paulvangent.com/2016/03/30/analyzing-a-discrete-heart-rate-signal-using-python-part-3/?replytocom=120
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
4. Configuring Remote GPIO¶
GPIO Zero supports a number of different pin implementations (low-level pin libraries which deal with the GPIO pins directly). By default, the RPi.GPIO library is used (assuming it is installed on your system), but you can optionally specify one to use. For more information, see the API - Pins documentation page.
One of the pin libraries supported, pigpio, provides the ability to control GPIO pins remotely over the network, which means you can use GPIO Zero to control devices connected to a Raspberry Pi on the network. You can do this from another Raspberry Pi, or even from a PC.
See the Remote GPIO Recipes page for examples on how remote pins can be used.
4.1. Preparing the Raspberry Pi¶
If you’re using Raspbian (desktop - not Raspbian Lite) then you have everything you need to use the remote GPIO feature. If you’re using Raspbian Lite, or another distribution, you’ll need to install pigpio:
$ sudo apt install pigpio
Alternatively, pigpio is available from abyz.me.uk.
You’ll need to enable remote connections, and launch the pigpio daemon on the Raspberry Pi.
4.1.1. Enable remote connections¶
On the Raspbian desktop image, you can enable Remote GPIO in the Raspberry Pi configuration tool:
Alternatively, enter
sudo raspi-config on the command line, and enable
Remote GPIO. This is functionally equivalent to the desktop method.
This will allow remote connections (until disabled) when the pigpio daemon is launched using systemctl (see below). It will also launch the pigpio daemon for the current session. Therefore, nothing further is required for the current session, but after a reboot, a systemctl command will be required.
4.1.2. Command-line: systemctl¶
To automate running the daemon at boot time, run:
$ sudo systemctl enable pigpiod
To run the daemon once using systemctl, run:
$ sudo systemctl start pigpiod
4.1.3. Command-line: pigpiod¶
Another option is to launch the pigpio daemon manually:
$ sudo pigpiod
This is for single-session-use and will not persist after a reboot. However,
this method can be used to allow connections from a specific IP address, using
the
-n flag. For example:
$ sudo pigpiod -n localhost # allow localhost only $ sudo pigpiod -n 192.168.1.65 # allow 192.168.1.65 only $ sudo pigpiod -n localhost -n 192.168.1.65 # allow localhost and 192.168.1.65 only
Note
Note that running
sudo pigpiod will not honour the Remote GPIO
configuration setting (i.e. without the
-n flag it will allow remote
connections even if the remote setting is disabled), but
sudo systemctl
enable pigpiod or
sudo systemctl start pigpiod will not allow remote
connections unless configured accordingly.
4.2. Preparing the control computer¶
If the control computer (the computer you’re running your Python code from) is a Raspberry Pi running Raspbian (or a PC running Raspberry Pi Desktop x86), then you have everything you need. If you’re using another Linux distribution, Mac OS or Windows then you’ll need to install the pigpio Python library on the PC.
4.2.1. Raspberry Pi¶
First, update your repositories list:
$ sudo apt update
Then install GPIO Zero and the pigpio library for Python 3:
$ sudo apt install python3-gpiozero python3-pigpio
or Python 2:
$ sudo apt install python-gpiozero python-pigpio
Alternatively, install with pip:
$ sudo pip3 install gpiozero pigpio
or for Python 2:
$ sudo pip install gpiozero pigpio
4.2.2. Linux¶
First, update your distribution’s repositories list. For example:
$ sudo apt update
Then install pip for Python 3:
$ sudo apt install python3-pip
or Python 2:
$ sudo apt install python-pip
(Alternatively, install pip with get-pip.)
Next, install GPIO Zero and pigpio for Python 3:
$ sudo pip3 install gpiozero pigpio
or Python 2:
$ sudo pip install gpiozero pigpio
4.2.3. Mac OS¶
First, install pip. If you installed Python 3 using brew, you will already have pip. If not, install pip with get-pip.
Next, install GPIO Zero and pigpio with pip:
$ pip3 install gpiozero pigpio
Or for Python 2:
$ pip install gpiozero pigpio
4.2.4. Windows¶
Modern Python installers for Windows bundle pip with Python. If pip is not installed, you can follow this guide. Next, install GPIO Zero and pigpio with pip:
C:\Users\user1> pip install gpiozero pigpio
4.3. Environment variables¶
The simplest way to use devices with remote pins is to set the
PIGPIO_ADDR environment variable to the IP address of the desired
Raspberry Pi. You must run your Python script or launch your development
environment with the environment variable set using the command line. For
example, one of the following:
$ PIGPIO_ADDR=192.168.1.3 python3 hello.py $ PIGPIO_ADDR=192.168.1.3 python3 $ PIGPIO_ADDR=192.168.1.3 ipython3 $ PIGPIO_ADDR=192.168.1.3 idle3 &
If you are running this from a PC (not a Raspberry Pi) with gpiozero and the
pigpio Python library installed, this will work with no further
configuration. However, if you are running this from a Raspberry Pi, you will
also need to ensure the default pin factory is set to
PiGPIOFactory. If RPi.GPIO is installed,
this will be selected as the default pin factory, so either uninstall it, or
use the
GPIOZERO_PIN_FACTORY environment variable to override it:
$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.3 python3 hello.py
This usage will set the pin factory to
PiGPIOFactory with a default host of
192.168.1.3. The pin factory can be changed inline in the code, as seen in
the following sections.
With this usage, you can write gpiozero code like you would on a Raspberry Pi, with no modifications needed. For example:
from gpiozero import LED from time import sleep red = LED(17) while True: red.on() sleep(1) red.off() sleep(1)
When run with:
$ PIGPIO_ADDR=192.168.1.3 python3 led.py
will flash the LED connected to pin 17 of the Raspberry Pi with the IP address
192.168.1.3. And:
$ PIGPIO_ADDR=192.168.1.4 python3 led.py
will flash the LED connected to pin 17 of the Raspberry Pi with the IP address
192.168.1.4, without any code changes, as long as the Raspberry Pi has the
pigpio daemon running..
4.4. Pin factories¶
An alternative (or additional) method of configuring gpiozero objects to use
remote pins is to create instances of
PiGPIOFactory objects, and use them when
instantiating device objects. For example, with no environment variables set:
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep factory = PiGPIOFactory(host='192.168.1.3') led = LED(17, pin_factory=factory) while True: led.on() sleep(1) led.off() sleep(1)
This allows devices on multiple Raspberry Pis to be used in the same script:, pin_factory=factory3) led_2 = LED(17, pin_factory=factory4) while True: led_1.on() led_2.off() sleep(1) led_1.off() led_2.on() sleep(1)
You can, of course, continue to create gpiozero device objects as normal, and create others using remote pins. For example, if run on a Raspberry Pi, the following script will flash an LED on the controller Pi, and also on another Pi on the network:
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep remote_factory = PiGPIOFactory(host='192.168.1.3') led_1 = LED(17) # local pin led_2 = LED(17, pin_factory=remote_factory) # remote pin while True: led_1.on() led_2.off() sleep(1) led_1.off() led_2.on() sleep(1)
Alternatively, when run with the environment variables
GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.3 set, the following
script will behave exactly the same as the previous one:
from gpiozero import LED from gpiozero.pins.rpigpio import RPiGPIOFactory from time import sleep local_factory = RPiGPIOFactory() led_1 = LED(17, pin_factory=local_factory) # local pin led_2 = LED(17) # remote pin while True: led_1.on() led_2.off() sleep(1) led_1.off() led_2.on() sleep(1)
Of course, multiple IP addresses can be used:) # local pin led_2 = LED(17, pin_factory=factory3) # remote pin on one pi led_3 = LED(17, pin_factory=factory4) # remote pin on another pi while True: led_1.on() led_2.off() led_3.on() sleep(1) led_1.off() led_2.on() led_3.off() sleep(1)
Note that these examples use the
LED class, which takes a pin
argument to initialise. Some classes, particularly those representing HATs and
other add-on boards, do not require their pin numbers to be specified. However,
it is still possible to use remote pins with these devices, either using
environment variables, or the pin_factory keyword argument:
import gpiozero from gpiozero import TrafficHat from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep gpiozero.Device.pin_factory = PiGPIOFactory(host='192.168.1.3') th = TrafficHat() # traffic hat on 192.168.1.3 using remote pins
This also allows you to swap between two IP addresses and create instances of multiple HATs connected to different Pis:
import gpiozero from gpiozero import TrafficHat from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep remote_factory = PiGPIOFactory(host='192.168.1.3') th_1 = TrafficHat() # traffic hat using local pins th_2 = TrafficHat(pin_factory=remote_factory) # traffic hat on 192.168.1.3 using remote pins
You could even use a HAT which is not supported by GPIO Zero (such as the Sense HAT) on one Pi, and use remote pins to control another over the network:
from gpiozero import MotionSensor from gpiozero.pins.pigpio import PiGPIOFactory from sense_hat import SenseHat remote_factory = PiGPIOFactory(host='192.198.1.4') pir = MotionSensor(4, pin_factory=remote_factory) # remote motion sensor sense = SenseHat() # local sense hat while True: pir.wait_for_motion() sense.show_message(sense.temperature)
Note that in this case, the Sense HAT code must be run locally, and the GPIO remotely.
4.5. Remote GPIO usage¶
Continue to:
|
https://gpiozero.readthedocs.io/en/master/remote_gpio.html
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
Welcome to the Parallax Discussion Forums, sign-up to participate.
binfile(fname): send a binary file to the P2 pauseafter(N): insert a 1ms pause after every N characters transmitted pausems(N): delay for N milliseconds recv(string): wait until string is received recvtimeout(N): set a timeout in ms for the recv() command scriptfile(fname): read script commands from file "fname" send(string): send a string to the P2 textfile(fname): send contents of a text file to the P2
loadp2 -b230400 -xTAQOZ -e "recv(TAQOZ# ) send{2 2 + . ^M}" -tThe script waits for the P2 to send the string "TAQOZ#", then sends "2 2 + ." and a carriage return (ctrl-M).
loadp2 -b230400 upython.binary -e "recv(>>> ) send(^E) textfile{myfile.py} send(^D)" -tThat script waits for the P2 to send the >>> sequence which is its prompt, then sends a ctrl-E (to enter paste mode), then sends the contents of the file "myfile.py", then sends a ctrl-D (to exit paste mode).
Can the delay time be made variable ?
A means to toggle DTR & RTS could be useful ? (in UB3, RTS reloads the Si5351A, and currently increments the upper control reply bits)
Can the script be contained in a file ? I see a send-file, but not a run file as script ?
That'll reset the chip on most P2 boards, so sounds dangerous.
No, for now the script is self contained. I guess having an option to run it from a file would be feasible. I'm not trying to solve every scripting problem here, just providing a simple way to get scripts to run in TAQOZ, micropython, and proplisp.
Thanks for the suggestions!
micropython takes up most of the P2, although my version does leave the debug area at the top of HUB ram free. Invoking it from another COG is probably possible. ozpropdev did some interesting things with running other programs alongside micropython.
My changes have mostly been in the platform independent code, and don't generally care what kind of transport is used underneath. I don't think it would be difficult to put all of this over a network instead of the serial layer, but obviously there would be some work involved on both the hardware and software sides.
When testing using TAQOZ I found it very useful to save such script files, as easy to read names, (done for the terminal pgm I use), and those include variable delays.
The flip to TAQOZ takes a finite amount of time
Here is an example of one of those tests, shows how useful terminal scripts can be...
{// is a comment, and {250} is a delay of 250ms {5} is a delay of 5ms strings inside quotes send directly, $ is hex prefix.
Some named files like this, would give users a quick series of board check operations than can do.
I copied the new loadp2 into the flexgui bin directory.
I also copied upython.py from \samples\upython\ to here as well, plus I added myfile.py which is just a single line "print('hello')"
I am on W10 and here is what I get from the command line... What did I break?
This is brilliant
Also, you probably don't strictly have to wait for the >>> prompt, there is some buffering going on and I think you could leave off the "^/>>>/" part of the script (that's the script command which waits for the prompt).
BTW I note when you exit from the >>> prompt in the command line, the terminal is left in an unusable state which means I cannot now do any more loadp2, etc. Is this fixable?
Currently I am trying to run this but I get caught up in what I think is loadp2 resetting the P2 and I have an SD Card in the slot causing the ROM to try and boot the P2. Have to step out so I will try this again when I get home.
Usually the loadp2 times out with no >>> received.
When it works, I get the os.mount(sd,'/sd') failing as below (note the sd.present() works fine).
Is the sd already mounted? I have noticed that os.mount(sd, '/sd') causes a whole lot of grief if /sd is already mounted, but if I do os.mount(sd, '/mysd') then micropython is happy and actually creates two different views of the SD card (/sd and /mysd).
After the script times out you should still be able to type commands at micropython. Is the ls function defined?
I think I need to step back and look at this some more. Perhaps a better approach would be to (optionally) have loadp2 listen on a socket for commands of things to send to the terminal and/or things to do such as resetting the board. Then it would be easy to have GUIs send scripts to the P2 at any point (as long as loadp2 is still running).
I haven’t tried entering any python after the failure. But I don’t think it’s already mounted as I retried this a number of times with everything starting from scratch and powering up the P2. Once I power the P2 I insert the SD card and then run the loadp2 command.
As to whether it’s the right approach, I don’t know.
What I would like is to launch python from the P2 from my OS ie run the upython binary from the P2. But this requires my P2 OS and I haven’t had time to get this running by recompiling the P1 spin code to p2asm yet. I’ve been hoping Chip might release a limited version of spin2 as it would be so much easier.
Have you tried fastspin? It does support compiling Spin1 on the P2.
Sorry, yes, "for" the P2. And maybe @Cluso99 is waiting for Chip's Spin2 so he can compile "on" the P2 using his OS? But I don't think the initial Spin2 release will support that.
It'll certainly be interesting to see what Chip comes up with. But in the meantime it is still possible to program the P2 in Spin.
I'm not sure how the spin1 to P2ASM would work. I haven't had time to try yet. My OS stays partially resident so there are a few gotchas that I need to rework, and I need to get Kye's spin FAT32 code converted. I've done but not tested the SD pasm driver. That was weeks ago
There is always something better to do when I get a chance - such as trying uPython.
Huh, I had forgotten that I ever did binary releases of loadp2. I guess I can do a new one, but loadp2 is still in flux. For now I suggest you use the loadp2.exe from the .zip file earlier in this thread -- it's based on the newest sources.
So, I downloaded latest FlexGUI and can't get it to load flash or RAM.
This is with my own board, so maybe that's an issue, but I don't think so.
Strange thing about this is that with SpinEdit, I can load RAM just fine using your Fastspin and loadp2.
Also, the Taqoz stuff seems to work in FlexGUI.
But, when trying to load RAM or Flash, I get:
Any idea what I might be doing wrong?
Does your board use the standard protocol for reset, using DTR/RTS? loadp2 resets the board then downloads a small helper program, which then changes the clock mode and frequency to do a fast download.
Hmmm, maybe that's the trouble; how is the clock set up on your board?
I think my clock and FTDI is exactly the same as Eval board...
I'll try a direct connection...
That didn't help...
That might slow it down a bit...
What baud is it trying to do?
Also, I have the FTDI I/O at 5V instead of 3.3 V...
This is what I get in verbose mode:
Works at 921600 too...
|
http://forums.parallax.com/discussion/comment/1483733/
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
Create-react-app with VS Code
Thibaud Ducasse
Updated on
・8 min read
Set up a basic React development environment using create-react-app and VS Code
Requirements
Note: I uploaded the final code on GitHub.
Create a new project using create-react-app
create-react-app provides a very easy way to generate a React app in seconds. This is currently developed by Facebook, and the recommended way to start a new project.
Open a terminal and go to the desired folder (create-react-app will create a folder for your app).
cd ~/Projects # this is my projects folder npx create-react-app my-app # replace `my-app` with the name of your app cd myapp npm start
You should see something like this:
Folder structure
The script will generate a few files, and it should look something like this:
Let's have a look at what's been created:
package.json: This file is related to npm. It holds our dependencies (the libraries you want to be able to use in your code). You can also describe your application, add useful scripts in order to automate common tasks, such as running tests, starting a server, deploying, etc.
package-lock.json: This is auto-generated by npm every time you add a new dependency. You should never have to touch it, and it is good practice to commit it to your repository.
.gitignore: When you commit files to a git repository, git will (by default) want to add every file that's in your project. But sometimes you might want to exclude a file, and
.gitignoreis exactlly that. By default, create-react-app excludes
node_modulesfor example, which is the folder containing all our dependencies. Since we are going to commit
package.jsonand
package-lock.jsonanyway, there is no need at all to commit them (plus they are super heavy).
publicfolder: This is where we find the root of our application,
index.html, and our favicon,
favicon.ico.
srcfolder: Our app folder. This is where our code lives, and where we are going to spend 98% of our time.
Let's have a look at the code
First, let's go to
index.html, and have a look at this line:
... <body> <noscript>You need to enable JavaScript to run this app.</noscript> // the next line <div id="root"></div> ...
This will be the HTML element to which the React application will be attached.
index.js is the first file that will be loaded in our application.
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; // the next line ReactDOM.render(<App />, document.getElementById('root'));
This line is the one that actually links our React app to the DOM (
root node, as we've seen just before).
// the two next lines import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root'));
These two first lines are everything that's necessary to write React code.
import React from 'react'; import ReactDOM from 'react-dom'; // the two next lines import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root'));
These ones are just importing our React components (here
App), and our CSS files.
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; // the next line import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root'));
This last line is used only if you are writing a PWA (Progressive Web App, more on this here). Yes, create-react-app is already configured as a PWA!
So what is this
App.js doing? Let's have a look:;
At the beginning, you can see the standard
import React from 'react' that you need to include in every file that uses
jsx (this cool HTML-like syntax that we use to write React components).
You may have noticed that we import a file called
App.css.
Open it, and look at what's written here:
.App { text-align: center; } .App-logo { animation: App-logo-spin infinite 20s linear; height: 40vmin; pointer-events: none; } ); } }
I'm not going to spend too much time on this, but let's take the example of the first class:
.App { text-align: center; }
And let's see how we use it in a React component:
function App() { return ( // the next line > ); }
As you can see, the main difference with "normal" HTML is that the name of the attribute is
className, instead of
class.
Configuring VS Code
Enough about
create-react-app and the code it generated, it's time to configure our code editor.
VS Code has pretty good defaults (syntax highlighting, autocompletion, 'go to definition', etc). But you can make it even better!
ESlint
Since JavaScript is not a compiled language, there is nothing that can tell us if something looks like it's going to fail before we actually run it. ESLint solves exactly this problem.
ESLint is the most popular JavaScript linter. A linter is a program that analyses your code, and tries to find potential errors, ahead of runtime. ESLint is highly configurable, and you can extend premade sets of rules, define your own rules, override existing rules, etc.
Luckily, create-react-app already comes with ESlint. So we don't have much to do!
Install the ESLint extension for VS Code. This will allow us to see the result of ESLint directly in VS Code.
Once installed, you can quickly test it. Go to
App.js again, and remove this line:
<a className="App-link" href="" target="_blank" // the next line
VS Code should start yelling at you:
Prettier
Prettier is an opinionated code formatter. People used to fight for hours around commas, semi-colons, etc. Prettier is an attempt at ending the debate. Since most editors have a Prettier plugin, you can "autoformat on save", which means you can write ugly code, and never worry about formatting!
You can use Prettier in different ways. My favorite one is to run it as part of the ESLint rules.
First, install the Prettier dependencies:
npm i -D prettier eslint-config-prettier eslint-plugin-prettier
Then, create a file, at the root of your app, called
.eslintrc.json as such:
{ "extends": [ "react-app", "prettier", "prettier/react" ], "plugins": [ "prettier" ], "rules": { "prettier/prettier": "error" } }
So what have we done?
eslint-config-prettieris a package that allows us to disable the rules that would conflict with the rules defined by Prettier.
eslint-plugin-prettieris the one that allows to run Prettier as an ESLint rule.
If you have a look at the
.eslintrc.json file that we just created, you'll notice that we have added a rule that basically says "everything that Prettier reports should be treated as an error".
Once everything is saved, go back to
App.js and have a look at what ESLint is saying now:
Autoformatting
So this is all good, now we see what's wrong about our code, but wouldn't it be nice if we could just fix everything automatically? Replacing double quotes with single quotes should be pretty straightforward for a computer, right?
ESLint has an option to autofix every error that can be autofixed. On the command-line, it's
--fix, and you can configure your VS Code so that this happens everytime you save.
Create a new folder, at the root of your app, called
.vscode, and inside this folder, a file called
settings.json:
{ "eslint.autoFixOnSave": true }
Go back to
App.js, and try saving your file now, it should get reformatted instantly!
Precommit hook
So now that we have linting and formatting all sorted, what happens if someone decides to contribute to our code without setting up everything we just set up? It will break everything, and you will be back to coding-style hell. So what can we do about it?
Two packages will help us with that:
- husky gives us a really easy way to set up git hooks.
- lint-staged will lint the files that are ready to be committed.
First, install them with:
npm i -D lint-staged husky
Go to your
package.json and add:
"lint-staged": { "**/*.js": [ "eslint --fix", "git add" ] }, "husky": { "hooks": { "pre-commit": "lint-staged" } }
And you're done! Now, every time you will try to commit unformatted files,
husky will launch
lint-staged, which will intercept the process and run ESLint first. And if there's an error ESLint can't fix, it will stop the whole process. Which means you can't commit code that doesn't work anymore!
Absolute imports
It is very common in a React project to organise your code in multiple nested folders.
Let's say we decide to implement something like Brad Frost's atomic design for example. A common way to implement it would be (this example is on GitHub):
App.js would import the
LoginPage template like this:
import React from "react"; // the next line import LoginPage from "./components/templates/LoginPage"; function App() { return ( <div style={{ padding: 20 }}> <LoginPage /> </div> ); } export default App;
This is all good! But now, if you go to
LoginPage.js, and have a look at how we have to import
LoginPassword:
import React, { useState } from "react"; // the next line import LoginPassword from "../organisms/LoginPassword"; const LoginPage = props => { return ( <> <LoginPassword /> </> ); }; export default LoginPage;
Notice the
../ to go up a folder? This will become really hard to follow once we start deeply nesting folders and files.
A good solution for that is something called absolute imports. At the root of your app, create a file called
jsconfig.json:
{ "compilerOptions": { "baseUrl": "./src/" }, "include": [ "src" ] }
Now you can import your files using an absolute path, starting from
./src/:
import React from "react"; // the next line import LoginPassword from "components/organisms/LoginPassword"; const LoginPage = () => { return ( <> <LoginPassword /> </> ); }; export default LoginPage;
While it might not seem like a big deal right now, because we only have one level of nesting, big applications tend to have very deeply nested components, which makes imports look like
../../../../MyComponentFolder/MyComponent very quickly!
Find the final code on GitHub.
🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained
In the next post we are going to explore CSS @apply to supercharge what we talk about here....
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/tducasse/create-react-app-with-vs-code-22j8
|
CC-MAIN-2020-24
|
en
|
refinedweb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.