text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringclasses 91
values | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
|---|---|---|---|---|---|
Building JavaScript Demos With TypeScript 2.2.1, Webpack 2, And Angular 2.4.9
CAUTION: This is the first time that I've used Webpack and I am in no way a Webpack expert. Actually, I'm barely a novice. This is just me trying to get my GitHub-based demo workflow to run using Webpack - the scope of this is no larger than that. In fact, this covers less than the Webpack intro in the Angular 2 documentation. This entire post is basically just a NOTE TO SELF.
Over the last few weeks, I've been evolving the way in which I develop my GitHub-based JavaScript demos. Once I learned that the System.js TypeScript plugin was dropping support for in-browser type-checking, I learned out how to use the TypeScript compiler to perform type-checking offline. But, once I decided to take the compilation process offline, I figured I might as well take my workflow one step further and start using Webpack 2 to bundle my files. After all, if I'm already using an offline build process, I might as well reduce the number (and size) of the files that I need to load. This post represents my novice approach to getting Webpack 2 to power by GitHub-based Angular 2 and JavaScript demos.
Run this demo in my JavaScript Demos project on GitHub.
As with the vast majority of my JavaScript demos, I keep the vendor files in a shared folder location so that they can be used by multiple demos. Of course, once I start compiling and bundling files offline for the GitHub demos, the use of shared files becomes somewhat less meaningful; however, I still want to reduce the number of raw source files that I have to check into GitHub. So, for my Webpack 2 exploration, I am continuing to keep my package.json file in a separate vendor folder:
/vendor/angular2/2.4.9-webpack/package.json
- {
- "name": "angular2-v2-4-9-webpack",
- "version": "2.4.9-webpack",
- "license": "ISC",
- "dependencies": {
- "@angular/common": "2.4.9",
- "@angular/compiler": "2.4.9",
- "@angular/core": "2.4.9",
- "@angular/forms": "2.4.9",
- "@angular/http": "2.4.9",
- "@angular/platform-browser": "2.4.9",
- "@angular/platform-browser-dynamic": "2.4.9",
- "@angular/router": "3.4.9",
- "@types/lodash": "4.14.57",
- "@types/node": "7.0.11",
- "angular2-template-loader": "0.6.2",
- "core-js": "2.4.1",
- "html-webpack-plugin": "2.28.0",
- "lodash": "4.17.4",
- "raw-loader": "0.5.1",
- "reflect-metadata": "0.1.10",
- "rxjs": "5.2.0",
- "systemjs": "0.20.10",
- "ts-loader": "2.0.2",
- "typescript": "2.2.1",
- "web-animations-js": "2.2.2",
- "webpack": "2.2.1",
- "zone.js": "0.8.4"
- }
- }
This is the minimum number of dependencies that I believe I need in order to get Angular 2 and Webpack 2 playing nicely together. I won't necessarily use all of these libraries in every demo (for example, not all Angular 2 demos need the Router); but, this should give me a small but flexible base from which to start exploring.
Once I start using Webpack 2, I am no longer going to be calling the TypeScript compiler directly. Instead, Webpack 2 will invoke the TypeScript compiler for me using the ts-loader loader. Of course, ts-loader still needs to know how to transpile the TypeScript source files; so, I am still providing a tsconfig.json file in my demo folder:
/demos/webpack-angular2/tsconfig.json
- {
- "compilerOptions": {
- "baseUrl": "../../vendor/angular2/2.4.9-webpack/node_modules/",
- "emitDecoratorMetadata": true,
- "experimentalDecorators": true,
- "lib": [
- "DOM",
- "ES6"
- ],
- "module": "commonjs",
- "moduleResolution": "node",
- "noImplicitAny": true,
- "paths": {
- "lodash": [
- "@types/lodash"
- ]
- },
- "pretty": true,
- "removeComments": false,
- "sourceMap": true,
- "suppressImplicitAnyIndexErrors": true,
- "target": "es5",
- "typeRoots": [
- "../../vendor/angular2/2.4.9-webpack/node_modules/@types/"
- ],
- "types": [
- "node"
- ]
- }
- }
Because my vendor files are not contained directly within my individual demo folders, I have to tell TypeScript how to resolve imports. As such, I have to provide typeRoots and a baseUrl so that the TypeScript compiler knows where to locate modules. This way, when I import lodash, for example, it knows where to find the type definition file for lodash (in this case, using the "paths" property) so that it can validate my consumption of lodash.
NOTE: If your node_modules folder is in the same folder as your Webpack 2 config, some of this configuration becomes unnecessary as the node_modules folder would be in an "expected" location and modules will be resolved naturally.
Tranpsiling and type-checking TypeScript is only half the battle. If you've ever looked at my earlier Angular 2 demos, you'll see that they make - literally - hundres of network requests to load source files and type defintion files (*.d.ts) for in-browser type-checking and transpilation. All of those files are still necessary for the demo; only, with an offline build process, we can drastically reduce the number of requests made over the wire. Instead of making hundreds of requests, we can bundle common files together:
- Webpack 2 runtime - This is the code that wires all of the dependencies together during application execution.
- Polyfill - This is the code that fills in any holes with the Browser's adherence to modern JavaScript Standards.
- Vendor - This is the 3rd-party code that we're consuming in the application.
- App - This is the actual custom application code and I am writing.
NOTE: Type definition files are not included in these bundles since they are only consumed during the transpiling process - once the TypeScript compiler runs offline, the type definition files are no longer needed at runtime.
These groups don't actually have to be four separate files - we could create just one giant bundle. However, what we're trying to do here is isolate the parts of the code that change for different reasons. For example, the Webpack 2 runtime will probably never change (unless we upgrade Webpack); and, the polyfills won't change until we change our browser support or new browsers are released; vendor code will change only as we include or remove 3rd-party libraries; and, our app code will change with every single change to our application logic.
By compiling these four groups down into different bundles, it allows us to provide more granular caching mechanisms. For my GitHub demos this doesn't really matter much since the demos don't evolve over time. But, for a production application, it would be great for the vendor filename to remain the same across builds so that the user only has to download the latest application code and not re-download the same vendor code over and over again.
Of course, Webpack doesn't know the difference between app code and vendor code and polyfill code - this separation has to be defined in the Webpack configuration file in terms of "entry" files. Here's the configuration file that I'm using for my GitHub demos:
/demos/webpack-angular2/webpack.config.js
- // Load the core node modules.
- var HtmlWebpackPlugin = require( "../../vendor/angular2/2.4.9-webpack/node_modules/html-webpack-plugin" );
- var webpack = require( "../../vendor/angular2/2.4.9-webpack/node_modules/webpack" );
- module.exports = {
- // I am going to generate 3 separate JavaScript files (that the HtmlWebpackPlugin
- // will automatically inject into my HTML template). Creating three files helps me
- // isolate the parts of the code that change often (my code) from the parts of the
- // code that change infrequently (the vendor code).
- entry: {
- polyfill: "./app/main.polyfill.ts",
- vendor: "./app/main.vendor.ts",
- main: "./app/main.ts"
- },
- // In normal development, I might use "[name].[chunkhash].js"; however, since this
- // is just getting committed to GitHub, I don't want to create a new hash-based file
- // for every file-save event. Instead, I can use the "hash" option in the
- // HtmlWebpackPlugin to help with cache-busting per build.
- output: {
- filename: "[name].js",
- path: "./build"
- },
- resolve: {
- extensions: [ ".ts", ".js" ],
- // Tell Webpack to use my shared vendor folder when resolving modules that it
- // finds in "import" statements.
- modules: [
- "../../vendor/angular2/2.4.9-webpack/node_modules/"
- ]
- },
- resolveLoader: {
- // Tell Webpack to use my shared vendor folder when resolving loaders that it
- // finds in this config (ex, "ts-loader") (or in inline references, I suppose).
- modules: [
- "../../vendor/angular2/2.4.9-webpack/node_modules/"
- ]
- },
- module: {
- rules: [
- {
- test: /\.ts$/,
- loaders: [
- // I compile the TypeScript content into ES5 JavaScript. In addition
- // to transpiling the code, it is also running type-checks based on
- // the tsconfig.json file.
- "ts-loader",
- // Given the transpiled code, I convert Template and Style URL
- // references into require() statements that will subsequently get
- // consumed by the raw-loader.
- // --
- // NOTE: Do not include the "keepUrl=true" that is in some examples;
- // that inlines the content, but does not replace the property name
- // used in the component meta-data.
- "angular2-template-loader"
- ]
- },
- // When the "angualr2-template-loader" runs, it will replace the @Component()
- // "templateUrl" and "styleUrls" with inline "require()" calls. As such, we
- // need the raw-loader so that require() will know how to load .htm and .css
- // file as plain-text.
- {
- test: /\.(htm|css)$/,
- loader: "raw-loader"
- }
- ]
- },
- plugins: [
- // I move common references in the Entry files down into the lowest-common entry
- // file in this list.
- // --
- // CAUTION: The order of these chunk names has to be in the REVERSE order of the
- // order in which you intent to include them in the Browser. I believe, but am not
- // sure, that this is because common dependencies are moved to the next file down
- // in this list. So, if "main" and "vendor" have things in common, they will be
- // moved down to "vendor". Were the order reversed, with "vendor" above "main",
- // then common dependencies would be moved down to "main" (which is what we want
- // to avoid).
- new webpack.optimize.CommonsChunkPlugin({
- names: [
- "main",
- "vendor",
- "polyfill",
- // Extract the Webpack bootstrap logic into its own file by providing a
- // name that wasn't listed in the "entry" file list.
- // --
- // NOTE: I don't really need this for my kind of GitHub based development;
- // but, this seems to be a common pattern as it moves frequently changing
- // code out of the "vendor" file.
- "manifest"
- ]
- }),
- //",
- // This will append a unique query-string hash (for cache busting) to the
- // injected files after each build. All files get the same hash, which makes
- // this DIFFERENT from using the "chunkhash" in the "output" config.
- hash: true
- }),
- // I compact the JavaScript content.
- new webpack.optimize.UglifyJsPlugin({
- keep_fnames: true
- })
- ]
- };
The first thing you may notice here is the long file paths. Again, since my vendor files are stored in a shared folder location, I have to tell Webpack how to resolve both module names and Webpack Loader names. For example, when I tell Webpack to use "ts-loader" to compile the imported *.ts files, Webpack has to know to go up two directories and down into the shared vendor folder in order to figure out what "ts-loader" is. If your node_modules folder is in the same directory as your Webpack config, most of this pathing becomes unnecessary since Webpack uses node's module resolution strategy (with some additional logic wrapped around it).
The "entry" files tell Webpack which bundles to create. It does this by opening those files, creating a dependency graph of imports, and then bundling all the dependencies into a single file. On its own, this doesn't really get us what we want because all of the "vendor" files get doubly-bundled into the main app file as well. This is because Webpack doesn't know that it should separate-out common dependencies - that's what the CommonsChunkPlugin does: it takes common dependencies from 2 or more dependency graphs and moves them to just one of the emitted files.
The order of the files in the CommonsChunkPlugin has to be in the reverse order of the way in which those files need to be included in the HTML page. This is because (I believe) the CommonsChunkPlugin will move common dependencies down that list. As such, you want your more "vendory" files at the bottom so that they contain all the common dependencies as they [the dependencies] get dragged down that list.
Once these various entry files have been emitted by the compilation process, the HtmlWebpackPlugin will then auto-inject them as Script tags into the given HTML template. To keep things simple, all of my entry files - including the main HTML page - are just variations of the "main" script:
- main.ts
- main.vendor.ts
- main.polyfill.ts
- main.htm
These all get compiled down into the "output" directory, "./build", with the exception of the "main.htm" which we want to store in the root of the demo, so the browser knows where to find it. The main.htm gets moved up a directory - from the build directory - because the filename provided to the HtmlWebpackPlugin contains a "../" relative path traversal.
While our main.ts file contains imports of our app modules, the main.vendor.ts and main.polyfill.ts are a little different; they are essentially a list of unconsumed imports to the files that we want to include in the various bundles. For example, here's my polyfill file:
- // Import these libraries for their side-effects.
- import "core-js/client/shim.min.js";
- import "zone.js/dist/zone.js";
- import "reflect-metadata/Reflect.js";
- // Load the Web Animations API polyfill for most browsers (basically any browser other than Chrome and Firefox).
- // import "web-animations-js/web-animations.min.js";
And, here's my vendor file:
- // Import these libraries for their side-effects.
- // --
- // CAUTION: As you add more "import" statements to your application code, you will have
- // to come back to this file and add those imports here as well (otherwise that imported
- // content may get bundled with your main application bundle, not your vendor bundle.
- import "@angular/core";
- import "@angular/platform-browser-dynamic";
- import "lodash";
- import "rxjs/add/observable/of";
- import "rxjs/Observable";
As you can see, I'm not actually consuming these imports - I'm just defining them. On its own, this will tell Webpack to bundle the various imports into each one of the resultant entry files. And, when used in conjunction with the CommonsChunkPlugin, it will ensure that common imports only get included in one of the entry files (based on the order of the files defined in the CommonsChunkPlugin configuration).
In the vendor file, I'm only including the imports that I actually use in the app. For example, I'm not including "@angular/router" here because my demo app doesn't use routing. This is the tricky thing about these common dependencies - as you add new dependencies to your main application, you have to remember to come back and update the vendor file so that those new dependencies don't accidentally get bundled into the main application bundle. I am not sure if there is some "Webpack way" to help ensure that this doesn't happen? Or, if this is just a matter of process and it's up to you, as the developer, to keep it locked down?
NOTE: If you forget to update your vendor file, nothing will "break" - it just means the new "vendor dependency" will get bundled into the "main" entry file rather than extracted by the CommonsChunkPlugin.
To test all of this, I created a simple hello-world type demo that included RxJS and Lodash (to test my dependencies):
- // Import the core angular services.
- import { Component } from "@angular/core";
- import { Observable } from "rxjs/Observable";
- import * as _ from "lodash";
- // Import these modules to create side-effects.
- import "rxjs/add/observable/of";
- @Component({
- selector: "my-app",
- styleUrls: [ "./app.component.css" ],
- templateUrl: "./app.component.htm"
- })
- export class AppComponent {
- public movies: Observable<string[]>;
- // I initialize the app component.
- constructor() {
- // NOTE: Neither the use of an RxJS stream nor the use of Lodash makes any real
- // sense in this scenario; I'm only using these libraries in order to ensure that
- // the imports work and result in the proper Vendor bundles.
- this.movies = Observable.of(
- _.map(
- [
- "Conversations with Other Women",
- "Planet of the Apes",
- "Fight Club",
- "The Theory of Flight"
- ],
- ( movie: string ) : string => {
- return( movie + "." );
- }
- )
- );
- }
- }
Technically, I don't actually need this line in the module:
import "rxjs/add/observable/of";
... because this line is only needed for a side-effect (to modify the Observable class) and is already being executed in my main.vendor.ts file. That said, it is important that I include it here as both a self-documenting feature and as one that can be used outside of my Webpack build process (where there may not be a main.vendor.ts file that already executes said import).
Here is the root components template, defined in the @Component() meta-data and inlined by the "angular2-template-loader" loader:
- <p>
- Best <strong>Helena Bonham Carter</strong> movies:
- </p>
- <ul>
- <li *
- {{ movie }}
- </li>
- </ul>
- <p>
- <em>This demo was built using webpack 2 and TypeScript 2.2.1.</em>
- </p>
To pull it all together, I created a demo-local package.json file that provided a few run scripts for invoking the webpack binary from my shared vendor folder:
- {
- "scripts": {
- "build": "../../vendor/angular2/2.4.9-webpack/node_modules/.bin/webpack",
- "watch": "../../vendor/angular2/2.4.9-webpack/node_modules/.bin/webpack --watch"
- }
- }
Then, when we compile the project and run the code, we get the following page output:
As I said at the onset of this post, there's nothing here that isn't covered in Angular's introduction to Webpack. In fact, my post contains considerably less information. But, this is how I got Webpack 2 working with my JavaScript demos, which have slightly different constraints like a shared set of vendor files. As I learn more about Webpack, the one thing I really want to do is try to keep my application code "webpack agnostic". That means I want to avoid things like importing CSS files into my JavaScript modules, since that only makes sense in a Webpack build context. I like magic, but I don't like shenanigans.
Reader Comments
Ben, I know, mostly tutorials show splitting polyfills and vendor files in two separate entry points. But if you have two bundles, Tree-Shaking will not work properly. AFAIK, you need one entry point for both polyfills and vendor files, so that Webpack can statically analyze used and not used exports and Uglify can remove dead code. Can you compare total bundle sizes with and without splitting please?
How come you're not using the Angular CLI? Wouldn't that make the process simpler
@Colin - Agree. And Angular CLI only generates main.ts and polyfills.ts :-) No vendor.ts.
@Oleg. What do you mean about no vendor.ts?
When using the latest Angualr CLI with --aot, it creates the following scripts in the HTML:
inline.bundle.js
polyfills.bundle.js
main.bundle.js
styles.bundle.js
vendor.bundle.js
I've created the project with Angular 4 by setting --ng4 flag ():
ng new --ng4 mydemoproject
And I can not see vendor.ts. It's here
@Oleg,
To be honest, I don't know much about Tree Shaking or the AoT compiler yet. I've heard of the concept, but I haven't actually seen it in practice. That said, I think there are two competing concepts here - dead code elimination and efficient cache management. The Tree Shaking helps eliminate dead code; but, splitting up the bundles is done [in part] to help the Browser only re-download files as necessary. The idea is to split apart the things that change at different rates. Since vendor scripts are fairly stable (comparatively), they can be cached for a longer period by the Browser. Compared to the "app" bundle, which probably is outdated after every single deploy.
@Colin,
I haven't read up on the CLI yet. This has been a journey from in-browser System.js to in-browser System.js w/ type-checking (via TypeScript plugin), to System.js with offline type-checking, to Webpack 2. I've basically been evolving the way that I put my demos together.
Also, since the demo have a slightly unique structure, in that many demos share the same vendor code, I am not sure how well that will work with the expectation of the Angular CLI. I just haven't read up on it enough to know if I can configure it to work this way. Of course, since its all based on tsconfig and webpack.config files, I assume it can ... just not there yet :)
@Ben,
Yes, splitting ist very important. You can achieve that with AggressiveSplittingPlugin This also was my idea when I tried to split merged polyfills and vendor files. Saidy, but it doesn't work with HtmlWebpackPlugin. There is an offical issue regarding this bug. When it would work, we had a perfectly setup :-)
@Oleg,
That's interesting. I don't any experience, yet, with http2 other than what I've heard on various podcasts and presentations. I've heard some of the WebPack people talk about http2 as being a mixed bag -- that's not a perfect solution, and there is still room for bundling files. Sounds like even the Aggressive Splitting plugin also gets more course than individual files. Anyway, cool stuff -- so much to learn, I feel like I've only scratched the surface.
|
https://www.bennadel.com/blog/3242-building-javascript-demos-with-typescript-2-2-1-webpack-2-and-angular-2-4-9.htm
|
CC-MAIN-2019-26
|
refinedweb
| 3,540
| 55.03
|
42064/how-do-i-use-the-xor-operator-in-python-regular-expression
$ to match the end of the ...READ MORE
Hi. Good question! Well, just like what ...READ MORE
If you're already normalizing the inputs to ...READ MORE
What i found is that you can use ...READ MORE
You can use np.maximum.reduceat:
>>> _, idx = np.unique(g, ...READ MORE
For Python 3, try doing this:
import urllib.request, ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
You can simply the built-in function in ...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/42064/how-do-i-use-the-xor-operator-in-python-regular-expression
|
CC-MAIN-2021-21
|
refinedweb
| 119
| 81.19
|
Among the hundreds of new feature announcements at Build, one gem is hidden in plain sight: an improvement to the Kudu platform (Windows Azure Web Sites) which enables you to capture a dump file of your website’s process across the wire. No more remoting into the destination VM, fiddling around with tool downloads, and putting the dumps in a shared FTP folder. You can now generate a minidump – or even a full dump if you need to – by hitting a diagnostics endpoint on your website.
Specifically, if you set up a Windows Azure Web Site at foo.azurewebsites.net, you can hit foo.scm.azurewebsites.net/diagnostics/processes/0/dump and after providing your deployment credentials your download will be ready to go.
To test this, I created a simple ASP.NET MVC application that hangs in one of its controllers:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
Thread.Sleep(Timeout.Infinite);
return View();
}
}
I deployed the application to Windows Azure Web Sites, hit the offending controller, and while the browser was indefinitely waiting for a response, captured a dump file using the diagnostic endpoint.
You can then open these dump files in Visual Studio or WinDbg, or any other dump analysis tool of your choice. For example, when I opened the dump in Visual Studio, I could easily find the outstanding request and the call stack of the hung thread using the Parallel Stacks window.
To summarize, obtaining a dump file (even a minidump) of a running web sites is an extremely powerful capability, and having the ability to do so web sites running in Windows Azure is nothing short of incredible. Good luck debugging your own web sites with this trick!
|
http://blogs.microsoft.co.il/sasha/2013/07/01/capturing-dumps-of-windows-azure-web-sites/
|
CC-MAIN-2013-48
|
refinedweb
| 286
| 58.72
|
Unicode data in Django
This document is for Django's SVN release, which can be significantly different from previous releases. Get old docs here: 0.96, 0.95.
New in Django development version (section 10.3.2 for MySQL 5.1) for details on how to set or alter the database character set encoding.
- PostgreSQL users, refer to the PostgreSQL manual (section 21.2.2 in PostgreSQL 8) for details on creating databases with the correct e-mail).
Because some string operations come up again and again, Django ships with a few useful functions that should make working with Unicode and bytestring objects a bit easier.
Conversion functions.
URI and IRI handling
Web frameworks have to deal with URLs (which are a type of UR(u'Paris & Orléans') u'Paris%20%26%20Orl%C3%A9ans' >>> iri_to_uri(u'/favorites/François/%s' % urlquote(u.), = u'\85') # UTF-8 encoding of Å
Templates
You can use either Unicode or bytestrings when creating templates manually:
from django.template import Template t1 = Template('This is a bytestring template.') t2 = Template(u.
Django’s e-mail framework (in django.core.mail) supports Unicode transparently. You can use Unicode data in the message bodies and any headers. However, you’re still obligated to respect the requirements of the e-mail specifications, so, for example, e-mail addresses should use only ASCII characters.
The following code example demonstrates that everything except e-mail'...' EmailMessage(subject, body, sender, recipients).send()
Form submission.
Questions/Feedback
If you notice errors with this documentation, please open a ticket and let us know!
Please only use the ticket tracker for criticisms and improvements on the docs. For tech support, ask in the IRC channel or post to the django-users list.
|
http://www.djangoproject.com/documentation/unicode/
|
crawl-001
|
refinedweb
| 288
| 59.4
|
/* Copyright (C) 1996 N.M. Maclaren Copyright (C) 1996 The University of Cambridge This includes code that really should have been part of ANSI/ISO C, but was left out for historical reasons (despite requests to define ftty), plus the get_lock() and log_message() functions. */ #include "header.h" #include <sys/types.h> #include <unistd.h> #include <syslog.h> #include <signal.h> #define UNIX #include "kludges.h" #undef UNIX void do_nothing (int seconds) { /* Wait for a fixed period, possibly uninterruptibly. This should not wait for less than the specified period, if that can be avoided. */ sleep((unsigned int)(seconds+2)); /* +2 is enough for POSIX */ } int ftty (FILE *file) { /* Return whether the file is attached to an interactive device. */ return isatty(fileno(file)); } void set_lock (int lock) { /* Check that we have enough privileges to reset the time and that no other updating msntp process is running, but don't bother with fancy interlocking. This function is really only to permit the daemon mode to be restarted in a cron job and improve the diagnostics; it can be replaced by a 'return' statement if it causes implementation difficulties. Note that there is little point in clearing the lock under Unix, but do so anyway. */ FILE *file; long pid; if (lockname == NULL || lockname[0] == '\0') return; if (lock) { errno = 0; if ((file = fopen(lockname,"r")) != NULL && fscanf(file,"%ld",&pid) == 1 && kill(pid,0) == 0) { if (verbose || isatty(STDIN_FILENO) || isatty(STDOUT_FILENO)) fatal(0,"another msntp process is currently running",NULL); else fatal(0,NULL,NULL); } if (file != NULL) fclose(file); errno = 0; if ((file = fopen(lockname,"w")) == NULL || fprintf(file,"%ld\n",(long)getpid()) <= 0 || ferror(file) || fclose(file) != 0) fatal(1,"unable to write PID to %s",lockname); adjust_time(0.0,1,0.0); } else { errno = 0; if (remove(lockname) != 0) fatal(1,"unable to remove the msntp lockname %s",lockname); } } /* * Log a message, crudely. * This is used in only one place, but could be used more widely. */ void log_message (const char *message) { syslog( #ifdef LOG_DAEMON LOG_DAEMON | #endif LOG_WARNING, "%s", message); }
|
http://opensource.apple.com/source/ntp/ntp-45.1/ntp/sntp/unix.c
|
CC-MAIN-2016-36
|
refinedweb
| 338
| 57.67
|
The shapefile format does not allow for specifying the map projection of the data. When ESRI created the shapefile format everyone worked with data in only one projection. If you tried to load a layer in a different projection into your GIS weird things would happen. Not too long ago as hardware capability increased according to Moore's Law, GIS software packages developed the ability to reproject geospatial layers on the fly. You could now load in layers in any projection and as long as you told the software what projections were involved the map would come together nicely.
ArcGIS 8.x allowed you to manually assign each layer a projection. This information was stored in the prj file. The prj file contains a WKT (Well-Known Text) string which has all the parameters for the map projection. So the format is quite simple and was created by the Open GIS Consortium.
But there are several thousand "commonly-used" map projections which were standardized by the European Survey Petroleum Group (EPSG). And there's no way to accurately detect the projection from the coordinates in the shapefile. For these reasons the Python Shapefile Library does not currently handle prj files.
If you need a prj file, the easiest thing to do is write one yourself. The following example creates a simple point shapefile and then the corresponding prj file using the WGS84 "unprojected" WKT.
import shapefile as sf filename = 'test/point' # create the shapefile w = sf.Writer(sf.POINT) w.point(37.7793, -122.4192) w.field('FIRST_FLD') w.record('First','Point') w.save(filename) # create the PRJ file prj = open("%s.prj" % filename, "w") epsg = 'GEOGCS["WGS 84",' epsg += 'DATUM["WGS_1984",' epsg += 'SPHEROID["WGS 84",6378137,298.257223563]]' epsg += ',PRIMEM["Greenwich",0],' epsg += 'UNIT["degree",0.0174532925199433]]' prj.write(epsg) prj.close()
I've thought about adding the ability to optionally write prj files but the list of "commonly-used" WKT strings is over .5 megs and would be bigger than the shapefile library itself. I may eventually work something out though.
The easiest thing to do right now is just figure out what WKT string you need for your data and write a file after you save your shapefile. If you need a list of map projection names, epsg codes, and corresponding WKT strings you can download it from the geospatialpython project site here on Google Code.
A word of warning if you are new to GIS and shapefiles: the prj file is just metadata about your shapefile. Changing the projection reference in the prj file will not change the actual projection of the geometry and will just confuse your GIS software.
At spatialreference.org the .prj files corresponding to thousands of projections can be easily found and downloaded.
Very cool! Thanks. I was completely unaware of that site. What a great resource.
This is great write-up. I want to find it out so I'm looking to download it to the link you gave. Thanks.
Accounting Packages
|
http://geospatialpython.com/2011/02/create-prj-projection-file-for.html
|
CC-MAIN-2017-26
|
refinedweb
| 501
| 64.41
|
This project is done by Jaeyoung Lim
Overview
In this project I have built a usb2ppm interface, which is a programmable board that can generate ppm signals. Commands can be programmed to come from potentiometers or command from a PC connected via a USB cable.
There are some literature that explains how to control the control inputs by generating ppm signals using an Arduino or other MCUs. This is done using timer interrupts in the MCU. However, to be able to do time consuming tasks as serial communications, it can be challenging to use timer interrupts as the serial communication can be interrupted while not finished. This article is about my work of how I have solved the problem and build a working model.
PPM Signals
PPM(Pulse Position Modulation) is a signal that consists of a series of pules, which each channel values corresponds to the poistion of the pulse.
As from the picture above, a complete PPM frame has a length of 22.5ms. For Accessing Turnigy 9X, 22mms is the right value. After a overlong start pulse, 8 channel information is transmitted. The length of channel impulse ranges from 0.7ms to 1.7ms, which corresponds to the stick position linearly.
Reference :
Wiring
To interface with the turnigy 9X trainer port, a 3.5mm stereo jack. The tip of the jack is used for signal and the ring is used as ground. The signal is wired to pin 10. This is because pin 10 is directly hard wired to the Atmega 328 timer. Connecting the signal wires other than pin 10 will not work.
Above is a basic prototype used for testing. For demo, the video below shows Turnigy 9X displaying the channel inputs received from the usb2ppm.
Software (Firmware)
Timer interrupts were used to generate ppm signals. For timer interrupts, we use the 16 bit timer in Atmega 328. In the code, timer1 is used to match the timing of the start and end pulse.
ISR(TIMER1_COMPA_vect) { if (timer_ptr == number_of_outputs) { timer_ptr = 0; //reset the pointer to 0 OCR1A = timer_framelength - (timer_accumulator * timer_correction_factor); //calculate the padding timer_accumulator = 0; //set the accumulator to 0 } else { OCR1A = (pulses[timer_ptr] + timer_pause) * timer_correction_factor; //set the pulse length timer_accumulator += pulses[timer_ptr] + timer_pause; //add the pulse length to the accumulator timer_ptr++; //increment the pointer } }
Other approaches use simple delay functions to generate serials of pulses. This can work as a simple and dirty way but is problematic as the end pulse will not be properly synced, which will result in unstable signal generation.
All codes are shared by the OpenUSB2PPM repository. ()
Software (PC)
Basic Serial communication with c++ with the arduino is used from the reference:
The usb2ppm code encodes each channel values of integer into a string using serial_encode ppm(). For reference I have written the code below.
usb2ppm.h
#include #include #include using namespace std; extern char* rtrn; char* encode_PPM(int cmd_ch1, int cmd_ch2, int cmd_ch3, int cmd_ch4);
usb2ppm.cpp
#include &amp;amp;amp;quot;usb2PPM.h&amp;amp;amp;quot; char* encode_PPM(int cmd_ch1, int cmd_ch2, int cmd_ch3, int cmd_ch4){ int cmd_ch[4] = { 0, 0, 0, 0}; //Default values for each channels char output_string[26]=&amp;amp;amp;quot;&amp;amp;amp;quot;; char* output_string_p = output_string; rtrn = (char*)malloc(26); char const_ch[4] = { 'x','y', 'z', 'k' }; cmd_ch[0] = cmd_ch1; cmd_ch[1] = cmd_ch2; cmd_ch[2] = cmd_ch3; cmd_ch[3] = cmd_ch4; int j = 0; //for loop for each channel value processing for (int i = 0; i 1023){ cmd_ch[i] = 1023; } else if (cmd_ch[i] &amp;amp;amp;lt; 1){ cmd_ch[i] = 0; } char cmd_ch_s[5]=&amp;amp;amp;quot;&amp;amp;amp;quot;; char* cmd_ch_sp = cmd_ch_s; _itoa_s(cmd_ch[i], cmd_ch_s, 10); //convert to single string for communication with Arduino *(output_string_p + j) = const_ch[i]; j++; while (*(output_string_p + j) = *(cmd_ch_sp++)) { j++; } } //printf(&amp;amp;amp;quot;string :%sn&amp;amp;amp;quot;, output_string); strcpy_s(rtrn,25, output_string); return rtrn; }
Open USB2PPM Project
All codes are shared by the OpenUSB2PPM repository. ().
One thought on “USB2PPM Interface for accessing transmitter trainer ports using arduino”
Pingback: USB2PPM Interface | 404warehouse
|
https://404warehouse.net/2015/08/08/usb2ppm-interface-for-accessing-transmitter-trainer-ports/
|
CC-MAIN-2017-17
|
refinedweb
| 680
| 52.9
|
Cache::Memory - Memory based implementation of the Cache interface
use Cache::Memory; my $cache = Cache::Memory->new( namespace => 'MyNamespace', default_expires => '600 sec' );
See Cache for the usage synopsis.
The Cache::Memory class implements the Cache interface. This cache stores data on a per-process basis. This is the fastest of the cache implementations, but is memory intensive and data can not be shared between processes. It also does not persist after the process dies. However data will remain in the cache until cleared or it expires. The data will be shared between instances of the cache object, a cache object going out of scope will not destroy the data.
my $cache = Cache::Memory->new( %options )
The constructor takes cache properties as named arguments, for example:
my $cache = Cache::Memory->new( namespace => 'MyNamespace', default_expires => '600 sec' );
See 'PROPERTIES' below and in the Cache documentation for a list of all available properties that can be set.
See 'Cache' for the API documentation.
Cache::Memory adds the property 'namespace', which allows you to specify a different caching store area to use from the default. All methods will work ONLY on the namespace specified.
my $ns = $c->namespace(); $c->set_namespace( $namespace );
For additional properties, see the 'Cache': Memory.pm,v 1.5 2003/08/14 13:49:30 caleishm Exp $
|
http://search.cpan.org/dist/Cache-2.01/lib/Cache/Memory.pm
|
crawl-003
|
refinedweb
| 216
| 56.15
|
After completing this chapter, you will be able to
Use the XDocument and XElement classes in the System.Xml.Linq namespace.
Searching for items in an XML file
In this chapter, you’ll continue working with data in a Visual Studio 2013 application. In Chapter 17 you learned how to establish a connection to a database by using the Data Source Configuration Wizard and how to bind Windows Forms controls to an Access database and extract records. Accessing data is conceptually similar in a Windows Store app, although the process of binding data to XAML controls is somewhat different. You’ll learn the syntax in this chapter, and the information that you access will come ...
No credit card required
|
https://www.oreilly.com/library/view/microsoft-visual-basic/9780735673380/ch18.html
|
CC-MAIN-2018-47
|
refinedweb
| 119
| 51.99
|
The debugging process in the programming world is usually tedious, not easy and take a lot of time. That's why there are many developers that focus on how to improve the development process on multiple technologies. In PHP, some people have become the idea of implementing such a debugging bar that the PHP developer can use to debug the code on the view without using
var_dump,
echo etc. Although many modern frameworks like Symfony, already include such an useful debugging bar (Symfony Profiler):
There are other like Laravel, Zend, Phalcon etc that doesn't offer such utility. That's why an independent library comes in handy in those cases, therefore we want to introduce you the PHP Debug Bar project.
What is PHP Debug Bar
The Debug Bar library allows you to integrate easily in any projects an useful debug bar that can display profiling data from any part of your application. It comes built-in with data collectors for standard PHP features and popular projects.
-.
- Very well documented.
For detailed information about this project, please visit their official website or the repository at Github. You can see a live demo in their website as well.
Installation
The library can be easily used an installed with composer using the following command:
composer require maximebf/debugbar
After its installation you will be able to include the classes of PHP Debug bar and implement the renderer in the view.
How to use?
Rendering is performed using the
DebugBar\JavascriptRenderer class. It contains all the useful functions to included the needed assets and generate a debug bar, however you can implement an standard debug bar using the
StandardDebugBar class:
<?php use DebugBar\StandardDebugBar; $debugbar = new StandardDebugBar(); $debugbarRenderer = $debugbar->getJavascriptRenderer(); $debugbar["messages"]->addMessage("hello world!"); ?> <html> <head> <!-- As a good practice, load CSS etc in the head tag --> <?php echo $debugbarRenderer->renderHead() ?> </head> <body> <!-- Render the bar in the body tag --> <?php echo $debugbarRenderer->render() ?> </body> </html>
The default client side implementation of the debug bar is made entirely in Javascript and is located in the debugbar.js file. It adds a bottom-anchored bar which can have tabs and indicators. The bar can be in an open or close state. When open, the tab panel is visible. An indicator is a piece of information displayed in the always-visible part of the bar. The bar handles multiple datasets by displaying a select box which allows you to switch between them. The state of the bar (height, visibility, active panel) can be saved between requests (enabled in the standard bar).
Each panel is composed of a widget which is used to display the data from a data collector. Some common widgets are provided in the widgets.js file. The PhpDebugBar namespace is used for all objects and the only dependencies are jQuery and FontAwesome (css). FontAwesome is optional but is used to add nice icons. The main class is PhpDebugBar.DebugBar. It provides the infrastructure to manage tabs, indicators and datasets. When initialized, the DebugBar class adds itself to the <body> of the page. It is empty by default.
For a more detailed implementation, we recommend you to visit the demo source code in the repository that implements the debug bar.
How to contribute?
The project is open source under the MIT license, which means that you can report issues, create pull requests on the official repository.
Become a more social person
|
https://ourcodeworld.com/articles/read/577/php-debug-bar-display-profiling-data-from-any-part-of-your-application-in-any-php-project
|
CC-MAIN-2018-17
|
refinedweb
| 569
| 56.76
|
Abstract adapter class for recording audio signals. More...
#include <audiorecorderadapter.h>
Abstract adapter class for recording audio signals.
The class has an internal circlar buffer which holds the incoming audio data for a maximum of a few seconds. The user can retrieve the data in form of vector (packet) by calling readAll(&packet).
This class has to be implemented by the actual sound device implementation (AudioRecorderForQt). The implementation has to call pushRawData.
The adapter incorporates an autonomous fully automatic level control.
Definition at line 51 of file audiorecorderadapter.h.
Constructor.
Definition at line 68 of file audiorecorderadapter.cpp.
Empty destructor.
Definition at line 67 of file audiorecorderadapter.h.
Automatic noise estimation and threshold adjustment.
This function constructs a histogram of the intensities of all incoming packages. Typically this histogram has a pronounced peak at the left edge, representing the background noise of the microphone in periods of silence. The function locates the edges of the spectrum and adjusts the noise threshold as well as the gain factor.
Definition at line 277 of file audiorecorderadapter.cpp.
Control the beginning and the end of recording.
This function detects the beginning and the end of the recording period. To this end it counts how many packages have a larger energy than the recording trigger treshold. If there are several of them in a row, the function sends a message that the recording started to all other modules.
The recording process can also be restarted while it is still running provided that the energy falls below the mEnergyRt-threshold.
Definition at line 351 of file audiorecorderadapter.cpp.
Convert an intensity (variance) of the signal to a VU level.
Definition at line 181 of file audiorecorderadapter.cpp.
Convert a VU level to the corresponding intensity. This function is the inverse of convertIntensityToLevel.
Definition at line 192 of file audiorecorderadapter.cpp.
Cut trailing silence.
The local buffer of the adapter has a length of a few seconds. When the recording starts, the buffer will contain a period of silence before the key was hit. This function removes this part of the vector.
Definition at line 399 of file audiorecorderadapter.cpp.
Definition at line 75 of file audiorecorderadapter.h.
Definition at line 80 of file audiorecorderadapter.h.
The implementation calls this function when new data is available.
This function is called by the implementation when newly read data is ready to be pushed to the local buffer in the adapter. The implementation has to convert the actual PCM data format to floating point values in range [-1,1]. Then it has to call the present function.
The raw signal is multiplied by a gain factor mGain which is adjusted dynamically during the recording process.
Definition at line 214 of file audiorecorderadapter.cpp.
Read all data from the internal buffer.
Reads all data from the internal buffer into the packet vector and clears the internal buffer. This function is called by the SignalAnalyzer.
Definition at line 163 of file audiorecorderadapter.cpp.
Reset input level control.
This function resets the automatic input level control. It is usually called when the reset button below the VU meter is pressed. The function sets the input gain of the impemented input device to 1 by calling the corresponding virtualmfunction. It also sets the local gain to 1 and clears the intensity histogram.
Definition at line 104 of file audiorecorderadapter.cpp.
Set and reset the muting flag.
This will mute the input signal with the effect of sending 0 as input signal and sending the value 0 to the VU meter.
Definition at line 125 of file audiorecorderadapter.cpp.
The implementation of the audio device is allowed to change the sampling rate in which case this function is called. It adjusts the actual maximal buffer size so that the maximal time of recording is kept constant.
Reimplemented from AudioBase.
Definition at line 143 of file audiorecorderadapter.cpp.
Definition at line 77 of file audiorecorderadapter.h.
Definition at line 78 of file audiorecorderadapter.h.
Attack rate at which the sliding level goes up (1=instantly).
Definition at line 58 of file audiorecorderadapter.h.
Capacity of the local circular audio buffer in seconds.
Definition at line 56 of file audiorecorderadapter.h.
dB shift for off mark (high value = shorter recording)
Definition at line 63 of file audiorecorderadapter.h.
Decay rate at which the sliding level goes down.
Definition at line 59 of file audiorecorderadapter.h.
Level above which the input mGain is automatically reduced.
Definition at line 62 of file audiorecorderadapter.h.
Level below which retriggering (restart) is allowed.
Definition at line 60 of file audiorecorderadapter.h.
Level above which the recorder starts to operate.
Definition at line 61 of file audiorecorderadapter.h.
Counts counting incoming PCM values.
Definition at line 96 of file audiorecorderadapter.h.
Counter threshold for updating energy.
Definition at line 97 of file audiorecorderadapter.h.
Local audio buffer.
Definition at line 110 of file audiorecorderadapter.h.
Buffer access mutexbo.
Definition at line 111 of file audiorecorderadapter.h.
Recording amplification factor.
Definition at line 95 of file audiorecorderadapter.h.
Histogram of intensities.
Definition at line 108 of file audiorecorderadapter.h.
Is the input device muted.
Definition at line 94 of file audiorecorderadapter.h.
Counter for the number of packages.
Definition at line 106 of file audiorecorderadapter.h.
First intensity moment of a single packet.
Definition at line 98 of file audiorecorderadapter.h.
Second intensity moment of a single packet.
Definition at line 99 of file audiorecorderadapter.h.
Flag true if recording is on.
Definition at line 102 of file audiorecorderadapter.h.
Flag true if start/retriggering possible.
Definition at line 103 of file audiorecorderadapter.h.
Sliding VU level of the signal.
Definition at line 100 of file audiorecorderadapter.h.
Standby flag.
Definition at line 105 of file audiorecorderadapter.h.
Level at which recording stops.
Definition at line 101 of file audiorecorderadapter.h.
Instance of stroboscope.
Definition at line 113 of file audiorecorderadapter.h.
Wait for the data analysis to be completed.
Definition at line 104 of file audiorecorderadapter.h.
Update interval in milliseconds, defining the packet size.
Definition at line 57 of file audiorecorderadapter.h.
|
http://doxygen.piano-tuner.org/class_audio_recorder_adapter.html
|
CC-MAIN-2022-05
|
refinedweb
| 1,013
| 53.78
|
[Previous] [Contents] [Next]
Remove Duplicate Entries from a List
The Problem:
So far, so goodthe membership list is now in the format "Membershipnumber Tab Lastname, Firstname," and I've sorted it into ascending order using Table
Sort. But I can already see a ton of duplicate entries that I'll need to knock out.
The Solution:
Regular expressions to the rescue again! Choose Edit
Replace to display the Find and Replace dialog box. Next, clear any formatting and check the "Use wildcards" box. Enter (*^13)(\1)@ in the "Find what" box and \1 in the "Replace with" box. Click the Replace All button. The \1 identifies a recurrence of the previous expressionin this case, any sequence of characters followed by a carriage return (represented by the code ^13). The @ makes Word find one or more occurrences of the repeated item. So the expression (*^13)(\1)@ finds a paragraph that is repeated by itself one or more times, and the replacement \1 replaces what is found (the repeated paragraph or paragraphs) with the paragraph itself.
[Previous] [Contents] [Next]
|
http://www.brainbell.com/tutorials/ms-office/Word/Remove_Duplicate_Entries_From_A_List.htm
|
crawl-002
|
refinedweb
| 177
| 64
|
Modular Multiplication Without Overflow
May 28, 2013
Let’s begin with an example, calculating 56 * 37 modulo 100 using 8-bit arithmetic, so no intermediate total may be 256 or greater. We start by representing a = 56 = 3 * 16 + 8 and b = 37 = 2 * 16 + 5, so:
a1 = 8
a2 = 3
b1 = 5
b2 = 2
Then the four intermediate products with their shifts are:
p11 = 8 * 5 = 40
p12 = 8 * 2 = 16 > 32 > 64 > 128 (28) > 56
p21 = 3 * 5 = 15 > 30 > 60 > 120 (20) > 40
p22 = 3 * 2 = 6 > 12 > 24 > 48 > 96 > 192 (92) > 184 (84) > 168 (68) > 136 (36)
We’re using binary arithmetic, so each number doubles as it is shifted, taking it modulo 100 as we go. The product of two low-half numbers is not shifted, the product of a low-half and high-half number is shifted 4 times (since log2 16 = 4), and the product of two high-half numbers is shifted 8 times. Then the intermediate products are summed, again removing m each time an intermediate sum exceeds m:
s = 40 + 56 = 96
s = 96 + 40 = 136 (36)
s = 36 + 36 = 72
And that’s the final answer: 56 * 37 = 2072, which is 72 (mod 100).
Here’s the code:
(define (mod-mul a b m) ; assumes a,b < 2^64 and m < 2^63
(define (shift x k)
(let loop ((k k) (x x))
(if (zero? k) x
(let* ((x (* x 2))
(x (if (< x m) x (- x m))))
(loop (- k 1) x)))))
(let* ((two32 (expt 2 32))
(a1 (remainder a two32))
(a2 (quotient a two32))
(b1 (remainder b two32))
(b2 (quotient b two32))
(p11 (modulo (* a1 b1) m))
(p12 (shift (modulo (* a1 b2) m) 32))
(p21 (shift (modulo (* a2 b1) m) 32))
(p22 (shift (modulo (* a2 b2) m) 64))
(s (+ p11 p12))
(s (if (< s m) s (- s m)))
(s (+ s p21))
(s (if (< s m) s (- s m)))
(s (+ s p22))
(s (if (< s m) s (- s m))))
s))
And here’s a somewhat larger example:
> (define a 17259738289493410580109721600)
> (define b 10327523882682224844906430464)
> (define m 8631375519702822467321987072)
> (mod-mul a b m)
7869126927168251407166865408
You can run the program at.
This seems to work for arbitrary 64-bit values, and for me it runs a little faster than splitting into two 32-bit parts. If you have a recent gcc, you can cheat with:
On x86_64 there is also 4 lines of asm that will do it quickly. There are faster methods if one has lots of operations with the same modulus.
I see that Mathew’s question was about addition. With unsigned types in C I use:
to return (a + b) mod n. This requires that a and b are already modulo n, hence n > a,b (if you don’t know, just mod them. but often you know they’re in range). If n-a > b, then there won’t be overflow so we just add; otherwise we do a+b-n. Since this is an unsigned type, it wraps ok around the max integer size, and because a and b were modulo n when we started, one subtract will be enough.
On my previous post, the “UV” in the mulmod macro should be “unsigned long”. The comment about removing the mods is indicating performance — they don’t hurt anything other than wasting time if you already know the values are mod m.
FORTH is tricky since the support for 64 bit math in general is very limited. This is specific to x86 with 80 bit IEEE floating point math. OTOH, 32 bit modular multiplication can be done easily without overflow due to words that generate 64 bit intermediate result.
|
https://programmingpraxis.com/2013/05/28/modular-multiplication-without-overflow/2/
|
CC-MAIN-2016-36
|
refinedweb
| 611
| 67.12
|
#include <Wire.h> #include <LiquidCrystal_I2C.h>#define lcdAddr 0x20 // set the address of the I2C device the LCD is connected to// create an lcd instance with correct constructor for how the lcd is wired to the I2C chipLiquidCrystal_I2C lcd(lcdAdrr, 4, 5, 6, 0, 1, 2, 3, 7, NEGATIVE); // addr, EN, RW, RS, D4, D5, D6, D7, Backlight, POLARITY// as 20x4 (16,2 for 16x2) lcd.setBacklight(1); // switch on the backlight for ( int i = 0; i < charBitmapSize; i++ ) { lcd.createChar ( i, (uint8_t *)charBitmap[i] ); } lcd.home (); // go home to character 0 on line 0 (1st line) lcd.print("Hello, ARDUINO "); lcd.setCursor(0,1); // character 0 on line 1 (2nd line) lcd.print (" FORUM - fm "); lcd.setCursor(0,2) // character 0 on line 2 (3rd line) lcd.print("This is line 3"); lcd.setCursor(0,3) // character 0 on line 3 (4th line) lcd.print("This is line 3"); delay(1000);}void loop(){ lcd.clear() lcd.home (); // Do a little animation by writing to the same location for ( int i = 0; i < 2; i++ ) { for ( int j = 0; j < 16; j++ ) { lcd.print (char(random(7))); } lcd.setCursor ( 0, 1 ); } delay (200);}
The last thing that took me long time to figure out is that the backlit pot ....
If your LCD connections are (Left to Right) - VSS, VDD, VO, RS, RW, E, D0, D1, D2, D3, D4, D5, D6, D7, A (or LED+), K (or LED-) then the connection goes to the following bits on the I2C chipRS - 6RW - 5E - 4D4 - 0D5 - 1D6 - 2D7 - 3Backlight - 7This makes your constructor 4,5,6,0,1,2,3,7 so use the following example sketch:-
And I saw the other posts about changing the constructor, and asked wtf they would do that and not just keep one standard way of doing it.
As far as the LCD spin out goes, I only put that there as I've not used a 20x4 display so wasn't 100% sure they were all identical. I'd guessed they were as the backpacks work on those two, but safer to have the OP make sure. ;-)Hopefully he'll report back if it's worked for him. I know some people can get tremely frustrated when things don't work and get the 'it's no good, I'm fed up, it's rubbish' red mist. I have a couple of mates with low patience levels like that.
I also learned that you do have to initialize with lcd.begin(columns, rows).
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy
|
http://forum.arduino.cc/index.php?topic=142255.msg1070267
|
CC-MAIN-2016-40
|
refinedweb
| 452
| 80.62
|
How do I close the browser window at the end of a Selenium test?
I have googled for the answer, but the
.stop()so frequently mentioned doesn't work for me. The Chrome window the test was running in remains open.
def test_getResults(self): sel = selenium('localhost', 4444, "*chrome", '') sel.start() # do stuff def tearDown(self): sel = selenium('localhost', 4444, "*chrome", '') sel.close() sel.stop()
Any ideas? I'm using Selenium Server 2.8.0 with Python 2.6 and mostly using Chrome 14 windows to test.
Yes there is - browser.quit(); Although when I used to run these types of tests before switching to WebDriver I used to have in my TearDown - self.selenium.stop() That usually did it for me.
Okay. I will try .quit(). I found that .stop() will stop the server, but not close the window.
.quit() did not work
I verified in C# that webdriver.Quit() closes a firefox window, I didn't try it with a chrome driver.
I saw there was an old defect on Selenium not closing Chrome that was fixed a few months ago, maybe you should reopen it?
That may be what I'm encountering. I will test with another browser when I get a chance.
I tried with Firefox. .stop() doesn't work. .close() results in "Exception: ERROR Server Exception: sessionId should not be null; has this session been started yet?"
You need to use "quit()". I don't think "close()" would actually close the last remaining window.
driver.close() and driver.quit() are two different methods for closing the browser session in Selenium WebDriver..
Hi Sneha Singh, and welcome to Stack Overflow. Your answer is a good start, but you could make it better by adding a bit more context; can you describe the difference between the driver.close and driver.quit methods and how you would choose between them? Maybe including links to official documentation would help too - see the advice at [answer].
Does the context manager `with webdriver.Firefox() as wd` take care of `quit` for you?
You're actually creating a second Selenium session in your tearDown() function. You need to put the session created in setUp() into an instance variable, then close that session in tearDown().
class TestFoo(unittest.TestCase): def setUp(self): self.selenium = selenium('localhost', 4444, "*chrome", '') self.selenium.start() def tearDown(self): self.selenium.stop() def test_bar(self): self.selenium.open("/somepage") #and so forth
I have worked with Web Driver in both java and C# and I use
In Java :
WebDriver driver; driver.quit();
In C# :
IWebDriver Driver; Driver.Quit();
In Python, using selenium webdriver for Chrome, I needed to call
stop_client()before
from selenium import webdriver
in setUp():
options = webdriver.chrome.options.Options() options.add_argument("--disable-extensions") # optional and off-topic, but it conveniently prevents the popup 'Disable developer mode extensions' self.driver = webdriver.Chrome(chrome_options=options)
In tearDown():
self.driver.stop_client() self.driver.close()
May we just call driver.quit() for that?
WebDriver driver; driver.quit();
Above will close all open browser windwos.
And
WebDriver driver; driver.close();
This will close current browser window in focus.
Using TestNG and Java.
Assume this method is located in some BaseTest class which is inherited by test class, so try this:
@AfterClass(alwaysRun = true) protected void tearDown() { driver.quit(); driver = null; }
why the last command? driver=null;
I use it in scope init driver logic, like if null then new driver instance is being creating. That command is optional however.
You can use either
driver.close();or
driver.quit();.
Use
close()for one browser to close and
quit()is to close all browsers using webdriver. But why
close()is not closed at runtime, but it is closed at debugging I don't know.
Your answer is weak (because you don't give much other information) and doesn't add much to the question and existing answers. You also asked a different question which really should be posted as a separate question (with a lot more information)
This is what worked for me:
taskkill /f /fi "pid gt 0" /im iexplore.exe
I have this in my pre-build events in the Visual Studio Solution. This is can be run from the command line, just call it in your project and you should be all set.
I also have the following line to close the the IE driver in case of failure to execute
driver.Quit()or
taskkill /f /fi "pid gt 0" /im IEDriverServer.exe
Could you indicate how the questioner could run this within their code and with chrome? I assume they want to incorporate it into their suite and not perform a one off action
If you use headless mode you still see them not closing try this solution 1) Get the driver as singleton
@Singleton class BrowserInstance { ChromeDriver getDriver(){ ChromeOptions options = new ChromeOptions() options.addArguments("--headless --disable-gpu") return new ChromeDriver(options) } }
2) Use Close and quit in finally block
finally { chromeDriver.close() chromeDriver.quit() }
Result: you will be using only one instance at time and if you see task manager you will not find chromedriver and chrome process hanging.
Maybe my solution will be not a super smart one, but before each automated test case I put:
time.sleep(2) driver = webdriver.Chrome()
driver.implicitly_wait(10)
Maximizes the window
driver.maximize_window()
And to close all windows of the test case I use:
def close(): driver.close() close()
And this works for me in Python.
user246 9 years ago
Is there a quit method?
|
https://libstdc.com/us/q/sqa/1941
|
CC-MAIN-2021-25
|
refinedweb
| 916
| 68.97
|
Eval Functions
To create an eval function, the following abstract class must be extended. The parameter T is the return type of the eval function.
public abstract class EvalFunc<T extends Datum> { abstract public void exec(Tuple input, T output) throws IOException; }
Input to the Functions
The arguments to the function get wrapped in a tuple and are passed as the parameter input above. Thus, the first field of input is the first argument and so on.
For example, suppose I have a data set A =
<a, b, c> <1, 2, 3>
Suppose, I have written an Eval Function MyFunc and my PigLatin is as follows:
B = foreach A generate MyFunc($0,$2);
Then MyFunc will be called first with the tuple <a, c> and then with the tuple <1, 3>.
Output of the functions
When extending the abstract class, the type parameter T must be bound to a subclass of Datum. (The compiler will allow you to subclass EvalFunc<Datum> but you will get an error on using that function). When T is bound to a particular type of Datum ( DataAtom, or Tuple, or DataBag, or DataMap), the eval function gets handed, through the parameter output, a Datum of type T to produce its output in.
Note that in case T is a databag, although you get handed a DataBag as the parameter output, this is an append-only data bag. Its contents always remain empty. This is a performance optimization (we use it for pipelining) based on the assumption that you wouldnt want to examine your own output.
Example
As an example, here is the code for the builtin function TOKENIZE, that expects as input 1 argument of type data atom, and tokenizes the input data atom string to a data bag of tuples, one for each word in the input string.
public class TOKENIZE())); } }
Advanced Features
Schemas: Eval functions can declare their output schema by overriding the following method in EvalFunc. See: PigLatinSchemas.
/** * @param input Schema of the input * @return Schema of the output */ public Schema outputSchema(Schema input) { return input.copy(); }
Algebraic Eval Functions If the input to your function might be large (i.e. the input tuple may contain a large bag of tuples nested inside of it) and you are concerned about performance, you may want to consider writing your function in such a way that it can receive its input in small "chunks," one at a time, and then merge the per-chunk outputs to obtain the final output. (In the map/reduce model, the "combiner" feature does this.) To enable this feature, your eval function must implement the interface Algebraic. See AlgebraicEvalFunc for details.
Final cleanup action If your function needs to do some final action after being called the last time for a particular input set, it can override the finish method of the class EvalFunc.
/** * Placeholder for cleanup to be performed at the end. User defined functions can override. * */ public void finish(){}
|
http://wiki.apache.org/pig/EvalFunction?action=diff
|
CC-MAIN-2016-22
|
refinedweb
| 492
| 58.72
|
prefixed XHTML elements are not rendered properly
VERIFIED INVALID
Status
()
▸
DOM
People
(Reporter: Manos Batsis, Unassigned)
Tracking
Firefox Tracking Flags
(Not tracked)
Details
Attachments
(3 attachments, 1 obsolete attachment) Short version: XHTML Elements that are serialized and appended to document via innerHTML bear redundant namespace prefixes. This breaks rendering as CSS rules are not applied to these elements. This only applies to the case of XMLSerializer > innerHTML (see attached testcase). The thing is, since both the serializer and the innerHTML method *know* this serialization goes to the host document (which is XHTML and already has the namespace as default and the node that is serialized is actually the result of document.importNode) maybe the prefix should be supressed at some point, unless this can be fixed via CSS. The thing is that the CSS situation is already complicated, as the rules in my page should not be applied to *any* paragraph (i havent used any @namespace). Reproducible: Always Steps to Reproduce:
Created attachment 161251 [details] testcase that demonstrates the rendering issue and all the steps that lead to the redundant prefixes
The prefixes shouldn't make the slightest difference to CSS. Could you create a real testcase (1k or less, no external resources) that clearly demonstrates the problem? Thanks...
Created attachment 161252 [details] testcase that demonstrates the rendering issue and all the steps that lead to the redundant prefixes Sorry, attached the wrong file :-/
Attachment #161251 - Attachment is obsolete: true
Created attachment 161253 [details] minimal testcase demonstrating the issue on non-dynamic content
BTW, if the minimal attachment(161253) is viewed as application/xhtml+xml, the rules are not applied at all (correctly of course).
Created attachment 161257 [details] minimal testcase demonstrating the... (application/xhtml+xml mode) Same testcase as minimal testcase, but in application/xhtml+xml mode. I removed the comments surrounding the css, and made it correct xml. You'll see that both <p> elements get a green background color now. In text/html the second <p> element doesn't get the green background-color, because html documents don't know anything about namespaces, I think.
In attachment 161253 [details] you're inserting elements in the XHTML namespace into an HTML document. Why not just create HTML elements? Drop the XHTML namespace and things work as you want them to.
(In reply to comment #7) > In attachment 161253 [details] you're inserting elements in the XHTML namespace into an > HTML document. Um, it's an XHTML document with a doctype and all. The only thing making it invalid XHTML is the undefined xhtml:p element (ok and the <br /> should not be there).
It's not XHTML. The MIME type makes it XHTML, not your DOCTYPE. I'm not sure what Ian meant in comment 2, but I guess this is INVALID.
Thanks but the DOCTYPE was authored by w3c ;-) Seriously now, throwing the MIME answer to this is both irrelevant and impractical. Irrelevant: I don't actually ask prefixed elements to be styled when serving as text/html (the prefixes make the markup invalid anyway), I'm looking for a way to get away without the redundant prefixes in the document. Setting the innerHTML of a node is usefull even against appendChild as a more performant solution, so why not make it clever enough to remove the prefixes/declarations? I also suggest having importNode as a precondition for this, as I thought it may be of help. Impractical: with the persentage of the web able to handle application/xhtml+xml, i don't have a choice. What should I do, go back to HTML? Thanks for listening.
Actually, Anne and Peter are right. Using the text/html with XHTML is allowed only if the XHTML satisfies the backwards-compatibility requirements spelled out in Appendix C of the XHTML specification. Such documents are NOT parsed with XML parsers but with the tag-soup parser. So in fact, namespaces do not belong in such documents. Marking invalid, since you are in fact inserting XML in a non-XML document, as Peter said. I appreciate your inability to use the proper XHTML MIME type due to IE bugs, but that doesn't mean we need to completely break our XML support to deal with it... For further reading, I recommend -- that explains the issues involved at length.
Status: UNCONFIRMED → RESOLVED
Last Resolved: 14 years ago
Resolution: --- → INVALID
To clarify, the discussion in bug 155723 is about using innerHTML on actual XHTML documents, sent with a proper XML MIME type. Those should all handle namespace prefixes correctly. One more thing I just noticed. Comment 0 says: > The thing is, since both the serializer and the innerHTML method > *know* this serialization goes to the host document The serializer does NOT in fact know that. It has to serialize as something that, when saved to an XML file and then viewed would get rendered as XHTML. Which means it needs to put a namespace on things. The bug I was thinking you were talking about is that the XHTML with these namespace prefixes, when loaded as XHTML, does not work. That's clearly not the case (as the XHTML testcase in this bug demonstrates). The remaining issue (use of a prefix instead of a default namespace) is already covered by bug 155723.
Note that my solution in comment 7 does work. Just change the line '<xsl:stylesheet'+ to '<xsl:stylesheet'+
> What should I do, go back to HTML? Yes. <> <> ->VERIFIED
Status: RESOLVED → VERIFIED
Component: DOM: Mozilla Extensions → DOM
Product: Core → Core
|
https://bugzilla.mozilla.org/show_bug.cgi?id=263144
|
CC-MAIN-2018-17
|
refinedweb
| 918
| 61.67
|
BookBeaming
From OLPC
<discontinued project> Danielfuhry 21:29, 17 February 2009 (UTC)
- creator felt it would require reverse engineering or NDA... (but there are many ways to achieve this goal)
Description & Goals
Summary
BookBeaming receives static content using a conventional World Space satellite radio.
Status
The prototyp
works with the TONGSHI DAMB-R Radio and the Africa Learning Channel.
As of 26.01.08 any active audio stream can be tapped and recorded. This was however not the original purpose.
Since January the prototyp is broken due to changes in the codewords used. Specifications appear to be nonpublic.
Goals
Access to a wide range of content from the weather report to health care.available content (archive.org)
Collaboration
Sharing one satellite radio could bypass satellite radio shortage in an particular areas.
other ideas
Some of the receivers are equipped with a FM transmitter. (frequencies 87.7, 88.1, 87.9, 107.5, 107.7, 107.9) Not working on either battery or USB power. Othere issues signal is too weak (theoretically it could be possible to increase the signal strenght in a firmware or hardware modification)
example source code for audio
Records the current channel via usb. Requires pyusb. It is possible to use this for recording data transmissions. (data still needs to be reformated according to codewords)
import usb import struct def opendevice(idVendor, idProduct): devices=[] for b in usb.busses(): for d in b.devices: if d.idVendor==idVendor and d.idProduct==idProduct: devices.append(d) if len(devices)==1: device=devices[0] return device elif not devices: raise "Device not found" else: raise "More than one device found" def read(dh): try: r = dh.bulkRead(0x00000082,0x40,10) except: return read(dh) return struct.pack(64*'B',*r) """ b before -128 <= number <= 127 now 08.03.2008 it's B 0 to 255""" if __name__=="__main__": device1=opendevice(0x174e, 0x5357) dh=device1.open() dh.claimInterface(0) flob=open('out.mp3','wb') while 1==1: buffer1 = read(dh) buffer2 = read(dh) d = "".join([buffer1, buffer2]) #print repr(d) console out flob.write(d) fileobj.close()
See also
Peripherals/Satellite_Broadcasting
|
http://wiki.laptop.org/index.php?title=BookBeaming&oldid=227039
|
CC-MAIN-2015-48
|
refinedweb
| 351
| 51.55
|
Hello guys,
I want to create a custom panel for my online simulator using matrix keypad 4x3 and library USBKeyboard that can send key stroke to pc for simulate the normal usb keyboard.
my idea is the follow:
ARDUINO UNO board, connect the keypad with an IC PCF8574P( with address 0x20) and wire library for use only two wire, use the usb shield with 2 diode (zener 3,6v 0,5w) and three resistors.
I try to write a code for that project but don’t work. but if i use only one code this work fine, in order if i simulate a USBkeyboard with one switch it works and if i use only the two wire keypad it works fine but if i combine both not working.
the code is the follow:
#include "UsbKeyboard.h" #include <Wire.h> #include <i2ckeypad.h> #define ROWS 4 #define COLS 3 //matrix keypad Address #define PCF8574_ADDR 0x20 //Object keypad i2ckeypad kpd = i2ckeypad(PCF8574_ADDR, ROWS, COLS); char key; void setup() { // Disable timer0 since it can mess with the USB timing. Note that // this means some functions such as delay() will no longer work. TIMSK0&=!(1<<TOIE0); // Clear interrupts while performing time-critical operations cli(); // Force re-enumeration so the host will detect us usbDeviceDisconnect(); delayMs(250); usbDeviceConnect(); // Set interrupts again sei(); Wire.begin(); //inizialize Wire library kpd.init(); //inizialize object keypad } void loop() { UsbKeyboard.update(); key=kpd.get_key(); if (key != ' \0 ') { UsbKeyboard.sendKeyStroke(KEY_H, MOD_SHIFT_LEFT); UsbKeyboard.sendKeyStroke(KEY_E); UsbKeyboard.sendKeyStroke(KEY_L); UsbKeyboard.sendKeyStroke(KEY_L); UsbKeyboard.sendKeyStroke(KEY_O); UsbKeyboard.sendKeyStroke(KEY_SPACE); UsbKeyboard.sendKeyStroke(KEY_W, MOD_SHIFT_LEFT); UsbKeyboard.sendKeyStroke(KEY_O); UsbKeyboard.sendKeyStroke(KEY_R); UsbKeyboard.sendKeyStroke(KEY_L); UsbKeyboard.sendKeyStroke(KEY_D); UsbKeyboard.sendKeyStroke(KEY_ENTER); } } /** * Define our own delay function so that we don't have to rely on * operation of timer0, the interrupt used by the internal delay() */ void delayMs(unsigned int ms) { for (int i = 0; i < ms; i++) { delayMicroseconds(1000); } }
i don’t have idea why isn’t working, i spent three days but i don’t understand why =( =( =(
i wait for you help me!
|
https://forum.arduino.cc/t/4x3-matrix-keypad-and-usbkeyboard-emulation/109485
|
CC-MAIN-2021-43
|
refinedweb
| 338
| 53
|
This simple app allows you to use the MSN web search.
Instead of taking space off of your taskbar it simply seats on the notification area and can be invoked by double-clicking the "systray" icon or via right-click menu.
It will also work as a web address bar, meaning that you can type an http address and will be redirected directly to that page.
It also uses the feature of suggesting websites by using a list of your previously visited websites.
It requires .NET Framework 2.0
enjoy it,
Gus.
Forum Read Only
This forum has been made read only by the site admins. No new threads or comments can be added.
This simple app allows you to use the MSN web search.
(June, 15th) - Added support to UNC paths.
Where can I download this application?
I like the source, it's so... Simple
private void searchButton1_Click(object sender, EventArgs e) { this.FadeDownTo(0); string text1 = this.searchBox.Text.Replace("\"", "%22"); if (this.searchBox.Text.StartsWith("http")) { Process.Start(this.searchBox.Text.ToString()); } else if (this.searchBox.Text.StartsWith("https")) { Process.Start(this.searchBox.Text.ToString()); } else if (this.searchBox.Text.StartsWith("www")) { Process.Start("http://" + this.searchBox.Text.ToString()); } else { Process.Start("" + text1); } } public void SetOpacityAndWait(int opacity) { base.Opacity = ((double) opacity) / 100; this.Refresh(); Thread.Sleep(20); } public int Int32Opacity { get { return (int) (base.Opacity * 100); } } public void FadeUpTo(int max) { for (int num1 = this.Int32Opacity; num1 <= max; num1 += 5) { this.SetOpacityAndWait(num1); } } public void FadeDownTo(int min) { for (int num1 = this.Int32Opacity; num1 >= min; num1 -= 5) { this.SetOpacityAndWait(num1); } }
Great program by the way
The link to download the software is right beneth the picture as "[Save]".
Gus
Glad you liked.
I was meant to be simple right out of the board.
Works great.
Well done.
Oh also I can open the search bar window, then open the About box, which closes the search bar window, that's good except I can right click the notification icon and click open and that will open the search bar window underneath the About box. That makes the "Always on top" option false advertisement.
Also have the search bar window open and Paint.NET open, Paint.NET's Translucent undocked tool boxes over take the search toolbar window, also making "Always on top" false advertisement.
When I have the About box open and then open another instance of it via right cliking the notification icon, it hurls some more vomit, here's the greenish yellow bits:
************** Exception Text **************
System.InvalidOperationException: Form that is already visible cannot be displayed as a modal dialog box. Set the form's visible property to false before calling showDialog.
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at MSNTray.MainForm.aboutTool)
Plus, why isn't there an option to not have the about box on top? I find it pretty annoying telling you about these bugs and it being on top of everything else (not including Paint.NET's Translucent undocked tool boxes)
I'd also like to see an option to change the transparency levels of the search bar window and the About box.
I would like to be able to set this prog up to start when windows starts, plus I'd like an installer so I don't have to put it in C:\Program Files\MSN Search Bar\ and add a shortcut to it in the All Programs part of the Start Menu, in the quick launch bar and on the desktop.
Is this product made by MSN or Microsoft? A unknowing user would think "This is a product of Microsoft, but it is a hacked version since the real name of the creator has been replaced by this "Gus Pinto" guy. Or is that a worker from Microsoft? Maybe I should SUE!" It is just a bit strange seeing all these logos and MSN information that a non-tech user would shizen their pants over. Just stuff like the tooltip of the notification icon says "MSN Search" it should be less Fake Microsoftian and less confusing to all users.
Why doesn't the about box fade out when I close it? It should. It should also be more flat across the board, like the search bar window has a cross for closing the window, but the about box has the word "Close" for it. You should try and keep the style for both windows the same so that a user can grow into it and refer to the style fast. Do stuff like change the style of the About box to blue so that it looks the same as the search bar window and then keep it that way.
Also, there is no way of returning or bringing up a new window for the search bar from the about box, it should say "Search bar" or have an icon we can click on to return to the search bar window. Just make sure the style is the same across the board when you add this feature.
What? Do you think I went overboard?
Sorry GusPinto, this is how I am. I can't help but find bugs and problems with programs. Sometimes I don't verbalise these bugs, but I had to let a rip here
I hope you comply with the above.
Loadsgood.
Yeah it's really good, except it vomits when my firewall denies it internet access. Here's the food bits of the vomit:
************** Exception Text **************
System.ComponentModel.Win32Exception: An error occurred in sending the command to the application
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(String fileName)
at MSNTray.MainForm.searchButton1_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.PerformClick()
at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.TextBoxBase.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
Other than that it works great
EDIT: Could you add that down arrow from MSN Search to the left of "Search Web" and make a menu which says "Web" "Images" etc. and when I click one of those it changes the "Search Web" button to say "Search Images", Search [option clicked here]"?
Also could you get it to detect the user's regional settings of the computer and change the MSN Search to the local MSN Search for that user? If they don't have an MSN Search for their region just have it go to the .com one.
Could you make the search bar window and the about box movable?
Go this app.
Loadsgood.
Hey LoadsGood, my good ol' buddy. See any updates I added to NinerStat here?
- Loadsgood wrote.
Elwoh's still intact. Hence my display photo. I'll send the latest copy over to you but don't leak out the release.
. And yes, the HTML rendering failed for some reason, I'll have to see why as soon as i get VS installed again. There are ALOT more updates in there, [View] that you'll have to see for your self later.
And I'll think you'll like "PersonalFeed". I've added what you've requested a little while back. Still working on that clock!
- GusPinto wrote
You know it makes me feel good telling people about bugs in their software.... I think I might pick it up again and tell people about bugs in their software rather than holding back or not being bothered opening a new IE window. Plus I like this peice of software, it works well except for those bits I pointed out. I think there was some more but yesterday I thought I'd tell you if they were there in the new release and now I've forgotten what they were... Meh doesn't matter.
And as for you Mister Steve 411... I'm all confused on the situation with Elwoh so as long as I can scream at you for the missing features and the bugness I'm happy
Damn trial version of MagicISO.
Loadsgood.
Pick on me all you want, Miss. LoadsGood.
I need my VS CD's.
Steve.
- Steve411 wrote:Pick on me all you want, Miss. LoadsGood.
I need my VS CD's.
Steve.
That Miss better be short for Misster
Haha you still don't have your VS CDs... I tells you someone took them.
Get some replacement CDs from Microsoft
Loadsgood.
"Visit online" button checks to see which feed you select, then it loads the appropriate page into the html view on the right. I have also added Group Sorting, "Right Click - > Assign to Group" or "Right Click - > New Group" for instant loading... There is also a properties dialog with a bunch of shizzle info on it. I've re-re-written the RSS Reader class from the top now and a bunch of stuff added there as well. Custom item sorting, item browsing, removing.. etc.
Here's some code for the RssItem struct gathering, instead of idexes.
/* this it how we did it in the past...VERY hard to figure out the item index in a list view */
public RssItem getItem(int Index)
{
return (RssItem)List[Index];
}
/* this is how we do it now.. VERY easy to loop through the items.:) */
public RssItem getItem(RssItem item)
{
RssItem nItem = new RssItem();
foreach(RssItem i in Functions.feed.Items)
{
if(item.title == i.title)
{
if(Functions.feed.Items.InnerList.Contains(i))
{
return (RssItem)i;
}
}
}
return nItem;
}
To use the new bit of code we just browse like this.
/* Validation is required before we send it off to the InnerList.
Tried it without current-to-current validation and it failed.
This fixes that with ease. */
foreach(XPListViewItem i in ListItems.SelectedItems)
{
foreach(RssItem rItem in Functions.feed.Items)
{
if(rItem.title == i.Text)
{
ThePostDetails.PostData = Functions.feed.Items.getItem(rItem).Link;
}
else{}
}
}
I am always posting updates about NinerStat [even SOURCE!] on my Blog. For example, here is a post that I think you've seen a while ago. All the content described in the post is still intact, and I'm back to coding, installed VS NO MORE NOTEPAD!
.
You can now even sort the items into groups with a click of a mouse button. Even got that toolbar menu you wanted up. Auto Grouping, though, is my favorite feature. I can keep track of my favorite posters here on C9 and even use ColorDeco in the process.
I've removed the ZoomFactor for just a little while. Added an advanced reader with easy ColorDeco activation and grouping. Subscriptions are all set to go as well.
PM me on MSN and I'll send you a copy.
NinerStat - Start something Extraordinary.
Mommy, when can I be a C# gurry?.
Steve.
Wow go Steve. How many features do you want?
I just hope they don't clash or else it'll be a minefield full of bugs. I'll MSN you one day..... one day....
Great work you doing there on NinerStat
Loadsgood.
|
http://channel9.msdn.com/Forums/Sandbox/MSN-System-Tray-Web-Search
|
CC-MAIN-2015-18
|
refinedweb
| 1,867
| 76.11
|
Creating & Importing Data for ArcGIS
geographic formatting & spatial dataframes also be that the people researching AI algorithms aren’t interested in making themselves obsolete, but I doubt it; the drive to automate and simplify your own workflow is generally too high for such far-flung fears.
Sourcing Proper Data
Let’s explore ArcGIS’ native data creation & import settings before running some more visualizations.
For any meaningful analysis you’d like to do, the data probably isn’t already up on the ArcGIS cloud and neatly formatted for feature layering, though they do have some nice searchable layers already out there.
If you’re fortunate you’ve just grabbed a pre-cleaned CSV from some government-hosted API, or perhaps you had to painstakingly query a SQL server that hasn’t been updated since 1980.
CSV-compatible formats are by far the most common, so we’ll begin working under those assumptions. Even graph networks are JSON-compatible, which is what we’ll eventually upload.
Go and find some data of interest to you. For example, the Johns Hopkins University Center for Systems Science and Engineering maintains a beautifully ordered repository of domestic and international COVID-19 data:
CSSEGISandData/COVID-19
This is the data repository for the 2019 Novel Coronavirus Visual Dashboard operated by the Johns Hopkins University…
github.com
And a huge list of government and private sources — fine data to work with. I pulled down yesterday’s US daily report in CSV format.
Double Check your Data
This is all made quite simple with Jupyter notebooks; nothing more than
df = pd.read_csv(‘../data/covid_data.csv’) and you’ve got a brilliant dataframe.
File paths are important as well, if only to keep your project neatly structured with subdirectories. Using
../ to extend the working directory is quite the same as keeping your clothes neatly folded in drawers rather than strewn haphazardly about the room.
The data is quite well ordered; we’ve got 58 rows, one for each US state/region.
The actual case numbers are in their own columns, and show “numbers so far” rather than “new numbers today”.
If we want to compare them later over time, we could just aggregate each daily CSV in the repository and compare it against the previous day. JHU also put out a time series CSV that seems to have already taken care of this.
Getting a general statistical overview with
df.describe() is also quite helpful:
The mean death count of 5093 for 58 regions lines up well with the 296,000 deaths so far. The mean
Case_Fatality_Ratio of 1.72 is somewhat alarming, of course — that should indicate an average of one death per 1.72 recorded cases, unless the documentation says otherwise.
Fitting Into the Pipe
Now we’ve got workable data and know (generally) what it’s about, we can put it into ArcGIS.
Their Spatially Enabled Dataframe extends Pandas’ usual Dataframe, so there isn’t too much complexity involved in working between the two.
We start by making a GIS object to interface with the various modules:
from arcgis.gis import GIS
# instantiate new GIS object
gis = GIS("", 'username', 'password')
ArcGIS uses Feature Collections as cloud-hostable data structures. We can convert our covid dataframe by passing it through the
gis.content.import_data() method:
# import dataframe as feature collection
covid_fc = gis.content.import_data(df)
Now we need to transform it to a JSON (since we’re working with an API, after all):
import json# create feature_collection_property dict
covid_fc_dict = dict(covid_fc.properties)# convert to JSON
covid_json = json.dumps({'featureCollection':{"layers": [covid_fc_dict]}}) # careful with the double nesting format
Finally we assign the
covid_json to some
Item properties to make it more easily searchable, then create & add the final
Item object to our GIS.
The above data is now a searchable GIS Item stored on your user-info cloud. Next time we’ll access the piped data to create a mapping feature layer.
|
https://mark-s-cleverley.medium.com/creating-importing-data-for-arcgis-394166e27fda?readmore=1&source=---------1----------------------------
|
CC-MAIN-2021-10
|
refinedweb
| 654
| 53.41
|
On 21/04/2010 19:38, Bas van Dijk wrote: > On Tue, Apr 20, 2010 at 12:56 PM, Simon Marlow<marlowsd at gmail.com> wrote: >> On 09/04/2010 12:14, Bertram Felgenhauer wrote: >>> >> > > I can see how forkIOWithUnblock (or forkIOWithUnnmask) can introduce a wormhole: > > unmaskHack1 :: IO a -> IO a > unmaskHack1 m = do > mv<- newEmptyMVar > tid<- forkIOWithUnmask $ \unmask -> putMVar mv unmask > unmask<- takeMVar mv > unmask m > > We can try to solve it using a trick similar to the ST monad: Funnily enough, before posting the above message I followed exactly the line of reasoning you detail below to discover that there isn't a way to fix this using parametricity. It's useful to have it documented, though - thanks. Cheers, Simon > {-# LANGUAGE Rank2Types #-} > > import qualified Control.Exception as Internal (unblock) > import Control.Concurrent (forkIO, ThreadId) > import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) > > newtype Unmask s = Unmask (forall a. IO a -> IO a) > > forkIOWithUnmask :: (forall s. Unmask s -> IO ()) -> IO ThreadId > forkIOWithUnmask f = forkIO $ f $ Unmask Internal.unblock > > apply :: Unmask s -> IO a -> IO a > apply (Unmask f) m = f m > > thisShouldWork = forkIOWithUnmask $ \unmask -> apply unmask (return ()) > > The following shouldn't work and doesn't because we get the following > type error: > > "Inferred type is less polymorphic than expected. Quantified type > variable `s' is mentioned in the environment." > > unmaskHack2 :: IO a -> IO a > unmaskHack2 m = do > mv<- newEmptyMVar > tid<- forkIOWithUnmask $ \unmask -> putMVar mv unmask > unmask<- takeMVar mv > apply unmask m > > However we can still hack the system by not returning the 'Unmask s' > but returning the IO computation 'apply unmask m' as) > > AFAIK the only way to solve the latter is to also parametrize IO with s: > > data IO s a = ... > > newtype Unmask s = Unmask (forall s2 a. IO s2 a -> IO s2 a) > > forkIOWithUnmask :: (forall s. Unmask s -> IO s ()) -> IO s2 ThreadId > forkIOWithUnmask f = forkIO $ f $ Unmask Internal.unblock > > apply :: Unmask s -> IO s2 a -> IO s a > apply (Unmask f) m = f m > > With this unmaskHack3 will give the desired type error. > > Of course parameterizing IO with s is a radical change that will break > _a lot of_ code. However besides solving the latter problem the extra > s in IO also create new opportunities. Because all the advantages of > ST can now also be applied to IO. For example we can have: > > scope :: (forall s. IO s a) -> IO s2 a > > data LocalIORef s a > > newLocalIORef :: a -> IO s (LocalIORef s a) > readLocalIORef :: LocalIORef s a -> IO s a > writeLocalIORef :: LocalIORef s a -> a -> IO s a > > regards, > > Bas
|
http://www.haskell.org/pipermail/libraries/2010-April/013545.html
|
CC-MAIN-2014-10
|
refinedweb
| 422
| 51.99
|
Personal Security System Using Arduino
Introduction: from this tutorial, I hope you learn how to use a buzzer and LED's to display how far away an object is from the ultrasonic sensor.
Step 1: Assemble Materials
Materials required are:
(1x) Arduino Uno
(1x) Breadboard
(1x) HC-SRO4 Ultrasonic Sensor
(1x) Buzzer
(1x) Green LED
(1x) Yellow LED
(1x) Red LED
(4x) 220 ohm Resistors
(10x) Jumper wires
Step 2: Setup
3
On Ultrasonic Sensor:
Echo = pin 6
Trig = pin 7
LEDs:
RedLED = pin 9
YellowLED = pin 10
GreenLED = pin 11 6 on the Arduino and connect the Echo pin on the sensor to pin 11 10 on the Arduino and then connect the anode of the red LED to pin 9. Once you have done that, your setup should look similar to the picture above.
*NOTE* 3 of the Arduino using a green wire and then connect the shorter leg of the buzzer to the negative channel of the breadboard using a 220 ohm resistor.
*NOTE*
It is HIGHLY recommended to use a resistor in connecting the shorter leg of the buzzer to the negative channel of the breadboard. This greatly reduces the volume of the buzzer and prevent it from dying to quickly.
Step 7: Code
Now that you have finished the setup, its time to code the Arduino. All you have to do, is to open the Arduino program on your computer and then copy and paste the code from below. Feel free to change the distances at which the ultrasonic sensor detects an object from and the volume of the buzzer!
#define trigPin 6<br>#define echoPin 7 #define GreenLED 11 #define YellowLED 10 #define RedLED 9 #define buzzer 3
int sound = 500;
void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(GreenLED, OUTPUT); pinMode(YellowLED, OUTPUT); pinMode(RedLED, OUTPUT); pinMode(buzzer, OUTPUT); }
void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/5) / 29.1; if (distance < 50) { digitalWrite(GreenLED, HIGH); } else { digitalWrite(GreenLED, LOW); } if (distance < 20) { digitalWrite(YellowLED, HIGH); } else { digitalWrite(YellowLED,LOW); }
if (distance < 5) { digitalWrite(RedLED, HIGH); sound = 1000; } else { digitalWrite(RedLED,LOW); } if (distance > 5 || distance <= 0){ Serial.println("Out of range"); noTone(buzzer); } else { Serial.print(distance); Serial.println(" cm"); tone(buzzer, sound); } delay(300); }
Once you've done that, and you've plugged in your Arduino to your computer, run the code and you're finished. If you've followed all the directions properly, the closer your hand or any object gets to the HC-SRO4 ultrasonic sensor, the LEDs should progressively light up until and you're so close that the buzzer will go off.
Step 8: The Working Arduino!
This is a really fun project, I had a lot of fun creating it. I just want to give a shoutout to my Computer Science teacher Mr. Smith for being so very helpful and being amazing!
hi nice project for beginners.
I wonder why my buzzer didn't ring
The coding above u wrote has a mistake in line 1
So the original was
#define trigPin 6<br>#define echoPin 7
The needed code is
#define trigPin 6#define echoPin 7
(just remove the <br>)
and make sure ur COM is 3 or 5 according to your number.
To change it watch this short vid below
Hey Its My Youtube Video Tutorial
Very nice
very easy and informative projects, my students here in Damascus loved it!, they practiced and implemented the basics they've been learning in this project, Appreciate the time you spent on writing this Instructble
The given code wasn't working for me, so I edited it. Here is what I came up with:
//This sketch tells you if you get too close using a HC-SR04 sonar,
//red, yellow, and green LEDs and a piezo buzzer.
#include <NewPing.h> //include HC-SR04 sensor library
#define TRIGGER_PIN 6 //set up trigger pin on HC-SR04
#define ECHO_PIN 7 //set up echo pin on HC-SR04
#define MAX_DISTANCE 200 //set up max distance on HC-SR04
#define GreenLED 11 //set up the green LED on pin 11
#define YellowLED 10 //set up the yellow LED on pin 10
#define RedLED 9 //set up the red LED on pin 9
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // set up sonar
int buzzer = 3; //set up piezo buzzer
void setup() //Let's get started!
{
Serial.begin (9600); //Let the serial monitor know it will be getting info
pinMode(GreenLED, OUTPUT); //Let ardino know that LED will be outputting
pinMode(YellowLED, OUTPUT); //Let ardino know that LED will be outputting
pinMode(RedLED, OUTPUT); //Let ardino know that LED will be outputting
pinMode(buzzer, OUTPUT); //Let ardino know that buzzer will be outputting
}
void loop() //Now for the fun stuff!
{
long distance=sonar.ping_cm(); //set up variable "distance" with sonar info
if (distance > 50) //If the distance is more than 50 cm
{
digitalWrite(GreenLED, HIGH); //turn on the green light
Serial.print(distance); //write the distance to the monitor
Serial.println(); //blank line for readability
digitalWrite(RedLED,LOW); // make sure the red LED is off
digitalWrite(YellowLED,LOW); // make sure the yellow LED is off
analogWrite(buzzer, LOW); // make sure the buzzer is off
}
else if (distance > 20 && distance < 50) //If the distance is more than 20 cm
{ // and less than 50 cm
digitalWrite(YellowLED, HIGH); //turn on the yellow light
Serial.print(distance); //write the distance to the monitor
Serial.println(); //blank line for readability
digitalWrite(GreenLED, LOW); // make sure the green LED is off
digitalWrite(RedLED,LOW);// make sure the red LED is off
analogWrite(buzzer, LOW);// make sure the buzzer is off
}
else if (distance > 5 && distance < 20) //If the distance is more than 5 cm
{ // and less than 20 cm
digitalWrite(RedLED, HIGH); //turn on the red light
Serial.print(distance); //write the distance to the monitor
Serial.println(); //blank line for readability
digitalWrite(GreenLED, LOW); // make sure the green LED is off
digitalWrite(YellowLED,LOW); // make sure the yellow LED is off
analogWrite(buzzer, HIGH); // turn on the buzzer
}
delay(300); //wait 300ms between readings so it doesn't get crazy
}
Im just starting to experiment with Arduino and your program writeup is so helpful! I love that you explained what each line did, It makes it so much easier to understand that the Arduino is doing! Do you have any tutorial or other program examples? I would love to learn from them!
I haven't made any tutorials. I just go through the code line by line, yes it takes time but I end up totally understanding the code afterwards-give it a shot
hi,
This is the problem occured when i upload to the uno
I had the same problem. It turn out that I was not using COM1 , I was using COM3, you may have the same problem.You just need to chance the port.
there is a problem in the code the formula calculating the the distance is wrong i think
use this code i made
the connections made where same as shown
const int trigPin = 6;
const int echoPin = 5;
#define GreenLED 11
#define YellowLED 10
#define RedLED 9
#define buzzer 3
int sound = 500;
void setup()
{
// initialize serial communication:
Serial.begin(9600);
pinMode(GreenLED, OUTPUT);
pinMode(YellowLED, OUTPUT);
pinMode(RedLED, OUTPUT);
pinMode(buzzer, OUTPUT);
}
long distanceOverTime(long first,long second)
{
return ((first-second)/.1)*.0223693629;//taking cm/s to mph
}
long holder;//store the cm from last time through loop.
long temp;//used to store the speed value after changes
int counter;
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
int tens;
int ones;
long Speed;
//);
if (cm<= 50) {
digitalWrite(GreenLED, HIGH);
}
else {
digitalWrite(GreenLED, LOW);
}
if (cm<= 30) {
digitalWrite(YellowLED, HIGH);
}
else {
digitalWrite(YellowLED,LOW);
}
if (cm<= 15) {
digitalWrite(RedLED, HIGH);
sound = 1000;
tone(buzzer, sound);
}
else {
digitalWrite(RedLED,LOW);
noTone(buzzer);
}
/* if (cm< 5 || cm<= 0){
Serial.println("Out of range");
noTone(buzzer);
}
else {
Serial.print(cm);
Serial.println(" cm");
tone(buzzer, sound);
}*/
delay(300);;
}
Hello, I have a problem , when I used your code it never stopped buzzing.Do you have any idea why?. I really need yours or anybodies help.Thanks.
How can I modify it so I don't have it plugged to my computer al the time?
Hi,
This project didn't work when I used the program you kindly wrote, I had to change a few things in it (which was very difficult for a fresh beginner like me).
Evantually it worked fine
Thank you for a very nice project
Pleasee send the code to
phinahasphilip2000@gmail.com
Plssss it is our first mission
Hope u will send plss,,,,
Hi! I like the project very much and I want to make it. But, I have an ultrasonic sensor of three pins instead of four. I need help to solve the problem. Could you help me?
sorry ,
I didn't see your reply,
I'll send it in the next days since I'm on vacation right now
good
Hi,
I'm gonna try this feature in the next few days, thank you for that.
Where can I find the software to creat such a schemes like you did?
Where
thank uu
HOW DID YOU DO IT? CAN YOU GIVE A TUTORIAL
i think (RedLED,LOW) IS WRONG IT SHOULD BE WRITTEN IN ('RedLED',LOW);
I was think if some one could help me with the code if i want it to work exactly opposite to this. For eg. the buzzer doesnot make sound if any object is near but buzz is it moves away.
is this code working properly!!!!!
do we need to install library for ultrsonic sensor??
Sorry for the post below I figured out the problem. just had to delete <br> and hit return.
All good now and the ibl is really well done congrats!
Very good
Great arduino project.
I kike it
|
http://www.instructables.com/id/Personal-Security-System-Using-Arduino/
|
CC-MAIN-2017-43
|
refinedweb
| 1,672
| 57
|
4 replies on
1 page.
Most recent reply:
Oct 25, 2006 7:18 PM
by
Ivan Lazarte
Although barely two years old, the Dojo project, like most things Ajax these days, has gone through a fast and furious pace of development. Judging from its list of available features, Dojo aims to be nothing less than a complete API and toolkit for developing rich-client Ajax applications. Because Dojo is based on pure JavaScript, Dojo-based applications are not tied to any server-side technology, such as JSF or .NET.
The Dojo project's latest release adds to the already rich palette of Ajax widgets a charting component, a clock, a progress bar, and enhancements to an already feature-rich text editor. Support for internationalization, accessibility support, and namespaces are also part of this release. Several of these features are available in online demos.
While early Ajax APIs and widget toolkits appealed to developers mainly as eye candies, Dojo's recent improvements to its API documentation tool indicate a shift to a more enterprise-ready focus:
These improvements will make Dojo appealing to entirely new audiences and will bring Ajax applications to a new level of acceptance as a first-class user environment.
These improvements will make Dojo appealing to entirely new audiences and will bring Ajax applications to a new level of acceptance as a first-class user environment.
With heavyweights IBM and AOL on the Dojo Foundation's board, more features required by enterprise developers are the Dojo project's roadmap.
Perhaps the most interesting feature in this release is support for direct 2D graphics that take advantage of browser support for SVG. The Dojo 2D, or DFX, package aims to support two scenarios:
The drawing starts as a template written in an SVG subset... In case of IE, SVG is translated to VML using XSLT preserving attach points. The widget author can modify elements using the provided API.
The drawing is created from scratch. It is created using the provided API.
Our main target is SVG. VML is supported using a translation layer. Canvas can be targeted later using the proposed API definition.
Our main target is SVG. VML is supported using a translation layer. Canvas can be targeted later using the proposed API definition.
2D features in the dojo.fgx package already include objects supporting filling an area, including gradient fills, brush strokes, as well as drawing various matrices and shapes.
dojo.fgx
Dojo enables you to build completely browser-based applications independent of any server-side component. This contrasts with JSF, which advocates a model whereby client-side HTML and JavaScript components are paired with server-side peers written in Java. Dojo apps can run entirely inside a browser, and invoke remote services via XML APIs over HTTP on an as-needed basis. They would also be coded up entirely in JavaScript. What do you think of this type of self-contained Ajax application?
|
http://www.artima.com/forums/flat.jsp?forum=276&thread=181997
|
CC-MAIN-2017-43
|
refinedweb
| 488
| 55.13
|
Not like SSH wasn’t pretty secure before, due to encryption, but every step towards security helps.
I took note to his advice on moving SSH to a non-standard port:
Security though obscurity you scoff? Perhaps. But it’s easy, causes no inconvenience, and might just reduce the number of attacks. That sounds like a winner to me.
I have also noticed that moving SSH to a non-standard port decreasing the amount of hacking activity against SSH by almost 100%.
Also it adds another benefit: the ability to expose SSH on multiple machines that may be natted on a network and sharing a single external IP such as on a cable or dsl modem. Just give each machine you want to expose a different non-standard port to run SSH on. I would recommend a VPN over exposing SSH to the Internet, but in some cases it may be necessary as some remote locations may not allow VPN traffic leaving their networks…
Technorati Tags: SSH, security, securing, secure, list, lists, VPN, linux
import this. » Blog Archive » HOWTO: Five steps to a more secure SSH // October 31, 2006 at 7:44 pm |
[...] Jon Barnhardt has some additional comments regarding moving ssh to a non-standard port. [...]
Tim Archer // April 10, 2007 at 7:16 am |
I had the same problem where my SSH server was getting attacked all day long. I made a simple change in just changing the port it listens on.
I did a small write on how to do this at
|
http://midspot.wordpress.com/2006/10/31/great-article-on-securing-ssh/
|
crawl-002
|
refinedweb
| 255
| 60.65
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
method calling problem in openErp/python
hi,
i have a problem understanding how to call methods on objects in openERP:
example: something(self,cr,uid,ids,context=None)
sometimes the method is called with only one parameter, sometimes with all the parameters, sometimes a few, sometimes you can omit the 'self' parameter, aargghh...
The exceptions i get (when calling a method wrongly) are also very confusing (in terms of nr of parameters)
Practically i always have to 'brute force/guess' every possibility before i can make a call, i just don't understand the logic. All my time is wasted on this stupid 'guessing-work'
Calling the function according to the prototype just does't seem to work in 90% of the cases.
It's so confusing, i'm very used to C++/Java and this method calling is really giving me a headache, 90% of my time is spent on how to figure out the correct way to call it. The prototypes of the methods just don't make any sense on how to call them.
Can someone please explain what i need to read/learn so i understand how to call member functions in openErp without always guessing the parameters (type,nr,..)?
thank you very much if you
for example: i need to call a method
def make_initial_invoice(self, cr, uid, ids, context={}):
i calll it like this:
and raises this exception: takes at most 5 arguments (7 given)
why does it say 7 parameters? I only give three, right??
even when i do this agreement.make_initial_invoice(cr,uid,1)
it's not working
What am i missing here? Basic Python? Or is it normal to 'guess' how to call every method?
You have to read all the openERP guide. The truth is that I learned debugging over all the openERP code. I work with Linux Mint, eclipse and that's all. When I don't know what's happening I only have to put a breakpoint there. At first it's a little bit weird but when you understand the logic it's quite easy.
Thanks for your reply, my mistake was confusing a 'model' with a 'row'. I'm also using Ubuntu+eclipse with debugging, i've read the guide, but IMO, it's the naming of the classes/members particularly which is so confusing. I prefer calling a model of a cat, 'cat_model' and a record 'cat_record'. Names like cat_cat, mixed with cat are way too confusing. IMHO. :)
|
https://www.odoo.com/forum/help-1/question/method-calling-problem-in-openerp-python-24887
|
CC-MAIN-2017-04
|
refinedweb
| 442
| 69.72
|
20 June 2012 08:06 [Source: ICIS news]
SINGAPORE (ICIS)--Qatar Petrochemical Co (QAPCO) will start up its 300,000 tonne/year low density polyethylene (LDPE) plant, or LDPE-3, at Mesaieed in ?xml:namespace>
The source did not specify the reason for the delay from the previous target start-up date of end-May.
“The [new] plant should be starting up later today or latest by tomorrow,” the source said.
“We will not ship out material for sales in July but instead from August. It is better for us to build up some inventories prior to the first sales,” the source said.
QAPCO's two existing 200,000 tonne/year LDPE units at the same site are operating at 100% of
|
http://www.icis.com/Articles/2012/06/20/9571126/qatars-qapco-to-start-up-ldpe-3-unit-on-20-21-june.html
|
CC-MAIN-2015-11
|
refinedweb
| 122
| 69.62
|
Nearby: SWAD-Europe events page | Workshop home page | Workshop Announcement | Attendees | Position papers
Next day Friday 2003-11-14
02:19:49 <dmwaters> {server notice} Ok guys, that server is you. I will restart the server once configs are done pushing and when I've updated dns
02:22:43 Disconnected from irc.freenode.net (Connection reset by peer)
02:23:06 Users on #swade: @logger
08:29:27 <NickServ> This nickname is owned by someone else
08:29:27 <NickServ> If this is your nickname, type /msg NickServ IDENTIFY <password>
09:12:48 <libby> hello nick
09:21:28 <libby> daveb: redland, storage, open source
09:22:10 <libby> frank: inferencing, european projects, case studies, thesauri, portals, sw apps
09:22:42 <libby> ...run 2 courses on sw for students
09:23:42 <libby> mark ? : phd, ontology mapping
09:23:56 <jeen> mark van assem
09:24:15 <libby> mike: a new developer; new user of the technology
09:24:45 <libby> jack: startup, lgpl software
09:24:57 <libby> crap, keep missing names :(
09:25:31 <libby> ?? & jeen - sesame - stoarge query and inferencing, java
09:25:57 <libby> jeen: main interest in query, also inferencing
09:26:01 <nmg> arjohn and jeen
09:26:35 <libby> AndyS: network retrieval, query; now a user
09:27:09 <jeen> libby: ilrt, squish, interested in applications, web services, photo metada, coauthor of foaf
09:27:29 <nmg> nmg: AKT project (), interactive SW applications (CS AKTiveSpace), 3store RDF storage and inference
09:28:10 <libby> martin pike: stilo; xml, using and implementing SW technologies, aerospace
09:28:45 <libby> nick james: stilo - not research, industrial useage, lots of experience using databases
09:28:59 <libby> ?? works with frank
09:29:04 <libby> (sorry missed name)
09:29:16 <jeen> heiner stuckenschmidt
09:29:33 <jeen> postdoc researcher, works on distributed querying
09:29:34 <libby> ...how to use sesame for querying, physically distributed repositories, sub-parts of a query in difefrent places and rejoin
09:29:50 <libby> steve harris: 3-store and other bits
09:30:28 <libby> jo walsh: free software developer; perl+rdf; bots, http query; rather like joseki/serql
09:30:48 * jeen is a victim of his preconceptions again :/
09:31:00 <libby> dave reynolds: hplabs, sw, wrote jena 1 db backend; now inference, owl support
09:31:52 <libby> daniel krech, mindlab; before rdflib, bdb, zope, storage, apps, foaf,
09:32:20 <libby> kevin wilkinson, hplabs, palo alto - database guy, issues of scaling, using rdf in db
09:32:41 <libby> gregorio from crete (??): visting Frank, storage, retrieval, KR, rules
09:32:51 <libby> gregorius
09:33:14 <libby> frank: he and gregorius have written a SW textbook
09:34:35 <libby> zack: @semantics, building real, commercial sw apps
09:35:07 <libby> alberto: @semantics, rdfstore, rdql, exchange of ideas
09:35:49 <libby> dirk: @semantics; non-rdf things are important also for commercial apps, e.g. freetxt
09:36:10 <libby> ?? (sorry) an end-user of sesame, web serivces based on that
09:36:45 <jeen> sander van splunter
09:36:46 <libby> ?? (sorry) a developer of SWI prolog, recently storage and handling of rdf in prolog
09:36:57 <arjohn> jan wielemaker
09:36:58 <dajobe-lap> ^jan
09:37:39 <libby> guus: now at vrij university; recent interest in ontology enginnering, multimedia; webont co-chair; working on best practices wg
09:37:59 <libby> ...draft charter
09:42:52 <libby> talking briefly about position papers
09:43:43 <libby> jeen:
09:44:03 <libby> compositionality; datatypes; schema awareness
09:45:00 <libby> rdf output
09:46:38 <arjohn> demo server:
09:47:36 <libby> alberto:
09:49:07 <libby> RDFStore: C/perl toolkit, rfstore: graph, freetext, content searching. ; bsd license
09:52:07 <libby> btrees: was bdb; now custom; no sql, yet; would not use features of sql
09:54:42 <libby> find a way of searching using bitmaps
10:01:27 <libby> interesting stats on retrievel speeds; dirk: no dependance on N (num statements) only on M , nnumber of hits. hence no theoretical limit to db size
10:02:30 <libby> ditto with rdql queries
10:04:06 <libby> lond-run, queries won;t scale
10:05:02 <libby> long-run
10:05:21 <libby> 'swiss-knife problem'
10:08:53 <libby> Jan Wielemaker(?):
10:09:08 <libby> wants to have 3m triples running on laptop, using prolog
10:10:49 <libby> prolog not good for transitive closure
10:11:51 <libby> 3m triples loaded in 10 secs
10:12:04 <libby> form rdf/xml source about 10x slower
10:12:16 <libby> owl is a challenge
10:17:06 <libby> dave beckett:
10:18:26 <libby> redalnd stores everything, not hashes, because disk access is slow
10:19:50 <libby> redland, even
10:20:23 <libby> no schema support....thinks freetext is useful
10:22:08 <libby> jeen/dirk using special namespaces as escape-hatch e.g. for free-text searching
10:25:15 <libby> jeen: queries and contexts. 3-store does this
10:25:24 <jeen> ...and so should we :/
10:27:04 <libby> yeah, I was fiddling with this cos it gets right down to the problem of storage. otherwise you can;t get at provenance via query...or not quickly anyway
10:27:34 <libby> kevin wilkinson(?):
10:28:28 <jeen> true; though in our case the main bottleneck is adding support in the API. the actual storage can be solved, but changing the API without breaking stuff...
10:28:43 <jeen> we have a legacy problem it seems :)
10:30:11 <libby> jim ley and I have been playign with simple SQL storage patterns and: provenance makes it much slower, but, uniqueness seems to be the most important aspect.
10:30:38 <swh> libby: I didnt find that context added much to the cost
10:30:52 <nmg> uniqueness in what sense? of triples in a context?
10:31:06 <libby> kevin: jena uses sql dbs for backend storage. big diff is move from jena1: 2 tables; jena 2 - more
10:31:40 <libby> yeah, unique per context
10:32:24 <nmg> from what I remember, we found this to be expensive as well (building indexes across SPOM)
10:33:19 * libby talking at 500,000 triple level, small-scale, but signifiacant dfferences at that stage
10:33:22 <swh> yeah, SPOM indexes bite too much
10:33:58 <swh> are uniq-ing code is at the app level
10:34:09 <swh> subj-pred-obj-model
10:34:12 <libby> sub pred ob provenance
10:34:15 <libby> ah, gotya
10:34:17 <nmg> (expect we should probably call them SPOC now that 'model' is unfashionable)
10:34:17 <swh> model-context
10:34:37 <libby> heh, spoc!
10:35:06 <AndyS> Subj-Pred-Obj-Context
10:35:19 <libby> kevin: interested in legacy data. sorta columns are preds in general rdbms
10:36:25 <libby> ...denormalized schema; faster than jena 1 byt 2x storage
10:37:20 <libby> now looking at:
10:37:24 <libby> (I think)
10:37:38 <libby> 'pattern mining'
10:42:27 <libby> synthetic rdf generator
10:43:15 <libby> Daniel Krech up.
10:43:23 * libby doesn't see paper
10:43:36 <libby> d'oh:
10:44:37 <AndyS> Joseki has an RDFLib-bases
10:44:45 <libby> does it?
10:44:51 <AndyS> Joseki has an RDFLib-based client library
10:44:58 <AndyS> "Pyseki"
10:45:23 <libby> daniel: contexts. python
10:45:26 <libby> zope btrees
10:45:28 <AndyS> Want a Perl one as well
10:45:50 <AndyS> Any other language requests? (no promises!)
10:47:24 <libby> is this Jack Rusher?
10:47:25 <libby>
10:47:34 <dajobe-lap> yes
10:48:15 <libby> b-tree impl from scratch; read rather than write, long ints; 3 indexes
10:48:37 <libby> sorted longint sets; binary search, mapped to string table
10:48:52 <jeen> sounds interesting as a backend system.
10:50:01 <libby> java. no ql stuff yet. seems to scale well and perform well
10:53:01 <libby> steve: 3-store
10:53:12 <libby> needed somewhere to put 50m triples
10:53:37 <libby> soundness but not completeness; some corner cases nnot covered.
10:54:02 <nmg> it was 15M not 50M...
10:54:02 * AndyS interested in finding out what the corner cases are
10:54:13 <dajobe-lap> later...
10:54:39 <libby> oops sorry nmg
10:55:07 <libby> lots of interactive apps, need to keep speed up. inserts slower, needs more work.
10:55:45 <nmg> AndyS: the gist is that we evaluate the entailment rules in a fixed order and only pass over most of them once - we get the useful entailments that we need for our applications from this approach
10:55:48 <libby> now about 26m triples, 152 bytes/triple; 5gig. ints, freetest searching
10:56:12 <libby> ...joeski-like remote api
10:56:43 <AndyS> Wonder what the schema for the result set is?
10:56:47 <libby> [that's cool. /me wants to steal your data...]
10:57:15 <libby> ...has context-extension to rdql
10:57:24 <nmg> AndyS: we don't have a formal schema for it (coughcough), but it would be easy enough to reverse engineer one from the data
10:57:31 <libby> ...store data about whether parse succeeful, date and time etc.
10:57:43 <nmg> libby: data is in
10:57:48 <libby> plan to support 'owl-tiny'
10:58:09 <libby> distributed storage and query to increase scalablility
10:58:15 <AndyS> NMG: WHat about ??
10:58:40 <nmg> OWL-Tiny is own name for the subset of OWL-Lite that contains property characteristics and equality/inequality relations from OWL Lite
10:59:04 <libby> are you supporting inverseFunctionalProperty?
10:59:45 <nmg> AndyS: ah. well, I'm sure we'll add support for that (I don't think that it was around when we wrote the XML return format)
11:00:05 <nmg> libby: as yet, no, but high on the wishlist
11:00:09 <libby> --lunchtime--
11:00:25 <jeen> libby, you're only saying that because you've never been in our canteen yet...
11:00:32 <nmg> context-based truth maintenance is probably the top of the list, OWL-Tiny probably after that
11:00:36 <nmg> swh may disaghree, of course ;)
11:20:49 <CaptSolo> hi all :)
11:32:12 <CaptSolo> everybody's busy at the workshop?
11:37:56 <Wack> busy with lunch, probably :]
11:39:06 <CaptSolo> ah, true, lunch is a VERY important part :>
11:39:36 <CaptSolo> it would be interesting to hear about the workshop...
11:39:50 <CaptSolo> isn't somebody there who can do real-time blog? ;>
11:40:23 <Wack> libby is reporting stuff here
12:01:05 <CaptSolo> logger url
12:01:10 <CaptSolo> logger help
12:04:21 * nmg returns from lunch
12:04:53 <CaptSolo> wack: you were right about lunch i guess ;]
12:05:28 <CaptSolo> (is there an URL where one can see this channel logged?)
12:07:06 <Wack> logger pointer?
12:07:08 <Wack> logger pointer
12:07:35 <libby>
12:09:12 <dajobe-lap> it should be live now
12:11:21 <libby> dajobe-lap: the other loggers seem to be dead :(
12:12:10 <libby> nick james:
12:12:24 <libby> (there was a massive netsplit last night)
12:12:32 <libby> using maths with RDF
12:13:11 <afs> afs is now known as AndyS
12:13:13 <libby> simple rdf storage - for presentation
12:13:18 <libby> not searching
12:14:11 <libby> martin pike: trying to capture the process of making a plane, so that when people leave or die, don't lose that info
12:14:59 <libby> scaling will become important
12:15:49 <swh> version control for RDF is an interesting subject
12:16:29 <libby> jo walsh:
12:16:35 <CaptSolo> swh: that might be interesting, true
12:16:37 <libby> interested in restful api
12:16:47 <CaptSolo> swh: has there been a presentation on version control?
12:16:58 <swh> CaptSolo: the last speaker mentioned it
12:17:13 <swh> (they have some support for branches or similar)
12:17:23 <CaptSolo> they = some software?
12:17:38 <libby> jo: returns a graph that returns more than what you ask for
12:17:40 <CaptSolo> what software?
12:18:02 <libby> descriped here I think...
12:18:12 <jeen> omm support change tracking as well actually.
12:18:23 <libby> jo: better ways of representing context
12:18:42 <libby> ...e.g. ericp's summary
12:18:51 <CaptSolo> swh: CVS would not be sufficient for RDF as we must control the triples, not the order how it is presented in textual form
12:19:16 <libby> ...sending queries over http api...dreaming of an ideal ql - like serql
12:19:34 <swh> CaptSolo: yes, you need to diff the triples - I came up with a diff like algorithm, be efficient (linear or near) implenntation is hard
12:19:47 <swh> ...but efficient...
12:20:12 <nmg> diffing the triples isn't enough - you need to take account of bNodes
12:20:33 <nmg> jeremy carroll had something about RDF graph canonicalisation at ISWC which is relevant here
12:20:44 <swh> bnaode are all different from all other bnodes, unless they have IDs
12:21:07 <swh> its a subset of the canon. problem
12:23:02 <nmg> well, the id assigned to a bNode may change from one version to the next, while the graph structure itself remains the same. is the Node in one version really different from the bNode in the other?
12:23:29 <swh> in diff terms, yes
12:26:01 <libby> relational datbases
12:26:06 <libby> one true schema?
12:28:00 <libby> kevin: built-in query optimisers
12:28:18 <libby> dirk: work with rdf schemas?
12:28:30 <jeen> was that what he asked?
12:29:15 <libby> I was trying to say: work with the sorts of db schemas used for RDF?
12:29:24 <libby> I'm not sure taht he asked that either :)
12:30:09 <libby> daveR: an overflow structure and optimisations. not translated to a fixed schema
12:31:03 <libby> swh: many dbs don't like multiple joins
12:32:16 <libby> nmg: didn't have time to write our own
12:33:14 <libby> dirk: probbaly ought to reexamine backend if so many joins
12:34:30 <libby> nick james: optimisers can;t gather statistics effectively in triples bucket structure
12:35:46 <libby> swh: uses partly backchaining, partially forward-chaining
12:36:10 <libby> jeen: exhaustive forward chaining operation
12:36:23 <libby> ...seems to work quite well :)
12:37:59 <libby> albert: what about changing data - reindex every week?
12:39:10 <libby> dirk: if many blank nodes in data and queries then be difficult: optimise the rdf to remove the blank nodes
12:39:40 <libby> AndyS: transactions, management, backups, support for relational technology
12:40:06 <libby> ...all good reasons to use sql databases
12:41:38 <libby> arjohn: jdbc itself is a bottlenack
12:42:57 <AndyS> Jena experience of JDBC is that drivers return whole query to client before first result to app, not stream as required :-( (MySQL and PostgreSQL documented features)
12:44:12 <arjohn> second andy's remark. this behaviour is very bad for memory footprint when big query results are returned:-(
12:44:17 <AndyS> Means whole result in memory at one time - big boo! No cursors
12:44:33 <swh> AndyS: there is a low level mysql api that has streaming
12:44:40 <swh> (but we dont use it ;)
12:45:16 <AndyS> Is that a network API? I want DB on a different machinne
12:46:13 <swh> I will move some of the 3s stuff to hte streaming api, and its all nw transparent (of course)
12:46:22 <swh> the api is more fiddly than the chunked one
12:49:41 <AndyS> This is the C API isn't it? mysql_connect takes a host name
12:50:42 <AndyS> Do you use prepared statments? Coudl they be useful?
12:51:04 <swh> no, but I guess they could be - maybe query caching too, but its not really an issue at the moment
12:51:12 <swh> the ram is more useful for disk caches
12:51:24 <AndyS> I wondered about an app having common patterns of access
12:51:30 <arjohn> speeds up parsing but doesn't help getting the results
12:51:56 <AndyS> arjohn - is it for tuning? Of are there std prepared queries you use?
12:52:08 <swh> is parse speed an issue? I guess I could cache the pre-optimiser results
12:52:39 <arjohn> we use it while uploading data
12:52:50 <swh> ahh, right, I plan to look at that
12:56:48 <libby> jo: why can;t every triple be reified in jena2?
12:57:01 <libby> daveR: because a statemnt can be reified multiple times
12:59:45 <libby> swh: left joins are bad; however for RDF they don;t seem to be too bad (with indexes)
13:01:34 <swh> maybe, were supposed to be bad, by db theory is a little rought and probalby out of date
13:05:13 <swh> urgh :-/ z39.50
13:09:29 <libby> ...discussion of pros and cons of extensions to RDF, e.g. for dates, geo stuff
13:11:08 <AndyS> This is a good role for a WG - identify a set of operators that all can expect
13:11:22 <AndyS> ... or is that the profiles problem again
13:11:56 <libby> yeah, operators like those in xquery would be good
13:12:13 <AndyS> (application) profiles - a restriction of a broad standard to a subset
13:13:19 <AndyS> xquery ops are probably a baseline
13:14:18 <AndyS>
13:15:13 <AndyS> "D2R MAP is a declarative language to describe mappings between relational database schemata and OWL ontologies"
13:22:16 <AndyS> Any use of (e.g. Lucene) text indexing engines?
13:23:10 <AndyS> How does it mix with the main store?
13:25:04 * AndyS waiting to hear from Jeen
13:27:42 <jeen> we integrate on the api level, so the text index is wrapped directly from source, we don't pull the data into the main (sql) store
13:27:55 <jeen> "lazy" evaluation, if you will
13:28:16 <AndyS> So it is triple match and feed value expressions to the text db?
13:30:03 <libby> arjohn: any advantages to using digests or hashes? (digests are crypto)
13:30:15 <libby> dirk: sha1 is dirt cheap.
13:30:56 <libby> (??) sees no problem with generating any of these
13:31:07 <libby> swh: ditto - did some tests, esp md5
13:32:24 <libby> libby: tests for clashes?
13:32:36 <libby> sswh: tests for it, but very very unlikely to happen
13:35:05 <swh> "probability of a hash collision occurring in a knowledge base of 500 million resources and literals is around 1:10^-10"
13:35:23 <libby> and you use full md5 hashes?
13:35:29 <swh> nope, top half
13:35:45 <swh> with all 128 bits it would be eve safer, but too slow
13:35:45 <libby> I think I use part of a sha1
13:35:53 <libby> right, cool
13:35:55 <swh> if you like, but md5 is more common
13:36:06 <libby> not sure why we picked sha1
13:36:12 <libby> random, probbaly :)
13:36:23 <swh> doesnt really matter
13:45:38 <libby> jeen: does more or less 1-2-1 mapping between serql and sql query
13:48:14 <jeen> my main point was actually that this mapping is an optional thing. if such a mapping is not possible, the gear is still there to evaluate the query.
13:48:40 <AndyS> Jena does similar - each store gets a chnace to
13:48:51 <AndyS> optimize a query - or part of a query
13:49:37 <AndyS> sounds like Sesame's mapping is more sophisticated
13:50:25 <jeen> It's not really that complex I think.
14:33:52 <jeen>
14:34:33 <jeen> SWAP - Semantic Web and Peer 2 Peer
14:50:30 <jeen>
14:50:46 <jeen> (sort of relevant for aggregation discussion)
14:51:22 <jeen> tool by Borys Omalyaenko that analyzes RDF data and finds 'same invididuals'.
14:51:28 <jeen> application-specific though.
14:51:39 <swh> nmg wrote something similar - dont have url to hand
14:52:17 <AndyS> Any clues to find the paper (unique naming problem?!)
14:53:49 <AndyS> SIMILE is currently looking at this for matching dc:creators in image catalogues
14:54:11 <AndyS> SIMILE ==
15:00:27 <AndyS> nmg - any clues for that paper on "same individual" problem?
15:01:36 <nmg> let me have a look
15:01:45 <AndyS> jeen - is there a URL for Boris's work?
15:01:55 * AndyS wants to pass refs on to others on SIMILE
15:03:09 <AndyS> s/Boris/Borys/
15:06:45 <nmg> AndyS: we had a paper in EKAW2002 describing some aspects of the coreference/sameIndividualAs problem, available at
15:09:43 <jeen> there's his homepage:
15:10:08 <jeen> I don't know if there is any publication about his SameIndividualAs tool, or if the code is available. I assume it is...
15:15:18 <AndyS> Getting close:
15:17:29 <jeen> yeah, but it's only the demo. no description or code download...
15:17:45 <AndyS> ISWC paper reference (well - name/title) anyone?
15:17:59 <libby> ---discussion on test data, - generated data better than real data, plus generated data not personal
15:18:13 <libby> ---discussion on provenance/contexts etc
15:19:06 <nmg> AndyS: Benchmarking DAML+OIL Repositories, Yuanbo Guo, Jeff Heflin and Zhengxiang Pan
15:19:28 * libby asks for contexts or something in rdf2 - for network retrieval
15:19:41 <AndyS> Thanks nmg
15:19:58 <nmg> AndyS:
15:23:46 <jeen>
15:23:55 <jeen> paper by macgregor about contexts
15:51:10 <dajobe-lap> - end of meeting -
15:51:19 <dajobe-lap> back 09:00 GMT+1 tomorrow
Next day Friday 2003-11-14
The IRC chat here was automatically logged without editing and contains content written by the chat participants identified by their IRC nick. No other identity is recorded.
Alternate versions: RDF and Text
|
http://www.w3.org/2001/sw/Europe/events/20031113-storage/logs/2003-11-13.html
|
crawl-002
|
refinedweb
| 3,792
| 62.01
|
Tool for fixing trivial problems with your code.
Project description
pybetter
Tool for fixing trivial problems with your code.
Originally intended as an example for my PyCon Belarus 2020 talk about LibCST.
Usage
Simply provide a valid Python source code file as one of the argument and it will try to fix any issues it could find.
Usage: pybetter [OPTIONS] [PATHS]... Options: --noop Do not make any changes to the source files. --diff Show diff-like output of the changes made. --select CODES Apply only improvements with the provided codes. --exclude CODES Exclude improvements with the provided codes. --exit-code <CODE> Exit with provided code if fixes were applied. --help Show this message and exit.
Example
# cat test.py def f(): return (42, "Hello, world") # pybetter test.py --> Processing 'test.py'... [+] (B003) Remove parentheses from the tuple in 'return' statement. All done! # cat test.py def f(): return 42, "Hello, world"
Available fixers
B001: Replace 'not A in B' with 'A not in B'
Usage of
A not in Bover
not A in Bis recommended both by Google and PEP-8. Both of those forms are compiled to the same bytecode, but second form has some potential of confusion for the reader.
# BEFORE: if not 42 in counts: sys.exit(-1) # AFTER: if 42 not in counts: sys.exit(-1)
B002: Default values for
kwargsare mutable.
As described in Common Gotchas section of "The Hitchhiker's Guide to Python", mutable arguments can be a tricky thing. This fixer replaces any default values that happen to be lists or dicts with None value, moving initialization from function definition into function body.
# BEFORE def p(a=[]): print(a) # AFTER def p(a=None): if a is None: a = [] print(a)
Be warned, that this fix may break code which intentionally uses mutable default arguments (e.g. caching).
B003: Remove parentheses from the tuple in 'return' statement.
If you are returning a tuple from the function by implicitly constructing it, then additional parentheses around it are redundant.
# BEFORE: def hello(): return ("World", 42) # AFTER: def hello(): return "World", 42
B004:
__all__attribute is missing.
Regenerate missing
__all__attribute, filling it with the list of top-level function and class names.
NB: It will ignore any names starting with
_to prevent any private members from ending up in the list.
# BEFORE: def hello(): return ("World", 42) class F: pass # AFTER: def hello(): return "World", 42 class F: pass __all__ = [ "F", "hello", ]
B005: Replace "A == None" with "A is None"
"Comparisons to singletons like None should always be done with
isor
is not, never the equality operators." (PEP8)
# BEFORE: if a == None: pass # AFTER: if a is None: pass
B006: Remove comparisons with either 'False' or 'True'.
PEP8 recommends that conditions should be evaluated without explicit equality comparison with
True/
Falsesingletons. In Python, every non-empty value is treated as
Trueand vice versa,
so in most cases those comparisons can be safely eliminated.
NB:
is Trueand
is Falsechecks are not affected, since they can be used to explicitly check for equality with a specific singleton, instead of using abovementioned "non-empty" heuristic.
# BEFORE: if a == False or b == True or c == False == True: pass # AFTER: if a or b or c: pass
B007: Convert f-strings without expressions into regular strings.
It is wasteful to use f-string mechanism if there are no expressions to be extrapolated.
# BEFORE: a = f"Hello, world" # AFTER: a = "Hello, world"
B008: Collapse nested
withstatements
Degenerate
withstatements can be rewritten as a single compound
withstatement, if following conditions are satisfied:
- There are no statements between
withstatements being collapsed;
- Neither of
withstatements has any leading or inline comments.
# BEFORE: with a(): with b() as other_b: print("Hello, world!") # AFTER: with a(), b() as other_b: print("Hello, world!")
B009: Replace unhashable list literals in set constructors
Lists cannot be used as elements of the sets due to them being mutable and hence "unhashable". We can fix the more trivial cases of list literals being used to create a set by converting them into tuples.
# BEFORE: a = { [1, 2, 3], } b = set([[1, 2], ["a", "b"]]) c = frozenset([[1, 2], ["a", "b"]]) # AFTER: a = { (1, 2, 3) } b = set([(1, 2), ("a", "b")]) c = frozenset([(1, 2), ("a", "b")])
NB: Each of the fixers can be disabled on per-line basis using flake8's "noqa" comments.
Installation
# pip install pybetter
Getting started with development
# git clone # poetry install
License
This project is licensed under the MIT License - see the LICENSE file for details
Authors
- Kirill Borisov (lensvol@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/pybetter/
|
CC-MAIN-2021-04
|
refinedweb
| 783
| 62.68
|
Launching multiple instances of same ROS node (with different names)
The problem is in simulating two independent different robots in Gazebo: Copter and Rover with same mavros functionality. (Two independent instances of mavros would do great) Can two instances of mavros nodes be run using different names?
So, I tried to call mavros and the problem turned out to be "A new node registered with same name" which terminates Gazebo. To avoid this problem, I have tried to rename node-calls and the attempts include the following mentioned below.
<node ns="copter" pkg="mavros" type="mavros_node" name="mavros"> <node ns="rover" pkg="mavros" type="mavros_node" name="mavros">
1. Using namespaces as shown above; This still registers the node name as "/mavros" instead of "/copter/mavros" and "/rover/mavros"
2. Coding separate mavros_node codes for copter and rover instead of mavros_node.cpp. The modified version contains the lines shown below.
ros::init(argc, argv, "mavros_copter"); //In mavros_node_copter.cpp ros::init(argc, argv, "mavros_rover"); //In mavros_node_rover.cpp
mavros_node.cpp, mavros_node_copter.cpp and mavros_node_rover.cpp source files are all placed in the same original folder. The entire package is then compiled with catkin_make. But, even then, using "mavros_copter" and "mavros_rover" as node name won't work with ROS Service properly while using "mavros" works.
<node pkg="mavros" type="mavros_node" name="mavros"> is the original code in launch file which works.
type="mavros_node_copter" name="mavros" (works)
type="mavros_node_copter" name="mavros_copter" (doesn't work)
3. I tried rqt_graph and this is the most confusing part in the software simulation. mavros node is shown as an independent node. I tried to assess how mavros is interacting with Gazebo and where how that is getting called and rqt_graph doesn't provide that information (even for original code which works).
4. Remapping nodes is not possible using roslaunch while command-line options like rosrun can be used.
I even tried
_name:="something" in command line along with roslaunch; But, that does not seem to work. (Original name is retained somehow)
Can you please let me know how multiple instances of same node can be run? (Optional: It will be great if you let me know how mavros is interacting with Gazebo)
Any help will be greatly, gratefully and whole-heartedly appreciated. Thanks for your time and consideration.
Prasad N R
Reference question: Multiple robots in ROS Gazebo SITL with separate MAVlink/MAVproxy codes
copter_circuit -> apm_sitl_copter & copter_circuit.world -> node_copter
rover_circuit1 -> apm_sitl_rover & rover_circuit1.world (.so plugin) -> node_rover
Output of roswtf , launch commands , CMakeLists.txt and the original folder structure can be found in Google Drive (uploaded sometime ago).
Can you please let me know if I should create new packages? (namely mavros_copter and mavros_rover and guidance on that will be gratefully appreciated)
A relatively small video has been made regarding the same.
Post exact launch code at gist. Cape-posty error?
Use (place node inside).
2: Did you edit CMakeLists.txt? But that wrong approach anyway...
3: What you expect? Use
rosnodeto verify.
4: What you try to remap??? Remap change topic or service name, not node. And again:
__name, not
_name!
@vooon , Thanks for that excellent clarification; If you find difficulty, I will upload on Github (multiple git init required) Trying __name and rosnode ; Thank you so much and I consider this an opportunity to thank you for excellent contributions to robotic softwares.
@vooon and viewers, you are humbly requested to let me know the mistake; "mavros_copter" node ( = "mavros" ) doesn't work like "mavros" (with __name:= override or directly using in launch file) What files that I should modify?
The output of rosnode info is too cryptic to understand and SearchMonkey returns nothing when I search for "mavros" in files (except mavros_node.cpp). I am ready to help with documentation on mavros once this research is finished. (I really wish to finish this soon and hope to contribute more)
|
https://answers.ros.org/question/247783/launching-multiple-instances-of-same-ros-node-with-different-names/
|
CC-MAIN-2021-04
|
refinedweb
| 640
| 66.13
|
$ cnpm install rollup-plugin.
babel 7.x
npm install --save-dev rollup-plugin-babel@latest
babel 6.x
npm install --save-dev rollup-plugin-babel@3
import { rollup } from 'rollup'; import babel from 'rollup-plugin-babel'; rollup({ entry: 'main.js', plugins: [ babel({ exclude: 'node_modules/**' }) ] }).then(...)
All options are as per the Babel documentation, plus)
options.extensions: an array of file extensions that Babel should transpile (by default the Babel defaults of .js, .jsx, .es6, .es, .mjs. are used)
Babel will respect
.babelrc files – this is generally the best place to put your configuration.
Ideally, you should only be transforming your. This rollup plugin automatically deduplicates those helpers, keeping only one copy of each one used in the output bundle. Rollup will combine the helpers in a single block at the top of your bundle. To achieve the same in Babel 6 you must use the
external-helpers plugin.
Alternatively, if you know what you're doing, you can use the
transform-runtime plugin. If you do this, use
runtimeHelpers: true:
rollup.rollup({ ..., plugins: [ babel({ runtimeHelpers: true }) ] }).then(...)
By default
externalHelpers option is set to
false so babel helpers will be included in your bundle.
If you do not wish the babel helpers to be included in your bundle at all (but instead reference the global
babelHelpers object), you may set the
externalHelpers option to
true:
rollup.rollup({ ..., plugins: [ babel({ plugins: ['external-helpers'], externalHelpers: true }) ] }).then(...)
This is not needed for Babel 7 - it knows automatically that Rollup understands ES modules & that it shouldn't use any module transform with it. The section below describes what needs to be done for Babel 6.
The
env will work for Babel <6.13. Rollup will throw an error if this is incorrectly configured.
However, setting
modules: false in your
.babelrc may conflict if you are using
babel-register. To work around this, specify
babelrc: false in your rollup config. This allows Rollup to bypass your
.babelrc file. In order to use the
env preset, you will also need to specify it with
modules: false option:
plugins: [ babel({ babelrc: false, presets: [['env', { modules: false }]], }), ];
The following applies to Babel 6 only. If you're using Babel 5, do
npm i -D rollup-plugin-babel@1, as version 2 and above no longer supports Babel 5
npm install --save-dev rollup-plugin-babel@3 babel-preset-env babel-plugin-external-helpers
// .babelrc { "presets": [ [ "env", { "modules": false } ] ], "plugins": [ "external-helpers" ] }
rollup-plugin-babel exposes a plugin.
It's main purpose is to allow other tools for configuration of transpilation without forcing people to add extra configuration but still allow for using their own babelrc / babel config files.
import babel from 'rollup-plugin-babel'; export default babel.custom(babelCore => { function myPlugin() { return { visitor: {}, }; } return { // Passed the plugin options. options({ opt1, opt2, ...pluginOptions }) { return { // Pull out any custom options that the plugin might have. customOptions: { opt1, opt2 }, // Pass the options back with the two custom options removed. pluginOptions, }; }, config(cfg /* Passed Babel's 'PartialConfig' object. */, { code, customOptions }) { if (cfg.hasFilesystemConfig()) { // Use the normal config return cfg.options; } return { ...cfg.options, plugins: [ ...(cfg.options.plugins || []), // Include a custom plugin in the options. myPlugin, ], }; }, result(result, { code, customOptions, config, transformOptions }) { return { ...result, code: result.code + '\n// Generated by some custom plugin', }; }, }; });
MIT
|
https://npm.taobao.org/package/rollup-plugin-babel
|
CC-MAIN-2020-16
|
refinedweb
| 542
| 51.24
|
Bugs item #728330, was opened at 2003-04-27 02:21 Message generated for change (Comment added) made by rwgk You can respond by visiting: Category: Installation Group: Python 2.3 Status: Open >Resolution: Remind >Priority: 9 Submitted By: Ralf W. Grosse-Kunstleve (rwgk) Assigned to: Neal Norwitz (nnorwitz) Summary: Don't define _SGAPI on IRIX Initial Comment: Python release: 2.3b1 Platform: IRIX 6.5 MIPSpro Compilers: Version 7.3.1.2m Commands used: ./configure --prefix=/usr/local_cci/Python-2.3b1t make The socket module fails to compile. The output from the compiler is attached. ---------------------------------------------------------------------- >Comment By: Ralf W. Grosse-Kunstleve (rwgk) Date: 2004-05-22 01:23 Message: Logged In: YES user_id=71407 Based on Maik's posting from 2004-03-08 08:53 I've worked out a small bug-fix patch relative to Python-2.3.4c1 that leads to successful creation of _socket.so under three different versions of IRIX: 6.5.10 with MIPSpro 7.3.1.2 6.5.21 with MIPSpro 7.41 6.5.23 with MIPRpro 7.3.1.3 I've consistently used #if defined(__sgi) && _COMPILER_VERSION>700 to restrict the changes to IRIX. However, to be sure I've also verified that the Python installation is still OK under Redhat 8 and Tru64 Unix 5.1. I will upload the patch. It is also available here: ule_patch For completeness I've also posted these files: ule_patched_c ule_original_c I've made an effort to keep the patch minimally intrusive, but it is certainly not "clean." However, the status quo is so bad that it can only get better. We have not been able to switch to Python 2.3 because of the problems with the socket module. It would be fantastic if the bug-fix patch could be included in the 2.3.4 final distribution. ---------------------------------------------------------------------- Comment By: Maik Hertha (mhertha) Date: 2004-03-08 08:53 Message: Logged In: YES user_id=768223 I got Python 2.3.3 compiled with MipsPro Compilers: Version 7.3.1.3m. The following changes were made to satisfy all needs. Line 206 in Modules/socketmodule.c #define _SGIAPI 1 NEW: #undef _XOPEN_SOURCE NEW: #define HAVE_GETADDRINFO 1 NEW: #define HAVE_GETNAMEINFO 1 #define HAVE_INET_PTON NEW: #include <sys/types.h> NEW: #include <sys/socket.h> NEW: #include <netinet/in.h> #include <netdb.h> Line 269: /* #include "addrinfo.h" */ In addition to this I extend the CFLAGS with -D_BSD_TYPES to satisfy the u_short and friends definition. --maik./ ---------------------------------------------------------------------- Comment By: Bill Baxter (billbaxter26) Date: 2004-03-03 08:20 Message: Logged In: YES user_id=892601 Got it down to one error: % > ./python Lib/test/test_socket.py Traceback (most recent call last): File "Lib/test/test_socket.py", line 6, in ? import socket File "/usr/local/spider/lib/python2.3/socket.py", line 44, in ? import _socket ImportError: 210454:./python: rld: Fatal Error: unresolvable symbol in /usr/local/spider/lib/python2.3/lib-dynload/_socketmodule.so: _xpg5_accept xpg5_accept does appear in any library on our SGI's that are only 1-2 years old. It does appear in libc in very recent revisions of Irix (> 6.5.19?) Does anyone know how to get Python 2.3 to avoid the use of xpg5_accept? Thanks ---------------------------------------------------------------------- Comment By: Bill Baxter (billbaxter26) Date: 2004-01-12 10:59 Message: Logged In: YES user_id=892601 Has anyone encountered problems with different versions of IRIX 6.5? I finally got sockets to work in Python2.3.3, but only on the most up-to-date version of IRIX (uname -v = 01100304). On any other machine with a lower version (archetecture doesn't seem to matter), I get messages which all seem to be related to sockets: 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_vsnprintf 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_recv 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_connect 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_bind 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_getsockopt 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_sendto 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_setsockopt 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_accept 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_recvfrom 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_socket 152272:python2.3: rld: Error: unresolvable symbol in python2.3: _xpg5_getsockname Upgrading all of our SGIs is not something I have control over. ---------------------------------------------------------------------- Comment By: Maik Hertha (mhertha) Date: 2003-12-22 10:52 Message: Logged In: YES user_id=768223 Sorry if there is something unclear. Redefine means: Set a value which is required to satisfy ifdef-statements in the header files. As you see in the definitions, given in the comment, the value for _NO_XOPEN4 is set as a result of some dependencies automatically defined. A redefinition of _SGIAPI in the socketmodule.c is not sufficient alone. Therefore to satisfy all requirements in the header files, you should set the values for _NO_XOPEN4 and _NO_XOPEN5 also manually. Howto do in socketmodule.c? ... #define _SGIAPI 1 #define _NO_XOPEN4 1 #define _NO_XOPEN5 1 ... If you are familiar with regular expressions, then you will know that _NO_XOPEN[45] is a shorthand for _NO_XOPEN4, _NO_XOPEN5. Sorry if there was something wrong in my comment. ---------------------------------------------------------------------- Comment By: Bill Baxter (billbaxter26) Date: 2003-12-22 07:49 Message: Logged In: YES user_id=892601 Can someone please clarify mherta's comment from 2003-12-16? How should we "redefine _NO_XOPEN[45] in the socketmodule.c at the same position like the _SGIAPI redefinition"? Should those lines of code be added to socketmodule.c, or are they the source of the problem? Is _NO_XOPEN[45] shorthand for _NO_XOPEN[4] and _NO_XOPEN[5] or are they all different? Thanks. ---------------------------------------------------------------------- Comment By: Maik Hertha (mhertha) Date: 2003-12-16 09:27 Message: Logged In: YES user_id=768223 I've tested the latest Python 2.3.3c1 to compile. The problem reported is still present. To avoid the error messages, about the incompatible types of several netdb-functions (like inet_pton), you should redefine _NO_XOPEN[45] in the socketmodule.c at the same position like the _SGIAPI redefinition. If there are error messages that types like u_short and u_char are not defined, please add -D_BSD_TYPES in the Makefile (BASECFLAGS is okay). If anybody don't need a executable compiled with MipsPro, gcc from the freeware.sgi.com could be a choice. The problem for this seems in /usr/include/standards.h: #define _NO_XOPEN4 (!defined(_XOPEN_SOURCE) || (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE+0 >= 500))) #define _NO_XOPEN5 (!defined(_XOPEN_SOURCE) || (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE+0 < 500))) As the first option is true (_XOPEN_SOURCE is set to 600 in pyconfig.h) the second option will be false. The constant #define NI_NUMERICHOST 0x00000002 /* return numeric form of hostname */ is enveloped in a clause #ifdef _NO_XOPEN4 && _NO_XOPEN5 (/usr/include/netdb.h) which is always false. In the manual pages there is a example which uses the constant NI_NUMERICHOST and compiles without error message. I'm not sure to cut off the file pyconfig.h from compiling the socketmodule.c? Any comments? ---------------------------------------------------------------------- Comment By: Hans Nowak (zephyrfalcon) Date: 2003-10-30 19:04 Message: Logged In: YES user_id=173607 My $0.02... Yesterday I successfully compiled Python 2.3.2, with socket module. I'm using an O2 running IRIX 6.5.11f. I didn't encounter any of the problems described before, and had no problems with _SGIAPI or anything. The reason it didn't compile was that u_long and u_char were not defined in some places; /usr/include/netinet/tcp.h to be precise, and a Python file (getaddrinfo.c). I'm using gcc 3.3 (the one downloaded from freeware.sgi.com). If anyone is interested, drop me a mail at hans at zephyrfalcon.org and I'll put the binary online somewhere. ---------------------------------------------------------------------- Comment By: Bill Baxter (billbaxter26) Date: 2003-10-24 12:59 Message: Logged In: YES user_id=892601 Here's the output from 'gmake', using MIPSpro Compiler 7.30 on IRIX 6.5 Sorry, I don't know how to attach something using the "Add a Comment" box. Is there another way to post? The patch at was edited into socketmodule.c : #include <netdb.h> #endif /* GCC 3.2 on Irix 6.5 fails to define this variable at all. Based on the above code, I'd say that the SGI headers are just horked. */ #if defined(__sgi) && !defined(INET_ADDRSTRLEN) #define INET_ADDRSTRLEN 16 #endif /* Generic includes */ #include <sys/types.h> #include <signal.h> --------------------------------------------------------------------------- cc -OPT:Olimit=0 -DNDEBUG -n32 -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/socketmodule.c -o Modules/socketmodule.o cc-1047 cc: WARNING File = ./Modules/socketmodule.c, Line = 195 Macro "_SGIAPI" (declared at line 210 of "/usr/include/standards.h") has an incompatible redefinition. #define _SGIAPI 1 ^ cc-1020 cc: ERROR File = /usr/include/netdb.h, Line = 198 The identifier "socklen_t" is undefined. extern int iruserok_sa(const void *, socklen_t, int, const char *, ^ cc-1047 cc: WARNING File = ./Modules/addrinfo.h, Line = 145 Macro "_SS_ALIGNSIZE" (declared at line 246 of "/usr/include/sys/socket.h") has an incompatible redefinition. #define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) ^ cc-1020 cc: ERROR File = ./Modules/socketmodule.c, Line = 822 The identifier "NI_NUMERICHOST" is undefined. NI_NUMERICHOST); ^ cc-1515 cc: ERROR File = ./Modules/socketmodule.c, Line = 3054 A value of type "int" cannot be assigned to an entity of type "const char *". retval = inet_ntop(af, packed, ip, sizeof(ip)); ^ 3 errors detected in the compilation of "./Modules/socketmodule.c". gmake: *** [Modules/socketmodule.o] Error 2 ---------------------------------------------------------------------- Comment By: Michael Hudson (mwh) Date: 2003-10-23 03:25 Message: Logged In: YES user_id=6656 Just to be clear, please "attach" the build rather than pasting it inline. ---------------------------------------------------------------------- Comment By: Anthony Baxter (anthonybaxter) Date: 2003-10-22 19:19 Message: Logged In: YES user_id=29957 Did you try 2.3.2 with the patch from the 2.3.2 build bugs page? If it failed, please post the build log of the failing bit to this bug. ---------------------------------------------------------------------- Comment By: Bill Baxter (billbaxter26) Date: 2003-10-22 11:26 Message: Logged In: YES user_id=892601 Has there been any progress since August on getting Python-2.3 to compile on IRIX 6.5? I really need to have sockets working to use python. ---------------------------------------------------------------------- Comment By: Maik Hertha (mhertha) Date: 2003-08-14 04:37 Message: Logged In: YES user_id=768223 I have the same problem on IRIX 6.5.19m and MIPSpro 7.3.1.3m on a FUEL 600Mhz. The situation seems a little bit strange on this system. But I have luck and get it compiled. As the current implementation is not clean, my resolution also. Which should be changed to get it work. The manpage for gethostbyaddr_r says: #include <sys/types> #include <sys/socket> #include <netinet/in.h> #include <netdb.h> So I included this in the __sgi-clause in socketmodule.c. Looking in the header-files shows, that some variables are defined if #define _NO_XOPEN4 1 #define _NO_XOPEN5 1 are set, before the includes. This defines some more variables, so that pyconfig.h should be changed. #define HAVE_ADDRINFO 1 #define HAVE_SOCKADDR_STORAGE 1 Sure there are warnings about the redefinition of the _(SGIAPI|NO_XOPEN4|NO_XOPEN5) but it compiles and the tests don't fail. Also my applications run without exception or coredump on FUEL, Octane, Octane 2. ---------------------------------------------------------------------- Comment By: Neal Norwitz (nnorwitz) Date: 2003-08-01 05:10 Message: Logged In: YES user_id=33168 Ralf, I will try to work on this, but it won't be for a week or two probably. Can you tell me which machines (by name) work and doesn't work. The only IRIX machine I seem to know about it rattler. ---------------------------------------------------------------------- Comment By: Ralf W. Grosse-Kunstleve (rwgk) Date: 2003-08-01 00:34 Message: Logged In: YES user_id=71407 For the records: The Python2.3 (final) socket module still does not compile under IRIX 6.5.20. It only compiles under 6.5.10. ---------------------------------------------------------------------- Comment By: Jeremy Hylton (jhylton) Date: 2003-07-17 11:07 Message: Logged In: YES user_id=31392 I applied a slight variant of Neal's patch and that seemed to fix things. It still seems wrong that we define _SGIAPI, but that will have to wait for 2.3.1. ---------------------------------------------------------------------- Comment By: Jeremy Hylton (jhylton) Date: 2003-07-17 06:54 Message: Logged In: YES user_id=31392 I learned a little about inet_ntop() in the last few minutes. It looks like the size_t argument is an older spelling, and the current POSIX says it should be socklen_t. Regardless, it looks like we're using the new definition when IRIX is actually providing the older definition. Neal attached a patch that looks like it should clean up the problem. Have you tried it? I think a better solution would be to teach configure how to find inet_ntop() via netdb.h, but that's probably too hard to get done in the new couple of hours. ---------------------------------------------------------------------- Comment By: Jeremy Hylton (jhylton) Date: 2003-07-17 06:42 Message: Logged In: YES user_id=31392 There seem to be two causes of worry. The actual compiler error in your build log and the use of _SGIAPI that Casavanti warns again. It looks like the compiler problems is because our inet_ntop() prototype is wrong. That is Python says the last argument is a socklen_t, but IRIX and Linux man pages both say size_t. Perhaps size_t and socklen_t are different sizes on IRIX, but not on Linux. What happens if you change it to size_t? The problematic code would appear to be these lines from socketmodule.c: #if defined(__sgi)&&_COMPILER_VERSION>700 && !_SGIAPI /* make sure that the reentrant (gethostbyaddr_r etc) functions are declared correctly if compiling with MIPSPro 7.x in ANSI C mode (default) */ #define _SGIAPI 1 #include "netdb.h" #endif It's the only use the _SGIAPI symbol that Casavant says we shouldn't use. What happens if you remove the use _SGIAPI, i.e. just make it #if defined(__sgi) && _COMPILER_VERSION > 700 /* make sure that the reentrant (gethostbyaddr_r etc) functions are declared correctly if compiling with MIPSPro 7.x in ANSI C mode (default) */ #include "netdb.h" #endif ---------------------------------------------------------------------- Comment By: Ralf W. Grosse-Kunstleve (rwgk) Date: 2003-07-16 17:27 Message: Logged In: YES user_id=71407 We have confirmed that the socket module in Python 2.3b1 and 2.3b2 fails to compile under these versions of IRIX: 6.5.10, MIPSpro 7.3.1.2m 6.5.19, MIPSpro 7.3.1.3m 6.5.20, MIPSpro 7.3.1.3m (latest available, to my knowledge) If Python 2.3 goes out without a working socket module it will be useless for many people in science where IRIX is still found quite frequently. Maybe even worse, we will also no longer be able to advertise Python as a language that "runs everywhere." ---------------------------------------------------------------------- Comment By: Ralf W. Grosse-Kunstleve (rwgk) Date: 2003-07-15 15:37 Message: Logged In: YES user_id=71407 Date: Tue, 15 Jul 2003 15:06:25 -0500 From: "Brent Casavant" <bcasavan at sgi.com> To: "Ralf W. Grosse-Kunstleve" <rwgk at yahoo.com> Subject: Re: IRIX & Python Ralf, I read through the sourceforge report. I don't have a sourceforge account so I didn't add there, but feel free to distribute my ramblings. First, they should be very careful about what version of the operating system they are using. Real IPv6 support was only added a few releases ago (6.5.20 I believe, though my memory is hazy). Some of the functions/macros corresponding to IPv6 were introduced prior to that point, but implementation may not have been complete. If they have to play tricks with #define values to get a symbol recongnized it most likely means that SGI didn't intend for that symbol to be used yet. I suspect the problems they are seeing are because they are using some version of IRIX 6.5.x that includes inet_ntoa() definitions under _SGIAPI, but for which real support was not yet complete. The namespace of symbols that begin with a single underscore and a capital letter is reserved for the OS vendors, and the fact that someone is trying to manually insert a definition of _SGIAPI into the source should be a big red warning flag. That said, there is a correct method to deal with the new capabilities of IRIX 6.5.x over time. This comes in two parts. A better explanation is in /usr/include/optional_sym.h First, when a new symbol is added to IRIX, the corresponding header file will always have the following line in it: #pragma optional some_new_symbol The presence of this #pragma will cause the linker to not complain if the symbol is missing when the executable is linked. If SGI neglects to do so it is a bug that should be reported to us. The second part is that calls to these "optional" symbols should be protected by a run-time check to see if the symbol is actually present. Just like this: #include <optional_sym.h> #include <header_file_for_some_new_symbol.h> . . . if (_MIPS_SYMBOL_PRESENT(some_new_symbol)) { /* New function is present, use it */ qux = some_new_symbol(foo, bar, baz); } else { /* New function isn't present, do something else */ qux = builtin_some_new_symbol(foo, bar, baz); } This ensures that a single executable will be able to function properly (or at least degrade gracefully) on all version of IRIX 6.5.x. In other words you can compile on 6.5.20 and run on 6.5.8, or vice versa. In particular, this means that compile-time detection of features such as inet_ntoa() is incorrect for IRIX 6.5.x -- these decisions should be made at run-time instead. If the decision is made at compile time the executable may well not execute on an older version of IRIX 6.5.x. Unfortunately GNU configure is not equipped to utilize such advanced binary-compatability mechanisms, so there's no "easy" way to get GNU configure'd software to run across all IRIX 6.5.x releases, short of compiling only on the original non-upgraded version of IRIX 6.5. Hope that helps, Brent Casavant On Tue, 15 Jul 2003, Ralf W. Grosse-Kunstleve wrote: > We are developing a Python-based () application for > IRIX. Until now the Python IRIX port was fully supported, but the last > two beta releases of Python (2.3b1 and 2.3b2) make me increasingly > worried because the crucial socket module (TCP/IP sockets) fails to > build. A while ago I've filed a bug report, but the Python developers > appear to be stuck: > >? func=detail&aid=728330&group_id=5470&atid=105470 > > Is there a way to bring this to the attention of developers at SGI to > hopefully get some help? > > Thank you in advance! > Ralf > -- Brent Casavant Silicon Graphics, Inc. Where am I? And what am I IRIX O.S. Engineer doing in this handbasket? bcasavan at sgi.com 44.8562N 93.1355W 860F -- Unknown ---------------------------------------------------------------------- Comment By: Ralf W. Grosse-Kunstleve (rwgk) Date: 2003-06-30 07:21 Message: Logged In: YES user_id=71407 The socket module still fails to compile with Python 2.3b2, in addition to two other extensions. The full make log is attached. ---------------------------------------------------------------------- Comment By: Martin v. Löwis (loewis) Date: 2003-05-21 23:47 Message: Logged In: YES user_id=21627 I think it would be best if detect presence of inet_aton/inet_pton. Is IPv6 support possible on this system? Then it would be best if that was detected, as well. If it is not possible to detect aton/pton/ipv6, what is the problem with not using them? I'd like to have a look at the relevant headers (in particular to understand the duplicate definition of _SGIAPI), indeed. ---------------------------------------------------------------------- Comment By: Neal Norwitz (nnorwitz) Date: 2003-05-21 16:35 Message: Logged In: YES user_id=33168 Argh!!! This is a nightmare. The attached hack ^h^h^h patch fixes the problem, but ... _SGIAPI needs to be defined (~192 in socketmodule.c) in order to get the prototypes for inet_aton, inet_pton. But _SGIAPI can't be defined in the standard header files because XOPEN_SOURCE is defined. Martin, do you have any other suggestions? I don't see how to do this right within configure. If you want I can send you the header file(s). ---------------------------------------------------------------------- Comment By: alexandre gillet (gillet) Date: 2003-05-12 10:41 Message: Logged In: YES user_id=150999 I had the same problem compiling socket on Irix. We did find that on our system ENABLE_IPV6 is not define and all the error are cause by that. System that do not enable IPV6 are not well supported with the socketmodule.c code. We were able to compile socket after making few change in the code: I am not sure if I did it right but it compile. I will post my patch but I do not see any place to attach my file example: See line 2794,2800 + #ifdef ENABLE_IPV6 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; + #else + char packed[sizeof(struct in_addr)]; + #endif I am not sure how to post the patch or file. ---------------------------------------------------------------------- Comment By: Ralf W. Grosse-Kunstleve (rwgk) Date: 2003-05-05 11:44 Message: Logged In: YES user_id=71407 This is not in my area of expertise, but I've tried a couple of (probably stupid) things: #include <standards.h> in socketmodule.c instead of #define _SGIAPI. This resulted in even more errors. ./configure --disable-ipv6 Same errors as before. I am lost here. Sorry. But you still have ssh access to rattler.lbl.gov if that helps. Accounts for other Python developers are a possibility. ---------------------------------------------------------------------- Comment By: Martin v. Löwis (loewis) Date: 2003-05-04 05:39 Message: Logged In: YES user_id=21627 Can you analyse these compiler errors in more detail, please? What, in your opinion, is causing these problems, and how would you correct them? ---------------------------------------------------------------------- You can respond by visiting:
|
http://mail.python.org/pipermail/python-bugs-list/2004-May/023150.html
|
CC-MAIN-2013-20
|
refinedweb
| 3,646
| 68.97
|
/* -*- . * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Robert O'Callahan <robert@ocallahanLINEBREAKER_H_ #define NSLINEBREAKER_H_ #include "nsString.h" #include "nsTArray.h" #include "nsILineBreaker.h" class nsIAtom; /** * A receiver of line break data. */ 00050 class nsILineBreakSink { public: /** * Sets the break data for a substring of the associated text chunk. * One or more of these calls will be performed; the union of all substrings * will cover the entire text chunk. Substrings may overlap (i.e., we may * set the break-before state of a character more than once). * @param aBreakBefore the break-before states for the characters in the substring. */ virtual void SetBreaks(PRUint32 aStart, PRUint32 aLength, PRPackedBool* aBreakBefore) = 0; /** * Indicates which characters should be capitalized. Only called if * BREAK_NEED_CAPITALIZATION was requested. */ virtual void SetCapitalization(PRUint32 aStart, PRUint32 aLength, PRPackedBool* aCapitalize) = 0; }; /** * A line-breaking state machine. You feed text into it via AppendText calls * and it computes the possible line breaks. Because break decisions can * require a lot of context, the breaks for a piece of text are sometimes not * known until later text has been seen (or all text ends). So breaks are * returned via a call to SetBreaks on the nsILineBreakSink object passed * with each text chunk, which might happen during the corresponding AppendText * call, or might happen during a later AppendText call or even a Reset() * call. * * The linebreak results MUST NOT depend on how the text is broken up * into AppendText calls. * * The current strategy is that we break the overall text into * whitespace-delimited "words". Then(u); } static inline PRBool IsComplexASCIIChar(PRUnichar u) { return !((0x0030 <= u && u <= 0x0039) || (0x0041 <= u && u <= 0x005A) || (0x0061 <= u && u <= 0x007A)); } static inline PRBool IsComplexChar(PRUnichar u) { return IsComplexASCIIChar(u) || NS_NeedsPlatformNativeHandling(u) || (0x1100 <= u && u <= 0x11ff) || // Hangul Jamo (0x2000 <= u && u <= 0x21ff) || // Punctuations and Symbols (0x2e80 <= u && u <= 0xd7ff) || // several CJK blocks (0xf900 <= u && u <= 0xfaff) || // CJK Compatibility Idographs (0xff00 <= u && u <= 0xffef); // Halfwidth and Fullwidth Forms } // Break opportunities exist at the end of each run of breakable whitespace // (see IsSpace above). Break opportunities can also exist between pairs of // non-whitespace characters, as determined by nsILineBreaker. We pass a whitespace- // delimited word to nsILineBreaker if it contains at least one character // matching IsComplexChar. // We provide flags to control on a per-chunk basis where breaks are allowed. // At any character boundary, exactly one text chunk governs whether a // break is allowed at that boundary. // // We operate on text after whitespace processing has been applied, so // other characters (e.g. tabs and newlines) may have been converted to // spaces. /** *); /** * Feed Unicode text into the linebreaker for analysis. aLength must be * nonzero. * @param aSink can be null if the breaks are not actually needed (we may * still be setting up state for later breaks) */ nsresult AppendText(nsIAtom* aLangGroup, const PRUnichar* aText, PRUint32 aLength, PRUint32 aFlags, nsILineBreakSink* aSink); /** * Feed 8-bit text into the linebreaker for analysis. aLength must be nonzero. * @param aSink can be null if the breaks are not actually needed (we may * still be setting up state for later breaks) */ nsresult AppendText(nsIAtom* aLangGroup, const PRUint8* aText, PRUint32 aLength, PRUint32 aFlags, nsILineBreakSink* aSink); /** * Reset all state. This means the current run has ended; any outstanding * calls through nsILineBreakSink are made, and all outstanding references to * nsILineBreakSink objects are dropped. * After this call, this linebreaker can be reused. * This must be called at least once between any call to AppendText() and * destroying the object. * @param aTrailingBreak this is set to true when there is a break opportunity * at the end of the text. This will normally only be declared true when there * is breakable whitespace at the end. */ nsresult Reset(PRBool* aTrailingBreak); private: // This is a list of text sources that make up the "current word" (i.e., // run of text which does not contain any whitespace). All the mLengths // are are nonzero, these cannot overlap. struct TextItem { TextItem(nsILineBreakSink* aSink, PRUint32 aSinkOffset, PRUint32 aLength, PRUint32 aFlags) : mSink(aSink), mSinkOffset(aSinkOffset), mLength(aLength), mFlags(aFlags) {} nsILineBreakSink* mSink; PRUint32 mSinkOffset; PRUint32 mLength; PRUint32 mFlags; }; // State for the nonwhitespace "word" that started in previous text and hasn't // finished yet. // When the current word ends, this computes the linebreak opportunities // *inside* the word (excluding either end) and sets them through the // appropriate sink(s). Then we clear the current word state. nsresult FlushCurrentWord(); nsAutoTArray<PRUnichar,100> mCurrentWord; // All the items that contribute to mCurrentWord nsAutoTArray<TextItem,2> mTextItems; PRPackedBool mCurrentWordContainsComplexChar; // True if the previous character was breakable whitespace PRPackedBool mAfterBreakableSpace; // True if a break must be allowed at the current position because // a run of breakable whitespace ends here PRPackedBool mBreakHere; }; #endif /*NSLINEBREAKER_H_*/
|
http://xulrunner.sourcearchive.com/documentation/1.9.1.9-3/nsLineBreaker_8h-source.html
|
CC-MAIN-2018-05
|
refinedweb
| 770
| 54.52
|
02-01-2017
11:39 AM
Through a lot of experimentation, I was able to integrate a Python package manager called Anaconda with the NX Open API.
Is it possible to do the same with cmake or an open source library like Google's Draco?
The online documentation just stated this....
When you perform linking in a C++ project, you need to include all of the library files. Due to the continuous addition of JA functions, the libnxopencpp library was reaching its physical limit, so it is split into multiple libraries. The libraries are based on the namespaces available. There are currently 35 different namespaces in NX Open, so 35 new libraries are added. Each library name starts with libnxopoencpp.
You need to refer to all of the libraries when building a new NX Open C++ application and incorporate the new library files into your existing C++ projects when modifying those.
Note
Only linking is affected. The compilation process for NX Open programs remains the same.
The NX Open C++ wizard and uflink script are updated for the new libraries.
|
https://community.plm.automation.siemens.com/t5/NX-Programming-Customization-Forum/integrating-open-source-C-libraries/td-p/388794
|
CC-MAIN-2017-47
|
refinedweb
| 180
| 65.01
|
![endif]-->
a Arduino library for the MAX7221 and MAX7219
These two chips provide an easy way to control either an array of 64 LEDs or up to 8 digits of 7-segment displays. A detailed description of the hardware and a schematic can be found here.
As a teaser here is a picture of my rather crappy (but working) testbed...
There is already a library and a lot of code-examples for the Arduino and the MAX72XX available, but the focus had always been on controlling LEDs laid out in some sort of rectangular matrix. I use the MAX72XX to drive 7-segment displays, so I wanted a function to display numbers (decimal and hexadecimal) and also the limited set of alphanumeric characters that make (visual) sense on this kind of displays. But the library also provides a basic set of functions by which either individual or groups of LEDs can be switched on and off.
All the libraries API-functions are called through a variable of type
LedControl which you have to create inside your projects code.
A typical code for library initialization will look like this :
/* We start by including the library */ #include "LedControl.h" /* * Now we create a new LedControl. * We use pins 12,11 and 10 on the Arduino for the SPI interface * Pin 12 is connected to the DATA IN-pin of the first MAX7221 * Pin 11 is connected to the CLK-pin of the first MAX7221 * Pin 10 is connected to the LOAD(/CS)-pin of the first MAX7221 * There will only be a single MAX7221 attached to the arduino */ LedControl lc1=LedControl(12,11,10,1);
The first step is obvious. We have to include the
LedControl-library.
Then we create an instance of type
LedControl through which we talk to the MAX72XX devices. The initialization of an
LedControl takes 4 arguments. The first 3 arguments are the pin-numbers on the Arduino that are connected to the MAX72XX. You are free to choose any of the digital IO-pins on the arduino, but since some of the pins are also used for serial communication or have a led attached to them its best to avoid pin 0,1 and 13. I choose pins 12,11 and 10 in my example. The library does not check the pin-numbers to be valid in any way. Passing in something stupid (pin 123??) will break your app.
You don't have to initialize the pins as outputs or set them to a certain state, the library will do that for you.
The fourth argument to
LedControl(dataPin,clockPin,csPin,numDevices) is the number of cascaded MAX72XX devices you're using with this
LedControl. The library can address up to 8 devices from a single
LedControl-variable. There is a little performance penalty implied with each device you add to the chain, but amount of memory used by the library-code will stay the same, no matter how many devices you set. Since one
LedControl cannot address more than 8 devices, only values between 1..8 are allowed here.
Here is the prototype for a new
LedControl-instance:
/* * Create a new controller * controlled */ LedControl(int dataPin, int clkPin, int csPin, int numDevices);
If you need to control more than 8 MAX72XX, you can always create another
LedControl-variable that uses 3 different pins on your Arduino board.
The only thing you have to do is to initialize another
LedControl
/* we have to include the library */ #include "LedControl.h" // Create a LedControl for 8 devices... LedControl lc1=LedControl(12,11,10,8); // ... and another one. Now we control 1024 LEDs from an Arduino, not bad! // Note : the second one must use different pins! LedControl lc2=LedControl(9,8,7,8);
There is no way to read the pin-numbers from your code, but there is a function that requests the maximum number of devices attached to an
LedControl. This can be very handy when you want to loop over the full list of MAX72XX devices attached. Here is a piece of code that switches all of the MAX72XX-devices from power saving mode into normal operation. I'll think you'll get the idea even though we haven't talked about the
shutdown(addr)s consume quite a lot of energy when they are lit. For battery operated devices you'll definitely want to save power by switching the whole display off, when the user does not need it. A special command sequence can put the MAX72XX into shutdown mode.
The device will switch off all the LEDs on the display, but the data is retained. You can even continue to send new data during shutdown mode. When the device is activated later on, the new data will appear on your display. Here is an example for an invisible countdown on a 7-segment display:
//create a new device LedControl lc=LedControl(12,11,10,1); void countDown() { int i=9; lc.setDigit(0,(byte)i,false); //now we see the number '9' delay(1000); //switch the display off ... lc.shutdown(0,true); //and count down silently while(i>1) { //data is updated, but not shown lc.setDigit(0,(byte)i,false); i--; delay(1000); } //when we switch the display on again we have already reached '1' lc.shutdown(0,false); lc.setDigit(0,(byte)i,false); }
Here is the prototype for method
LedControl.shutdown(addr)
/* *.
(This is a kind of experts feature not really needed by most users of the library. Since the library initializes the
MAX72XX to safe default values, you don't have to read this section in order to make your hardware work)
When a new LedControl is created it will activate all 8 digits on all devices. Each lit digit will be switched on for 1/8 of a second by the multiplexer circuit that drives the digits. If you have any reason to limit the number of scanned digits, this is what happens : The LEDs get switched on more frequently, and therefore will be on for longer periods of time. Setting the scan limit to 4 would mean that a lit Led is now switched on for 1/4 of a second, so the
MAX72XX has to provide the current on the segment-driver for a longer period of time.
You should read the relevant section of the
MAX72XX datasheet carefully! Its actually possible to kill your
MAX72XX by choosing a bad combination of the resistor
RSet that limits the current through the LEDs and the number of digits scanned by the device.
The only reason to tweak the scanlimit at all, is that the display looks too dark. But this is most likely due to the fact that you haven't raised the intensity on startup. Anyway, here's the prototype of
setScanLimit() for those who need it:
/* * Set the number of digits (or rows) to be displayed. * See datasheet for side effects your display.
RSetwhich limits the maximum current going through the LEDs.
The
setIntensity(int addr, int intensity) method lets you control brightness in 16 discrete steps. Larger values make the display brighter up to the maximum of 15. Values greater than 15 will be discarded without changing the intensity of the LEDs.
You might be surprised to find out that an intensity of zero will not switch the display completely off, but we already know how to do this with the
shutdown()-function.
/* * Set the brightness of the display. * Params: * int addr the address of the display to control * int intensity the brightness of the display. * Only values between 0(darkest) and 15(brightest) are valid. */ void setIntensity(int addr, int intensity);
When a new
LedControl is created the library will initialize the hardware with ...
A blanked display is probably what everybody wants on startup. But with the intensity at a minimum and the device in shutdown-mode no LEDs will light up in the startup configuration. Most users will do their own initialization inside the
setup()-function. Here is a piece of code that can be used as a template for creating an
LedControl that is ready to light up LEDs at a medium brightness as soon as display data arrives.
//we have to include the library #include "LedControl.h" //and create the LedControl LedControl lc=LedControl(12,11,10,1); void setup() { //wake up the MAX72XX from power-saving mode lc.shutdown(0,false); //set a medium brightness for the Leds lc.setIntensity(0,8); } }
Before we start to light up LEDs there is one more thing:
LedControl.clearDisplay(addr)! It should be obvious what the functions does...
/* * Switch all LEDs on the display off. * Params: * int addr The address of the display to control */ void clearDisplay(int addr);
All LEDs off after this one, that's it...
Ok, I made this one up, but with 8
MAX72XX you could create a text display for 12 characters. The picture of my test-setup at the top of the article reveals that I have only single 5x7 matrix. But this cheap display is fine for testing the basic concepts of the
LedControl library.
There are 3 different ways to switch a Led in a Matrix on or off. We start with a function that controls each one of the LEDs individually...
Here is the prototype for the function that switches LEDs on or off.
/* * Set the status of a single Led. * Params : * addr address of the display * row the row of the Led (0..7) * col the column of the Led (0..7) * state If true the led is switched on, * if false it is switched off */ void setLed(int addr, int row, int col, boolean state);
The
addr and the
state arguments should be clear, but what exactly is a
row and what is a
column on the matrix? It really depends on the wiring between the
MAX72XX and your matrix. The
LedControl-library assumes the setup used in this schematic:
There are 8 rows (indexed from 0..7) and 8 columns (also indexed from 0..7) in the matrix. If we want to light up the LED which is located at the very right of the 3'rd row from the top, simply take the index of the Led (2.7) and use is as the row and column arguments.
Here's some code that lights up a few LEDs
//switch on the led in the 3'rd row 8'th column //and remember that indices start at 0! lc.setLed(0,2,7,true); //Led at row 0 second from left too lc.setLed(0,0,1,true); delay(500); //switch the first Led off (second one stays on) lc.setLed(0,2,7,false);
setLed() is fine if you light up only a few LEDs, but if more LEDs need to be updated, it would require many lines of code. So there are two more functions in the library, that control a complete row and column with a single call.
The
setRow(addr,row,value)-function takes 3 arguments. The first one is the already familiar address of our device. The second one is the row that is going to be updated and the third one the value for this row.
But how do we know which LEDs light up for a specific value? The value, a byte, uses a simple encoding where each bit set to 1 represents a lit led and an unset bit a Led switched off. Here is an example:
We want to light up the marked LEDs from the schematic...
The index for the row to be updated is 2. Now we have to set the byte-value for the LEDs to be lit. The easiest approach is to include the standard header-file <binary.h> to your sketch. Now you can write down the value in binary encoding and have an exact mapping between bits set to 1 and the LEDs to be switched on. To light up the the LEDs from the example we could simply write:
//include this file so we can write down a byte in binary encoding #include <binary.h> //now setting the LEDs from the third row on the first device is easy lc.setRow(0,2,B10110000);
If for any reason you can not specify the value in binary encoding, here is a simple table that maps the decimal values of each bit to the Led it affects. The two rows at bottom give an example for how to calculate the decimal value for the example from above.
Inside your code you would use
lc.setRow(0,2,176) to update this row on the first
MAX72XX attached to the Arduino. As a side-effect the
setRow()-call is much faster than calling
setLed() in turn for each Led. So use this method wherever you can.
Here is the signature of the method :
/* * Set all 8 LEDs in a row to a new state * Params: * addr address of the display * row row which is to be set (0..7) * value each bit set to 1 will light up the corresponding Led. */ void setRow(int addr, int row, byte value);
What can be done for rows can likewise be done with columns. The
setColumn()-method updates 8 LEDs in the vertical columns.
Here is an example.
This time we want the 4 LEDs at the bottom of column 6 to be lit. We can use the the binary encoding again. Here the leftmost bit in the value refers to the Led at the top of the column:
//include this file so we can write down a byte in binary encoding #include <binary.h> //now setting the leds from the sixth column on the first device is easy lc.setColumn(0,5,B00001111);
and here is the table that maps bits to the LEDs for columns:
The signature of the method is almost the same a the row-version of it:
/* * Set all 8 LEDs in a column to a new state * Params: * addr address of the display * col column which is to be set (0..7) * value each bit set to 1 will light up the corresponding Led. */ void setColumn(int addr, int col, byte value);
A complete example for the Led matrix functions can be found on the demo-page for the library.
A note on performance...
There is an important difference between the way the
setRow()- and the
setColumn()- methods update the Leds:
setRow()only needs to send a single
int-value to the
MAX72XXin order to update all 8 LEDs in a row.
setColumn()uses the
setLed()-method internally to update the LEDs. The library has to send 8
intsto the driver, so there is a performance penalty when using
setColumn(). You won't notice that visually when using only 1 or 2 cascaded LED boards, but if you have a long queue of devices (6..8) which all have to be updated at the same time, that could lead to some delay that is actually visible.
It's not the standard usage for 7-segment LEDs...
... but looks good!
The most common use of 7-segment displays is to show numbers. The first function we look at, takes an argument of type byte and prints the corresponding digit on the specified column. The range of valid values runs from 0..15. All values between 0..9 are printed as digits, values between 10..15 are printed as their hexadecimal equivalent.
Any other value will simply be ignored, which means nothing will be printed. The column on the display will not be blanked, it will simply retain its last valid value. The decimal point on the column can be switched on or off with an extra argument.
Here is a small example that prints an int value (-999..999) on a display with 4 digits.
void printNumber(int v) { int ones; int tens; int hundreds; boolean negative; if(v < -999 || v > 999) return; if(v<0) { negative=true; v=v*-1; } ones=v%10; v=v/10; tens=v%10; v=v/10; hundreds=v; if(negative) { //print character '-' in the leftmost column); }
This is the prototype for the function:
/* * Display a (hexadecimal) digit on a 7-Segment Display * Params: * addr address of the display * digit the position of the digit on the display (0..7) * value the value to be displayed. (0x00..0x0F) * dp sets the decimal point. */ void setDigit(int addr, int digit, byte value, boolean dp);
The
digit-argument must be from the range 0..7 because the MAX72XX can drive up to eight 7-segment displays. The index starts at 0 as usual.
There is a limited set of characters that make (visual) sense on a 7-segment display. A common use would be the character '-' for negative values and the 6 characters from 'A'..'F' for hex-values.
The
setChar(addr,digit,value.dp)-function accepts a value of type char for the whole range of 7-bit ASCII encoding. Since the recognizable patterns are limited, most of the defined characters will be the
<SPACE>-char. But there are quite a few characters that make sense on a 7-segment display. your convenience, the hexadecimal characters have also been redefined at
the character values 0x00...0x0F. If you want to mix digits and characters on the display, you can simply take the same byte argument that you would have used for the
setDigit()-function and it will print the hexadecimal value.
The prototype of the function is almost the same as the one for displaying digits.
/* * Display a character on a 7-Segment display. * There are only a few characters that make sense here : * '0','1','2','3','4','5','6','7','8','9','0', * 'A','b','c','d','E','F','H','L','P', * '.','-','_',' ' * Params: * addr address of the display * digit the position of the character on the display (0..7) * value the character to be displayed. * dp sets the decimal point. */ void setChar(int addr, int digit, char value, boolean dp);
Some commented demos for the
LedControl-library are on page LedControlDemos. You can also download the code for the demos from there.
The sourcecode for the library is on GitHub
The latest binary release is always available from the LedControl Release Page
Instructions to install a library for the Arduino IDE are found here
Now create a new sketch with the following content...
#include "LedControl.h" void setup() {} void loop() {}
... hit the verify button and the library will be compiled and is available for all of your sketches that start with a
#include "LedControl.h" line.
The Zip-File also contains 3 example sketches which are documented on the LedControlDemos page.
Currently none
setChar()function.
WProgramm.hto
Arduino.h. The include statement in
LedControl.hwas updated so the library compiles under pre- and post-1.0 versions of the IDE
You are also welcome to send questions, objections or corrections to <e.fahle@wayoda.org>, or create an issue on the GitHub page for the library
The source code for this library is released under the Terms of the GNU Lesser General Public License version 2.1.
|
http://playground.arduino.cc/Main/LedControl
|
CC-MAIN-2018-05
|
refinedweb
| 3,187
| 71.75
|
Mat−oriented
Let us understand how Matplotlib can be used to plot a sine function in a plot −
import matplotlib.pyplot as plt import numpy as np data = np.arange(0.0, 4.0, 0.1) y = 2 + np.sin(2 * np.pi * data) fig, ax = plt.subplots() ax.plot(data, y) ax.set(xlabel='x-axis data', ylabel='y-axis data',title='A simple plot') ax.grid() plt.show()
The required packages are imported and its alias is defined for ease of use.
The data is created using NumPy package.
An empty figure is created using the ‘figure’ function.
The ‘subplot’ function is used to create outlines for three different plots.
The data is plotted using the ‘plot’ function.
The set function is used to provide labels for ‘X’ and ‘Y’ axis.
The title of the plot is defined.
It is shown on the console using the ‘show’ function.
|
https://www.tutorialspoint.com/how-can-matplotlib-be-used-to-create-a-sine-function-in-python
|
CC-MAIN-2022-05
|
refinedweb
| 150
| 70.7
|
> gzip_win.zip > getopt.c
/* Getopt for GNU. #ifndef __STDC__ # ifndef const # define const # endif #endif /* This tells Alpha OSF/1 not to define a getopt prototype in
. */ #ifndef _NO_PROTO #define _NO_PROTO #endif #include #include "tailor. */ #endif /* GNU C library. */ /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a long-named option. Because this is not POSIX.2 compliant, it is being phased out. */ /* #define GETOPT_COMPAT */ /* = 0; /*. */ /* XXX 1003.2 says this must be 1 before any call. */ int optind = 0; /*. */ #define BAD_OPTION '\0' int optopt = BAD_OPTION; /*. */ #include #define my_index strchr --; } } /* `EOF'. BAD_OPTION after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return BAD_OPTION., 0); } #endif /* _LIBC or not __GNU_LIBRARY__. */ == EOF) BAD_OPTION: break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); } #endif /* TEST */
|
http://read.pudn.com/downloads64/sourcecode/windows/file/224321/getopt.c__.htm
|
crawl-002
|
refinedweb
| 154
| 71.82
|
Debugging "Plugin Crash"
In the meantime you might want to checkout Tools/Xml Tools 2.4.9 Unicode/
I’ve forked the XPatherizerNPP github project and it can be downloaded here:
Thank you for suggestion on the other plugin! XML Tools seems a bit unstable, also its XPath component doesn’t seem to work correctly. Attempting to evaluate “.” in a Microsoft sample XML file does not return any nodes… The plugin loads, but the XPath functionality doesn’t seem to work. All dependencies have been installed per the installation readme.
Please let me know if there are any issues with my project upload; I have limited experience with git. I’ve spent a long time working IT but only dabbled with development.
Thanks very much!
Stating what is probably obvious, it appears the the plugin infrastructure can’t handle the messaging protocols of the current version of Notepad++. I am trying to borrow newer implementations of the infrastructure from other plugins, though it will be patch work at best as I don’t understand most of the code I am looking at.
See for the current version also the files are splitted up more, but has nicer interfaces to access data.
Have you checked if the 32bit build suffers from the same issues?
@chcg - I saw your update to the DLLexport folder; didn’t catch it before I made a new update:
I’m seeing a new error now: “XPatherizerNPP.dll just crashed in runPluginCommand(size_t i : 22)”
Not a lot of reference material for that online.
Otherwise I solved the SCNotification issues by remapping the main.cs calls to “ScNotification” in the Scintilla_iface.cs file, changed the “nc.nmhdr.code” calls to “nc.Header.Code” and redefined all the namespaces from “XPatherizerNPP” to “Kbg.NppPluginNET” and “Kbg.NppPluginNET.PluginInfrastructure”
I borrowed from the plugin and used all infrastructure there.
Any suggestions are still appreciated!
Like to note that I only see the error “XPatherizerNPP.dll just crashed in runPluginCommand(size_t i : 22)” when I try to “Show XPatherizer Windows”
So it’s choking on the ScNotification messages when Notepad++ runs “UnmanagedExports.cs”. The form object is “null” and I’m not sure how it creates an instance of the form… It gets through line 66 of “UnmanagedExports.cs” when trying to load the form and crashes.
I’ve not given up…
I discovered that the “Notification” routine in Main.CS is no longer triggered by UnmanagedExports.cs. I changed the function name to “OnNotification” and modified the argument to match the object being passed in from “beNotified” in the UnmanagedExports.cs callback.
This caused the event handler to correctly trigger when NPP finishes loading, initializing the search & result forms prior to them being called. The “XPatherizerNPP.dll just crashed in runPluginCommand(size_t i : 22)” error is now gone as it is not trying to load a null form object.
Now the problem is that the Scintilla interface does not appear to be returning the correct memory address for the file that is meant to be analyzed. From line 42 in NppPluginNETBase.cs:
Win32.SendMessage(nppData._nppHandle, (uint) NppMsg.NPPM_GETCURRENTSCINTILLA, 0, out curScintilla);
This returns an address that, when passed into “SciMsg.SCI_GETTEXT” returns a whole big bunch of gibberish (looks like Asian characters of some kind). Soooo I’m trying to figure out what’s going on with that. Slow progress! Learning as I go…
I’ve updated the code in the git repo: l
Did you build the plugin for 32bit and checked that it is working there as expected?
Additionally maybe remove the int casts in NppPluginNETHelper.cs from
public ClikeStringArray(int num, int stringCapacity) { _nativeArray = Marshal.AllocHGlobal((num + 1) * IntPtr.Size); _nativeItems = new List<IntPtr>(); for (int i = 0; i < num; i++) { IntPtr item = Marshal.AllocHGlobal(stringCapacity); Marshal.WriteIntPtr((IntPtr)(_nativeArray + (i * IntPtr.Size)), item); _nativeItems.Add(item); } Marshal.WriteIntPtr((IntPtr)(_nativeArray + (num * IntPtr.Size)), IntPtr.Zero); }
@chcg Thanks! I have changed the plugin to 32 bit.
I’ve actually got the SCI_GETTEXT working by utilizing the “ScintillaGateway” object as defined in the plugin infrastructure I’ve integrated.
It appears that the old “SciMsg.SCI_GETTEXT” was returning ASCII when I needed Unicode. The plugin infrastructure somehow resolves this, and I’m simply leaning on that to get it done.
Now my issue appears to be that the XML Nodes are being parsed incorrectly… The parent node is being listed as a child of itself in the output… I’m slowly digging through the source code to figure out what element is chopping up the XML.
Thanks for the help and suggestions! I’ve uploaded the new code to GIT again.
Ok, I’ve merged the branch back into master and it seems like everything works… I don’t know what the XPML functionality is supposed to be, and without a working version I’m not sure how to troubleshoot it. I’ve removed the XPML options from the menu.
The functional 32 bit version of the plugin is available here:
|
https://community.notepad-plus-plus.org/topic/15320/debugging-plugin-crash/13?lang=en-US
|
CC-MAIN-2022-33
|
refinedweb
| 834
| 58.18
|
Tech Off Thread14 posts
Forum Read Only
This forum has been made read only by the site admins. No new threads or comments can be added.
Set IIsWebDirectory Permissions via WMI in C#
Conversation locked
This conversation has been locked by the site admins. No new comments can be made.
Let's say I just uploaded a directory structure to my website under W3SVC/123456/Root/foo/bar/baz. The metabase only contains an entry for W3SVC/123456/Root. How do I set IIS permissions (i.e. AuthAnonymous) on /foo/bar/baz given there is no metabase key for that IIsWebDirectory yet.
Any attempt at referencing the following produces an "Invalid Object" ManagementException:
IIsWebDirectorySetting="W3SVC/123456/Root/foo/bar/baz"
Looking for examples using WMI in C#. No ADSI or VBScript please.
Hehe, yeah, this is a fun one.
>
First, there is a utility (vbscript) available to help you set permissions:
Second, if you can avoid using anonymous access, that's best. Use impersonation to tell your ASP code "act like the user that is using this".
I just saw your "NO VBSCRIPT" comment... sorry about that.
I was looking at this exact problem about a month ago because I wanted to stay away from scripts as well. P-Invoke is an ugly but sometimes necessary approach when it comes to ACE/ACL. I know Microsoft is adding new permission toys in 2.0.
This may be of help:
"Note A NULL ACL in the SECURITY_DESCRIPTOR grants unlimited access to everyone all the time. For more information about the implications of unlimited access, see Creating a Security Descriptor for a New Object."
<still looking for a better answer... will revise this in a few.. I want to know as well
Actually, my question has nothing to do with ACLs at all. I am interested in setting the following properties:
IIsWebDirectory.AccessRead
IIsWebDirectory.AccessScript
IIsWebDirectory.AccessExecute
IIsWebDirectory.EnableDirBrowsing
IIsWebDirectory.AuthAnonymous
Thanks,
Mark
Hi Mark,
Sorry about the wrong tangent!
You'd like to set up an IIS virtual directory through C# and WMI and have the operation perform just like you were doing mmc configuration of a new virtual directory?
This would be a physical path, not a virtual. IIsWebDirectory is for physical paths off the site root, IIsWebVirtualDir would be for virtuals.
Thanks again,
Mark
Are you on IIS 6.0?
I sure am!
Here is an abbreviated example of the code I am wrestling with:
ConnectionOptions connection = new ConnectionOptions();
ManagementScope scope = new ManagementScope(@"\\localhost\root\MicrosoftIISV2", connection);
scope.Connect();
string mpath = "IIsWebDirectorySetting='W3SVC/" + siteIndex + "/ROOT" + path + "'"; // path is "/foo/bar" for example
ManagementPath mp = new ManagementPath(mpath);
ManagementObject dir = new ManagementObject(scope, mp, null);
dir.SetPropertyValue("AuthAnonymous", false);
dir.SetPropertyValue("AccessRead", true);
dir.SetPropertyValue("AccessScript", true);
dir.SetPropertyValue("EnableDirBrowsing", false);
dir.Put();
That last Put() command is what throws the "Invalid Object" exception on me.
Thanks,
Mark
I'm doing a compare and contrast with your code and some Microsoft example code in VBScript:"SpawnInstance()" sticks out as something to research as they say it is "required" which tells me it can be a sticky point. It appears that they create the object without yet giving the path... just create an IIsWebDirectorySetting object first, no path. Next, on your object, set the properties. I'm not set up to test this so forgive me if this is getting off base. Once you've set your properties, including a path and name, then you may find it does the Put properly.
I know the following is using IIsWebVirtualDirectory rather than IIsWebDirectory but the concept should still be valid:
Yeah, that's pretty much equivalent to this piece of code, which also fails with the same error:
ManagementClass clsIIsWebDirectorySetting = new ManagementClass(scope, new ManagementPath("IIsWebDirectorySetting"), null);
ManagementObject dir = clsIIsWebDirectorySetting.CreateInstance();
dir.Properties["Name"].Value = "W3SVC/" + account + "/ROOT" + path;
dir.Put();
If I try the VBScript version of this, I also get "Invalid Object":
strNewVdir = "W3SVC/666666/Root/foo/bar"
' Make connections to WMI, to the IIS namespace on MyMachine.
set locatorObj = CreateObject("WbemScripting.SWbemLocator")
set providerObj = locatorObj.ConnectServer("localhost", "root/MicrosoftIISv2")
' Add a virtual directory to the site. This requires SpawnInstance().
Set vdirClassObj = providerObj.Get("IIsWebDirectorySetting")
Set vdirObj = vdirClassObj.SpawnInstance_()
vdirObj.Name = strNewVdir
vdirObj.AuthFlags = 5 ' AuthNTLM + AuthAnonymous
vdirObj.EnableDefaultDoc = True
vdirObj.DirBrowseFlags = &H4000003E ' date, time, size, extension, longdate
vdirObj.AccessFlags = 513 ' read, script
' Save the new settings to the metabase
vdirObj.Put_()
So clearly, this is not a C# issue, so maybe I'm just using WMI the wrong way!
Arrrgh!
- Mark.
I was going to suggest this after initially reading the thread... but I thought "nah, that's too easy"
Guess sometimes it's the simple things...
Copyright your problem and solution before it becomes the next Microsoft interview question!
"Umm, let me think, string path = "some/path"; string [] pathParts = path.Split('/'); recursiveFunction(rootPath, pathParts, 0)..."
That's really scary -- I used the same variable names.
Great minds think alike.
I got it to work, by the way.
- Mark
Hi All,
I'm having the exact same problem! Just wondering if you can point me to some more information about how to create the metabase keys?
I don't need the recursive trick, I just need to set the AuthAnonymous property on a sub directory of a virtual directory, but i can't actually get a reference to the sub directory until i've manually edited the properties on the sub dir.... [C]
Thanks!
|
https://channel9.msdn.com/Forums/TechOff/45432-Set-IIsWebDirectory-Permissions-via-WMI-in-C
|
CC-MAIN-2017-51
|
refinedweb
| 905
| 50.94
|
Parent Directory
|
Revision Log
Whitespace. (Portage version: 2.2.20/cvs/Linux x86_64, signed Manifest commit with key 9433907D693FB5B8!)
Updating remote-id in metadata.xml (Portage version: 2.2.20/cvs/Linux x86_64, signed Manifest commit with key E9402A79B03529A2!)
Update ebuild to EAPI 5. Specify LICENSE more precisely. Move site-init file to canonical)
import changes from Prefix overlay (Portage version: 2.1.6.13/cvs/Linux i686) (Signed Manifest commit)
clean up (Portage version: 2.1.6.4/cvs/Linux 2.6.27-gentoo-r8 i686) (Signed Manifest commit)
Remove intermediate version. (Portage version: 2.2_rc17/cvs/Linux 2.6.27-gentoo-r4 i686) (Signed Manifest commit)
ppc stable, bug #250219 (Portage version: 2.2_rc17/cvs/Linux 2.6.25-gentoo-r7 x86_64) (Unsigned Manifest commit)
x86 stable wrt #250219 (Portage version: 2.1.4.5) (Unsigned Manifest commit)
stable amd64, bug 250219 (Portage version: 2.1.4.5) (Signed Manifest commit)
stable ppc64, bug 250219 (Portage version: 2.2_rc12/cvs/Linux 2.6.25-gentoo-r7 ppc64) (Unsigned Manifest commit)
Version bump. (Portage version: 2.2_rc13/cvs/Linux 2.6.26-gentoo-r1 i686) (Signed Manifest commit)
Remove all old-style digests from the system and regen the Manifest files.
Version bump, thanks Flameeyes. (Portage version: 2.1.4_rc12) (Signed Manifest commit)
Remove old. (Portage version: 2.1.3.19) (Signed Manifest commit)
stable amd64 (bug 195020) (Portage version: 2.1.3.16) (Signed Manifest commit)
stable on ppc64 (Portage version: 2.1.3.9) (Unsigned Manifest commit)
stable ppc, bug #195020 (Portage version: 2.1.3.12) (Unsigned Manifest commit)
stable x86, bug 195020 (Portage version: 2.1.3.9) (Signed Manifest commit)
Add ~x86-fbsd keyword as per bug #178434 by Joe Peterson. (Portage version: 2.1.2.7) (Signed Manifest commit)
Autoload instead of require. Make use of elisp.eclass defaults. (Portage version: 2.1.2.4) (Signed Manifest commit)
add load path correctly, fixes bug 169588, reported by Ulrich Mueller <ulm@kph.uni-mainz.de> (Portage version: 2.1.2-r9) (Signed Manifest commit)
version bump: added a quote to a variable, removed virtual/emacs from DEPEND (Portage version: 2.1.1-r2) (Signed Manifest commit)
clean up (Portage version: 2.1.1-r2) (Signed Manifest commit)
Regenerate digest in Manifest2 format. (Portage version: 2.1.2-r8) (Signed Manifest commit)
*** empty log message ***
marking php-1.1.0 stable (Portage version: 2.0.51.22-r3) (Unsigned Manifest commit)
marking php-mode-1.1.0 ~ppc64 (Portage version: 2.0.51.22-r2) (Unsigned Manifest commit)
stable amd64 (Portage version: 2.0.51.19) (Manifest recommit) (Portage version: 2.0.51.19)
Updated Copyright dates to 2005. (Manifest recommit)
Stable on x86 and ppc. (Manifest recommit)
ChangeLog fixes (Manifest recommit)
(Manifest recommit)
Version bumped. Changed versioning. Thanks to Doug Goldstein <cardoe@cardoe.com>, closing bug #45456 (Manifest recommit)
Version bumped. Changed versioning. Thanks to Doug Goldstein <cardoe@cardoe.com>, closing bug #45456
added ~amd64 to keywords (Manifest recommit)
metadata
digest fix
minor upstream
minor upstream
repoman: trim trailing.
|
https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/app-emacs/php-mode/Manifest?sortby=author&view=log&hideattic=0&r1=1.17
|
CC-MAIN-2020-16
|
refinedweb
| 505
| 55.5
|
doublespace.java
Write a method named doubleSpace that accepts a Scanner for an input file and a PrintStream for an output file as its parameters, writing into the output file a double-spaced version of the text in the input file. You can achieve this task by inserting a blank line between each line of output. import java.io.*; import java.util.*; public class DoubleSpace { public static void main(String[] args) throws FileNotFoundException { doubleSpace(); } public static void doubleSpace(String inFile, String outFile) throws FileNotFoundException { // read the input file and store as a long String String output = ""; Scanner input = new Scanner(new File("file1.txt")); while (input.hasNextLine()) { output += input.nextLine() + "\n\n"; } input.close(); // write the doubled output to the outFile PrintStream out = new PrintStream(new File("file2.txt")); out.print(output); } }
|
http://www.chegg.com/homework-help/questions-and-answers/write-method-named-doublespace-accepts-scanner-input-file-printstream-output-file-paramete-q3211830
|
CC-MAIN-2014-23
|
refinedweb
| 132
| 54.93
|
.
Glaubitz posted his thoughts about Linux Mint:
Well, Linux Mint is generally very bad when it comes to security and quality.
First of all, they don't issue any Security Advisories, so their users cannot -- unlike users of most other mainstream distributions [1] -- [2]..
Another example of such a hi-jack are their new "X apps" which are supposed to deliver common apps for all desktops which are available on Linux Mint. Their first app of this collection is an editor which they forked off the Mate editor "pluma". And they called it "xedit", ignoring the fact that there already is an "xedit" making the old "xedit" unusable by hi-jacking its namespace.
Add to that, that they do not care about copyright and license issues and just ship their ISOs with pre-installed Oracle Java and Adobe Flash packages and several multimedia codec packages which infringe patents and may therefore not be distributed freely at all in countries like the US.
To conclude, I do not think that the Mint developers deliver professional work. Their distribution is more a crude hack of existing Debian-based distributions. They make fundamental mistakes and put their users at risk, both in the sense of data security as well as licensing issues.
I would therefore highly discourage anyone using Linux Mint until Mint developers have changed their fundamental philosophy and resolved these issues.
Other LWN.net readers shared their thoughts about Linux Mint:
H2: "...thanks for noting many of the things bad and wrong with Mint. Your list is quite good. I've suffered directly from Mint deciding to make one of my tools the default in Mint, for a while, until the flood of Mint users who were in general totally incompetent forced me to drop all support for them, permanently. Mint is totally non supportable by any downstream source because of their ridiculously broken, by design, update/packaging decisions.
Clem had never once thought it necessary to talk to me about his decision, nor would he ever admit that his FrankenDebianBuntu ( unique creature in the world, managing to break fundamentally not just one, but TWO source distributions at once) is in fact totally unsupportable by any sane person.
Not to mention his monstrosity, LMDE, which is not at all Debian, at least it's not since the primary dev of that left in disgust at the absurd garbage clem was forcing into lmde."
Flussence: "The root cause of that issue is that they've built their distro atop one that doesn't namespace packages sanely (or at all). Debian also has had the same dilemma internally with ack, chromium, dolphin, etc. but they choose to work around it by changing the name, sometimes the binary, of one of the two programs; the end result is that the one on the losing side of the deal ends up harder to find.
Everything else you've said is valid, but this one is squarely Debian's fault."
Job: "Thank you for that. At least it shows that I'm not the only one dumbfounded by the apparent insanity here.
It's one thing that this is a hobbyist project, but when real people are actually put at risk because of your hobby, it is not unfair to demand at least some accountability."
Beolach: "Linux Mint is *NOT* a desktop environment - it is a Linux Distribution. As part of their distribution they also created their own desktop environment, but the name of the DE is Cinnamon, not Linux Mint. And Cinnamon is IMO one of the good things Linux Mint has done - I strongly agree w/ their design goal of a traditional desktop UI. Fortunately, Cinnamon can be & is packaged in other distributions, including Debian.
But Linux Mint is a full Distribution, not just the Cinnamon DE, and as such has a *much* larger scope, and in that larger scope has made decisions that I strongly disagree with. In addition to glaubitz's list, the issue that turned me off of Linux Mint is their very old kernel versions - 3.19 in their latest release. And it's not even an older LTS kernel release; it's a no-longer supported kernel. 3.18 would have been better (assuming they kept up w/ the LTS minor updates, of course).
There are how-to guides out there for upgrading Linux Mint to a more recent kernel, but they're all just about grabbing an Ubuntu or Debian kernel. So it's back to the Frankendebuntu situation, make-your-own monster this time."
Johannbg: "All these distributions are fundamentally the same thing with their greatest collaborated achievement being collectively making upstream life miserable about the needless deviation they all do to distinguish themselves from each other. "
Leoluk: "The quality of Linux Mint (the distribution) is questionable. Their applications (Cinnamon and MATE) are, however, of very high quality. Both are packaged by many other distributions nowadays and work just as well as in Linux Mint itself."
Welinder: "It would probably be more productive if you (Debian, ...) asked yourself the question, given all the shortcomings you see, why is Linux Mint so popular? For me, the answer is that Linux Mint protects the users against what I will be nice and call misguided innovation on the desktop. The fads of the day."
Glaubitz: "One of the main reasons for being popular is the fact that they do not care about licensing issues. They ship their ISO files with pre-installed Adobe Flash, Oracle Java packages as well as multimedia codecs (which people want) which violate intellectual copyrights and patents. Unless the maintainers of a distribution want to violate copyright laws intentionally and make themselves attractive targets for lawyers, there is nothing they can do to alleviate that. Debian and other aren't not shipping those packages because they want to make life hard for their users, it's because they cannot, legally speaking.
Canonical - as a company - was able to negotiate contracts with companies like Skype or Adobe, so they can offer the software packages of these companies in their third-party repositories, but it would still be illegal to ship software like libdvdcss2 in most countries. However, there are no companies behind distributions like Arch, Gentoo or Debian and they therefore cannot negotiate such contracts.
Again, the stance of the Mint developers - namely Clement Levebfre - is simply that they don't care about such issues which is already very dubious in the first place, not even mentioning the security issues they have."
Welinder: "I have yet to encounter a situation where a cve report has had Debian and Ubuntu responses, but no patch for Mint has shown up in my patch queue immediately or very soon thereafter. (I know about the "banned" packages and I have flipped the switch so I can see them and decide; I am not worried over local attacks, so grub can wait.)
Now, compare that non-situation to Debian's years of dragging feet regarding fixing the package management's trust in the network and its resultant vulnerability to man-in-the-middle attacks -- including those unintentional ones known as captive portals -- which would *disable* security updates entirely. (Debian 710229; Launchpad 1055614; and many others.)"
Glaubitz: "You may be aware of blacklisted package updates, but many users are not. I'm sorry, but making security updates *optional* is not up for discussion, on any operating system. Period.
And, as I have explained before, Linux Mint does not issue security advisories, so you - as a Linux Mint user - have no immediate and easy way to quickly verify whether your particular version of Linux Mint is affected by a certain CVE.
On Debian, I open up Google and type "Debian CVE-2015-7547" and I am immediately presented with a website which shows me which versions of Debian are affected by the recent glibc vulnerability and which are not. You *cannot* do that on Linux Mint which therefore disqualifies itself for any professional use. End of discussion."
|
http://www.infoworld.com/article/3036600/linux/is-linux-mint-a-crude-hack-of-existing-debian-based-distributions.html
|
CC-MAIN-2016-22
|
refinedweb
| 1,333
| 58.01
|
Functional programming is a programming paradigm in C# that is frequently combined with object oriented programming. C# enables you to use imperative
programming using object-oriented concepts, but you can also use declarative programming. In declarative programming, you are using
a more descriptive way to define
what you want to do and not how you want to do some action. As an example, imagine that you want to find
the top 10 books with price less than 20 ordered by title.
In functional programming, you will define something like:
books.Where(price<20).OrderBy(title).Take(10);
Here you just specify that you want to select books where the price is less than 20, order them by title, and take
the first ten. As you can see, you do not specify how
this should be done - only what you want to do.
Now you will say "OK, but this is just simple C# LINQ - why are we calling it
functional programming"? LINQ is just one implementation library that enables
you to use functional programming concepts. However, functional programming is much more, in this article you might find some interesting samples of usage.
Note that there are other languages that have better support for functional programming.
An example might be the F# language that has better support for functional programming
concepts and you can use it with C# code. However, if you do not want to learn a new language, here you can find what C# provides you in the functional programming area.
The base concept in functional programming is functions. In functional programming we need to create functions as any other objects, manipulate them,
pass them to other functions, etc. Therefore we need more freedom because functions are not just parts of classes - they should be independent objects.
In C# you can use a function object as any other object type. In the following sections, you can see how we can define function types, assign values to function
objects (references), and create complex functions.
Function objects must have some type. In C# we can define either generic functions or strongly typed delegates. Delegates might be recognized as a definition
of function prototypes where is defined the method signature. "Instance objects" of delegate types are pointers to functions (static methods, class methods)
that have a prototype that matches the delegate definition. An example of a delegate definition is shown in the following code:
delegate double MyFunction(double x);
This delegate defines a prototype of a function that has a double argument and returns
the result as a double value. Note that only types are important, actual names
of methods and their arguments are arbitrary. This delegate type matches a lot of trigonometric functions, logarithm, exponential, polynomial, and other functions.
As an example, you can define a function variable that references some math function, executes it via
a function variable, and puts the result in some other variable.
An example is shown in the following listing:
double
MyFunction f = Math.Sin;
double y = f(4); //y=sin(4)
f = Math.Exp;
y = f(4); //y=exp(4)
Instead of strongly typed delegates you can use generic function types Func<T1, T2, T3, ...,Tn,
Tresult> where T1, T2, T3, ...,Tn are types of the arguments (used if
the function has some arguments)
and Tresult is the return type. An example equivalent to the previous code is shown in the following listing:
Func<T1, T2, T3, ...,Tn,
Tresult>
Func<double, double> f = Math.Sin;
double y = f(4); //y=sin(4)
f = Math.Exp;
y = f(4); //y=exp(4)
You can either define your named delegates or use generic types. Besides
Func, you have two similar generic types:
Func
Predicate<T1, T2, T3, ...,Tn>
Func<T1,
T2, T3, ...,Tn, bool>
Action<T1, T2, T3, ...,Tn>
Func<T1, T2, T3, ...,Tn, void>
Predicate is a function that takes some arguments and returns either a true or false value. In the following example is shown
a predicate function that accepts a string parameter.
The value of this function is set to String.IsNullOrEmpty. This function accepts
a string argument and returns information whether or not this string
is null or empty - therefore it matches the Predicate<string> type.
String.IsNullOrEmpty
Predicate<string>
Predicate<string> isEmptyString = String.IsNullOrEmpty;
if (isEmptyString("Test"))
{
throw new Exception("'Test' cannot be empty");
}
Instead of Predicate<string>, you could use Func<string, bool>.
Func<string, bool>
Actions are a kind of procedures that can be executed. They accept some arguments but return nothing. In the following example is shown one action that accepts
string argument and it points to the standard Console.WriteLine method.
Console.WriteLine
Action<string> println = Console.WriteLine;
println("Test");
When an action reference is called with the parameter, the call is forwarded to the Console.WriteLine method. When you use Action types, you just need to define
the list
of input parameters because there is no result. In this example, Action<string>
is equivalent to Func<string, void>.
Action<string>
Func<string, void>
Once you define function objects, you can assign them other existing functions as shown in the previous listings or other function variables.
Also, you can pass them to other functions as standard variables. If you want to assign
a value to a function, you have the following possibilities:
Some examples of assigning values to functions are shown in the following listing:
Func<double, double> f1 = Math.Sin;
Func<double, double> f2 = Math.Exp;
double y = f1(4) + f2(5); //y=sin(3) + exp(5)
f2 = f1;
y = f2(9); //y=sin(9)
In this case, methods are referred as ClassName.MethodName. Instead of existing functions you can dynamically create functions and assign them to variables.
In this case you can use either anonymous delegates or lambda expressions. An example is shown in the following listing:
ClassName.MethodName
Func<double, double> f = delegate(double x) { return 3*x+1; }
double y = f(4); //y=13
f = x => 3*x+1;
y = f(5); //y=16
In this code we have assigned a delegate that accepts a double argument x and returns
a double value 3*x+1. As this dynamically created function matches
Func<double, double>,
it can be assigned to the function variable. In the third line is assigned an equivalent lambda expression. As you can see,
the lambda expression is identical to the function: it is just
a function representation in the format parameters => return-expression. In the following table are shown some lambda expressions and equivalent delegates:
Func<double, double>
() => 3
Lambda expression must have part for definition of argument names - if lambda expression do not have parameters empty brackets () should be placed. If there is only one parameter in the list brackets are not needed. After => sign you need to put an expression that will be returned.
As you can see, lambda expressions are equivalent to regular functions(delegates), but they are more
suitable when you are creating short functions. Also, one usefull advantage is that you do not have to explicitly define parameter types. In the example above is defined lambda expression (x, y) => x+y that can be used both for adding numbers but also for concatenating strings. If you use delegates you will need to explicitly define argument types, and you cannot use one delegate for other types.
(x, y) => x+y
The ability to build your own functions might be useful when you need to create your own new functions. As an example you can create some math functions that are not part of Math class but you need to use them. Some of these functions are:
Math
You can easily create these functions and set them to the functional variables as it is shown in the following listing:
Func<double, double> asinh = delegate(double x) { return Math.Log( x + Math.Sqrt(x*x+1) ) ;
Func<double, double> acosh = x => Math.Log( x + Math.Sqrt(x*x-1) ) ;
Func<double, double> atanh = x => 0.5*( Math.Log( 1 + x ) - Math.Log( 1 -x ) ) ;
You can create these functions either via delegates or lambda expressions as they are equivalent.
You can also add or subtract functions (delegates) in expressions. If you add two function values, when
the resulting function variable is called, both functions will be executed.
This is the so called multicast delegate. You can also remove some functions from the multicast delegate. In the following example I have added two functions that
match the Action<string> type:
static void Hello(string s)
{
System.Console.WriteLine(" Hello, {0}!", s);
}
static void Goodbye(string s)
{
System.Console.WriteLine(" Goodbye, {0}!", s);
}
These methods accept a string parameter and return nothing. In the following code is shown how you can apply delegate arithmetic in order to manipulate multicast delegates.
Action<string> action = Console.WriteLine;
Action<string> hello = Hello;
Action<string> goodbye = Goodbye;
action += Hello;
action += (x) => { Console.WriteLine(" Greating {0} from lambda expression", x); };
action("First"); // called WriteLine, Hello, and lambda expression
action -= hello;
action("Second"); // called WriteLine, and lambda expression
action = Console.WriteLine + goodbye
+ delegate(string x){
Console.WriteLine(" Greating {0} from delegate", x);
};
action("Third");// called WriteLine, Goodbye, and delegate
(action - Goodbye)("Fourth"); // called WriteLine and delegate
First, we have created three delegates pointing to the functions WriteLine, Hello, and Goodbye.
Then we have added a function Hello and a new lambda expression to the first delegate. Operator += is used for attaching new functions that will be called
by the multicast delegate. In the end it will create a multicast delegate that will call all three functions once it is called.
WriteLine
Hello
Goodbye
Hello
+=
Then the function Hello is removed from the delegate action. Note that
the function Hello is added directly via name but it is removed via
the delegate
hello that points to it. When the action is called a second time, only two functions will be called.
hello
In the third group is added the WriteLine delegate to the Goodbye method and a new anonymous delegate. This "sum" is assigned to the delegate action
so the previous combination is lost. When the action ("Third") is called, these three functions are executed.
WriteLine
Goodbye
In the end you can see how you can create an expression and execute it. In the last statement,
the result of the expression action - goodbye is a function mix
in the action without the Goodbye function. The result of the expression is not assigned to any delegate variable - it is just executed.
action - goodbye
If you put this code in some console application, the result would be similar to the following screenshot:
Also, you can always get the information about the current function set in the multicast delegate. The following code gets the invocation list of multicast delegate action and for each delegate in the invocation list outputs the name of the method:
action
action.GetInvocationList().ToList().ForEach(del => Console.WriteLine(del.Method.Name));
Beside the name, you can get other parameters of the function such as return type, arguments, and you can even explicitly call some delegates in the invocation list.
Now we can start with functional programming examples. The fact that functions can be passed as arguments enables us to create very generic constructions.
As an example, imagine that you want to create a generic function that determines
the number of objects in some array that satisfies some condition.
The following example shows how this function can be implemented:
public static int Count<T>(T[] arr, Predicate<T> condition)
{
int counter = 0;
for (int i = 0; i < arr.Length; i++)
if (condition(arr[i]))
counter++;
return counter;
}
In this function, we are counting the elements in the array that satisfies
the condition. Code that determines whether the condition is satisfied is not hard-coded
in the function and it is passed as an argument (predicate). This function can be used in various cases such as counting
the number of books where the title is longer
that 10 characters, or where the price is less than 20, or counting the negative numbers in the array. Some examples are shown below:
Predicate<string> longWords = delegate(string word) { return word.Length > 10; };
int numberOfBooksWithLongNames = Count(words, longWords);
int numberOfCheapbooks = Count(books, delegate(Book b) { return b.Price< 20; });
int numberOfNegativeNumbers = Count(numbers, x => x < 0);
int numberOfEmptyBookTitles = Count(words, String.IsNullOrEmpty);
As you can see, the same function is used in different areas - you just need to define
a different condition (predicate) that should be applied in the function.
A predicate can be a delegate, lambda expression, or existing static function.
You can use functional programming to replace some standard C# constructions. One typical example is using block shown in the following listing:
using
using (obj)
{
obj.DoAction();
}
Using block is applied on the disposable objects. In the using block you can work with the object, call some of the methods etc. When using block ends, object will be disposed. Instead of the using block you can create your own function that will warp the action that will be applied on the object.
public static void Use<T>(this T obj, Action<T> action) where T : IDisposable
{
using (obj)
{
action(obj);
}
}
Here is created one extension method that accepts action that should be executed and wrap call in the using block. Example of usage is shown in the following code:
obj.Use( x=> x.DoAction(); );
You can convert any structure such as if, while, foreach to function. In the following example is shown how you can output names from the list of strings using the ForEach extension method that is just equivalent to the foreach loop:
var names = new List<string>();
names.ForEach(n => Console.WriteLine(n));
Method of the List<T> class ForEach<T>(Action<T> action) works the same way as a standard for each loop, but this way you have more compact syntax. In the following examples will be shown some common usages of the functional programming.
ForEach<T>(Action<T> action)
The function that you saw in the previous listing is very generic and useful, but in most cases you do not even have to create it.
C# comes with a LINQ extension where you can find many useful generic functions. As an example, you can use
the LINQ Count method instead of the one defined
in the previous example to do the same thing. The same examples written with the LINQ
Count function are:
Count
Predicate<string> longWords = delegate(string word) { return word.Length > 10; };
int numberOfBooksWithLongNames = words.Count(longWords);
int numberOfCheapbooks = books.Count( delegate(Book b) { return b.Price< 20; });
int numberOfNegativeNumbers = numbers.Count(x => x < 0);
This function is directly built-in so you can use it. LINQ has many other useful functions such as
Average, Any, Min, that can be used the same way - just pass
the predicate
that should be used to check whether or not some objects in the array should be included. Some examples of other LINQ functions are shown in the following listing:
Average
Any
Min
int averageDigits = number.Average( digit => digit>=0 && digit < 10);
int isAnyCheaperThan200 = books.Any( b => b.Price< 200 );
int maxNegativeNumber = numbers.Max(x => x < 0);
In the LINQ library you have many functions that you can use out of box for functional programming. As an example you have a set of function that accepts predicate and process source collection - some of them are:
You can see more details about these methods in Using LINQ Queries article. LINQ has functions that work with regular functions that return some values. As an example if you pass criterion function that returns string or int you can order elements of collection using the following functions:
<source>.OrderBy(<criterion>).ThenBy(<criterion>)
Criterion is any function that for each element in the source collection returns some value that can be used for ordering. As an example if you want to use existing collection of books and order them by length and then by first letter you can use something like a following code:
string[] words = new string[] { "C#", ".NET", "ASP.NET", "MVC", "", "Visual Studio" };
Func<string, char> firstLetter = delegate(string s) { return s[0]; };
var sorted = words.OrderBy(word => word.Length).ThenBy(firstLetter);
In this example are used existing OrderBy and ThenBy functions from the LINQ library with passed lambda expressions and function variables as criterions.
I will not show too many details of LINQ here, but if you are interested in this, you can see
the Using LINQ Queries article. However, I will just show some examples of usage that some are not aware of.
Imagine that you need to find the number of nulls or empty strings in
an array of strings. Code for this looks like:
null
string[] words = new string[] { "C#", ".NET", null, "MVC", "", "Visual Studio" };
int num = words.Count( String.IsNullOrEmpty );
In practice, you will use LINQ for 90% of any functionalities you need to implement, and
you will create custom functions only for functionalities that are not
already provided.
Treating functions as regular objects enables us to use them as arguments and results of other functions. Functions that handle other functions are called higher order functions.
The Count function in the example above is a higher-order function because it accepts
a predicate function and applies it to each element when it checks the condition.
Higher-order functions are common when using the LINQ library. As an example, if you want to convert a sequence to
a new sequence using some function,
you will use something like the Select LINQ function:
var squares = numbers.Select( num => num*num );
In the example above is shown a LINQ function Select that maps each number in the collection of numbers to its square value. This
Select function
is nothing special, it can be easily implemented as the following higher-order function:
// Apply a function f T1 -> T2 to each element of data using a List
public static IEnumerable<T2> MySelect<T1, T2>(this IEnumerable<T1> data, Func<T1, T2> f)
{
List<T2> retVal= new List<T2>();
foreach (T1 x in data) retVal.Add(f(x));
return retVal;
}
In this example, the function iterates through the list, applies the function
f to each element, puts the result in the new list, and returns the collection.
By changing function f, you can create various transformations of
the original sequence using the same generic higher order function. You can see
more examples of this function in
Akram's comment below.
f
Here will be shown how higher-order functions can be used to implement composition of two functions. Let imagine that we have function f (of type Func<X,Y>) that converts elements of type X to the elements of type Y. Also, we would need another function g (of type Func<Y,Z>) that converts elements of type Y to the elements of type Z. These functions and element sets are shown in the following figure:
Func<X,Y>
Func<Y,Z>
Now, we would like to create a single function fog(x) that converts elements of type X directly to the elements of type Z (type of the function is Func<X,Z>). This function will work following way - first it will apply function f to some element of type X in order to calculate element from the set Y, and then it will apply function g on the results. This formula is shown below:
Func<X,Z>
fog(x) = g(f(x))
This function that represents composition of functions f and g has type Func<X,Z> and directly maps the elements of type X to the elements of type Z. This is shown on the following figure:
Now we can create higher-order function that implements this composition. This function will accept two function with generic types Func<X,Y> and Func<Y,Z> that represent functions that will be composed, and returns one function of type Func<X,Z> that represents resulting composition. The code of the higher-order function that creates composition of two functions is shown in the following listing:
static Func<X, Z> Compose<X, Y, Z>(Func<X, Y> f, Func<Y, Z> g)
{
return (x) => g(f(x));
}
As it is descripbed above, this higher-order function takes two functions f and g and creates a new function that accepts parameter x and calculates g(f(x)). According to the definition above this is composition of functions.
g
If you want to use this function to create
a function
that calculates exp(sin(x)), you will use code that looks like the following one:
Func<double, double> sin = Math.Sin;
Func<double, double> exp = Math.Exp;
Func<double, double> exp_sin = Compose(sin, exp);
double y = exp_sin(3);
In this case X, Y, and Z are the same types - double.
As you can see, the result of the Compose function is not a value - it
is a new function that can be executed. You can use a similar approach to generate your own functions.
Compose
One of the important features of functions is that they can be called asynchronously, i.e., you can start a function, continue with the work, and then wait
until the function finishes when you need results. Each function object in C# has
the following methods:
BeginInvoke
IsCompleted
EndInvoke
An example of asynchronous execution of the function is shown in the following listing:
Func<int, int, int> f = Klass.SlowFunction;
//Start execution
IAsyncResult async = f.BeginInvoke(5, 3, null, null); //calls function with arguments (5,3)
//Check is function completed
if(async.IsCompleted) {
int result = f.EndInvoke(async);
}
//Finally - demand result
int sum = f.EndInvoke(async);
In this example, a reference to some slow function that calculates the sum of two numbers is assigned to the function variable
f. You can separately begin invocation
and pass arguments, check if the calculation was finished, and explicitly demand result. An example of that kind of function is shown in the following listing.
public class Klass{
public static int SlowFunction(int x, int y){
Thread.Sleep(10000);
return x+y;
}
}
This is just a simulation, but you can use this approach in functions that send emails, execute long SQL queries, etc.
In the previous example, you saw that arguments are passed to the function but there are also two additional parameters set to
null. These arguments are:
This way you do not need to explicitly check if the function was executed - just pass
the callback function that will be called when the function finishes execution.
An example of the call with callback is shown in the following code:
Func<int, int, int> f = Klass.SlowFunction;
//Start execution
f.BeginInvoke(5, 3, async =>
{
string arguments = (string)async.AsyncState;
var ar = (AsyncResult)async;
var fn = (Func<int, int, int>)ar.AsyncDelegate;
int result = fn.EndInvoke(async);
Console.WriteLine("f({0}) = {1}", arguments, result);
},
"5,3"
);
The callback function (or lambda expression in this example) takes a parameter
async that has information about the asynchronous call. You can use
the AsyncState property
to determine the fourth argument of the BeginInvoke call (in this case are passed arguments as string "5,3"). If you cast
the parameter of the lambda expression
to AsyncResults you can find the original function and call its EndInvoke method. As a result, you can print it on the console window.
async
AsyncState
AsyncResults
As you can see, there is no need to explicitly check in the main code if the function
has finished - just let it know what should be done when it is completed.
Tuples are a useful way to dynamically represent a data structure in the form (1, "name", 2, true, 7). You can create tuples by passing
a set of fields that belong
to the tuple to the Tuple.Create method. An example of a function that uses tuples is shown below:
Tuple.Create
Random rnd = new Random();
Tuple<double, double> CreateRandomPoint() {
var x = rnd.NextDouble() * 10;
var y = rnd.NextDouble() * 10;
return Tuple.Create(x, y);
}
This function creates a random 2D point within area 10x10. Instead of the tuple you could explicitly
define a class Point and pass it in the definition,
but this way we have a more generic form.
Point
Tuples can be used when you want to define generic functions that use structured data. If you want to create
a predicate that determines whether
a 2D point is placed within a circle with radius 1, you will use something like
the following code:
Predicate<Tuple<double, double>> isInCircle;
isInCircle = t => ( t.Item1*t.Item1+t.Item2*t.Item2 < 1 );
Here we have a predicate that takes a tuple with two double items and determines whether the coordinates are in the circle. You can access any field in the tuple
using properties Item1, Item2, etc. Now let us see how we can use this function and predicate to find all points that are placed within the circle with radius 1.
Item1
Item2
for(int i=0; i<100; i++){
var point = CreateRandomPoint();
if(isInCircle(t))
Console.WriteLine("Point {0} in placed within the circle with radius 1", point);
}
Here we have a loop where we generate 100 random points and for each of them, we check whether the
isInCircle function is satisfied.
isInCircle
You can use tuples when want to create data structure without creating a predefined class. Tuples can be used in
the same code where you are using dynamic or anonymous objects
but one advantage of tuples is that you can use them as parameters or return values.
Here is one more complex example - imagine that you have represented information about company as tuples of type
Tuple<int, string, bool, int> where the first item
is ID, second is the name of the company, third is a flag that marks the tuple as branch, and the last item is
the ID of the head office. This is very common if you create some kind
of query like SELECT id, name, isOffice, parentOfficeID and where you put each column in
a separate dimension of the tuple.
Now we will create a function that takes a tuple and creates a new branch office tuple:
Tuple<int, string, bool, int>
S
ELECT id, name, isOffice, parentOfficeID
Tuple<int, string, bool, int?> CreateBranchOffice(Tuple<int, string, bool, int?> company){
var branch = Tuple.Create(1, company.Item2, company.Item3, null);
Console.WriteLine(company);
branch = Tuple.Create(10*company.Item1+1, company.Item2 +
" Office", true, company.Item1);
Console.WriteLine(t);
var office = new { ID = branch.Item1,
Name = branch.Item2,
IsOffice = branch.Item3,
ParentID = company.Item4 };
return branch;
}
In this example, the function accepts company and creates a branch office. Both company and branch offices are represented as tuples with four items. You can create
a new tuple
using the Tuple.Create method, and access the elements of the tuple using the
Item properties.
company
Item
Also, in this code is created an anonymous object office with properties
ID, Name, IsOffice, and ParentID which is equivalent to tuple (this object is just created but not used anywhere).
In this statement, you can see how easy it is to convert tuples to actual objects. Also, you can see one advantage of tuples - if you would like to return
office as a return value
you would have a problem defining the return type of the function CreateBranchOffice.
The office object is an anonymous object, its class is not known by name outside
of the function body, therefore you cannot define the return type of the function. If you want to return some dynamic structure instead of tuple, you would need to define
a separate class instead of an anonymous class, or you will need to set the return type as dynamic but in that case, you will lose information about the structure of
the returned object.
office
ID
Name
IsOffice
ParentID
CreateBranchOffice
object
dynamic
When we are talking about the functions we must talk about scope of variables. In the standard functions we have following types of variables:
When we create a delegate or lambda expression we use arguments and local variables, and we can reference variables outside the delegate. Example is shown in the following listing:
int val = 0;
Func<int, int> add = delegate(int delta) { val+=delta; return val; };
val = 10;
var x = add(5); // val = 15, x = 15
var y = add(7); // val = 22, y = 22
Here we have created one delegate that adds value of the parameter to the variable val that is defined outside the delegate. Also it returns a value as result. We can modify the variable val both in the main code and indirectly via delegate call.
val
Now what will happens if variable val is a local variable in the higher-order function that returns this delegate? Example of that kind of function is shown in the following listing:
val
static Func<int, int> ReturnClosureFunction()
{
int val = 0;
Func<int, int> add = delegate(int delta) { val += delta; return val; };
val = 10;
return add;
}
And with the calling code:
Func<int, int> add = ReturnClosureFunction();
var x = add(5);
var y = add(7);
This might be a problem because local variable val dies when ReturnClosureFunction is finished, but the delegate is returned and still lives in the calling code. Would the delegate code break because it references variable val that does not exist outside the function ReturnClosureFunction? Answer is - no. If delegate references the outside variable, it will be bound to the delegate as long as it lives in any scope. This means that in the calling code above will set the values 15 in the variable x, and 22 in the variable y. If a delegate references some variable outside his scope, this variable will behave as a property of the function object (delegate) - it will be part of the function whenever the function is called.
ReturnClosureFunction
ReturnClosureFunction
We will see how closures are used in the two following examples.
This interesting feature might be used to implement sharing data between the functions. Using the closures to share variables you can
implement various data structures such as lists, stack, queues, etc, and
just expose delegates that modify shared data. As an example let we examine the following code:
int val = 0;
Action increment = () => val++;
Action decrement = delegate() { val--; };
Action print = () => Console.WriteLine("val = " + val);
increment(); // val = 1
print();
increment(); // val = 2
print();
increment(); // val = 3
print();
decrement(); // val = 4
print();
Here we have one variable that is updated by the lambda expression increment and delegate decrement. Also, it is used by the delegate print. Each time you use any of the functions they will read/update the same shared variable. This will work even if the shared variable is out of
scope of usage. As an example we can create a function where this local
variable is defined, and this function will return three functions:
increment
decrement
print
static Tuple<Action, Action, Action> CreateBoundFunctions()
{
int val = 0;
Action increment = () => val++;
Action decrement = delegate() { val--; };
Action print = () => Console.WriteLine("val = " + val);
return Tuple.Create<Action, Action, Action>(increment, decrement, print);
}
In this example we are returning a tuple with three actions as a
return result. The following code shows how we can use these
these three functions outside the code where they are created:
var tuple = CreateBoundFunctions();
Action increment = tuple.Item1;
Action decrement = tuple.Item2;
Action print = tuple.Item3;
increment();
print(); // 1
increment();
print(); // 2
increment();
print(); // 3
decrement();
print(); // 2
This code is identical to the previous code where all
three functions are created in the same scope. Each time we call some of
the bounded functions, they will modify the shared variable that is not
in the scope anymore.
Now we will see another way how to use closures to implement caching. Caching can be implemented if we create a function that accepts function that should be cached, and return a new function that will cache results in some period. Example is shown in the following listing:
public static Func<T> Cache<T>(this Func<T> func, int cacheInterval)
{
var cachedValue = func();
var timeCached = DateTime.Now;
Func<T> cachedFunc = () => {
if ((DateTime.Now - timeCached).Seconds >= cacheInterval)
{
timeCached = DateTime.Now;
cachedValue = func();
}
return cachedValue;
};
return cachedFunc;
}
Here we have extended functions that returns some type T (Func<T> func). This extension method accepts period for caching value of function and returns a new function. First we have executed function in order to determine a value that will be cached and record time when it is cached. Then we have created a new function cachedFunc with the same type Func<T>. This function determines whether the difference between the current time and time when the value is cached is greater or equal of cache interval. If so, new cache time will be set to the current time and cached value is updated. As a result this function will return cached value.
Func<T> func
Variables cacheInterval, cachedValue and timeCached are bound to the cached function and behaves as a part of the function. This enables us to memoize last value and determine how long it should be cached.
In the following example we can see how this extension can be used to cache value of the function that returns the current time:
Func<DateTime> now = () => DateTime.Now;
Func<DateTime> nowCached = now.Cache(4);
Console.WriteLine("\tCurrent time\tCached time");
for (int i = 0; i < 20; i++)
{
Console.WriteLine("{0}.\t{1:T}\t{2:T}", i+1, now(), nowCached());
Thread.Sleep(1000);
}
We have created a function that accepts no arguments and returns a current date (the first lambda expression). Then we have applied Cache extension function on this function in order to create cached version. This cached version will return same value in the 4 seconds interval.
In order to demonstrate caching in the for loop are outputed values of the original and the cached version. Result is shown in the following output window:
As you can see, the cached version of function return the same time value each four seconds as it is defined in the caching interval.
Recursion is the ability that function can call itself. One of the most commonly used examples of recursion is calculation
of factorial of an integer number.
Factorial of n (Fact(n) = n!) is a product of all numbers less or equal to n, i.e., n! = n*(n-1)*(n-2)*(n-3)*...*3*2*1.
There is one interesting thing in the definition of factorial n! = n * (n-1)! and this feature is used to define recursion.
If n is 1, then we do not need to calculate factorial - it is 1. If n is greater than 1 we can calculate factorial of n-1 and multiply it with n.
An example of that
kind of a recursive function is shown in the following listing:
static int Factorial(int n)
{
return n < 1 ? 1 : n * Factorial(n - 1);
}
This is easy in the statically named function but you cannot do this directly in delegates/lambda expressions because they cannot reference themselves by name.
However, there is a trick to how you can implement recursion:
static Func<int, int> Factorial()
{
Func<int, int> factorial = null;
factorial = n => n < 1 ? 1 : n * factorial(n - 1);
return factorial;
}
In this higher-order function (it returns a function object) is defined factorial as
a local variable. Then factorial is assigned to the lambda expression that uses
the logic
above (if argument is 1 or less, return 1, otherwise call factorial with argument n-1). This way we have declared
a function before its definition and in the definition, we
have used a reference to recursively call it. In the following example is shown how you can use this recursive function:
factorial
var f = Factorial();
for(int i=0; i<10; i++)
Console.WriteLine("{0}! = {1}", i, f(i));
If you can implement factorial as a higher-order function, then it means that you can format it as an anonymous function. In the following example, you can see how
you can define a delegate that determines the factorial of a number. This
delegate is used in LINQ in order to find all numbers with factorial less than 7.
var numbers = new[] { 5,1,3,7,2,6,4};
Func<int, int> factorial = delegate(int num) {
Func<int, int> locFactorial = null;
locFactorial = n => n == 1 ? 1 : n * locFactorial(n - 1);
return locFactorial(num);
};
var smallnums = numbers.Where(n => factorial(n) < 7);
Also, you can convert it to a lambda expression and pass it directly to the LINQ function as shown in the following example:
var numbers = new[] { 5,1,3,7,2,6,4};
var smallnums = numbers.Where(num => {
Func<int, int> factorial = null;
factorial = n => n == 1 ? 1 : n * factorial(n - 1);
return factorial(num) < 7;
});
Unfortunately this lambda expression is not compact as you might expect because we need to define
the local factorial function. As you can see, it is possible to implement
recursion even with the anonymous functions/lambda expressions.
Partial functions are functions that reduce the number of function arguments by using default values. If you have a function with N parameters,
you can create a wrapper function with N-1 parameters that calls the original function with
a fixed (default) argument.
Imagine that you have a function Func<double, double, double> that has two
double arguments and returns one double result.
You might want to create a new single argument function that has the default value for the first argument. In that case you will create
a partial higher-order function that accepts the default
value for the first argument and creates a single argument function that always passes the same first value to the original function and the only argument just passes
the argument
to the function and sets the default value:
Func<double, double, double>
public static Func<T2, TR> Partial1<T1, T2, TR>(this Func<T1, T2, TR> func, T1 first)
{
return b => func(first, b);
}
Math.Pow(double, double) is an example of a function that can be extended with this partial function. Using this function, we can set
the default first
argument and derive functions such as 2x, ex (Math.Exp), 5x, 10x, etc.
An example is shown below:
Math.Pow(double, double)
Math.Exp
double x;
Func<double, double, double> pow = Math.Pow;
Func<double, double> exp = pow.Partial1( Math.E );// exp(x) = Math.Pow(Math.E, x)
Func<double, double> step = pow.Partial1( 2 );// step(x) = Math.Pow(2, x)
if (exp(4) == Math.Exp(4))
x = step(5); //x = 2*2*2*2*2
Instead of the first argument we can set the second one as default. In that case partial function would look like the following one:
public static Func<T1, TR> Partial2<T1, T2, TR>(this Func<T1, T2, TR> func, T2 second)
{
return a => func(a, second);
}
Using this function, we can derive from the Math.Pow functions such as square x2, square root
√ x , cube x3,
etc. Code that derives these functions from Math.Pow is shown in the following listing:
Math.Pow
double x;
Func<double, double, double> pow = Math.Pow;
Func<double, double> square = pow.Partial2( 2 ); // square(x) = Math.Pow(x,2)
Func<double, double> squareroot = pow.Partial2( 0.5 ); // squareroot(x) = Math.Pow(x, 0.5)
Func<double, double> cube = pow.Partial2( 3 ); // cube(x) = Math.Pow(x,3)
x = square(5); //x = 25
x = sqrt(9); //x = 3
x = cube(3); //x = 27
In the following example will be shown how you can use this feature.
I will explain partial functions (and currying later) with a mathematical example - determining
the distance of a point in a three dimensional coordinate system.
A point in a 3D coordinate system is shown in the following figure. As you can see, each point has three coordinates - one for each axis.
Imagine that you need to determine the distance from the point to the center of
the coordinate system (0,0,0). This function would look like:
static double Distance(double x, double y, double z)
{
return Math.Sqrt(x * x + y * y + z * z);
}
This function determines the standard Euclid distance in three dimensional space. You can use this function as any other function:
Func<double, double, double, double> distance3D = Distance;
var d1 = distance3D(3, 6, -1);
var d2 = distance3D(3, 6, 0);
var d3 = distance3D(3, 4, 0);
var d4 = distance3D(3, 3, 0);
Imagine that you are always working with points on the ground level - these are 2D points with
the last coordinate (altitude) always at z=0. On the previous figure is shown a Pxy point (projection of point P in the xy plane) where the z coordinate is 0. If you are working with two dimensional points in the XY plane and you want
to determine the distances of these points from the center, you can use the Distance function but you will need to repeat the last argument z=0 in each call,
or you will need to rewrite the original function to use only two dimensions. However, you can create
a higher-order function that accepts the original 3D function and returns a
2D function where the default value for z is always set. This function is shown in the following example:
Distance
static Func<T1, T2, TResult> SetDefaultArgument<T1, T2, T3,
TResult>(this Func<T1, T2, T3, TResult> function, T3 defaultZ)
{
return (x, y) => function(x, y, defaultZ);
}
This function accepts a function with three double arguments that returns
a double value, and a double value that will be the
fixed last argument.
Then it returns a new function with two double parameters that just passes two arguments and
a fixed value to the original function.
Now you can apply the default value and use the returned 2D distance function:
Func<double, double, double> distance2D = distance3D.SetDefaultArgument(0);
var d1 = distance2D(3, 6); // distance3D(3, 6, 0);
var d2 = distance2D(3, 4); // distance3D(3, 4, 0);
var d3 = distance2D(1, 2); // distance3D(1, 2, 0);
You can apply any altitude. As an example, instead of the points on altitude z=0, you might want to work with the points at altitude z=3 as shown in the following figure:
We can use the same distance3D function by setting the default argument to 3.
The code is shown in the following listing:
distance3D
Func<double, double, double> distance2D_atLevel = distance3D.SetDefaultArgument(3);
var d1 = distance2D_atLevel(3, 6); // distance3D(3, 6, 3);
var d2 = distance2D_atLevel(3, 3); // distance3D(3, 3, 3);
var d3 = distance2D_atLevel(1, 1); // distance3D(1, 1, 3);
var d4 = distance2D_atLevel(0, 6); // distance3D(0, 6, 3);
If you need a single dimension function you can create another function extension that converts
the two argument function to a single argument function:
static Func<T1, TResult> SetDefaultArgument<T1, T2, TResult>(this Func<T1, T2, TResult> function, T2 defaultY)
{
return x => function(x, defaultY);
}
This higher-order function is similar to the previous one but it uses a two-argument function and returns a single-argument function.
Here are some examples of how you can use this single value function:
Func<double, double> distance = distance2D.SetDefaultArgument(3);
var d1 = distance(7); //distance3D(7, 3, 0)
var d2 = distance(3); //distance3D(3, 3, 0)
var d3 = distance(0); //distance3D(0, 3, 0)
distance = distance3D.SetDefaultArgument(2).SetDefaultArgument(4);
double d4 = distance(12); //distance3D(12, 4, 2)
double d5 = distance(-5); //distance3D(-5, 4, 2)
double d6 = distance(-2); //distance3D(-2, 4, 2)
In this example, we are creating a single argument function Distance. We can create this function either by setting
a default parameter value to the two-parameter
distance2D function, or by setting two default values to the three-argument function distance3D.
In both cases, we will get a function with one argument. As you can see, parameter partitioning is
a good way to slice your functions.
Distance
distance2D
distance3D
In the previous example is shown how you can transform a function by reducing the number of arguments by one. If you want to break it further you will need to create
another higher order function for partitioning. Currying is another way to transform
a function by breaking an N-argument function to N single argument calls using a
single higher-order function.
As an example, imagine that you have a function that extracts the substring of
a string using the start position and length. This method might be called as in the following example:
var substring = mystring.Substring(3,5);
It would be more convenient if you would have two single argument functions instead of one two argument function and the call would look like:
var substring = mystring.Skip(3).Take(5);
With two single argument functions, you have more freedom to use and combine functions. As an example, if you need
a substring from the third character to the end,
you will use just the Skip(3) call. If you need just the first five characters of the string you will call only
Take(5) without Skip. In the original function, you will need to pass
the default arguments for start or length even if you do not need them, or to create various combinations of
the Substring function where the first argument will be defaulted to 0 and the
second defaulted to length.
Skip(3)
Take(5)
Skip
Substring
Currying is a method that enables you to break an N-argument function to N single argument calls. In order to demonstrate currying,
here we will use the same 3D Distance function as in the previous example:
Now we will use the following generic higher-order function for breaking
three parameter functions to a list of single argument functions:
static Func<T1, Func<T2, Func<T3, TResult>>> Curry<T1, T2,
T3, TResult>(Func<T1, T2, T3, TResult> function)
{
return a => b => c => function(a, b, c);
}
This function will break the three argument function into a set of three single argument functions (monads). Now we can convert
the Distance function
to the curried version. We would need to apply the Curry higher-order function with all
double parameters:
Curry
var curriedDistance = Curry<double, double, double, double>(Distance);
double d = curriedDistance(3)(4)(12);
Also, you can see how the function is called. Instead of the three argument function distance (3, 4, 12), it is called as a chain of single argument functions
curriedDistance(3)(4)(12).
In this example is used a separate function that returns the curried version of
the original function, but you might create it as an extension method.
The only thing you need to do is put it in a separate static class and add the this modifier in the first argument:
curriedDistance(3)(4)(12)
this
public static Func<T1, Func<T2, Func<T3, TResult>>>
CurryMe<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> function)
{
return a => b => c => function(a, b, c);
}
Now you can curry the function with a more convenient syntax (like a method of the function object without
explicitly defined types):
Func<double, double, double, double> fnDistance = Distance;
var curriedDistance = fnDistance.CurryMe();
double d = curriedDistance(3)(4)(12);
Only note that you can apply this extension to the function object (fnDistance). Here
we will demonstrate the usage of the curry function in the same example
as in the previous section - reducing three dimensional space.
fnDistance
With one curried function, you can easily derive any function with a lower number of arguments. As an example, imagine that you want to create
a two-dimensional distance
function that calculates the distances of the points on altitude z=3 as shown in the following example:
In order to derive a function that works only with points at the altitude z=3, you will need to call
the curried distance with parameter (3),
and as a result you will have a 2D function for determining the distances on that level.
An example is shown in the following listing:
Func<double, Func<double, double>> distance2DAtZ3 = curriedDistance(3);
double d2 = distance2DAtZ3(4)(6); // d2 = distance3D(4, 6, 3)
double d3 = distance2DAtZ3(0)(1); // d3 = distance3D(0, 1, 3)
double d4 = distance2DAtZ3(2)(9); // d4 = distance3D(2, 9, 3)
double d5 = distance2DAtZ3(3)(4); // d5 = distance3D(3, 4, 3)
If you need a single argument distance function that calculates the distance of points at y=4 and z=3, you can slice
the 2D function distance2DAtZ3 with an additional argument:
distance2DAtZ3
Func<double, double> distance1DAtY4Z3 = distance2DAtZ3)
If you have not already sliced the function distance2DAtZ3, you can directly apply two default arguments on the original curried function:
Func<double, double> distance1DAtY4Z3 = curriedDistance(4))
As you can see, currying enables you to easily reduce the number of arguments of
a multi-value function with just a single generic higher-order function,
instead of writing several partial functions for each argument that should be reduced, as in the previous example.
You can also use a higher order function to revert the curried function back. In this case,
the curried version with several single arguments will be converted back
to a multi-argument function. An example of the extension method that uncurries
the three argument curry function is shown in the following listing:
public static Func<T1, T2, T3, TR> UnCurry<T1, T2, T3, TR>(
this Func<T1, Func<T2, Func<T3, TR>>> curriedFunc)
{
return (a, b, c) => curriedFunc(a)(b)(c);
}
This function accepts the curried version of the function and creates a new three-argument function that will call
the curried function in single-argument mode.
An example of usage of the Uncurry method is shown in the following listing:
Uncurry
var curriedDistance = Curry<double, double, double, double>(Distance);
double d = curriedDistance(3)(4)(12);
Func<double, double, double, double> originalDistance = curriedDistance.UnCurry();
d = originalDistance(3, 4, 12);
In this article, we saw some basic possibilities of functional programming in C#. Functional programming is
a much wider area and cannot be explained in a single article.
Therefore there are a lot of other concepts in C# that you might need to explore in order to be capable of creating more effective functional programming code.
Some of these concepts are expression trees, lazy evaluations, caching, etc. Also you might find how functional programming is done in other languages such as
F# or Haskel. Although C# does not have the same possibilities like these languages you might find some ideas
about how to write more effective functional constructions.
In order to cover everything in functional programming, a whole book might be written about this topic,
but I believe that I have succeeded in covering the most important aspects in this article.
Also you can take a look at the comments section below where are posted a lot of examples (thanks to Akram for most of them) about the lazy evaluation, multiple inheritence, visitor design pattern implementation, folding, etc. I'm additng shorter versions of these examples in this article but you can find a lot of complete examples about these topics in comments.
You can also see some great examples of functional programming in the Data-driven programming combined with Functional programming in C# article.
I'm constanty improving this artice with help of other such as Akram and noav who are posting interesing examples ans suggestions in the comments section. Here you can see information about the major changes done.
|
https://www.codeproject.com/articles/375166/functional-programming-in-csharp?fid=1710661&df=90&mpp=25&sort=position&spc=relaxed&tid=4270152
|
CC-MAIN-2016-50
|
refinedweb
| 8,549
| 52.19
|
.
POLITICS
Translated byC.D.C. REEVEARISTOTLE
PoliticsARIS TOTLE
Politics
Translated,
by
C.D.C. Reeve
09 08 07 06 4 5 6 7 8 9
Aristotle [Politics. English] Politics/ Aristotle; translated, with introduction and notes, by C.D.C. Reeve. p. em. Includes bibliographical references and indexes. ISBN 0-87220-389-1 (cloth). ISBN 0-87220-388-3 (pbk.) 1. Political science-Early works to 1800. I. Reeve, C.D.C., 1 948-- . II. Title. JC7l .A41R44 1998 97-46398 320'.01'1-dc2 1 CIP
Acknowledgments Xlll
Introduction XVll
§3 Perfectionism XXV
§6 Theorizers xliii §7 Political Animals xlviii §8 Rulers and Subjects lix §9 Constitutions lxv § 1 0 The Ideal Constitution lxxii §1 1 Conclusion lxxviiiMap lxxx
BooK I Chapter 1 The City-State and Its Rule 1 Chapter 2 The Emergence and Naturalness of the City-State 2 Chapter 3 Parts of the City-State: Household; Master, and Slave 5 Chapter 4 The Nature of Slaves 6 Chapter 5 Natural Slaves 7 Chapter 6 Are There Natural Slaves? 9 Chapter 7 Mastership and Slave-Craft 12 Chapter 8 Property Acquisition and Household Management 12 Chapter 9 Wealth Acquisition and the Nature of Wealth 15 Chapter 10 Wealth Acquisition and Household Management; Usury 18
VIIVlll Contents
BooK II Chapter 1 Ideal Constitutions Proposed by Others 26 Chapter 2 Plato's Republic: Unity of the City-State 26 Chapter 3 Plato's Republic: Communal Possession of Women and Children ( 1 ) 28 Chapter 4 Plato's Republic: Communal Possession of Women and Children (2) 30 Chapter 5 Plato's Republic: Communal Ownership of Property 32 Chapter 6 Plato's Laws 36 Chapter 7 The Constitution of Phaleas of Chalcedon 41 Chapter 8 The Constitution of Hippodamus of Miletus 45 Chapter 9 The Spartan Constitution 49 Chapter 1 0 The Cretan Constitution 55 Chapter 1 1 The Carthaginian Constitution 58 Chapter 1 2 The Constitutions Proposed b y Solon and Other Legislators 61
BOOK III Chapter 1 City-States and Citizens 65 What Is a City-State? What Is a Citizen? Unconditional Citizens Chapter 2 Pragmatic Definitions of Citizens 67 Chapter 3 The Identity of a City-State 68 Chapter 4 Virtues of Men and of Citizens 70 Virtues of Rulers and Subjects Chapter 5 Should Craftsmen Be Citizens? 73 Chapter 6 Correct and Deviant Constitutions 75 Chapter 7 The Classification of Constitutions 77 Chapter 8 Difficulties in Defining Oligarchy and Democracy 78 Chapter 9 Justice and the Goal of a City-State 79 Democratic and Oligarchic Justice Contents IX
BooK IV Chapter 1 The Tasks of Statesmanship 101 Chapter 2 Ranking Deviant Constitutions 103 The Tasks of Book IV Chapter 3 Constitutions Differ Because Their Parts Differ 1 04 Chapter 4 Precise Accounts of Democracy and Oligarchy 106 Why Constitutions Differ Democracy and Its Parts Plato on the Parts of a City-State Kinds of Democracy Chapter 5 Kinds of Oligarchy 111 Chapter 6 Kinds of Democracy and Oligarchy 1 12 Chapter 7 Kinds of Aristocracy 1 14 Chapter 8 Polities 1 14 Chapter 9 Kinds of Polities 1 16 Chapter 10 Kinds of Tyranny 1 18 Chapter 1 1 The Middle Class ( 1 ) 1 18 Chapter 12 The Middle Class (2) 121 Chapter 1 3 Devices Used in Constitutions 123 Chapter 14 The Deliberative Part of a Political System 1 24 Chapter 1 5 Offices 1 27 Chapter 1 6 Judiciary 1 32
B ooKV Chapter 1 Changing and Preserving Constitutions 1 34 The General Causes of Faction The Changes Due to Faction Chapter 2 Three Principal Sources of Political Change 136 Chapter 3 Particular Sources of Political Change ( 1 ) 137X Contents
BooK VI Chapter 1 Mixed Constitutions 1 75 Kinds of Democracies Chapter 2 Principles and Features of Democracies 1 76 Chapter 3 Democratic Equality 1 78 Chapter 4 Ranking Democracies 1 79 Chapter 5 Preserving Democracies 1 82 Chapter 6 Preserving Oligarchies ( 1 ) 1 84 Chapter 7 Preserving Oligarchies (2) 185 Chapter 8 Kinds of Political Offices 1 87
BooK VII Chapter 1 The Most Choiceworthy Life 191 Chapter 2 The Political Life and the Philosophical Life Compared 193 Chapter 3 The Political and Philosophical Lives Continued 196 Chapter 4 The Size of the Ideal City-State 197 Chapter 5 The Territory of the Ideal City-State 200 Chapter 6 Access to the Sea and Naval Power 200 Chapter 7 Influences of Climate 202 Chapter 8 Necessary Parts of a City-State 203 Chapter 9 Offices and Who Should Hold Them 205 Chapter 1 0 The Division of the Territory 206 Chapter 1 1 The Location of the City-State and Its Fortifications 209 Chapter 1 2 The Location o f Markets, Temples, and Messes 211 Chapter 1 3 Happiness as the Goal of the Ideal City-State 212 The Importance ofVirtue Contents XI
BooK VIII Chapter 1 Education Should Be Communal 227 Chapter 2 The Aims of Education 227 Chapter 3 Education and Leisure 228 Music ( 1 ) Chapter 4 Gymnastic Training 23 1 Chapter 5 Music (2) 232 Chapter 6 Music (3): Its Place in the Civilized Life 236 Chapter 7 Music (4): Harmonies and Rhythms 239
Glossary 243
Bibliography 263
Traduttori traditori, translators are traitors. They are also thieves. I haveshamelessly plundered other translations of the Politics, borrowingwhere I could not improve. I hope others will find my own translationworthy of similar treatment. Anyone who has worked with John Cooper knows what a rare privilege it is to benefit from his vast knowledge, extraordinary editorialskills, and sound judgment. I am greatly in his debt for guiding the crucial early stages of this translation, and for characteristically trenchantand detailed comments on parts of Books I and III. His ideals of translation, "correct as humanly possible" and "ordinary English-where necessary, ordinary philosophical English," I have tried to make my own.Anyone who has translated Aristotle (or any other Greek writer, for thatmatter) will know that, though easy to state, they are enormously difficult to achieve. I owe an even larger debt, truly unrepayable, to Trevor Saunders(Books I and II) and Christopher Rowe (III and IV), who late in thegame, and by dint of their wonderfully thorough comments, inspired meto a complete revision of the entire translation. It is now much closer toAristotle than I, who learned Greek regrettably late in life, could everhave made it unaided. I am also very grateful to David Keyt (Books V and VI) and RichardKraut (VII and VIII) for allowing me to see their own forthcoming editions of these books, and for allowing me to benefit from their enviableknowledge of them. Keyt also commented perceptively on the Introduction. Paul Bullen not only arranged to have his Internet discussion list discuss parts of my work, but he himself sent me hundreds of suggestionsfor improvement, many of which I accepted gladly. What is of value here belongs to all these generous Aristotelians. Themistakes alone, of which there must surely still be many, are whollymme.
xiiiXIV Acknowledgments
XVXVI Note to the Reader
XVIIXVlll Introduction
As in all other cases, we must set out the phenomena and first of all go through the problems. In this way we must prove the endoxa . . . ideally all the endoxa, but if not all, then most of them and the most compelling. For if the problems are solved and the endoxa are left, it will be an adequate proof. (NE 1 1 4Sh2-7)
We must set out the phenomena, go through the problems, and provethe endoxa. But what are these things? And why is proving the mostcompelling of the endoxa an adequate proof of anything? Phenomena are things that appear to someone to be the case, whetherveridically or nonveridically.1 They include, in the first instance, empirical observations or perceptual evidence (APr. 46' 17-27, Gael. 297'2-6,297h23 -25). But they also include items that we might not comfortablycall observations at all, such as propositions that strike people as true orthat are commonly said or believed. For example, the following is a phenomenon: "The weak-willed person knows that his actions are base, butdoes them because of his feelings, while the self-controlled personknows that his appetites are base, but because of reason does not followthem" (NE 1 1 4Shi2-14).2 Phenomena are usually neither proved norsupported by something else. Indeed, they are usually contrasted withthings that are supported by proof or evidence (EE 12I6h26-28). Butthere is no a priori limit to the degree of conceptualization or theoryladenness manifest in them. They need not be, and in Aristotle seemrarely if ever to be, devoid of interpretative content; they are not Baconian observations, raw feels, sense data, or the like. The endoxa, or putative endoxa, are defined in the Topics as "thoseopinions accepted by everyone or by the majority or by the wiseeither by all of them or by most or by the most notable and reputable(endoxois)" (IOOh2I-23). But to count as endoxa these opinions cannotbe paradoxical ( 1 04' 1 0-1 1 ); that is to say, the many cannot disagreewith the wise about them, nor can "one or the other of these two classesdisagree among themselves" (I04h3 1-36). If there is such disagreement, what we have is a problem. Indeed, if just one notable philosopher rejects a proposition that everyone else accepts, that is sufficient to
a feature might be, Aristotle thinks, the fact that the sap at the joint between leaf and stem solidifies in colder temperatures. If he is right, theappropriate explanatory demonstration would look something like this(see APo. 98b36 -38):
( 1 ) All plants in which sap solidifies at the joint between leaf and stem in colder temperatures lose their leaves in the fall.
(2) All oak trees have sap that solidifies at the joint between leaf and stem in colder temperatures.
(3) Therefore, all oak trees lose their leaves in the fall.
But there are important conditions that ( 1 ) and (2) must satisfy if thisdemonstration is to yield a genuine scientific explanation: for example,(1) and (2) must be necessary and more fundamental than (3). Why doesAristotle impose these austere conditions? It is sometimes thought thathe does so because he mistakenly assimilates all the sciences to mathematics. There may be some truth in this, but the real reason surely has todo with the ideals of knowledge and explanation. If ( 1 ) and (2) are notnecessary, they will not adequately explain (3). For given that plantswith sap of the kind in question do not have to lose their leaves or thatoak trees do not have to have sap of that kind, why do oak trees none theless still inevitably lose their leaves? On the other hand, if ( 1 ) and (2) arenot biologically more fundamental than (3), they cannot be an adequateexplanation of it either. For in the true and complete biological theorythe more fundamental (3) will be used to explain (I) and (2). Hence inusing them to explain (3) we would be implicitly engaging in circular explanation, and circular explanation is not explanation at all (APo.72b2S-73•20). The nature of our scientific knowledge of derived principles is perhaps clear enough. But what sort of knowledge do we have of first principles, since we cannot possibly demonstrate them (NE1 140b33-1 141' 1)? Aristotle tells two apparently different stories by wayof an answer. The first, in Posterior Analytics 11. 19, runs as follows. Cognitive access to first principles begins with ( 1 ) perception of particulars(99b34-35). In some animals, perception of particulars gives rise to (2)retention of the perceptual content in the soul (99h39-J OO•I). Whenmany such perceptual contents have been retained, some animals (3)"come to have an account from the perception of such things"( 1 00•1-3). The retention of perceptual contents is memory; and a col- Introduction XXlll
The problem with this story is to explain what dialectic's way, thephilosopher's way, toward first principles actually is. The philosopher knows that the first principles in question are trueand their negations false. He has this on authority from the scientist,whose own knowledge is based on experience. Yet when the philosopheruses his dialectical skill to draw out the consequences of these princi-
§3 PerfectionismWe distinguish politics from the intellectual study of it, which we callpolitical science or political philosophy. The former is a hard-headed,practical matter engaged in by politicians; the latter is often a ratherspeculative and abstract one engaged in by professors and intellectuals.This distinction is alien to Aristotle. On his view, statesmanship or political science (politike episteme) is the practical science that genuine statesmen use in ruling, in much the way that medicine is the science genuinedoctors use in treating the sick. We also distinguish (not always very sharply, to be sure) between political philosophy and ethics or moral philosophy.9 The former dealswith the nature of the just or good society; the latter deals with individual rights and duties, personal good and evil, virtue and vice. This distinction too is foreign to Aristotle. On his view, ethics pretty much just isstatesmanship: ethics aims to define the human good, which is happiness or eudaimonia, so that armed with a dialectically clarified conception of our end in life we can do a better job of achieving it (NE1 094'22-24); statesmanship aims at achieving that same good not j ustfor an individual but for an entire COMMUNITY ( 1 323'14-23, NE1094h7-ll). But because we are by nature social or political animals (§7),we can achieve our ends as individuals only in the context of a political
10. Stephen Engstrom and Jennifer Whiting, eds., Aristotle, Kant, and the Sto ics: Rethinking Duty and Happiness (Cambridge: Cambridge University Press, 1996) includes some useful comparative studies of Aristotle's ethics with Kant's. Introduction XXVII
§4 Human NatureOf the various things that exist, "some exist by nature, some from othercauses" (Ph. 192h8-9). Those that exist (or come into existence) by nature have a nature of their own, i.e., an internal source of "change andstaying unchanged, whether in respect of place, growth and decay, or alteration" ( 192h 1 3- 1 5). Thus, for example, a feline embryo has within ita source that explains why it grows into a cat, why that cat moves and alters in the ways it does, and why it eventually decays and dies. A houseor any other artifact, by contrast, has no such source within it; instead"the source is in something else and external," namely, in the soul of thecraftsman who manufactures it ( 192h30- 3 1 , Metdph. 1 032'32-h lO). A natural being's nature, essence, function (ergon), and end (telos), orthat for the sake of which it exists (hou heneka), are intimately related.For its end just is to actualize its nature by performing its function( Cael. 286'8 -9, EN 1 1 68'6-9, EE 1 2 1 9' 1 3 - 1 7), and something thatcannot perform its function ceases to be what it is except in name (Mete.390•10-13, PA 640h33- 64 1'6, Pol. 1 253'23-25). Aristotle's view of natural beings is therefore "teleological": it sees them as defined by an endfor which they are striving, and as needing to have their behavior explained by reference to it. It is this end, essence, or function that fixes
what is best for the being, or what its perfections or virtues consist in(NE 1098•7-20, Ph. 195•23-25). Many of the things characterized as existing by nature or as productsof some craft are hylomorphic compounds, compounds of matter (huli)and form (morphe). Statues are examples: their matter is the stone ormetal from which they are made; their form is their shape. Human beings are also examples: their matter is (roughly speaking) their body;their soul is their form. Thus (with a possible exception discussed below)a person's soul is not a substance separate from his body, but is more likethe structural organization responsible for his body's being alive andfunctioning appropriately. Even city-states are examples: their matter istheir inhabitants and their form is their CONSTITUTION (§7). These compounds have natures that owe something to their matter and somethingto their form (Metaph. 1025b26-1 026•6). But "form has a better claimthan matter to be called nature" (Ph. 193b6-7). A human being, for example, can survive through change in its matter (we are constantly metabolizing), but if his form is changed, he ceases to exist (Pol. 1 276bl-1 3).For these reasons an Aristotelian investigation into human perfectionnaturally focuses on human souls rather than on human bodies. According to Aristotle, these souls consist of hierarchically organizedconstituents (NE 1. 1 3). The lowest rung in the hierarchy is nutritivesoul, which is responsible for nutrition and growth, and which is alsofound in plants and other animals. At the next rung up, we find perceptive and desiring soul, which is responsible for perception, imagination,and movement, and so is found in other animals but not in plants. Thisis the nonrational (alogon) part of the soul, which, though it lacks reason, can be influenced by it (Pol. 1 3 3 3• 1 7- 1 8 , NE 1 1 03•1-3,1 1 5 1" 1 5-28). The third part of the soul is the rational part, which hasreason ( 1 3 33• 1 7) and is identified with no us or understanding( 1 254•8 -9, 1 3 34b20, NE 1097b33 -1098•8). This part is further dividedinto the scientific part, which enables us to study or engage in theoretical activity or contemplation (theoria), and the deliberative part, whichenables us to engage in practical, including political, activity ( 1 3 33•25,NE 1 1 39•3-b5). Because the soul has these different parts, a perfectionist has a lot ofplaces to look for the properties that define the human good. He mightthink that the good is defined by properties exemplified by all three ofthe soul's parts; or he might, for one reason or another, focus on properties exemplified by one of the parts. To discover which of these optionsAristotle favors, we need to work through the famous function argu- Introduction XXIX
ment from the Nicomachean Ethics (a work whose final chapters lead naturally into the Politics). By doing so we shall be armed with the kind ofunderstanding of Aristotle's views on human nature and the good thathe supposes we will have when we read the Politics (see VII. l-3 ,1333"16-30). The function argument begins as follows:
[A] Perhaps we shall find the best good if we first find the function or task (ergon) of a human being. For just as the good-i.e., [doing] well-for a flute-player, a sculptor, and every craftsman, and, in general, for whatever has a function and action, seems to depend on its function, the same seems to be true for a human being, if a human being has some function. 1 3 [B] Then do the carpenter and the leather worker have their functions and actions, while a human being has none and is by nature inactive without any function? Or, just as eye, hand, foot, and in general every [body] part apparently has its functions, may we likewise ascribe to a human being some function over and above all of theirs? (NE 1097b24-33)
Just as every instrument is for the sake of something, the parts of the body are also for the sake of something, that is to say, for the sake of some action, so the whole body must evidently be for the sake of
some complex action. Similarly, the body too must be for the sake of the soul, and the parts of the body for the sake of those functions for which they are naturally adapted. 14 (PA 64Sb 14-20)
Thus the parts of the body are for the sake of the complex action of thebody as a whole, but the body as whole is for the sake of the soul and itsactivities. Even within the soul itself, moreover, the function of one part seemsto be for the sake of the function of another, for example, that of practical wisdom for the sake of that of theoretical wisdom (Pol. 1 333"24-30,1 334b 1 7-28).15 Now theoretical wisdom is the virtue of understanding,and understanding has a somewhat peculiar status. Unlike many othercapacities of the soul, such as memory or perception, its activities arecompletely separate from those of the body: "bodily activity is in no wayassociated with the activity of understanding" (GA 736b28-29). Couldit be, then, that our function or essence is over and above the functionsof all of our body parts, precisely because it lies exclusively in our understanding and consists exclusively in theoretical activity? If the answer is yes, Aristotle's perfectionism seems to be narrowly intellectualist: the good or happy life for humans will consist largely in theoreticalactivity alone. But it is not clear the answer is yes. Aristotle himself occasionally settles for expressing a weaker disjunctive conclusion: thehuman function consists in practical rational activity or theoretical rational activity (Pol. 1 33 3'24-30, NE 1 094'3 -7) . None the less, thestronger conclusion often seems to be in view (§6). For the moment,then, let us simply content ourselves by noticing how close to the function argument the stronger conclusion lies, however controversial or incredible we might initially find it. I said earlier (§3) that it is difficult to gauge the extent of Aristotle'snaturalism, because it is difficult to determine how naturalistic (in ourterms) some parts of his psychology are. Understanding is the majorsource of that difficulty. Human beings have a function, in any case, which is over and abovethe functions of their body parts. The next stage of the argument concerns its identification:
[C] What, then, could this be? For living is apparently shared with plants, but what we are looking for is special; hence we should set
14. This doctrine is very much alive in the Politics ( 1 333'1 6-b5).1 5 . Also EE 1 249b9-2 1 , MM 1 198b l 7-20, NE 1 145'6-9; §6. Introduction XXXI
aside the life of nutrition and growth. The life next in order is some sort of life of sense-perception; but this too is apparently shared, with horse, ox, and every other animal. The remaining possibility, then, is some sort of action of what has reason. Now this [the part that has reason itself has two parts, each of which has reason in a dif ferent way], one as obeying reason, the other as itself having it and exercising understanding. Moreover, life is also spoken of in two ways, and we must take life as activity, since this seems to be called life to a fuller extent. We have found, then, that the human function is the activity of the soul that expresses reason or is not without rea son. (NE 1 097b33-1 098"8; compare Pol. 1 333" 1 6-bS)
16. Does this entail that the human function cannot be theoretical activity or study? No. For Aristotle allows that study is itself a kind of ACTION (Pol. 1325bl6-21).xxxii Introduction
17. See Ph. 246'10-15, Metaph. 102 J h20-23, Rh. 1 366'36-b l ; Plato, Republic 3 52d-354'.18. In other words, it isn't a conceptual truth that the specifically moral virtues are what perfect our nature. But neither does Aristotle think that it is. Con trast Thomas Hurka, Perfectionism (Oxford: Clarendon Press, 1 993): 1 9-20. Introduction XXXIll
After all, (A) explicitly states that if human beings (or anything else)have a function, the good for them depends on their function. And,again, the fact that a human being's function is his end, or his essenceactivated, makes this an intelligible view. For to say that the good forhuman being is to best achieve his end is to say something that is at leasta serious candidate for truth. (F), the conclusion of the function argument, is that the human goodis an activity of the soul expressing virtue. But to that conclusion Aristotle adds a difficult coda:
[G] And if there are more virtues than one, the good will express the best and most complete virtue. [H] Further, in a complete life. For one swallow does not make a spring, nor does one day; nor, sim ilarly, does one day or a short time make us blessed and happy. (NE 1 098"1 7-20)
expressing virtue. The stronger version more narrowly identifies our nature or essence with theoretically rational activity, and our good with suchactivity when it expresses the virtue of wisdom. The trouble (if that is theright word) is that the function argument is an abstract metaphysical or(maybe) biological argument that seems far removed from life experience,and seems to some degree to be in conflict with it. Certainly, few people,if asked, would say that the good, or the good life, consisted exclusively inbeing active in politics (remember that practical wisdom is pretty muchthe same thing as statesmanship for Aristotle) or in theorizing (contemplating). They are far more likely to think that the good is pleasure or enjoyment, and that the good life is a pleasant or enjoyable one. This is a serious problem, if for no other reason than that people arefar more likely to be guided by their experience in these matters than byphilosophical arguments. Aristotle himself explicitly recognizes this(NE 1 1 72•34-h7, 1 1 79• 1 7-22). But he does not believe that the problemis insurmountable. For he thinks he can show that the various views ofhappiness defended by ordinary people on the basis of their experienceand by philosophers on the basis of experience and argument (NE1098b27-29) are all consistent with the conclusion of the function argument. For example, he thinks that the activities expressing virtue arepleasant, and "do not need pleasure to be added as some sort of ornament" (NE 1099• 1 5-16), so that the popular view that happiness is pleasure is underwritten rather than contradicted. Moreover, he concedesthat were such conflict to occur, it would be the conclusion of the argument that might have to be modified: "We should examine the first principle [i.e., human good or happiness]," he says, "not only from the conclusion and premises of a deductive argument, but from what is saidabout it; for all the facts harmonize with a true account, whereas thetruth soon clashes with a false one" (NE 1 098h9-l l ) . I t would b e misleading, therefore, flatly to describe the function argument as providing the metaphysical or biological foundations of Aristotelian ethics and statesmanship. This suggests too crude an inheritance from metaphysics and biology, too crude a naturalism. Thefunction argument employs concepts such as those of function, essence,and end which, though perhaps biological in origin, belong to Aristotle'smetaphysics. By using these concepts and by showing how they are related to the ethical and political notions of virtue and the good life, thefunction argument establishes the close connections between metaphysics, on the one hand, and ethics and statesmanship, on the other.But the ultimate test of the function argument is not simply the cogency Introduction XXXV
§5 Practical AgentsOur nature, essence, or function lies in the rational part of our souls, inany case, and the human good consists in rational activity expressingvirtue. This activity, as we have seen, can be either practical or theoretical or some mix of the two. But what more particularly do these types ofrational activity themselves consist in? We shall discuss practical activityin this section, theoretical activity in the next. Canonical practical ACTION or activity is action that is deliberatelychosen, that expresses deliberate choice (proairesis). Such choice is a desire based on deliberation (bouleusis) that requires a state of characterand is in accord with wish (boulesis), a desire for the good or the apparent good.20 Suppose, for example, that we are faced with a lunch menu.We wish for the good or happiness. We deliberate about which of the actions available to us in the circumstances will best promote it. Should weorder the fish (low fat, high protein) or the lasagna (high fat, high fiber)?
19. For further discussion of the function argument, see my Practices ofReason, 1 23-38; and J. Whiting, "Aristotle's Function Argument: A Defense," An cient Philosophy 8 ( 1 988): 33-48.20. NE 1 1 1 3'9-14 (reading kata ten boulesin), 1 1 39'3 1-bS, 1 1 1 3'3-5.XXXVI Introduction
We choose fish with a salad (low fat, high fiber), on the grounds that thiscombines low fat, high protein, and high fiber. For we believe that this isthe kind of food that best promotes health, and that being healthy promotes our happiness. If our appetite is then for fish and salad, we chooseit, and our action accords with our wish and our desire. If our appetite isconsistently or habitually in accord with our wish, so that it does notoverpower wish and wish does not have to overpower it, Aristotle saysthat (everything else being equal) we have the virtue of temperance(sophrosuni). Suppose we deliberately choose as before, but our appetite is for thelasagna; there are then two further possibilities. First, our appetite isstronger than our wish and overpowers it, so that we choose and eat thelasagna. In this case, we are weak-willed. We know the good but don't doit. Second, our wish is stronger and overpowers our still very insistentappetite. In this case, we are self-controlled. We do what we think best inthe teeth of our insistent and soon-to-be-frustrated appetite. Now thesethree things, weak will, self-control, and virtue are precisely states ofcharacter. And it is in part because our deliberate choices exhibit thesethat they involve such states. This is one way character is involved in deliberate choice, but there isanother. It is revealed by a fourth possibility. Here appetite is in accordwith wish, but wish is only for the apparent and not the genuine humangood (Pol. 133 1 b26-34 ). This possibility is realized by a vicious person(a person who has vices). He wishes for the good, but he mistakenly believes that the good consists (say) in gratifying his appetites. So if his appetite is for a high-fat diet, such as lasagna with extra cheese followed bya large ice cream sundae, that is what he wishes for and orders. Some people (virtuous, self-controlled, and weak-willed ones) havetrue conceptions of the good, then; others (vicious ones) have false conceptions. What explains this fact? Aristotle's answer in a nutshell ishabits, especially those habits developed early in life (NE l09Sb4-8)although nature and reason also have a part to play (Pol. 1 332•38-bS).We come to enjoy fatty foods, for example, by being allowed to eat themfreely when we are children and developing a taste for them (or perhapsby being forbidden them in a way that makes them irresistibly attractive). If we had acquired "good eating habits" instead, we would have adifferent conception of that part of the good that involves diet. Wewould want and would enjoy the fish and salad and not hanker for thelasagna and ice cream at all. Failing that, we would, as weak-willed orself-controlled people, at least not wish for it. Introduction XXXVII
2 1 . This should remind us of the money lovers, honor lovers, and wisdom lovers of Plato's Republic.XXXVlll Introduction
But what more precisely are the good habits that correct laws foster?What is it that is true of our feelings, our desires and emotions, whenthey are such as good or bad habits make them? Aristotle's answer is that properly habituated emotions "listen to reason" (NE 1 1 02b28-1 1 03•1), and so are in accord with wish, aiming at thesame thing it does (NE 1 1 1 9h l 5-18). When this happens, the feelings aresaid to be "in a mean" between excess and deficiency: "If, for example,our feeling is too intense or too weak, we are badly off in relation toanger, but if it is in a mean, we are well off; and the same is true in othercases" (NE l i OSh2S-28; also Ph. 247•3 -4) . Some of Aristotle's adviceabout how we might achieve this mean state helps explain its nature:
We must also examine what we ourselves drift into easily. For dif ferent people have different natural tendencies toward different ends, and we come to know our own tendencies by the pleasure and pain that arise in us. We must drag ourselves off in the contrary di rection. For if we pull far away from error, as they do in straighten ing bent wood, we shall reach the mean. (NE 1 I 09b l -7)
By noticing our natural proclivities, we can correct for them. Over time,with habit and practice, our feelings typically change, becoming moreresponsive or less resistant to wish, more in harmony with it. Providedthat wish embodies a correct conception of the good, we are then farmore likely to achieve the good and be happy than if our feelings successfully oppose wish or have to be overpowered by it. In the formercase, we miss the good altogether; in the latter, we achieve it but only atthe cost of the pain and frustration of our unsatisfied feelings. We eatfish and salad but we remain "hungry" and, in some cases, no doubt, obsessed with the forbidden lasagna and ice cream: an uncomfortable andunstable condition, as we know. In §4 we noticed a problem. It is conceptually guaranteed that if ourrational activities express genuine virtue, they constitute the humangood. But it is not guaranteed that the conventionally recognized ethicalvirtues-justice, temperance, courage, and the rest-are genuine ones.The doctrine of the mean is intended to solve this problem. A genuinevirtue is a state that is in a mean between excess and deficiency. Hence ifthe conventionally recognized virtues are such states, they are genuine Introduction XXXIX
virtues. Books III-V of the Nicomachean Ethics are for the most part intended to show that the antecedent of this conditional is true. We shallnot probe their details here, not all of which are entirely persuasive. It isenough for our purposes to see that the doctrine of the mean is intendedto fill what would otherwise be a lacuna in Aristotle's argument.22 Feelings are concerned with external goods; that is to say, with "goodsof competition," which include money, honor, bodily pleasure, and ingeneral goods that people tend to fight over; and with having friends,which "seems to be the greatest external good" (NE 1 1 69b9-l0). Wewould expect, therefore, that the virtues of character would be particularly concerned with external goods. And indeed they are. The vast majority are concerned with the goods of competition. Courage is concerned with painful feelings of fear and pleasant feelings of confidence;temperance, with the pleasures of taste and touch (NE l l l 8•2J-h8);generosity and magnificence, with wealth; magnanimity, with honor;special justice, with ACQUISITIVENESS (pleonexia), with wanting moreand more without limit of the external goods of competition (NE1 1 29h l-4). General justice (NE l l 29h2S-27) is especially concernedwith friendship and community. It is our needs for these goods that leadus to form communities that are characterized as much by mutuality ofinterest as by competition (l. l-2). But it is these same needs that oftenbring us into conflict with one another. The single major cause of political instability, indeed, is competition, especially between the rich andthe poor, for external goods such as wealth and honor (V. l ). The political significance of the virtues is therefore assured; without them no constitution can long be stable. For "the law has no power to secure obedience except habit" ( 1 269•20-21). Imagine that all our feelings, all our emotions and desires are in amean, so that we have all the virtues of character. Our feelings are in accord with our wish, and our wish is for the real and not merely the apparent good. Haven't we got all we need to ensure, as far as any humanbeing can, that we will achieve the good and live happily? Not quite.Until we have engaged in the kind of dialectical clarification of our conception of happiness undertaken in the Nicomachean Ethics, until wehave seen how to solve the problems to which it gives rise, and how to
§6 TheorizersThe political life is one of the three most favored types of lives. Anotheris the life of study or contemplation (bios theiiretikos), in which theoretical activity plays a very important role. Our focus now will be on the nature of that activity, the second type of rational activity in which ourgood consists, and on the relationship between it and the practical activity we discussed in §5. Study of any of the various sciences Aristotle recognizes is an exerciseof understanding (nous) and is a theoretical activity of some sort:
As we see from this passage, things that are ungenerated and imperishable for the whole of eternity are the best kind to study. Among these, thevery best is God himsel£ Hence the very best theoretical activity consistsin the study of God: theology. That is why only the study of theologyfully expresses wisdom (NE 1 1 412"1 6-20 with APo. 87"3 1-37). One reason Aristotle holds this view about theology is this. 27 TheAristotelian cosmos consists of a series of concentric spheres, with theearth at its center. God is the eternal first mover, or first cause of motionin the universe. But he does not act on the universe to cause it to move.He is not its efficient cause. He moves it in the way that an object of lovecauses motion in the things that love or desire it (DA 415"26-b7). He is
27. The other reasons are these: God is the best or most estimable thing there is, so that theology, the science that studies him, is the most estimable sci ence (Metaph. 983'5-7, 1074h34, 1075'1 1-12). He is also the most intelligi ble or most amenable to study of all things, because he is a pure or matter less form (Metaph. 1026'1 0-32). Introduction xlv
The most natural act for any living thing that has developed nor mally . . . is to produce another like itself (an animal producing an animal, a plant, a plant), in order to partake as best it can in the eter nal and divine. That is what all things strive for, and everything they do naturally is for the sake of that. (DA 4 1 5'26-h2)
Because all things are in essence trying to be as much like God as possible, we cannot understand them fully unless we see them in that light.And once we do see them in that light we still do not understand themfully until we understand theology, until we understand what God is.Theology is more intelligible, and hence better to study, than the othersciences for just this reason: the other sciences contain an area of darkness that needs to be illuminated by another science; theology can fullyilluminate itself. 28 Human beings participate in the divine in the same way as other animals do by having children. But they can participate in it yet more fullybecause they have understanding. For God, on Aristotle's view, is a pureunderstanding who is contemplating or holding in thought the completescience of himself: theology (Metaph. 983'6-7).29 Hence when humanbeings are actually studying theology they are participating in the veryactivity that is God himself. They thus become much more like Godthan they do by having children, or doing anything else. In the process,Aristotle claims, they achieve the greatest happiness possible (NE1).xlvi Introduction
litical life against the philosophical, but not giving decisive precedenceto either. What explains this caginess may not be faint-heartedness on Aristotle's part, however, but a confusion on ours. We need to distinguish thequestion of what happiness is from the question of what the best or happiest life is. Aristotle himself is quite decisive and consistent on the firstquestion: happiness is activity expressing virtue; the contenders arepractical activity and theoretical activity; the palm of victory invariablygoes to theoretical activity, although practical activity is often awardedsecond prize. This is as true in the Politics as it is in the NicomacheanEthics. But it does not tell us what the best life is. Here, as in the case of activities, there are two contenders, the political life and the philosophical or theoretical life (Pol. 1 324'29-3 1 ). Theselives sound like the activities already discussed but must not be confusedwith them. The political life involves taking part in politics with otherpeople and participating in a city-state ( 1 3 24'1 5-16); the philosophicallife is that of "an alien cut off from the political community" Introduction xlvii
§7 Political AnimalsAristotle famously claims that a human being is by nature a political animalY Less famously, but perhaps more controversially, he also claimsthat the city-state is itself a natural phenomenon, something that existsby nature (Pol. 1 252h30, 1253'1). These doctrines are closely relatedso closely, indeed, that they are based on the very same argument( 1 252'24-1253'19). We shall analyze that argument below, but before wedo we should look at the doctrines themselves. According to Aristotle, political animals are a subclass of herding orgregarious animals that "have as their task (ergon) some single thing thatthey all do together." Thus bees, wasps, ants, and human beings are allpolitical animals in this sense (HA 487h33-488'10). But human beingsare more political than these others (Pol. 1 253'7-18), because they arenaturally equipped for life in a type of community that is itself morequintessentially political than a beehive or an ant nest, namely, a household or city-state. What equips human beings to live in such communities is the natural capacity for rational speech, which they alone possess.For rational speech "is for making clear what is beneficial or harmful,and hence also what is just or unjust . . . and it is community in thesethat makes a household and a city-state" ( 1 253'14-1 7). It may well be as uncontroversial to say that human beings have a natural capacity to live in communities with others as it is to make parallelclaims about bees and ants. But why should we think that they will bestactualize this capacity in a community of a particular sort, such as anAristotelian household or city-state? Why not think that, unlike bees andants, human beings might realize their natures equally well either in isolation or in some other kind of political or nonpolitical community?32 Weshall return to these questions in due course. We now have some idea at least of what Aristotle means by saying thata human being is a political animal. But what does he mean by the far
would need masters, or why the latter would need them. Aristotle's ownview is that masters and slaves form a union "for the sake of their ownsurvival" ( 1 252•30-3 1). But this is very implausible. Animals also lackthe capacity to deliberate, on Aristotle's view, yet they seem to survivequite nicely without human masters who can deliberate;35 freed (supposedly) natural slaves do not simply die like flies. Masters may indeed benefit from having slaves to do the donkey work, while they spend theirleisure on philosophy or politics ( 1 255b36-37), but, since masters havebodies of their own and are capable of working on their own behalf, it isunclear why they need slaves in order to survive. We don't have slaves,and we survive. Not only is Aristotle's conception of the household politically or ethically controversial, then, but it isn't clear that, even if we granted himits controversial elements, he could succeed in showing that it is naturalbecause "naturally constituted to satisfy everyday needs" (1252h12-14). Somewhat similar problems beset the next stage in the emergence ofthe city-state: the village. First, the village is "constituted from severalhouseholds for the sake of satisfying needs other than everyday ones"( 1252h1 5-16). To determine whether these nonroutine needs are natural,we have to be told what they are. But all that Aristotle says is that households have to engage in barter with one another when the need arises( 1 257• 19-25). This does not help very much, because the things they exchange with one another seem to be just the sorts of things that thehousehold itself is supposed to be able to supply, such as wine and wheat( 1 257•2 5-28). Second, to count as a village a community of severalhouseholds must be governed in a characteristic way, namely, by a king( 1 252b20-22). This is natural, Aristotle explains, because villages are offshoots of households, in which the eldest is king ( 1 252b20-22). Theproblem is that on Aristotle's own view households involve various kindsof rule, not just kingly rule. For example, a head of household rules hiswife with political rule (1. 12). We might wonder, therefore, why a villagehas to be governed with kingly rule rather than with political rule, that isto say, with all the heads of households ruling and being ruled in turn. The final stage in the emergence of the city-state, and the conclusionof Aristotle's argument that the city-state exists by nature and that ahuman being is a political animal, is presented in the following terse andconvoluted passage:
(A) tells us that the city-state, unlike the village, has reached the goal ofpretty much total SELF-SUFFICIENCY. What does this mean? It seemsfairly clear that enough basic human needs are satisfied outside of thecity-state for human life to be possible there: households and villagesthat are not parts of city-states do manage to persist for considerable periods of time ( 1 252b22-24, 1 2 6 1 '27-29); individuals too can surviveeven in solitude ( 1 253'3 1-33, HA 487b33-488' 14). None the less, moreof these needs seem to be better satisfied in the city-state than outside it(see 1278b 17-30). For it is always need that holds any community together as a single unit (NE 1 1 33b6-7). (B) separates what gives rise to the city-state from what sustains itonce it exists. Fairly basic human needs do the former, but what sustainsa city-state in existence is that we are able to live well and achieve happiness only in it. Thus the city-state is self-sufficient not simply becauseour essential needs are satisfied there but because it is the communitywithin which we perfect our natures ( 1 253'3 1-37). (D) and (E) are the crucial clauses. (D) tells us that household, village,and city-state are like embryo, child, and mature adult: a single nature ispresent at each stage but developed or completed to different degrees.Where is that nature to be located? (E) suggests that it lies within the individuals who constitute the household, village, and city-state: they are political animals because their natural needs lead them to form, first, households, then villages, then city-states. "An impulse toward this sort ofcommunity," we are told, "exists by nature in everyone" ( 1 2 53'29-30). Introduction Iiii
36. Aristotle distinguishes household justice (to oikonomikon dikaion) from city state or political justice at NE 1 334bl 5-18.liv Introduction
piness will be correct, and one will possess practical wisdom in its unqualified form (NE 1 144b30 -1 14Sb2). But it is only in the best constitution that the virtues inculcated in a citizen through public education areunqualifiedly virtues of character (111.4, 1 293bJ-7). It follows that in noother constitution will the virtues that suit citizens to the constitutionprovide them with a correct conception of their happiness or with unqualified practical wisdom. Starting with the household, then, what wehave is a series of types of virtue and types of practical wisdom suited todifferent types of communities and constituting a single nature that isrealized or developed to different degrees in these different communities. It is for this reason that Aristotle thinks that human beings are by nature political animals, not just in the sense that, like bees, they are naturally found in communities, but also in the stronger sense that they perfect their natures specifically in political communities of a certain sort.The function argument has shown that human nature consists in rational activity, whether practical (political) or theoretical. Hence to perfecttheir natures human beings must acquire the unqualified virtues ofcharacter. But this they do, Aristotle has argued, only in a city-state;more specifically, in a city-state with the best constitution. The move from household to village or from village to city-state coincides, then, with a development in human virtue and practical w�sdom.How should we conceive of this development as occurring? If humanbeings were nonrational animals, the development would itself be onethat occurred through the operation of nonrational natural causes. Butbecause human beings have a rational nature, their natural development(which is always communal, as we have seen) essentially involves a development in their rational capacities; for example, an increase in the levelof the practical wisdom they possess. Imagine, then, that the householdalready exists. Its adult males possess a level of practical wisdom whichthey bring to bear in solving practical problems. The household is notself-sufficient: it produces a surplus of some needed items, not enoughof others. This presents a practical problem which it is an exercise ofpractical wisdom to solve. And it might be solved, for example, by noticing that other nearby households are in the same boat, and that exchanging goods with them would improve life for everyone involved. But exchange eventually leads to the need for money and with it to the need fornew communal roles (that of merchant, for example), new forms ofcommunal control (laws governing commerce), new virtues of character(such as generosity and magnificence which pertain to wealth), and newopportunities for the exercise of (a further developed) practical wis- Introduction lv
37. This account is modeled on the one Aristotle tells at 1 257' 14-hS.38. That the legislator in question may not have been brought up in the com munity for which he is developing a constitution should not blind us to the fact that the practical wisdom he exercises in developing that constitution is itself a communal achievement-an achievement internal to community.39. See Pol. 1253'30-3 1 , 1268h34-38, 1273h32-33, 1274b18-19, 1282b 14-16, 1 325h40-1 326'5. It is important to be clear, however, that the fact that Aris totle speaks of statesmanship (practical wisdom) as crafting (demiourgein) a city-state or its constitution does not mean that either is a product of craft, like a table, or that statesmanship (practical wisdom) is itself a craft. After all, Aristotle speaks of nature as crafting animals and other things (PA 645'7-10, GA 73 1 '24 ), and analogizes nature to a craft ( GA 73Qb27-32, 743hZ0-25, 789h8-12). But nature is not a craft nor are its products craft products. Statesmanship (practical wisdom) is in fact not a craft, but a virtue of thought (NE VI.4-8).lvi Introduction
form has a better claim to being called its nature than does its matter,what we are really asking is whether Aristotle thinks that a city-state'sconstitution is a source of its stability and change in the way that acanonical nature is. And surely he does. A city-state can change its matter (population) over time, but cannot sustain change from one kind ofconstitution to another ( 1 276"34-h l ) , or dissolution of its constitutionaltogether ( l 272h l4-15). Thus its identity over time is determined by itsconstitution. A population constitutes a single city-state if it shares asingle constitution ( 1 276"24-26). Thus its synchronic unity, its identityat a time, is also determined by its constitution. A city-state can grow orshrink in size, but its constitution sets limits to how big or small it can be(VII.4-5). What causes it to decay or to survive is also determined bythe type of constitution it has (Book V discusses these constitution-specific causes in considerable detail). Thus a city-state's constitution is indeed a canonical nature, an inner source of stability and change, and thecity-state meets all of Aristotle's conditions for existing by nature. It isno surprise, therefore, to find Aristotle claiming that the various kinds ofconstitutions, the various kinds of natures that city-states possess, are tobe defined in the same way as the different natures possessed by animalsbelonging to different species ( l 29Qh2S-39). So far we have been discussing the individual human beings in a citystate. But the very same process of nature indexing that occurs in themas they become parts of a city-state also occurs in the various subcommunities that make up that city-state. Consider the village, for example.When it is not yet part of a city-state, a village is a kingship. But when itbecomes part of a democratic city-state (say), though it may perhapshave a village elder of some sort, it is no longer a kingship plain and simple. For in a democracy authority is in the hands of all the free male citizens. Hence though the village elder may exercise kingly rule over villageaffairs, he must do so in a way that fits in with the democratic constitution of which his village is a part. And in that constitution he is under theauthority of others as a real king is not. The same is true of the household. Various types of rule are present in the household, as we saw, butthese are transformed when the household becomes part of a city-state.For the sort of virtue that a head of household possesses and the sort hetries to develop or encourage in its other members must themselves besuited to the larger constitution of which his household is a part (Pol.1. 12-13). Thus households and villages that are parts of a city-state havenatures that are transformed by being indexed to the constitution of thatcity-state. It is this that makes them into genuine parts of it. Introduction !vii
they will reject the idea that we perfect our natures or achieve our goodonly as members of it: it is as members of nonpolitical communities thatwe do that. Many people also believe that leading the good life involves followingthe cultural traditions and speaking the language of their own culture orethnic group. Aristotle would agree with them, but this is very largelybecause he assumes that city-states (or at least their citizens) will be ethnically, nationally, and even religiously homogeneous ( 1 1 27b22-36,1 328b l l-1 3): he is no cosmopolitan. Modern states by contrast are increasingly multicultural and polyethnic. If they are to respect the rightsof their citizens, and allow them (within limits) to pursue their own conceptions of the good, they need to be supportive of cultural and ethnicdiversity. They should not use their coercive powers to promote one culture or one ethnicity at the expense of others. Again, this means thatmost people will achieve the good or perfect their natures as members ofdifferent ethnic communities, and not as members of city-states as such. Religion, nationality, and ethnicity aside, it is perhaps more naturalfor us to think of public political life as being like work, something weengage in in order to "be ourselves" in our private lives and leisure time.We are most ourselves, we think, not in any public sphere, but in the private one. Politics, like work, is necessary, but it is valuable primarily forwhat it makes possible, not in itself. These styles of objection can of course be generalized. Many people,including probably most of us, believe that, at least as things stand, thereare many different, equally defensible conceptions of the human goodand the good life. We want to make room in the city-state for many ofthese conceptions. We want to be left free to undertake what John StuartMill calls "experiments in living" in order to discover new conceptions.Consequently, we do not want the city-state to enforce any one conception of the good life but to be largely neutral. We want it to allow different individuals and different communities (religious, ethnic, national) topursue their own conceptions of the good, provided that they do so inways that allow other individuals and communities to do the same. If wehold views of this sort, we will not agree with Aristotle that we perfectour natures or achieve our good as members of the city-state. We willclaim instead that we do so as members of communities that share ourconception of the good, but that lack the various powers, most particularly the coercive powers, definitive of the city-state. Needless to say, it might be responded on Aristotle's behalf that thiscriticism of his argument for the naturalness of the city-state simply ig- Introduction lix
nares the function argument, since it implicitly denies (or at least seriously doubts) that the human good just does consist in practical activityor in theorizing. This is a reasonable response so far as it goes. But, as wesaw in §4, the function argument is compelling only to the degree that itis underwritten by the facts of ethical and political experience. And whatis surely true is that those facts no longer underwrite it completely.What experience has taught us is that there are many different humangoods, many different good lives, many different ways to perfect ourselves, and much need for further experimentation and discovery inthese areas. That is one reason we admire somewhat liberal states whichrecognize this fact and give their citizens a lot of liberty to explore various conceptions of the good and to live in the way that they find mostvaluable and worthwhile.40
40. Recent discussions of the topics in this section include D. Keyt, "Three Basic Theorems in Aristotle's Politics," W. Kullmann, "Man as a Political Animal in Aristotle," and F. D. Miller, Nature, Justice, and Rights in Aristo tle 's Politics, 3 - 66. Some recent works on the natural origins of human com munities and virtues include J. H. Barkow, L. Cosmides, and]. Tooby (eds.), The Adapted Mind: Evolutionary Psychology and the Generation of Culture (New York: Oxford University Press, 1 992); M. Ridley, The Origins of Virtue: Human Instincts and the Evolution of Cooperation (New York: Viking, 1997); R. Wright, The Moral Animal (New York: Vintage, 1994).lx Introduction
claim were entirely true, it is not clear that it would support the normative ethical and political doctrines Aristotle rests on it. Why should our status as rulers or subjects depend on the degree ofour practical wisdom or virtue? Aristotle does not directly confront thisquestion. And one reason he doesn't is that, like Plato before him, hesees the city-state as analogous to the individual soul. In Politics 1. 5, forexample, he argues as follows: it is best for the body and desire to beruled by the part of the soul that has reason, that is to say, by practicalwisdom acting as the steward of understanding or theoretical reason(§6); the city-state is analogous to the soul; hence it is best for those withunqualified practical wisdom to rule those without it, whether they arewomen, natural slaves, or wild animals ( 1 2 S4b6-20). The psychological side of this analogy is relatively uncontroversial:given Aristotle's characterization of practical wisdom as alone possessing knowledge of the human good and of how best to achieve it, it surelyis best that practical wisdom should have authority over or rule the otherparts of the soul, since that maximizes the chances that the whole souland body, the whole person, will achieve what is best. But the politicalside of the analogy is vastly more problematic. We think that individual freedom or autonomy is a very important political value. We think not only that individuals want to achieve what isin fact best, but that they want to be free to evaluate for themselves whatis best for them, and to act on their own j udgment about it. They want toown their lives and choose their goals and projects for themselves, evenif this means that they sometimes make mistakes and regret theirchoices. We are suspicious of paternalism, especially when it is exercisedby the state, and balk at the idea of having others determine what weshould do with our lives, even when they might be better qualified tomake such determinations than we are. Because autonomy does notreach down below the individual, there is no comparable worry aboutthe parts of the soul. Autonomy is a personal, not a subpersonal, value.Thus in making use of the analogy between the soul and the city-state asa device for justifying rule in the latter, Aristotle conceals from himselfwhat is for us a fundamental political problem.41
42. Notice that this would be a very surprising result if the exercise of states manship in ruling others were the human good (happiness) or the most im portant component of it. For Aristotle thinks that the reason A should rule B is that B is better off or happier being ruled by A than by ruling himself. But B could not be better off being ruled by anyone, if in fact ruling were happiness or its most important component. Introduction lxiii
to safeguard the capacity for autonomy by, among other things, providing the kind of public education, and fostering the kind of public debate,that promotes it, and by preparing its citizens precisely to be citizenswho themselves promote and safeguard autonomy.
§9 ConstitutionsHuman beings encounter the political either as rulers or as subjects.That is one sort of political diversity. But there is another: the diversityexhibited by constitutions themselves. Hence just what a ruler or subject encounters in encountering the political also depends on the type ofconstitution he encounters it in. Our task in the present section is to understand these different constitutions, and Aristotle's characterizationof them as either correct or deviant. The traditional Greek view is that a constitution can be controlled by"the one, the few, or the many" ( 1 279•26-28): it can be either a monarchy, an oligarchy, or a democracy. Aristotle accepts this view to some extent, but introduces some important innovations. First, he argues thatdifferences in wealth are of greater theoretical importance than difference in numbers. Oligarchy is really control by the wealthy; democracy isreally control by the poor. It just so happens that the wealthy are alwaysfew in number, while the poor are always many ( 1 279b20-1 280•6,1 290b l 7-20). This allows him to see the importance of the middleclasses, those who are neither very rich nor very poor but somewhere inbetween ( 1 29Sb l-3), and to recognize the theoretical significance of aconstitution, a so-called POLITY, in which they play a decisive part( 1 293•40-b l ) . Second, Aristotle departs from tradition in thinking thateach of these three traditional types of rule actually comes in two majorvarieties, one of which is correct and the other deviant ( 1 289bS - l l ) . Ruleby "the one" is either a kingship (correct) or a tyranny (deviant); rule by"the few" is either an aristocracy (correct) or an oligarchy (deviant); ruleby "the many" is either a polity (correct) or a democracy (deviant). One important difference between these constitutions is that theyhave different aims or goals ( 1 289' 1 7-28), different conceptions of happiness: "it is by seeking happiness in different ways and by differentmeans that individual groups of people create different ways of life anddifferent constitutions" ( 1 3 28'41-b2).44 The goal of the ideal constitu-
44. Compare NE 1095'17-1096'10: people agree that the human good is called happiness, but they disagree about what happiness actually is or consists in.lxvi Introduction
aim at "the common benefit"; deviant ones at the benefit of the rulers( 1 279'26- 3 1 ) . His explanation is not very helpful, however, because hedoesn't specify the group, G, whose benefit is the common one, and hedoesn't tell us whether the common benefit is that of the individualmembers of G, or that of G taken as some kind of whole. When we try toprovide the missing information, moreover, we run into difficulties. A natural first thought about G, for example, is that it is the group ofunqualified citizens, those who participate in judicial and deliberativeoffice (111. 1-2, 5). But if G is restricted to these citizens, the commonbenefit and the private one coincide, since only the rulers participate inthese offices. Moreover, even the deviant constitutions aim at the benefitof a wider group than that of the unqualified citizens, since they alsoseem to aim at the benefit of the wives and children of such citizens( 1 260h8-20 with 1 3 1 0'34-36). Perhaps, then, G consists of all the free native inhabitants of the constitution. No, that won't do either, because now even some correct constitutions, such as a polity, will count as deviant. For the common benefit in a correct constitution is a matter of having a share in noble orvirtuous living ( 1 278h20-23, NE 1 142h3 1-33). Hence a polity will notaim at the benefit of its native-born artisans, tradesmen, or laborers,since there is "no element of virtue" in these occupations ( 1 3 1 9'26-28). These common characterizations of G all fail, but the last failurepoints in a promising direction. Let us begin with the class, N, of thefree native inhabitants of the constitution. There are two ways to construct the class of unqualified citizens from N. The first is to do so onthe basis of the type of justice internal to the constitution; the second isto do so on the basis of unqualified justice. If we proceed in the first way, "and the constitution is an oligarchy, for example, the unqualified citizens will be the wealthy male members of N. But if we proceed in thesecond way, the unqualified citizens of our oligarchy will be those whohave an unqualifiedly just claim to that status. And Aristotle thinks thatthe virtuous, the rich, and the poor all have such a claim, one that is proportional to their virtue ( 1 283'1 4-26, 1 280h40-128 1 '8, 1 294'1 9-20).Thus they ought to be unqualified citizens of any constitution. In fact,however, they are so only in correct constitutions, not in deviant ones. What I suggest, then, is that we construct G as follows: all the members of N, who have an unqualifiedly just claim to be unqualified citizens of the constitution, are members of G; all the wives and children ofmembers of G are members of G; no one else is a member of G. If a constitution aims at the benefit of G, it aims at the common benefit and is Introduction lxix
47. In 1.13, a similar claim is made about virtue: "the virtue of a part must be determined by looking to the virtue of the whole" ( l 260bJ4-16). Introduction Ixxi
The fact that there need be no more than this sort of general congruence between a city-state's happiness and the happiness of the individuals in its G class also explains why Aristotle's doctrine that individualsare parts of a city-state is no threat to his moderate individualism. Ahand can perform its task only as part of a body; there is general congruence between the health of a body and the health of all its parts; butin some circumstances, the closest we can come to preserving this congruence involves sacrificing a part. In this respect, Aristotle thinks, weare like hands. One will find this insufficiently reassuring only if onethinks that general congruence between the aim of a just city-state andthat of an individual in G is not enough, that more is required, that congruence must be guaranteed in all circumstances. Aristotle certainly failsto provide such reassurance, but this is almost certainly a strength ratherthan a weakness of his view. Properly or at least plausibly interpreted, then, Aristotle's treatmentof ostracism and his view that individuals are parts of city-states seem tobe compatible with the sort of moderate individualism he espouses. 48
48. Some of the topics in this section are further discussed in]. Barnes, ''Aristo tle on Political Liberty," and F. D. Miller, Nature, Justice and Rights in Aris totle's Politics, 143-308. Introduction lxxiii
tial catastrophe, obviously, but also an ethical one, since injustice in thedistribution of what constitutes the basis for all other distributions infects all those other distributions with injustice as well. Aristotle's ideal constitution thus fails to be just in its own terms; itfails to meet its own standards of justice. This is a major problem. But itpoints the way to a yet more serious one and then to a possible solution.Aristotle believes that unqualified justice must be based on virtue. Healso believes that virtue is not something children possess at birth. Morethan that, he believes that virtue is a social or political output, a consequence of receiving benefits, such as public education, that a constitution itself bestows. But no constitution can distribute all benefits on thebasis of a property, such as virtue, which is itself the result of the distribution of benefits. If justice is going to be based on some feature of individuals, it must be one that individuals do not acquire through a processwhich may itself be either just or unjust. Aristotle's theory fails to meetthis groundedness requirement, and so is strictly unsatisfiable. Yet the fact that Aristotle's theory of justice is unsatisfiable for thissort of reason suggests a way forward. His theory of justice needs to bemodified, so that the means of acquiring virtue are distributed on thebasis, not of virtue, but of a feature, such as being human, that is unproblematically possessed to an equal degree by all the children born inthe constitution, whether male or female, whether born to citizens or tononcitizens. The ideal constitution would have to provide equal opportunities to all the children possessing this feature. Then, at the appropriate stage, it would have to cull out as its future citizens those who hadindeed acquired virtue in this way. If this process were fairly carried out,it would ensure that people acquired their virtue in a just way. Subsequent virtue-based distributions of benefits would then not be unjustlybased. If Aristotle's ideal constitution were constructed in this way, itwould, of course, have to be very different from the constitution he describes, but at least it wouldn't fail to meet its own standards of justice. That problem, perhaps now to some extent solved, has to do with thebasis on which benefits are distributed in the ideal constitution. Thenext problem concerns what gets distributed. If someone is a naturalslave or a non-Greek of one sort or another, Aristotle thinks that he haspretty well no natural potential for virtue. Provided that his lack of suchpotential is determined by a fair process, it will then be unqualifiedlyjust, on Aristotle's view, for the ideal constitution to assign him no shareor a very small share in political benefits or in true happiness. But it doesnot follow that it will be just to assign him a share of political harms. For Introduction lxxv
terms themselves, which are far too vague to do the work required ofthem. Let us suppose for the sake of argument, however, that this defect,like the others, could be remedied, so that the ideal constitution was justin its own terms. Would it, then, be the ideal constitution to live in fromthe point of view of happiness, once again granting that happiness is, asAristotle thinks, activity expressing virtue? There are many ways to look at this question. We shall consider justone very important one, private property, which together with proportional equality is the sole guarantee of stability in a constitution( 1 307'26 -27). Property is a necessary component of the happy life:"Why should we not say that someone is happy when his activities express complete virtue and he has an adequate supply of external GOODS,not for some chance period but throughout a complete life?" (NE1 1 0 1 ' 1 4-16). But that does not tell us how the ideal constitution shouldhandle property ownership. Aristotle firmly rejects the idea, defendedby Plato, that private property should be abolished and that the citizensof the ideal constitution should possess their property in common. Hedoes so for three reasons. First, communally owned property is neglected. Second, "it is very pleasant to help one's friends, guests, orcompanions, and do them favors, as one can if one has property of one'sown" ( 1 263bS-7). And, third, without private property one cannot practice the virtue of generosity ( 1 263bl l - 1 4). To avoid these defects inPlato's proposals, as well as those generated by strictly private property,Aristotle designs an intermediate position: some property should becommunally owned and some should be privately owned, but the use ofeven the privately owned property should be communal ( 1 329b3 6-1 3 30'3 1 ) . Is this proposal an improvement on Plato's? Is it one thatshould attract us to a constitution that embodies it? To own property, according to the Rhetoric, is to have the power toalienate or dispose of it through either gift or sale ( 1 3 6 1 '2 1-22). ButAristotle stipulates that each of the unqualified citizens in the ideal constitution (each male head of household) should be given an equal allotment of land, one part of which is near the town, the other near thefrontier ( 1 330' 14-1 8). Moreover, he seems to favor making these allotments inalienable ( 1 266b14-3 1 , 1 270' 1 5 -34).50 But if they are inalienable, so that one cannot sell them or give them away, what does owningthem actually consist in? The natural thought is that it must consist in
50. If they were not inalienable, they could hardly continue to serve the purpose they are introduced to serve at 1330'14-25.Ixxviii Introduction
having private or exclusive use of them. But that thought is derailed, because the use of private property is communal. It seems, then, that amajor portion of what is called the private property of a citizen of theideal constitution is not something that he really and truly owns. Another passage from the Rhetoric tells us that ownership of propertyis secure if the use of it is in the owner's power ( 1 36 1" 1 9-21). Privatelyowned but communally used property would therefore seem to be insecurely owned at best. To be sure, this isn't what Aristotle intends to betrue in the ideal constitution. He thinks that the use of private propertyremains in the owner's power but that he will grant it to his fellow citizens out of virtue and friendship and not because the law requires himto do it (Pol. 1 263"21-40). None the less, the expectation on the part ofone citizen that another will do what virtue requires of him is pretty wellbound to make the owner's power seem notional rather than real. So what we have in the ideal constitution is a somewhat notional ownership of not very much (nonlanded) property. This will hardly recommend the constitution to those who think that private property is a goodthing. Indeed, it seems to be not much more than a notational variant ona system of communal ownership. It is scarcely surprising, therefore, thatit does not help much with the problems Aristotle raises for Plato. If communally owned property tends to be neglected, why will privately ownedbut communally used property fare any better? If I can use even what Idon't own, and so don't particularly have to take care of and maintain,ownership seems more like a curse than a blessing. By the same token, togive someone something of which he already has the use and you continue to retain the use is a wishy-washy sort of generosity at best, a palepleasure compared to that of using what one actually owns to do favorsfor one's friends. The system of property adopted in the ideal constitution, then, does not seem to be best from the point of view of maximizingthe citizen's happiness. Many other systems seem much more preferable;for example, fair taxation on private property and income, with the proceeds used to maintain public property and provide public servicesY
§ 1 1 Conclusion We have been looking at the central argument of the Politics, and atthe way Aristotle's perfectionism plays out there. We have seen the enormous price he pays in terms of political credibility for having too narrowa conception of what human perfection consists in (§§7-1 0): the politicaland philosophical lives are worthwhile but they are not the only onesthat are; virtue is worthwhile but it provides a poor basis for distributivejustice. We have seen the even larger price he pays for making false factual claims that are accretions to his perfectionism: without naturalslaves or women whose nature makes them incapable of ruling, Aristotle's ideal constitution would have to look very different than it does.None the less, if we strip away those accretions and broaden the perfectionism, we have a theory with considerable attractions and possibilities. 52 Arguably it is Aristotle's most important political legacy, both historically speaking and in fact. The central argument is just that, however: a major highway connecting the Politics to the rest of Aristotle's philosophy. But the Politics isn'treducible to its central argument; much fascinating material is to befound on the side roads. The discussion in Books V and VI, for example,of how different constitutions are preserved and destroyed is full of astute observations about people and their motives. In some ways, indeed, the Politics is best thought of not simply as anargument, but rather as an opportunity to think about some of the mostimportant human questions in unparalleled intellectual company. Engaged in the dialectical process of doing politics with Aristotle, one experiences the great seductive power of the philosophical life full force,but one also experiences the rather different power of the political life.To some degree, indeed, one senses that the two are, Aristotelian theoryto the contrary, not all that different, that the give and take of dialectic isvery like the give and take of politics, and that life's problems are no easier to solve in theory than in practice. This is not quite what the Politicstells us, to be sure, but it is, in a way that is mildly subversive of its message, what it dramatizes.
52. Thomas Hurka, Perfectionism, is one of the best general accounts of this sort of modified Aristotelian theory. Parts of it discuss Aristotle explicitly; all of it is relevant to understanding his thought. Am
TYRRHENIAN
SEA
IONIAN
SEA
c::. .
M E D I T E R R A N E A N
UBYA
0 100 200 0 100 200 300 Kilometers
PHRYGIA enedos A E G E A N "'T{_.rp ASIA Antis�{\_ � D0 �Myilene • Atarneus
LESBOS o•
" � • �s Cyme
e •
'Hestiaea/Oreu () \\� �Ei-l i > Chio� LYDIA et,i•�th� <> <'.. E A Sarf[{. S�Pi>.eu'<> '"'l 0 o s.,
� , 0�
5 E A B oo K I
Chapter 1We see that every CITY-STATE is a COMMUNITY of some sort, and that 1252"every community is established for the sake of some GOOD (for everyoneperforms every ACTION for the sake of what he takes to be good). Clearly,then, while every community aims at some good, the community thathas the most AUTHORITY of all and encompasses all the others aims 5highest, that is to say, at the good that has the most authority of all. Thiscommunity is the one called a city-state, the community that is political.1 Those,Z then, who think that the positions of STATESMAN, KING,HOUSEHOLD MANAGER, and MASTER of slaves are the same, are not correct. For they hold that each of these differs not in kind, but only inwhether the subjects ruled are few or many: that if, for example, someone rules few people, he is a master; if more, a household manager; ifstill more, he has the position of statesman or king-the assumption 10being that there is no difference between a large household and a smallcity-state. As for the positions of statesman and king, they say thatsomeone who is in charge by himself has the position of king, whereassomeone who follows the principles of the appropriate SCIENCE, ruling ISand being ruled in turn, has the position of statesman. But these claimsare not true. What I am saying will be clear, if we examine the matter ac-
1 . kuriotate koinonia: the most sovereign community, the one with the most au thority, is the city-state, because all the other communities are encompassed (periechein) by it or are its parts, so that the goods for whose sake they are formed are pursued in part for the sake of the good for which it is formed (see 1.2). These subcommunities include households, villages, religious societies, etc. The good with the most authority is HAPPINESS, since everything else is pursued in part for its sake, while it is pursued solely for its own sake. The science with the most authority, STATESMANSHIP, directs the entire city-state toward happiness. A more detailed version of this opening argument is given in NE 1. 1-2. Here it is being adapted to define what a city-state is.2. Plato, Statesman 258e-26 l a. Compare Xenophon, Memorabilia III. iv. l 2, III.vi. l 4 . 2 Politics I
Chapter 2 If one were to see how these things develop naturally from the begin- 25 ning, one would, in this case as in others, get the best view of them. First, then, those who cannot exist without each other necessarily form a couple, as [ I ] female and male do for the sake of procreation (they do not do so from DELIBERATE CHOICE, but, like other animals and plants, because the urge to leave behind something of the same kind as them- 30 selves is natural), and [2] as a natural ruler and what is naturally ruled do for the sake of survival. For if something is capable of rational foresight, it is a natural ruler and master, whereas whatever can use its body to labor is ruled and is a natural SLAVE. That is why the same thing is ben eficial for both master and slave.4 There is a natural distinction, of course, between what is female and12521 what is servile. For, unlike the blacksmiths who make the Delphian knife, nature produces nothing skimpily, but instead makes a single thing for a single TASK, because every tool will be made best if it serves to perform one task rather than many. 5 Among non-Greeks, however, a 5 WOMAN and a slave occupy the same position. The reason is that they do not have anything that naturally rules; rather their community consists of a male and a female slave. That is why our poets say "it is proper for Greeks to rule non-Greeks,"6 implying that non-Greek and slave are in nature the same. The first thing to emerge from these two communities7 is a house-
hold, so that Hesiod is right when he said in his poem, "First and fore- 10most: a house, a wife, and an ox for the plow."8 For an ox is a poor man'sservant. The community naturally constituted to satisfy everyday needs,then, is the household; its members are called "meal-sharers" byCharondas and "manger-sharers" by Epimenides the Cretan.9 But thefirst community constituted out of several households for the sake of 1Ssatisfying needs other than everyday ones is a village. As a COLONY or offshoot from a household, 10 a village seems to be particularly natural, consisting of what some have called "sharers of thesame milk," sons and the sons of sons. 1 1 That is why city-states wereoriginally ruled by kings, as nations still are. For they were constitutedout of people who were under kingships; for in every household the el- 20dest rules as a king. And so the same holds in the offshoots, because thevillagers are blood relatives. 12 This is what Homer is describing when hesays: "Each one lays down the law for his own wives and children."1 3 Forthey were scattered about, and that is how people dwelt in the distantpast. The reason all people say that the gods too are ruled by a king isthat they themselves were ruled by kings in the distant past, and somestill are. Human beings model the shapes of the gods on their own, and 25do the same to their way of life as well. A complete community constituted out of several villages, once itreaches the limit of total SELF-SUFFICIENCY, practically speaking, is acity-state. It comes to be for the sake of living, but it remains in existence for the sake of living well. That is why every city-state exists byNATURE, 14 since the first communities do. For the city-state is their end, 30and nature is an end; for we say that each thing's nature-for example,that of a human being, a horse, or a household-is the character it haswhen its coming-into-being has been completed. Moreover, that for the
sake of which something exists, that is to say, its end, is best, and self-1253• sufficiency is both end and best. It is evident from these considerations, then, that a city-state is among the things that exist by nature, that a human being is by nature a political animal, 15 and that anyone who is without a city-state, not by luck but by nature, is either a poor specimen or else superhuman. Like the one Homer condemns, he too is "clanless, lawless, and homeless."16 S For someone with such a nature is at the same time eager for war, like an isolated piece in a board game. 17 It is also clear why a human being is more of a political animal than a bee or any other gregarious animal. Nature makes nothing pointlessly, 18 10 as we say, and no animal has speech except a human being. A voice is a signifier of what is pleasant or painful, which is why it is also possessed by the other animals (for their nature goes this far: they not only per ceive what is pleasant or painful but signify it to each other). But speech is for making clear what is beneficial or harmful, and hence also what is IS just or unjust. For it is peculiar to human beings, in comparison to the other animals, that they alone have perception of what is good or bad, just or unjust, and the rest. And it is community in these that makes a household and a city-state.19 The city-state is also PRIOR in nature to the household and to each of 20 us individually, since the whole is necessarily prior to the part. For if the whole body is dead, there will no longer be a foot or a hand, except homonymously,20 as one might speak of a stone "hand" (for a dead hand will be like that); but everything is defined by its TASK and by its capac ity; so that in such condition they should not be said to be the same things but homonymous ones. Hence that the city-state is natural and 25 prior in nature to the individual is clear. For if an individual is not self sufficient when separated, he will be like all other parts in relation to the
whole. Anyone who cannot form a community with others, or who doesnot need to because he is self-sufficient, is no part of a city-state-he iseither a beast or a god. Hence, though an impulse toward this sort of 30community exists by nature in everyone, whoever first established onewas responsible for the greatest of goods. For as a human being is thebest of the animals when perfected, so when separated from LAW andJUSTICE he is worst of all. For injustice is harshest when it has weapons,and a human being grows up with weapons for VIRTUE and PRACTICALWISDOM to use, which are particularly open to being used for oppositepurposes.21 Hence he is the most unrestrained and most savage of ani- 35mals when he lacks virtue, as well as the worst where food and sex areconcerned. But justice is a political matter; for justice is the organizationof a political community, and justice22 decides what is just.
Chapter 3Since it is evident from what parts a city-state is constituted, we must 1253hfirst discuss household management, for every city-state is constitutedfrom households. The parts of household management correspond inturn to the parts from which the household is constituted, and a com-plete household consists of slaves and FREE. But we must first examineeach thing in terms of its smallest parts, and the primary and smallest 5parts of a household are master and slave, husband and wife, father andchildren. So we shall have to examine these three things to see what eachof them is and what features it should have. The three in question are [ 1 Jmastership, [2] "marital" science (for we have no word to describe theunion of woman and man), and [3] "procreative" science (this also lacks 10a name of its own). But there is also a part which some believe to beidentical to household management, and others believe to be its largestpart. We shall have to study its nature too. I am speaking of what iscalled WEALTH ACQUISITION. 23
15 But let us first discuss master and slave, partly to see how they stand in relation to our need for necessities, but at the same time with an eye to knowledge about this topic,24 to see whether we can acquire some better ideas than those currently entertained. For, as we said at the beginning, some people believe that mastership is a sort of science, and that master ship, household management, statesmanship, and the science of king ship are all the same. But others25 believe that it is contrary to nature to 20 be a master (for it is by law that one person is a slave and another free, whereas by nature there is no difference between them), which is why it is not just either; for it involves force.
Chapter 4 Since property is part of the household, the science of PROPERTY ACQUI SITION is also a part of household management (for we can neither live nor live well without the necessities). Hence, just as the specialized 25 crafts must have their proper tools if they are going to perform their tasks, so too does the household manager. Some tools are inanimate, however, and some are animate. The ship captain's rudder, for example, is an inanimate tool, but his lookout is an animate one; for where crafts 30 are concerned every assistant is classed as a tool. So a piece of property is a tool for maintaining life; property in general is the sum of such tools; a slave is a piece of animate property of a sort; and all assistants are like tools for using tools. For, if each tool could perform its task on com mand or by anticipating instructions, and if like the statues of Daedalus 35 or the tripods of Hephaestus-which the poet describes as having "en tered the assembly of the gods of their own accord"26-shuttles wove cloth by themselves, and picks played the lyre, a master craftsman would not need assistants, and masters would not need slaves.1254" What are commonly called tools are tools for production. A piece of property, on the other hand, is for ACTION. For something comes from a
shuttle beyond the use of it, but from a piece of clothing or a bed we getonly the use. Besides, since action and production differ in kind, and Sboth need tools, their tools must differ in the same way as they do. Lifeconsists in action, not production. Therefore, slaves too are assistants inthe class of things having to do with action. 27 Pieces of property are spo-ken of in the same way as parts. A part is not just a part of another thing,but is entirely that thing's. The same is also true of a piece of property. 10That is why a master is just his slave's master, not his simply, while aslave is not just his master's slave, he is entirely his. It is clear from these considerations what the nature and capacity of aslave are. For anyone who, despite being human, is by nature not his ownbut someone else's is a natural slave. And he is someone else's when, de- 1Sspite being human, he is a piece of property; and a piece of property is atool for action that is separate from its owner. 28
Chapter 5But whether anyone is really like that by nature or not, and whether it isbetter or just for anyone to be a slave or not (all slavery being against nature)-these are the things we must investigate next. And it is not difficult either to determine the answer by argument or to learn it from ac-tual events. For ruling and being ruled are not only necessary, they are 20also beneficial, and some things are distinguished right from birth, somesuited to rule and others to being ruled. There are many kinds of rulersand ruled, and the better the ruled are, the better the rule over them always is;29 for example, rule over humans is better than rule over beasts. 25For a task performed by something better is a better task, and where onething rules and another is ruled, they have a certain task. For whenevera number of constituents, whether continuous with one another or discontinuous, are combined into one common thing, a ruling element and 30a subject element appear. These are present in living things, because thisis how nature as a whole works. (Some rule also exists in lifeless things:
30. The reference is to the mese or hegemiin (leader), which is the dominant note in a chord (Pr. 920'21-22, Metaph. 1 0 1 8h26-29). 3 1 . exoterikoteras: see 1 278h3 1 note. 32. The difference between depraved people and those in a depraved condition is unclear. The former are perhaps permanently in the condition that the latter are in temporarily; the former incorrigibly depraved, the latter corri gibly so. In any case, both make poor models. 33. Both statesmen and kings rule willing subjects; in the virtuous desires obey understanding "willingly." See Introduction xxv-xxxviii. 34. Alternatively: "It is better for all of the tame ones to be ruled." But the dis tinction between tame and wild animals is not hard and fast: "All domestic (or tame) animals are at first wild rather than domestic, . . . but physically weaker"; "under certain conditions of locality and time sooner or later all animals can become tame" (Pr. 89Sh23-896' 1 1). Presumably, then, it is bet ter even for wild animals to be ruled by man. 35. For example, it is natural for Greeks to rule non-Greeks. Chapter 6 9
tion-those people are natural slaves. And it is better for them to be sub-ject to this rule, since it is also better for the other things we mentioned. 20For he who can belong to someone else (and that is why he actually doesbelong to someone else), and he who shares in reason to the extent ofunderstanding it, but does not have it himself (for the other animalsobey not reason but feelings), is a natural slave. The difference in the usemade of them is small, since both slaves and domestic animals help pro-vide the necessities with their bodies. 25 Nature tends, then, to make the bodies of slaves and free people different too, the former strong enough to be used for necessities, the latteruseless for that sort of work, but upright in posture and possessing allthe other qualities needed for political life-qualities divided into those 30needed for war and those for peace. But the opposite often happens aswell: some have the bodies of free men; others, the souls. This, at anyrate, is evident: if people were born whose bodies alone were as excellentas those found in the statues of the gods, everyone would say that those JSwho were substandard deserved to be their slaves. And if this is true ofthe body, it is even more justifiable to make such a distinction with re-gard to the soul; but the soul's beauty is not so easy to see as the body's. 12SS• It is evident, then, that there are some people, some of whom are nat-urally free, others naturally slaves, for whom slavery is both just andbeneficial. 36
Chapter 6But it is not difficult to see that those who make the opposite claim37 arealso right, up to a point. For slaves and slavery are spoken of in two ways:for there are also slaves-that is to say, people who are in a state of slavery-by law. The law is a sort of agreement by which what is conquered Sin war is said to belong to the victors. But many of those conversant withthe law challenge the justice of this. They bring a writ of illegality againstit, analogous to that brought against a speaker in the assembly. 38 Their
36. A more complex conclusion than we might expect. The idea is perhaps this: being a slave might not be just or beneficial for a natural slave who has long been legally free; similarly, being legally free might not be just or beneficial for a naturally free person who has long been a legal slave.37. That slavery is unjust.38. A speaker in the Athenian assembly was liable to a writ of illegality or graphe paranoman if he proposed legislation that contravened already existing law; i.e., the "war" rule would not be allowed in a civil context. 10 Politics I
39. Virtue together with the necessary external goods or resources are what en able someone to do something well, including use force. If someone is able to conquer his foes, this at least suggests that he has the virtues needed for success. See 1324hZZ-1325'14. 40. Reading eunoia with Dreizehnter and the mss. 4 1 . The two parties to the dispute share common ground because they both be lieve that "force never lacks virtue." But they disagree in their accounts of justice, and hence about whether the enslavement of conquered populations is unjust. Those who believe that justice is the rule of the more powerful be lieve that such enslavement is just, because justice (by definition) is always on the side of the conqueror, since his victory shows him to have the greater power. Those who believe that justice is benevolence (i.e., that it is the good of another) believe that enslavement is unjust because not beneficial for the slaves. Both accounts are canvassed by Thrasymachus in Book I of Plato's Republic (338c, 343c). Once their accounts are disentangled it is readily ap parent that their contrasting positions do nothing to confute Aristotle's own view that the one who is more virtuous should rule (1. 1 3). 42. Aristotle is assuming that even an unjust war will be undertaken in accor dance with the laws governing declarations of war, and so will be "legal." Thus by admitting that a person enslaved by the victor in an unjust war has been unjustly but legally enslaved, the proponent of the view here in ques tion denies both that enslaving is always just and that what is legal is always just. Chapter 6 11
as the best born would be slaves or the children of slaves, if any of themwere taken captive and sold. That is why indeed they are not willing todescribe them, but only non-Greeks, as slaves. Yet, in saying this, theyare seeking precisely the natural slave we talked about in the beginning. 30For they have to say that some people are slaves everywhere, whereasothers are slaves nowhere. The same holds of noble birth. Nobles regard themselves as well bornwherever they are, not only when they are among their own people, butthey regard non-Greeks as well born only when they are at home. Theyimply a distinction between a good birth and freedom that is unqualifiedand one that is not unqualified. As Theodectes' Helen says: "Sprung JSfrom divine roots on both sides, who would think that I deserve to becalled a slave?"43 But when people say this, they are in fact distinguish-ing slavery from freedom, well born from low born, in terms of virtueand vice alone. For they think that good people come from good people 40in just the way that human comes from human, and beast from beast.But often, though nature does have a tendency to bring this about, it is 12SSbnevertheless unable to do so. 44 It is clear, then, that the objection with which we began has something to be said for it, and that the one lot are not always natural slaves,nor the other naturally free. But it is also clear that in some cases there is Ssuch a distinction--cases where it is beneficial and just45 for the one tobe master and the other to be slave, and where the one ought to be ruledand the other ought to exercise the rule that is natural for him (so that heis in fact a master), and where misrule harms them both. For the samething is beneficial for both part and whole, body and soul; and a slave is 10a sort of part of his master-a sort of living but separate part of his body.Hence, there is a certain mutual benefit and mutual friendship for suchmasters and slaves as deserve to be by nature so related.46 When their relationship is not that way, however, but is based on law, and they havebeen subjected to force, the opposite holds. 1S
43. Nauck 802, fr. 3. Theodectes was a mid-fourth-century tragic poet who studied with Aristotle. Helen is Helen of Troy.44. See 1254b27-33.45. Reading kai dikaion.46. "Every human being seems to have some relations of justice with everyone who is capable of community in law and agreement. Hence there is also friendship between master and slave, to the extent that a slave is a human being" (NE 1 16 1bl-8). 12 Politics I
Chapter 7 It is also evident from the foregoing that the rule of a master is not the same as rule of a statesman and that the other kinds of rule are not all the same as one another, though some people say they are. For rule of a statesman is rule over people who are naturally free, whereas that of a master is rule over slaves; rule by a household manager is a monarchy, since every household has one ruler; rule of a statesman is rule over peo- 20 ple who are free and equal. A master is so called not because he possesses a SCIENCE but because he is a certain sort of person. 47 The same is true of slave and free. None the less, there could be such a thing as mastership or slave-craft; for ex ample, the sort that was taught by the man in Syracuse who for a fee 25 used to train slave boys in their routine services. Lessons in such things might well be extended to include cookery and other services of that type. For different slaves have different tasks, some of which are more esteemed, others more concerned with providing the necessities: "slave is superior to slave, master to master,"48 as the proverb says. All such 30 SCIENCEs, then, are the business of slaves. Mastership, on the other hand, is the science of using slaves; for it is not in acquiring slaves but in using them that someone is a master. But there is nothing grand or impressive about this science. The master needs to know how to command the things that the slave needs to know 35 how to do. Hence for those who have the resources not to bother with such things, a steward takes on this office, while they themselves engage in politics or PHILOSOPHY.49 As for the science of acquiring slaves (the just variety of it), it is different from both of these,50 and is a kind of warfare or hunting. These, then, are the distinctions to be made regarding slave and master.
Chapter 8 Since a slave has turned out to be part of property, let us now study1256• property and wealth acquisition generally, in accordance with our guid-
ing method. 5 1 The first problem one might raise is this: Is wealth acquisition the same as household management, or a part of it, or an assistantto it? If it is an assistant, is it in the way that shuttle making is assistant 5to weaving, or in the way that bronze smelting is assistant to statue making? For these do not assist in the same way: the first provides tools,whereas the second provides the matter. (By the matter I mean the substrate, that out of which the product is made-for example, wool for theweaver and copper for the bronze smelter.) 10 It is clear that household management is not the same as wealth acquisition, since the former uses resources, while the latter providesthem; for what science besides household management uses what is inthe household? But whether wealth acquisition is a part of householdmanagement or a science of a different kind is a matter of dispute. For ifsomeone engaged in wealth acquisition has to study the various sourcesof wealth and property, and52 property and wealth have many different 15parts, we shall first have to investigate whether farming is a part ofhousehold management53 or some different type of thing, and likewisethe supervision and acquisition of food generally. But there are many kinds of food too. Hence the lives of both animalsand human beings are also of many kinds. For it is impossible to live 20without food, so that differences in diet have produced different ways oflife among the animals. For some beasts live in herds and others livescattered about, whichever is of benefit for getting their food, becausesome of them are carnivorous, some herbivorous, and some omnivorous. 25So, in order to make it easier for them to get hold of these foods, naturehas made their ways of life different. And since the same things are notnaturally pleasant to each, but rather different things to different ones,among the carnivores and herbivores themselves the ways of life are different. Similarly, among human beings too; for their ways of life differ agreat deal. The idlest are nomads; for they live a leisurely life, because 30they get their food effortlessly from their domestic animals. But whentheir herds have to change pasture, they too have to move around withthem, as if they were farming a living farm. Others hunt for a living, differing from one another in the sort of hunting they do. Some live by 35
raiding; some-those who live near lakes, marshes, rivers, or a sea con taining fish-live from fishing; and some from birds or wild beasts. But 40 the most numerous type lives off the land and off cultivated crops. Hence the ways of life, at any rate those whose fruits are natural and do not provide food through EXCHANGE or COMMERCE, are roughly speak-] 256h ing these: nomadic, raiding, fishing, hunting, farming. But some people contrive a pleasant life by combining several of these, supplementing their way of life where it has proven less than self-sufficient; for exam ple, some live both a nomadic and a raiding life, others, both a farming 5 and a hunting one, and so on, each spending their lives as their needs jointly compel. It is evident that nature itself gives such property to all living things, both right from the beginning, when they are first conceived, and simi larly when they have reached complete maturity. Animals that produce 10 larvae or eggs produce their offspring together with enough food to last them until they can provide for themselves. Animals that give birth to live offspring carry food for their offspring in their own bodies for a cer tain period, namely, the natural substance we call milk. Clearly, then, we 15 must suppose in the case of fully developed things too that plants are for the sake of animals, and that the other animals are for the sake of human beings, domestic ones both for using and eating, and most but not all wild ones for food and other kinds of support, so that clothes and the 20 other tools may be got from them. If then nature makes nothing incom plete or pointless, it must have made all of them for the sake of human beings. That is why even the science of warfare, since hunting is a part of it, will in a way be a natural part of property acquisition. For this science ought to be used not only against wild beasts but also against those 25 human beings who are unwilling to be ruled, but naturally suited for it, as this sort of warfare is naturally just. One kind of property acquisition is a natural part of household man agement,54 then, in that a store of the goods that are necessary for life and useful to the community of city-state or household either must be available to start with, or household management must arrange to make 30 it available. At any rate, true wealth seems to consist in such goods. For the amount of this sort of property that one needs for the self-suffi ciency that promotes the good life is not unlimited, though Solon in his poetry says it is: "No boundary to wealth has been established for
human beings."55 But such a limit o r boundary has been established, justas in the other crafts. For none has any tool unlimited in size or num- 35ber,56 and wealth is a collection of tools belonging to statesmen andhousehold managers. It is clear, then, that there is a natural kind of property acquisition forhousehold managers and statesmen, and it is also clear why this is so.
Chapter 9But there is another type of property acquisition which is especiallycalled wealth acquisition, and justifiably so. It is the reason wealth and 40property are thought to have no limit. For many people believe that 1257"wealth acquisition is one and the same thing as the kind of property acquisition we have been discussing, because the two are close neighbors.But it is neither the same as the one we discussed nor all that far from it:one of them is natural, whereas the other is not natural, but comes froma sort of experience and craft. 57 Let us begin our discussion of the latter as follows. Every piece of 5property has two uses. Both of these are uses of it as such, 58 but they arenot the same uses of it as such: one is proper to the thing and the otheris not. Take the wearing of a shoe, for example, and its use in exchange.Both are uses to which shoes can be put. For someone who exchanges ashoe, for MONEY or food, with someone else who needs a shoe, is using 10the shoe as a shoe. But this is not its proper use because it does not cometo exist for the sake of exchange. The same is true of other pieces ofproperty as well, since the science of exchange embraces all of them. Itfirst arises out of the natural circumstance of some people having more 15than enough and others less. This also makes it clear that the part ofwealth acquisition which is commerce does not exist by nature: for peo-ple needed to engage in exchange only up to the point at which they hadenough. It is evident, then, that exchange has no task to perform in thefirst community (that is to say, the household), but only when the com- 20
55. Diehl 1.2 1 , fr. 1 . 7 1 . Solon (c. 640-560) was an Athenian statesman and poet, and first architect of the Athenian constitution. The limit to the amount of property needed for the good or happy life is determined by what happiness is. See 1257b28, NE 1 1 28b1 8-25, 1 1 53b21-25, EE 1 249'22-b25 .56. See 1 323h7-10.57. See 1 257'41-b5, 1258'38-bS.58. kath ' hauto: what something is as such or in itself or in its own right is what it is UNQUALIFIEDLY. 16 Politics I
munity has become larger. For the members of the household used to share all the same things, whereas those in separate households shared next many different things, which they had to exchange with one an other through barter when the need arose, as many non-Greek peoples 25 still do even to this day. For they exchange useful things for other useful things, but nothing beyond that-for example, wine is exchanged for wheat, and so on with everything else of this kind. This kind of exchange is not contrary to nature, nor is it any kind of wealth acquisition; for its purpose was to fill a lack in a natural self-suf- 30 ficiency. 59 None the less, wealth acquisition arose out of it, and in an in telligible manner. Through importing what they needed and exporting their surplus, people increasingly got their supplies from more distant foreign sources. Since not all the natural necessities are easily trans- JS portable, the use of money had of necessity to be devised. So for the purposes of exchange people agreed to give to and take from each other something that was a useful thing in its own right and that was conve nient for acquiring the necessities of life: iron or silver or anything else of that sort. At first, its value was determined simply by size and weight, 40 but finally people also put a stamp on it, so as to save themselves the trouble of having to measure it. For the stamp was put on to indicate the amount.J2S7b After money was devised, necessary exchange gave rise to the second of the two kinds of wealth acquisition, commerce. At first, commerce was probably a simple affair, but then it became more of a craft as expe rience taught people how and from what sources the greatest profit could be made through exchange. That is why it is held that wealth ac- S quisition is concerned primarily with money, and that its task is to be able to find sources from which a pile of wealth will come. For it is pro ductive of wealth and money, and wealth is often assumed to be a pile of money, on the grounds that this is what wealth acquisition and com merce are concerned to provide. 10 On the other hand, it is also held that money itself is nonsense and wholly conventional, not natural at all. For if those who use money alter it, it has no value and is useless for acquiring necessities; and often someone who has lots of money is unable to get the food he needs. Yet it is absurd for something to be wealth if someone who has lots of it will
59. "Eating indiscriminately or drinking until we are too full is exceeding the quantity that suits nature, since the aim of a natural appetite is to fill a lack" (NE l l l 8 b l 8 -1 9). Chapter 9 17
die of starvation, like Midas in the fable, when everything set before him I5turned to gold in answer to his own greedy prayer. That is why peoplelook for a different kind of wealth and wealth acquisition, and rightly so;for natural wealth and wealth acquisition are different. Natural wealthacquisition is a part of household management, whereas commerce has 20to do with the production of goods, not in the full sense, but throughtheir exchange. It is held to be concerned with money, on the groundsthat money is the unit and limit of exchange.60 The wealth that derives from this kind of wealth acquisition is with-out limit. For medicine aims at unlimited health, and each of the crafts 25aims to achieve its end in an unlimited way, since each tries to achieve itas fully as possible. (But none of the things that promote the end is unlimited, since the end itself constitutes a limit for all crafts.) Similarly,there is no limit to the end of this kind of wealth acquisition, for its endis wealth in that form, that is to say, the possession of money. The kindof wealth acquisition that is a part of household management, on theother hand, does have a limit, since this is not the task of household 30management. In one way, then, it seems that every sort of wealth has to have a limit.Yet, if we look at what actually happens, the opposite seems true, for allwealth acquirers go on increasing their money without limit. The explanation of this is that the two are closely connected. Each of the two 35kinds of wealth acquisition makes use of the same thing, so their usesoverlap, since they are uses of the same property. But they do not use itin accordance with the same principle. For one aims to increase it,whereas the other aims at a different end. So some people believe thatthis is the task of household management, and go on thinking that theyshould maintain their store of money or increase it without limit. 40 The reason they are so disposed, however, is that they are preoccu-pied with living, not with living well.61 And since their appetite for life isunlimited, they also want an unlimited amount of what sustains it. And 1258•those who do aim at living well seek what promotes physical gratifica-tion. So, since this too seems to depend on having property, they spendall their time acquiring wealth. And the second kind of wealth acquisi- 5tion arose because of this. For since their gratification lies in excess, theyseek the craft that produces the excess needed for gratification. If they
60. The unit (stoicheion) for obvious reasons; the limit (peras) because the price of something delimits its exchange value. See Introduction lxxvi.6 1 . See 12S2h29-30, 1280'3 1-32. 18 Politics I
Chapter 1 0 Clearly, we have also found the solution to our original problem about whether the craft of wealth acquisition is that of a household manager or20 a statesman, or not-this having rather to be available. For just as states manship does not make human beings, but takes them from nature and uses them, so too nature must provide land or sea or something else as a source of food, and a household manager must manage what comes from25 these sources in the way required. For the task of weaving is not to make wool but to use it, and to know which sorts are useful and suitable or worthless and unsuitable. For one might be puzzled as to why wealth ac quisition is a part of household management but medicine is not, even though the members of a household need health, just as they need life30 and every other necessity. And in fact there is a way in which it is the task of a household manager or ruler to see to health, but in another way it is not his task but a doctor's. So too with wealth: there is a way in which a household manager has to see to it, and another in which he does not, and an assistant craft does. But above all, as we said, nature must ensure that wealth is there to start with. For it is the task of nature35 to provide food for what is born, since the surplus of that from which they come serves as food for every one of them. 62 That is why the craft of acquiring wealth from crops and animals is natural for all people. But, as we said, there are two kinds of wealth acquisition. One has to do with commerce, the other with household management. The latter is necessary and commendable, but the kind that has to do with exchange is
justly disparaged, since it i s not natural but is from one another. 63 Hence 12S!Jbusury is very justifiably detested, since it gets wealth from money itself,rather than from the very thing money was devised to facilitate. Formoney was introduced to facilitate exchange, but interest makes moneyitself grow bigger. (That is how it gets its name; for offspring resemble Stheir parents, and interest is money that comes from money.)64 Hence ofall the kinds of wealth acquisition this one is the most unnatural.
Chapter 1 1Now that we have adequately determined matters bearing on knowledge,we should go through those bearing on practice. 65 A FREE person hastheoretical knowledge of all of these, but he will gain practical experi- 10ence of them to meet necessary needs.66 The practical parts of [I] wealthacquisition are experience of: [ 1 . 1] livestock, for example, what sorts ofhorses, cattle, sheep, and similarly other animals yield the most profit indifferent places and conditions; for one needs practical experience ofwhich breeds are by comparison with one another the most profitable, 1Sand which breeds yield the most profit in which places, as different onesthrive in different places. [ 1 .2] Farming, which is now divided into landplanted with fruit and land planted with cereals.67 [ 1 .3] Bee keeping andthe rearing of the other creatures, whether fish or fowl, that can be ofsome use. These, then, are the parts of the primary and most appropri-ate kind of wealth acquisition. 20 (2] Exchange's most important part, on the other hand, is (2. 1 ] trad-ing, which has three parts: [2. 1 . 1 ] ship owning, [2. 1 .2] transport, and(2. 1 .3] marketing. These differ from one another in that some are safer,others more profitable. The second part of exchange is (2.2] moneylending; the third is (2.3] wage earning. As for wage earning, some wageearners are (2 . 3 . 1 ] vulgar craftsmen, whereas (2.3.2] others are un- 2Sskilled, useful for manual labor only. [3] A third kind of wealth acquisition comes between this kind and
63. Because for everyone who makes a profit in a commercial transaction, some- one else makes a loss? See Rh. 138 1'21-33, Oec. 1 343'27-30.64. Takas means both "offspring" and "interest." See Plato, Republic 507a.65. See 1253b14-18.66. Alternatively: "but he cannot avoid practical experience of them."67. Ancient farming consisted in the cultivation of wheat and other cereals on flat open plains (psili) and the cultivation of grapes, olives, etc. on more hilly areas (pephuteumeni). 20 Politics I
the primary or natural kind, since it contains elements both of the nat ural kind and of exchange. It deals with inedible but useful things from 30 the earth or extracted from the earth. Logging and mining are examples. Mining too is of many types, since many kinds of things are mined from the earth. A general account has now been given of each of them. A detailed and precise account might be useful for practical purposes, but it would be 35 VULGAR to spend one's time developing it.68 (The operations that are most craftlike depend least on luck; the more they damage the body, the more vulgar they are; the most slavish are those in which the body is used the most; the most ignoble are those least in need of virtue.) Be sides, some people have written books on these matters which may be studied by those interested . For example, Chares of Paras and Apol-1259' lodorus of Lemnos69 have written on how to farm both fruit and cereals, and others have written on similar topics. Moreover, the scattered stories about how people have succeeded in acquiring wealth should be collected, since all of them are useful to 5 those who value wealth acquisition. For instance, there is the scheme of Thales of Miletus. 70 This is a scheme for getting wealthy which, though credited to him on account of his wisdom, is in fact quite generally ap plicable. People were reproaching Thales for being poor, claiming that it 10 showed his philosophy was useless. The story goes that he realized through his knowledge of the stars that a good olive harvest was coming. So, while it was still winter, he raised a little money and put a deposit on all the olive presses in Miletus and Chios for future lease. He hired them at a low rate, because no one was bidding against him. When the olive season came and many people suddenly sought olive presses at the same 15 time, he hired them out at whatever rate he chose. He collected a lot of money, showing that philosophers could easily become wealthy if they wished, but that this is not their concern. Thales is said to have demon strated his own wisdom in this way. But, as I said, his scheme involves a 20 generally applicable principle of wealth acquisition: to secure a monop oly if one can. Hence some city-states also adopt this scheme when they are in need of money: they secure a monopoly in goods for sale.
There was a man in Sicily who used some money that had been lent tohim to buy up all the iron from the foundries, and later, when the mer- 25chants came from their warehouses to buy iron, he was the only seller.He did not increase his prices exorbitantly and yet he turned his fifty sil-ver talents into one hundred and fifty. When Dionysius71 heard aboutthis, he told the man to take his wealth out, but to remain in Syracuse nolonger, as he had discovered ways of making money that were harmful to 30Dionysius' own affairs. Yet this man's insight was the same as Thales':each contrived to secure a monopoly for himself. It is also useful for statesmen to know about these things, since manycity-states have an even greater need for wealth acquisition and the associated revenues than a private household does. That is why indeed some 35statesmen restrict their political activities entirely to finance.
Chapter 1 2Household management has proved to have three parts: [ I ] one is mastership (which we discussed earlier), [2] another that of a father, and [3]a third, marital.72 For a man rules his wife and children both as free peo-ple, but not in the same way: instead, he rules his wife the way a states- 40man does,73 and his children the way a king does. For a male, unless he J251J'is somehow constituted contrary to nature, is naturally more fitted tolead than a female, and someone older and completely developed is nat-urally more fitted to lead than someone younger and incompletely developed. In most cases of rule of a statesman, it is true, people take turns atruling and being ruled, because they tend by nature to be on an equal 5footing and to differ in nothing. Nevertheless, whenever one person isruling and another being ruled, the one ruling tries to distinguish him-
self in demeanor, title, or rank from the ruled; witness what Amasis said about his footbath.74 Male is permanently related to female in this way.10 The rule of a father over his children, on the other hand, is that of a king, since a parent rules on the basis of both age and affection, and this is a type of kingly rule. Hence Homer did well to address Zeus, who is the king of them all, as "Father of gods and men.ms For a king should15 have a natural superiority, but be the same in stock as his subjects; and this is the condition of older in relation to younger and father in relation to child.
Chapter 1 3 It is evident, then, that household management is more seriously con-20 cerned with human beings than with inanimate property, with their virtue more than with its (which we call wealth), and with the virtue of free people more than with that of slaves. The first problem to raise about slaves, then, is this: Has the slave some other virtue more estimable than those he has as a tool or servant, such as temperance, courage, justice, and other such states of character?25 Or has he none besides those having to do with the physical assistance he provides? Whichever answer one gives, there are problems. If slaves have temperance and the rest, in what respect will they differ from the. free? If they do not, absurdity seems to result, since slaves are human and have a share in reason. Roughly the same problem arises about30 women and children. Do they too have virtues? Should women be tem perate, courageous, and just, or a child be temperate or intemperate? Or not? The problem of natural rulers and natural subjects, and whether their virtue is the same or different, needs to be investigated in general terms. If both of them should share in what is noble-and-good/6 why should
one of them rule once and for all and the other be ruled once and for all? 35(It cannot be that the difference between them is one of degree. Rulingand being ruled differ in kind, but things that differ in degree do notdiffer in that way.) On the other hand, if the one shares in what is nobleand-good, and not the other, that would be astonishing. For if the ruleris not going to be temperate and just, how will he rule well? And if thesubject is not going to be, how will he be ruled well? For if he is intern- 40perate and cowardly, he will not perform any of his duties. It is evident, 126()'therefore, that both must share in virtue, but that there are differencesin their virtue (as there are among those who are naturally ruled). 77 Consideration of the soul leads immediately to this view. The soul bynature contains a part that rules and a part that is ruled, and we say that 5each of them has a different virtue, that is to say, one belongs to the partthat has reason and one to the nonrational part. It is clear, then, that thesame holds in the other cases as well, so that most instances of rulingand being ruled are natural. For free rules slaves, male rules female, andman rules child in different ways, because, while the parts of the soul 10are present in all these people, they are present in different ways. Thedeliberative part of the soul is entirely missing from a SLAVE; a WOMANhas it but it lacks authority; a child has it but it is incompletely developed. We must suppose, therefore, that the same necessarily holds of thevirtues of character too: all must share in them, but not in the same way; ISrather, each must have a share sufficient to enable him to perform hisown task. Hence a ruler must have virtue of character complete, sincehis task is unqualifiedly that of a master craftsman, and reason is a mas-ter craftsman, 78 but each of the others must have as much as pertains tohim. It is evident, then, that all those mentioned have virtue of charac-ter, and that temperance, courage, and justice of a man are not the same 20as those of a woman, as Socrates supposed:79 the one courage is that of aruler, the other that of an assistant, and similarly in the case of the othervirtues too. If we investigate this matter in greater detail, it will become clear. Forpeople who talk in generalities, saying that virtue is a good condition of 25the soul, or correct action, or something of that sort, are deceivingthemselves. It is far better to enumerate the virtues, as Gorgias does,
80. See Plato, Meno 7 l d4-72a5, where Meno, following Gorgias, lists the dis tinct virtues of men, women, children, and slaves. 8 1 . Sophocles, Ajax 293. See 1277b22-24, Thucydides II.45. 82. That is to say, the end he will have as a mature adult (happiness), and toward which his father is leading him. 83. A reference to Plato, Laws 777e. 84. No full discussion of these topics appears in the Politics as we have it. 85. See 1253'18-29, 1337'27-30. Chapter 13 25
a city-state that its children be virtuous, and its women too. And it mustmake a difference, since half the free population are women, and fromchildren come those who participate in the constitution. So, since we have determined some matters, and must discuss the rest 20elsewhere, let us regard the present discussion as complete, and make anew beginning. And let us first investigate those who have expressedviews about the best constitution. B ooK I I
Chapter 1 Since we propose to study which political community is best of all for people who are able to live as ideally as possible, 1 we must investigate other constitutions too, both some of those used in city-states that are 30 said to be well governed, and any others described by anyone that are held to be good, in order to see what is correct or useful in them, but also to avoid giving the impression that our search for something different from them results from a desire to be clever. Let it be held, instead, that we have undertaken this inquiry because the currently available consti- 35 tutions are not in good condition. We must begin, however, at the natural starting point of this investi gation. For all citizens must share everything, or nothing, or some things but not others. It is evidently impossible for them to share nothing. For 40 a constitution is a sort of community, and so they must, in the first in stance, share their location; for one city-state occupies one location, and126Ja citizens share that one city-state. But is it better for a city-state that is to be well managed to share everything possible? Or is it better to share some things but not others? For the citizens could share children, 5 women, and property with one another, as in Plato's Republic.2 For Socrates claims there that children, women, and property should be communal. So is what we have now better, or what accords with the law described in the Republic?
Chapter 2 10 That women should be common to all raises many difficulties. In partic ular, it is not evident from Socrates' arguments why he thinks this legis-
1 . As not many people are; see 1 288b23-24. Ideal conditions are literally those that are answers to our prayers (kat' euchen). 2. See 423e-424a, 449a-466d.
26 Chapter 2 27
lation is needed. Besides, the end he says his city-state should have isimpossible, as in fact described, yet nothing has been settled about howone ought to delimit it. I am talking about the assumption that it is bestfor a city-state to be as far as possible all one unit; for that is the assumption Socrates adopts.3 And yet it is evident that the more of a unity 15a city-state becomes, the less of a city-state it will be. For a city-statenaturally consists of a certain multitude; and as it becomes more of aunity, it will turn from a city-state into a household, and from a house-hold into a human being. For we would surely say that a household ismore of a unity than a city-state and an individual human being than a 20household. Hence, even if someone could achieve this, it should not bedone, since it will destroy the city-state. A city-state consists not only of a number of people, but of people ofdifferent kinds, since a city-state does not come from people who arealike. For a city-state is different from a military alliance. An alliance isuseful because of the weight of numbers, even if they are all of the same 25kind, since the natural aim of a military alliance is the sort of mutual assistance that a heavier weight provides if placed on a scales. A nation willalso differ from a city-state in this sort of way, provided the multitude isnot separated into villages, but is like the Arcadians.4 But things fromwhich a unity must come differ in kind. That is why reciprocal EQUAL-ITY preserves city-states, as we said earlier in the Ethics,5 since this must 30exist even among people who are free and equal. For they cannot all ruleat the same time, but each can rule for a year or some other period. As aresult they all rule, just as all would be shoemakers and carpenters ifthey changed places, instead of the same people always being shoemak- 35ers and the others always carpenters. But since it is better to have the lat-ter also where a political community is concerned, it is clearly better,where possible, for the same people always to rule. But among thosewhere it is not possible, because all are naturally equal, and where it is atthe same time just for all to share the benefits or burdens of ruling, it is 126Jbat least possible to approximate to this if those who are equal take turnsand are similar when out of office. For they rule and are ruled in turn,just as if they had become other people. It is the same way among those 5who are ruling; some hold one office, some another.
Chapter 3 But even if it is best for a community to be as much a unity as possible, this does not seem to have been established by the argument that every one says "mine" and "not mine" at the same time (for Socrates takes this as an indication that his city-state is completely one).7 For "all" is am-20 biguous. If it means each individually, perhaps more of what Socrates wants will come about, since each will then call the same woman his wife, the same person his son, the same things his property, and so on for each thing that befalls him. But this is not in fact how those who have25 women and children in common will speak. They will all speak, but not each. And the same goes for property: all, not each. It is evident, then, that there is an equivocation involved in "all say." (For "all," "both," "odd," and "even," are ambiguous, and give rise to contentious argu-30 ments even in discussion.)8 Hence in one sense it would be good if all said the same, but not possible, whereas in the other sense it is in no way conducive to concord. But the phrase is also harmful in another way, since what is held in common by the largest number of people receives the least care. For people give most attention to their own property, less to what is commu-
nal, or only as much as falls to them to give.9 For apart from anythingelse, the thought that someone else is attending to it makes them neglect 35it the more (just as a large number of household servants sometimes giveworse service than a few). Each of the citizens acquires a thousand sons,but they do not belong to him as an individual: any of them is equallythe son of any citizen, and so will be equally neglected by them all. Be- 40sides, each says "mine" of whoever among the citizens is doing well or 1262•badly10 in this sense, that he is whatever fraction he happens to be of acertain number. What he really means is "mine or so-and-so's," refer-ring in this way to each of the thousand or however many who constitutethe city-state. And even then he is uncertain, since it is not clear who hashad a child born to him, or one who once born survived. Yet is this way Sof calling the same thing "mine" as practiced by each of two or ten thou-sand people really better than the way they in fact use "mine" in citystates? For the same person is called "my son" by one person, "mybrother" by another, "my cousin" by a third, or something else in virtue 10of some other connection of kinship or marriage, one's own marriage, inthe first instance, or that of one's relatives. Still others call him "my fel-low clansman" or "my fellow tribesman." For it is better to have a cousinof one's own than a son in the way Socrates describes. Moreover, it is impossible to prevent people from having suspicionsabout who their own brothers, sons, fathers, and mothers are. For the re- ISsemblances that occur between parents and children will inevitably betaken as evidence of this. And this is what actually happens, according tothe reports of some of those who write accounts of their world travels.They say that some of the inhabitants of upper Libya have their womenin common, and yet distinguish the children on the basis of their resem- 20blance to their fathers. 11 And there are some women, as well as some females of other species such as mares and cows, that have a strong naturaltendency to produce offspring resembling their sires, like the mare inPharsalus called "Just."12
9. For example, someone might have official responsibility for or a special in terest in some common property.10. See Republic 463e2-5.1 1 . See Herodotus IV. 1 80. At Rh. 1360'33-35, Aristotle comments on the util ity of such travel writings in drafting laws.1 2 . She is called "Just" because in producing offspring like the sire, she made a just return on his investment, and showed herself to be a virtuous and faith ful wife. See HA 586'12-14. Pharsalus was in Thessaly in northern Greece. 30 Politics II
Chapter 4 Moreover, there are other difficulties that it is not easy for the establish- 25 ers of this sort of community to avoid, such as voluntary or involuntary homicides, assaults, or slanders. None of these is pious when committed against fathers, mothers, or not too distant relatives (just as none is even against outsiders).13 Yet they are bound to occur even more frequently 30 among those who do not know14 their relatives than among those who do. And when they do occur, the latter can perform the customary expi ation, whereas the former cannot. It is also strange that while making sons communal, he forbids sexual intercourse only between lovers, 15 but does not prohibit sexual love itself or the other practices which, between father and son or a pair of broth- 35 ers, are most indecent, since even the love alone is. It is strange, too, that Socrates forbids such sexual intercourse solely because the pleasure that comes from it is so intense, but regards the fact that the lovers are father 40 and son or brother and brother as making no difference. 16 It would seem more useful to have the farmers rather than the guardians share their women and children . 17 For there will be lessJ262h friendship where women and children are held in common.18 But it is the ruled who should be like that, in order to promote obedience and prevent rebellion. In general, the results of such a law are necessarily the opposite of 5 those of a good law, and the opposite of those that Socrates aims to achieve by organizing the affairs of children and women in this way. For we regard friendship as the greatest of goods for city-states, since in this condition people are least likely to factionalize. And Socrates himself
13. Reading hosper kai pros apothen with the mss. The sentence is ambiguous, even if kai is omitted, as it is by Ross and Dreizehnter. But it cannot mean or imply that homicides, assaults, and slanders are pious when committed against outsiders. The implication is that these acts are particularly impious when committed against relatives, since even against outsiders they are so. See Plato, Laws 868c-873c. 14. Reading gnorizont011 with Dreizehnter and the mss. 1 5 . Homosexual male lovers are meant. 16. See Republic 403a--c. 17. The ideal city-state described in the Republic has three parts, producers (farmers), guardians, and philosopher-kings. The latter two share their women, children, and other property in common. The text is less clear about whether this is also true of the producers. See 1 264'1 1-bS. 18. Perhaps for the sort of reason given at 1 263'8-21. Chapter 4 31
Chapter 5 The next topic to investigate is property, and how those in the best con stitution should arrange it. Should it be owned in common, or not? One could investigate these questions even in isolation from the legislation dealing with women and children. I mean even if women and children1263" belong to separate individuals, which is in fact the practice everywhere, it still might be best for property either to be owned or used commu nally. For example, [ 1 ] the land might be owned separately, while the crops grown on it are communally stored and consumed (as happens in some nations). [2] Or it might be the other way around: the land might 5 be owned and farmed communally, while the crops grown on it are di vided up among individuals for their private use (some non-Greeks are also said to share things in this way). [3) Or both the land and the crops might be communal. If the land is worked by others, the constitution is different and eas ier. But if the citizens do the work for themselves, property arrange- 10 ments will give rise to a lot of discontent. For if the citizens happen to be unequal rather than equal in the work they do and the profits they enjoy, accusations will inevitably be made against those who enjoy or take a lot but do little work by those who take less but do more. It is generally dif- 15 ficult to live together and to share in any human enterprise, particularly in enterprises such as these. Travelers away from home who share a jour ney together show this clearly. For most of them start quarreling because they annoy one another over humdrum matters and little things. More over, we get especially irritated with those servants we employ most reg- 20 ularly for everyday services. These, then, and others are the difficulties involved in the common ownership of property. The present practice, provided it was enhanced by virtuous character22 and a system of correct laws, would be much su perior. For it would have the good of both-by "of both" I mean of the 25 common ownership of property and of private ownership. For while property should be in some way communal, in general it should be pri vate. For when care for property is divided up, it leads not to those mutual accusations, but rather to greater care being given, as each will be attending to what is his own. But where use is concerned, virtue will ensure that it is governed by the proverb "friends share everything in 30 common."
evils people will lose through sharing, but also how many good things. The life they would lead seems to be totally impossible. One has to think that the reason Socrates goes astray is that his as- 30 sumption is incorrect. For a household and a city-state must indeed be a unity up to a point, but not totally so. For there is a point at which it will, as it goes on, not be a city-state, and another at which, by being nearly not a city-state, it will be a worse one. It is as if one were to reduce a har- 35 mony to a unison, or a rhythm to a single beat. But a city-state consists of a multitude, as we said before,27 and should be unified and made into a community by means of education. It is strange, at any rate, that the one who aimed to bring in education, and who believed that through it the city-state would be excellent, should think to set it straight by mea sures of this sort, and not by habits, philosophy, and laws28-as in Sparta and Crete, where the legislator aimed to make property communal by 40 means of the MESSES.1 264• And we must not overlook this point, that we should consider the im- mense period of time and the many years during which it would not have gone unnoticed if these measures were any good. For practically speaking all things have been discovered, 29 although some have not been collected, and others are known about but not used. The matter would 5 become particularly evident, however, if one could see such a constitu tion actually being instituted. For it is impossible to construct his city state without separating the parts and dividing it up into common messes or into clans and tribes. Consequently, nothing else will be legis lated except that the guardians should not do any farming, which is the 10 very thing the Spartans are trying to enforce even now. But the fact is that Socrates has not said, nor is it easy to say, what the arrangement of the constitution as a whole is for those who participate in it. The multitude of the other citizens constitute pretty well the entire multitude of his city-state, yet nothing has been determined about them,
27. At 1261•18. 28. Good habits promote the virtues of character; philosophy, here probably to be understood fairly loosely, promotes the virtues of thought, and the good use of LEISURE; laws sustain both. 29. See also 1329h25-35. Two of Aristotle's other views explain this otherwise implausible claim: ( I ) The world and human beings have always existed (Mete. 3 52bl6-17, GA 7 3 J h24-732•3, 742hJ7-743• 1 , DA 4 1 5•2S-h7). (2) Human beings are naturally adapted to form largely reliable beliefs about the world and what conduces to their welfare in it (Metaph. 993•30-hl l , Rh. 1355'1 5-17). Chapter 5 35
whether the farmers too should have communal property or each his 15own private property, or whether their women and children should beprivate or communal. 30 If all is to be common to all in the same way, howwill they differ from the guardians? And how will they benefit from submitting to their rule? Or what on earth will prompt them to submit toit-unless the guardians adopt some clever stratagem like that of theCretans? For the Cretans allow their slaves to have the same other things 20as themselves, and forbid them only the gymnasia and the possession ofweapons. On the other hand, if they31 too are to have such things, as theydo in other city-states, what sort of community will it be? For it will inevitably be two city-states in one, and those opposed to one another. 32 25For he makes the guardians into a sort of garrison, and the farmers,craftsmen, and the others into the citizens. 33 Hence the indictments,lawsuits, and such other bad things as he says exist in other city-stateswill all exist among them. And yet Socrates claims that because of theireducation they will not need many regulations, such as town or market 30ordinances and others of that sort. Yet he gives this education only to theguardians. 34 Besides, he gives the farmers authority over their property,although he requires them to pay a tax.35 But this is likely to make themmuch more difficult and presumptuous than the helots,36 serfs, andslaves that some people have today. 35 But be that as it may, whether these matters are similarly essential ornot, nothing at any rate has been determined about them; neither are therelated questions of what constitution, education, and laws they willhave. The character of these people is not easy to discover, and the difference it makes to the preservation of the community of the guardiansis not small. But if Socrates is going to make their women communaland their property private, who will manage the household in the way 12641
30. Aristotle is justified in thinking that Socrates is vague about this. Farmers initially seem to have a traditional family life and to possess private prop erty. But casual remarks at 433d and 454d--e suggest that this may not be so, that female producers will not necessarily be housewives, but will be trained in the craft for which their natural aptitude is highest.3 1 . The citizens other than the guardians.32. This is a criticism that Socrates brings against other city-states at Republic 422e-423b.33. See Republic 4 1 5a-417b, 4 19a-42l c, 543b--c.34. See Republic 424a-426e.3 5 . See Republic 4 16d--e.36. Helots were the serf population of Sparta. 36 Politics II
the men manage things in the fields? Who will manage it, indeed, if the farmers' women and property are communal? It is futile to draw a com parison with wild beasts in order to show that women should have the5 same way of life as men: wild beasts do not go in for household manage ment.37 The way Socrates selects his rulers is also risky. He makes the same people rule all the time, which becomes a cause of conflict even among people with no merit, and all the more so among spirited and warlike10 men. 38 But it is evident that he has to make the same people rulers, since the gold from the god has not been mixed into the souls of one lot of people at one time and another at another, but always into the same ones. He says that the god, immediately at their birth, mixed gold into the souls of some, silver into others, and bronze and iron into those who are15 going to be craftsmen and farmers. Moreover, even though Socrates deprives the guardians of their hap piness, he says that the legislator should make the whole city-state happy.39 But it is impossible for the whole to be happy unless all, most, or some of its parts are happy. For happiness is not made up of the same20 things as evenness, since the latter can be present in the whole without being present in either of the parts,40 whereas happiness cannot. But if the guardians are not happy, who is? Surely not the skilled craftsmen or the multitude of VULGAR CRAFTSMEN. These, then, are the problems raised by the constitution Socrates de-25 scribes, and there are others that are no less great.
Chapter 6 Pretty much the same thing holds in the case of the Laws, which was written later, so we had better also briefly examine the constitution
there. In fact, Socrates has settled very few topics in the Republic: theway in which women and children should be shared in common; the sys-tem of property; and the organization of the constitution. For he divides 30the multitude of the inhabitants into two parts: the farmers and the defensive soldiers. And from the latter he takes a third, which is the part ofthe city-state that deliberates and is in authorityY But as to whether thefarmers and skilled craftsmen will participate in ruling to some extent ornot at all, and whether or not they are to own weapons and join in bat- JStie-Socrates has settled nothing about these matters.42 He does think,though, that guardian women should join in battle and receive the sameeducation as the other guardians. Otherwise, he has filled out his account with extraneous discussions,43 including those about the sort ofeducation the guardians should receive. 40 Most of the Laws consist, in fact, of laws, and he has said little about 1265"the constitution. He wishes to make it more generally attainable by ac-tual city-states,44 yet he gradually turns it back toward the other constitutionY For, with the exception of the communal possession of womenand property, the other things he puts in both constitutions are the Ssame: the same education,46 the life of freedom from necessary work,47and, on the same principles, the same messes--except that in this constitution he says that there are to be messes for women too;48 andwhereas the other one consisted of one thousand weapon owners, thisone is to consist of five thousand.49 All the Socratic dialogues have some- 10thing extraordinary, sophisticated, innovative, and probing about them;but it is perhaps difficult to do everything well. Consider, for example,the multitude just mentioned. We must not forget that it would need aterritory the size of Babylon or some other unlimitedly large territory to
15 keep five thousand people in idleness, and a crowd of women and ser vants along with them, many times as great. We should assume ideal conditions, to be sure, but nothing that is impossible. It is stated that a legislator should look to just two things in establish- 20 ing his laws: the territory and the people. 5° But it would also be good to add the neighboring regions too, if first, the city-state is to live a politi cal life, 51 not a solitary one; for it must then have the weapons that are useful for waging war not only on its own territory but also against the 25 regions outside it. But if one rejects such a life, both for the individual and for the city-state in common, the need to be formidable to enemies is just as great, both when they are invading its territory and when they are staying away from it. 52 The amount of property should also be looked at, to see whether it would not be better to determine it differently and on a clearer basis. He says that a person should have as much as he needs in order to live tem- 30 perately, which is like saying "as much as he needs to live well." For the formulation is much too general. Besides, it is possible to live a temper ate life but a wretched one. A better definition is "temperately and gen erously"; for when separated, the one will lead to poverty, the other to luxury. For these are the only choiceworthy states that bear on the use of 35 property. One cannot use property either mildly or courageously, for ex ample, but one can use it temperately and generously. Hence, too, the states concerned with its use must be these. It is also strange to equalize property and not to regulate the number 40 of citizens, leaving the birth rate unrestricted in the belief that the exis tence of infertility will keep it sufficiently steady no matter how many births there are, because this seems to be what happens in actual city-1265b states.53 But the same exactness on this matter is not required in actual city-states as in this one. For in actual city-states no one is left destitute, because property can be divided among however great a number. But, in this city-state, property is indivisible,54 so that excess children will nee-
50. This is not said anywhere in our text of the Laws, but Aristotle may be in ferring it from 704a-709a, 747d, 842c-e. His subsequent criticisms overlook 737d, 758c, 949e ff. 5 1 . City-states typically lead a political life in part by interacting with other city-states ( 1 327b3-6), but even isolated city-states can lead such a life pro vided their parts interact appropriately ( 132Sb23-27). 52. Reading apousin with Bender. The mss. have apelthousin: "when they are leaving it." The political life is discussed in the Introduction xlvi-xlvii. 53. Aristotle apparently overlooks Laws 736a, 740b-74 la, 923d. 54. See Laws 740b, 74 lb, 742c, 855a-b, 856d-e. Chapter 6 39
essarily get nothing, no matter whether they are few or many. One might 5well think instead that it is the birth rate that should be limited, ratherthan property, so that no more than a certain number are born. (Oneshould fix this number by looking to the chances that some of those bornwill not survive, and that others will be childless.) To leave the numberunrestricted, as is done in most city-states, inevitably causes poverty 10among the citizens; and poverty produces faction and crime. In fact,Pheidon of Corinth,55 one of the most ancient legislators, thought thatthe number of citizens should be kept the same as the number of house-hold estates, even if initially they all had estates of unequal size. But in 15the Laws, it is just the opposite. 56 Our own view as to how these thingsmight be better arranged, however, will have to be given later.57 Another topic omitted from the Laws concerns the rulers: how theywill differ from the ruled. He says that just as warp and woof come fromdifferent sorts of wool, so should ruler be related to ruled. 58 Further- 20more, since he permits a person's total property to increase up to fivetimes its original value, 59 why should this not also hold of land up to acertain point? The division of homesteads also needs to be examined, incase it is disadvantageous to household management. For he assigns twoof the separate homesteads resulting from the division to each individ-ual; but it is difficult to run two households.60 25 The overall organization tends to be neither a democracy nor an oligarchy but midway between them; it is called a POLITY, since it is madeup of those with HOPLITE weapons.61 If, of the various constitutions, heis establishing this as the one generally most acceptable to actual citystates, his proposal is perhaps good, but if as next best after the first con- 30
stitution, it is not goodY For one might well commend the Spartan con stitution, or some other more aristocratic one. Some people believe, in- 35 deed, that the best constitution is a mixture of all constitutions, which is why they commend the Spartan constitution. For some say that it is made up of oligarchy, monarchy, and democracy; they say the kingship is a monarchy, the office of senators an oligarchy, and that it is governed democratically in virtue of the office of the overseers (because the over seers are selected from the people as a whole). Others of them say that 40 the overseership is a tyranny, and that it is governed democratically be cause of the messes and the rest of daily life.63 But in the Laws it is said1266" that the best constitution should be composed of democracy and tyranny, constitutions one might well consider as not being CONSTITU TIONS at all, or as being the worst ones of all. 64 Therefore, the proposal of those who mix together a larger number is better, because a constitu- 5 tion composed of a larger number is better. 65 Next, the constitution plainly has no monarchical features at all, but only oligarchic and democratic ones, with a tendency to lean more toward oligarchy. This is clear from the method of selecting officials. For to select by lot from a previously elected pool is common to both. But it is oli garchic to require richer people to attend the assembly, to vote for offi- 10 cials, and to perform any other political duties, without requiring these things of the others.66 The same is true of the attempt to ensure that the majority of officials come from among the rich, with the most important ones coming from among those with the highest PROPERTY ASSESSMENTY
62. Plato seems to have chosen his constitution for both reasons (Laws 739a ff., 745e ff., 805b--d, 853c). 63. See 1 294hl 3-40. On senators, kings, and overseers, see 11.9 and notes. 64. Plato describes monarchy (not tyranny) and democracy as the "mothers" of all constitutions (Laws 693d-e). He describes the constitution he is propos ing, which is not the best but the second best, as a mean between monarchy and democracy (756e). In the Republic, where he sets out the best constitu tion, he agrees with Aristotle that democracy and tyranny are the worst con stitutions possible (580a-c). 65. The conclusion hardly follows. But the point is perhaps this: a constitution in which principles drawn from a large number of other constitutions are mixed will serve the interests of more citizens (whatever their own political leanings) and so will be more stable ( 1 270h17-28) and more just ( 1 294' 1 5-25). 66. See Laws 756b-e, 763d-767d, 9 5 1 d-e. 67. This is true of the market and city-state managers but it is not so clearly true of other important officials. See Laws 753b--d , 755b--756b, 766a-c, 946a. Chapter 7 41
Chapter 7There are other constitutions, too, proposed either by private individu-als or by philosophers and statesmen. But all of them are closer to theestablished constitutions under which people are actually governed thaneither of Plato's. For no one else has ever suggested the innovations ofsharing children and women, or of messes for women.71 Rather, they 35begin with the necessities. Some of them hold, indeed, that the most important thing is to have property well organized, for they say that it isover property that everyone creates faction. That is why Phaleas of Chalcedon,72 the first to propose such a constitution, did so; for he says thatthe property of the citizens should be equal. He thought this was not 40difficult to do when city-states were just being founded, but that in those 1 266balready in operation it would be more difficult. Nonetheless, he thoughtthat a leveling could very quickly be achieved by the rich giving but not
receiving dowries, and the poor receiving but not giving them. (Plato,5 when writing the Laws, thought that things should be left alone up to a certain point, but that no citizen should have more than five times the smallest amount, as we also said earlier-)13 However, people who make such laws should not forget, as in fact they do, that while regulating the quantity of property they should regulate the quantity of children too.10 For if the number of children exceeds the amount of property, it is cer tainly necessary to abrogate the law. But abrogation aside, it is a bad thing for many to become poor after having been rich, since it is a task to prevent people like that from becoming revolutionaries.15 That leveling property has some influence on political communities was evidently understood even by some people long ago; for example, both by Solon in his laws/4 and the law in force elsewhere which pro hibits anyone from getting as much land as he might wish. Laws likewise prevent the sale of property, as among the Locrians75 where the law for-20 bids it unless an obvious misfortune can be shown to have occurred. In yet other cases it is required that the original allotments be preserved in tact. It was the abrogation of this provision, to cite one example, that made the constitution of Leucas76 too democratic, since as a result men no longer entered office from the designated assessment classes. But25 equality of property may exist and yet the amount may be too high, so that it leads to luxurious living, or too low, so that a penny-pinching life results. It is clear, then, that it is not enough for the legislator to make property equal, he must also aim at the mean. Yet even if one prescribed a moderate amount for everyone, it would be of no use. For one should level desires more than property, and that cannot happen unless people30 have been adequately educated by the laws. 77 Phaleas would perhaps reply that this is actually what he means; for he thinks that city-states should have equality in these two things: prop erty and education. But one also ought to say what the education is going to be. And it is no use for it be one and the same. For it can be one35 and the same, but of the sort that will produce people who deliberately choose to be ACQUISITIVE of money or honor or both. Besides, people re-
73. At 1 26Sb21-23. 74. Discussed at 1273h3S-1 274"2 1 . 7 5 . A Greek settlement in southern Italy. Their legislator Zaleucus (mentioned at 1274'22- 3 1 ) was famous for trying to reduce class conflict, and may have been the author of the law in question. 76. A Corinthian colony founded in the seventh century. 77. See 1337'10-32, NE 1 179'33-1 1 8 1 b23. Chapter 7 43
78. Homer, Iliad IX. 3 1 9. Achilles is complaining that if his war prizes can be taken away by Agamemnon, then noble and base are being honored to the same degree.79. The pleasure of satisfying one's hunger comes in part from alleviating the pains of hunger, but other pleasures need involve no pain. See NE 1 1 73bl 3-20; Plato, Republic 359c, 373a-d, 583b-588a.80. Reading autim with some mss. Alternatively (Ross and Dreizehnter): "if any one should wish to find enjoyment through themselves (hautim). " But this makes Aristotle's proposed cure irrelevant to its target.8 1 . On Aristotle's view there are two relevant candidate pleasures-the pleasure of practical political activity and the pleasure of philosophical contempla tion. The former, however, which involves living a life with other people, in volves pain, while the latter, which is compatible with living a solitary life, does not. The contrast is particularly clear at NE 1 177'22-b26. 44 Politics II
82. A wealthy money-changer who united Atarneus and Assos (two strongholds on the coast of Asia Minor) into a single kingdom, which was attacked by the Persian general Autophradates c. 350, and where Aristotle lived in the late 340s. 83. An obol is one sixth of a drachma. The two-obol payment (diobelia) was in troduced after the fall of the oligarchy of 41 1 I 10. It seems to have been, in effect, a form of poor relief. See Ath. XXVIII. 3. 84. See 1257b40-1258'14. Chapter S 45
Chapter 8Hippodamus of Miletus, the son of Euryphon, invented the division ofcity-states and laid out the street plan for Piraeus. 86 His love of honorcaused him also to adopt a rather extraordinary general lifestyle. Somepeople thought he carried things too far, indeed, with his long hair, ex- 25pensive ornaments, and the same cheap warm clothing worn winter andsummer. He also aspired to understand nature as a whole, and was thefirst person, not actually engaged in politics, to attempt to say somethingabout the best constitution. The city-state he designed had a multitude of ten thousand citizens, 30divided into three parts. He made one part the craftsmen, another thefarmers, and a third the defenders who possess the weapons. He also divided the territory into three parts: sacred, public, and private. Thatwhich provided what is customarily rendered to the gods would be sacred; that off which the defenders would live, public; and the land be- JSlonging to the farmers, private. He thought that there are just threekinds of law, since the things lawsuits arise over are three in number: ARROGANT behavior, damage,87 and death. He also legislated a single courtwith supreme authority, consisting of a certain number of selected elders, to which all lawsuits thought to have not been well decided are tobe referred. He thought that verdicts in law courts should not be ren- 40
85. Epidamnus in the Adriatic was a colony of Corinth and Corcyra founded in the seventh century. The identity of Diophantus is uncertain, and his scheme otherwise unknown.86. Hippodamus was a fifth-century legislator and city-state planner. Around the middle of the fifth century he went as a colonist to Italy, where he laid out the city-state ofThurii. Piraeus is the harbor area near Athens. Aristotle comments on city-state planning at 1330h29-3 1 .87. blabin: covering both personal injury and damage to property. 46 Politics II
1268• dered by casting ballots. Rather, each juror should deposit a tablet: if he convicts unqualifiedly, he should write the penalty on the tablet; if he acquits unqualifiedly, he should leave it blank; if he convicts to some ex tent and acquits to some extent, he should specify that. For he thought S that present legislation is bad in this regard, because it forces jurors to violate their judicial oath by deciding one way or the other. 88 Moreover, he established a law that those who discovered something beneficial to the city-state should be honored, and one another that children of those who died in war should receive support from public funds. He assumed that this had not been legislated elsewhere, whereas in reality such a law 10 existed both in Athens and in some other city-states. All the officials were to be elected by the people, and the people were to be made up of the city-state's three parts. Those elected should take care of commu nity, foreign affairs, and orphans. These, then, are most of the features 1S of Hippodamus' organization, and the ones that most merit discussion. The first problem is the division of the multitude of citizens. The craftsmen, farmers, and those who possess weapons all share in the con stitution. But the fact that the farmers do not possess weapons, and that the craftsmen possess neither land nor weapons, makes them both virtu- 20 ally slaves of those who possess weapons. So it is impossible that every office be shared. For the generals, civic guards, and practically speaking all the officials with the most authority will inevitably be selected from those who possess weapons. But if the farmers and craftsmen cannot participate, how can they possibly have any friendly feelings for the con- 25 stitution? "But those who possess weapons will need to be stronger than both the other parts." Yet that is not easy to arrange unless there are lots of them. And, in that case, is there any need to have the others partici pate in the constitution or have authority over the selection of officials? Besides, what use are the farmers to Hippodamus' city-state? Skilled 30 craftsmen are necessary (every city-state needs them), and they can sup port themselves by their crafts, as in other city-states. It would be rea sonable for the farmers to be a part of the city-state, if they provided
88. In Athenian law juries decided guilt or innocence by casting a ballot. The penalty for some crimes was prescribed by law. For others, the jury had to choose between a penalty proposed by the prosecutor and a counterpenalty proposed by the defendant. In neither case could a juror propose some penalty of his own devising. Hippodamus is proposing to give a juror more discretion in both sorts of cases. Jurors in Athens took a judicial oath to ren der the most just verdict possible. Chapter 8 47
food and sustenance for those who possess weapons. But, as thingsstand, they have private land and farm it privately. Next, consider the public land, which is to feed the defenders. If they 35themselves farm it, the fighting part will not be different from the farm-ing one, as the legislator intends. And if there are going to be some oth-ers to do so, different from those who farm privately and from the warriors, they will constitute a fourth part in the city-state that participatesin nothing and is hostile to the constitution. Yet if one makes those who 40farm the private land and those who farm the public land the same, thequantity of produce from each one's farming will be inadequate for twohouseholds. 89 Why will they not at once feed themselves and the soldiers 1268hfrom the same land and the same allotments? There is a lot of confusionin all this. The law about verdicts is also bad, namely, the requirement that thejuror should become an ARBITRATOR and make distinctions in his decisions, though the charge is written in unqualified terms. This is possible Sin arbitration, even if there are lots of arbitrators, because they confertogether over their verdict. But it is not possible in jury courts; and, indeed, most legislators do the opposite and arrange for the jurors not toconfer with one another.90 How, then, will the verdict fail to be confused 10when a juror thinks the defendant is liable for damages, but not for asmuch as the plaintiff claims? Suppose the plaintiff claims twenty minas,but the juror awards ten (or the former more, the latter less), anotherawards five, and another four. It is clear that some will split the award in 1Sthis way, whereas some will condemn for the whole sum, and others fornothing. How then will the votes be counted? Furthermore, nothingforces the one who just acquits or convicts unqualifiedly to perjure him-self, provided that the indictment prescribes an unqualified penalty. Ajuror who acquits is not deciding that the defendant owes nothing, onlythat he does not owe the twenty minas. A juror who convicts without be- 20lieving that he owes the twenty minas, however, violates his oathstraightway. As for his suggestion that those who discover something beneficial tothe city-state should receive some honor, such legislation is sweet to lis-
89. Presumably, because of the lost efficiency of scale. One can produce less from two farms than from a single farm of the same acreage.90. Athenian juries of five hundred to one thousand members were not unusual. They gave their verdicts directly without conferring. 48 Politics II
ten to, but not safe.91 For it would encourage "sychophancy,"92 and 25 might perhaps lead to change in the constitution. But this is part of an other problem and a different inquiry. For some people93 raise the ques tion of whether it is beneficial or harmful to city-states to change their traditional laws, if some other is better. Hence if indeed change is not beneficial, it is not easy to agree right off with Hippodamus' suggestion, though it is possible someone might propose that the laws or the consti- 30 tution be dissolved on the grounds of the common good. Now that we have mentioned this topic, however, we had better ex pand on it a little, since, as we said, there is a problem here, and change may seem better. At any rate, this has certainly proved to be beneficial in the other sciences. For example, medicine has changed from its tradi- 35 tiona! ways, as has physical training, and the crafts and sciences gener ally. So, since statesmanship is held to be one of these, it is clear that something similar must also hold of it. One might claim, indeed, that the facts themselves provide evidence of this. For the laws or customs of the distant past were exceedingly simple and barbaric. For example, 40 the Greeks used to carry weapons and buy their brides from one an other. Moreover, the surviving traces of ancient law are completely1261)' naive; for example, the homicide law in Cyme says that if the prosecutor can provide a number of his own relatives as witnesses, the defendant is guilty of murder. Generally speaking, everyone seeks not what is tradi tional but what is good. But the earliest people, whether they were 5 "earth-born" or the survivors of some cataclysm, were probably like or dinary or foolish people today (and this is precisely what is said about the earth-born indeed}.94 So it would be strange to cling to their opin ions. Moreover, it is not better to leave even written LAWS unchanged. For just as it is impossible in the other crafts to write down everything 10 exactly, the same applies to political organizations. For the universal law must be put in writing, but actions concern particulars.
9 1 . Though Aristotle does favor such legislation in at least one kind of case, see 1309' 1 3-14. 92. By the middle of the fifth century some people in Athens, known as sycho phants, made a profession of bringing suits against others for financial, po litical, or personal reasons. Aristotle worries that Hippodamus' law will en courage sychophancy through giving people an incentive to pose as public benefactors by bringing false charges of sedition and the like against others. 93. See Herodotus 111.80; Plato, Laws 772a-d, Statesman 298c ff.; Thucydides 1.7 1 . 94. The cataclysm view i s expressed i n Plato, Laws 677a ff., Timaeus 22c ff. The earth-born are described at Statesman 272c-d and Laws 677b-678b. Chapter 9 49
Chapter 9There are two things to investigate about the constitution of Sparta, ofCrete, and, in effect, about the other constitutions also. First, is there 30anything legislated in it that is good or bad as compared with the best organization? Second, is there anything legislated in it that is contrary tothe fundamental principle or character of the intended constitution? It is generally agreed that to be well-governed a constitution shouldhave leisure from necessary tasks. But the way to achieve this is not easy 35to discover. For the Thessalian serfs often attacked the Thessalians, justas the helots-always lying in wait, as it were, for their masters' misfortunes-attacked the Spartans. Nothing like this has so far happened inthe case of the Cretans. Perhaps the reason is that, though they war with 40one another, the neighboring city-states never ally themselves with the 1269"rebels: it benefits them to do so, since they also possess SUBJECT PEOPLESthemselves. Sparta's neighbors, on the other hand, the Argives, Messe-nians, and Arcadians, were all hostile. The Thessalians, too, first experi- 5enced revolts because they were still at war with their neighbors, theAchaeans, Perrhaebeans, and Magnesians. If nothing else, it certainlyseems that the management of serfs, the proper way to live together with
them, is a troublesome matter. For if they are given license, they become arrogant and claim to merit equality with those in authority, but if they10 live miserably, they hate and conspire. It is clear, then, that those whose system of helotry leads to these results still have not found the best way. 96 Furthermore, the license where their women are concerned is also detrimental both to the deliberately chosen aims of the constitution and to the happiness of the city-state as well. For just as a household has a15 man and a woman as parts, a city-state, too, is clearly to be regarded as being divided almost equally between men and women. So in all consti tutions in which the position of women is bad, half the city-state should be regarded as having no laws. And this is exactly what has happened in Sparta. For the legislator, wishing the whole city-state to have en-20 durance, makes his wish evident where the men are concerned, but has been negligent in the case of the women. For being free of all con straint,97 they live in total intemperance and luxury. The inevitable re sult, in a constitution of this sort, is that wealth is esteemed.98 This is particularly so if the citizens are dominated by their women, like most25 military and warlike races (except for the Celts and some others who openly esteemed male homosexuality). So it is understandable why the original author of the myth of Ares and Aphrodite paired the two;99 for all warlike men seem obsessed with sexual relations with either men or30 women. That is why the same happened to the Spartans, and why in the days of their hegemony, many things were managed by women. And yet what difference is there between women rulers and rulers ruled by women? The result is the same. Audacity is not useful in everyday mat-35 ters, but only, if at all, in war. Yet Spartan women were very harmful even here. They showed this quite clearly during the Theban invasion;100 for they were of no use at all, like women in other city-states, 1 0 1 but caused more confusion than the enemy.
spite lengthy wars. Indeed, they say that there were once ten thousand Spartiates.105 Whether this is true or not, a better way to keep high the number of men in a city-state is by leveling property. But the law dealing with the procreation of children militates against this reform. For the127rJ legislator, intending there to be as many Spartiates as possible, encour ages people to have as many children as possible, since there is a law ex empting a father of three sons from military service, and a father of four from all taxes. But it is evident that if many children are born, and the S land is correspondingly divided, many people will inevitably become poor. Matters relating to the board of overseers 106 are also badly organized. For this office has sole authority over the most important matters; but the overseers are drawn from among the entire people, so that often very 10 poor men enter it who, because of their poverty, are107 open to bribery. (This has been shown on many occasions in the past too, and recently among the Andrians; for some, corrupted by bribes, did everything in their power to destroy the entire city-state. 1 08) Moreover, because the of fice is too powerful-in fact, equal in power to a tyranny-even the kings were forced to curry favor with the overseers. And this too has IS harmed the constitution, for from an aristocracy a democracy was emerging. Admittedly, the board of overseers does hold the constitution to gether; for the people remain contented because they participate in the most important office. So, whether it came about because of the legisla- 20 tor or by luck, it benefits Spartan affairs. For if a constitution is to sur vive, every part of the city-state must want it to exist and to remain as it is. 109 And the kings want this because of the honor given to them; the noble-and-good, because of the senate (since this office is a reward of 25 virtue); and the people, because of the board of overseers (since selec-
tions for it are made from all). Still, though the overseers should be chosen from all, it should not be by the present method, which is exceedingly childish. 1 1 0 Furthermore, the overseers have authority over the most importantjudicial decisions, though they are ordinary people. Hence it would bebetter if they decided cases not according to their own opinion, but inaccordance with what is written, that is to say, laws. Again, the overseers' 30lifestyle is not in keeping with the aim of the constitution.111 For it involves too much license, whereas in other respects112 it is too austere, sothat they cannot endure it, but secretly escape from the law and enjoythe pleasures of the body. 1 13 35 Matters relating to the senate also do not serve the Spartans well. 1 14 Ifthe senators were decent people, with an adequate general education inmanly virtue, one might well say that this office benefits the city-state.Although, one might dispute about whether they ought to have lifelongauthority in important matters,115 since the mind has its old age as well asthe body. 1 16 But when they are educated in such a way that even the legis 40 1271•lator himself doubts that they are good men, it is not safe. And in fact inmany matters of public concern, those who have participated in this office have been conspicuous in taking bribes and showing favoritism. Thisis precisely why it is better that the senators not be exempt from INSPECTION, as they are at present. It might seem that the overseers should in 5spect every office, but this would give too much to the board of overseers,and is not the way we say inspections should be carried out. The method of electing senators is also defective. Not only is the selection made in a childish way, 117 but it is wrong for someone worthy of 10
1 1 0. The overseers may have been chosen by acclamation, like the senate, but it is also possible that they were chosen by lot. See Plato, Laws 692a.1 1 1 . Reading tes politeias with Scaliger. Alternatively: "not in keeping with the aim of the city-state (tes poleos)."1 12. en de tois a/lois: or "in the case of other people."1 1 3. See Plato, Republic 548b.1 14. The senate (gerousia) had 28 members in addition to the two kings (dis cussed below). All were over 60 years old, and were probably selected from aristocratic families. The senate prepared the agenda of the citizen assem bly, and had other political and judicial functions.1 1 5. The apparent conflict with the characterization of the overseers at 1270b28-29 is perhaps removed by 1 275b9-1 1 .1 1 6. See Rh. 1 389h1 3-1 390•24.1 1 7. Members of the senate were chosen by an elaborate process of acclamation. See 1 306•18-1 9, Plutarch, Lycurgus XXVI. 54 Politics II
the office to ask for it: a man worthy of the office should hold it whether he wants to or not. But the fact is that the legislator is evidently doing the same thing here as in the rest of the constitution. He makes the citi zens love honor and then takes advantage of this fact in the election of 15 the senators; for no one would ask for office who did not love honor. Yet the love of honor and of money are the causes of most voluntary wrong doings among human beings. The question of whether or not it is better for city-states to have a kingship must be discussed later;ll8 but it is better to choose each new 20 king, not as now, 119 but on the basis of his own life. (It is clear that even the Spartan legislator himself did not think it possible to make the kings noble-and-good. At any rate he distrusts them, on the grounds that they are not sufficiently good men. That is precisely why they used to send out a king's opponents as fellow ambassadors, and why they regard fac- 25 tion between the kings as a safeguard for the city-state.) Nor were matters relating to the messes (or so-called phiditia) well legislated by the person who first established them. For they ought to be publicly supported, as they are in Crete. 120 But among the Spartans each individual has to contribute, even though some are extremely poor and 30 unable to afford the expense. The result is thus the opposite of the legis lator's deliberately chosen aim. He intended the institution of messes to be democratic, but, legislated as they are now, they are scarcely democ ratic at all, since the very poor cannot easily participate in them. Yet 35 their traditional way of delimiting the Spartan constitution is to exclude from it those who cannot pay this contribution. The law dealing with the admirals has been criticized by others, and rightly so, since it becomes a cause of faction.121 For the office of admiral is established against the kings, who are permanent generals, as pretty 40 much another kingship. One might also criticize the fundamental principle of the legislator as1271b Plato criticized it in the Laws.122 For the entire system of their laws aims at a part of virtue, military virtue, since this is useful for conquest. So, as
1 1 8. At 111. 14-17. 1 19. Sparta had two hereditary kings, each descended from a different royal house, both of whom were members of the senate and ruled for life. They had a military as well as a political and religious function. 1 20. See 1 272' 1 2-27. 1 2 1 . For examples, see 1301h18-2 1 , 1306h3 1-33. 1 22. At 625c-638b. Chapter 10 55
long as they were at war, they remained safe. But once they ruledsupreme, they started to decline, because they did not know how to be atleisure, and had never undertaken any kind of training with more 5AUTHORITY than military training. Another error, no less serious, is thatalthough they think (rightly) that the good things that people competefor are won by virtue rather than by vice, they also suppose (not rightly)that these GOODS are better than virtue itself.123 Matters relating to public funds are also badly organized by the Spar- 10tiates. For they are compelled to fight major wars, yet the public treasuryis empty, and taxes are not properly paid; for, as most of the land belongsto the Spartiates, they do not scrutinize one another's tax payments. 124Thus the result the legislator has produced is the opposite of beneficial: IShe has made his city-state poor and the private individuals into lovers ofmoney. So much for the Spartan constitution. For these are the things onemight particularly criticize in it.
Chapter 1 0The Cretan constitution closely resembles that of the Spartans; in some 20small respects it is no worse, but most of it is less finished. For it seems,or at any rate it is said, 125 that the constitution of the Spartans is largelymodeled on the Cretan; and most older things are less fully elaboratedthan newer ones. They say that after Lycurgus relinquished theguardianship of King Charillus126 and went abroad, he spent most of his 25time in Crete, because of the kinship connection. For the Lyctians werecolonists from Sparta, and those who went to the colony adopted the organization of the laws existing among the inhabitants at that time. Henceeven now their subject peoples employ these laws, in the belief that 30Minos127 first established the organization of the laws. The island seems naturally adapted and beautifully situated to rule
123. This criticism of Sparta and other oligarchies is repeated with various elaborations and emphases at 1334'2-h5, 1324h5-1 1 , l 3 33b5-1 l .124. Thucydides 1. 132 tells u s that the regular custom o f the Spartans was "never to act hastily in the case of a Spartan citizen and never to come to any irrevocable decision without indisputable proof."125. See Herodotus 1.65; Plato, Minos 3 18c-d, 320a, b.126. The posthumous son of Lycurgus' elder bother King Polydectes.127. Semimythical Cretan king, husband of Pasiphae, the mother of the Mino taur. 56 Politics II
the Greek world since it lies across the entire sea on whose shores most 35 of the Greeks are settled. In one direction it is not far from the Pelopon nese, and in the other from Asia (the part around Cape Triopium) and from Rhodes. That is why Minos established his rule over the sea too, subjugating some islands, establishing settle -:1ents on others, and finally attacking Sicily, where he met his death near Camicus.128 40 The Cretan way of organizing things is analogous to the Spartan. The helots do the farming for the latter, the subject peoples for the former.1272" Both places have messes (in ancient times, the Spartans called these an dreia rather than phiditia, 129 like the Cretans-a clear indication that they came from Crete). Besides, there is the organization of the constitution. For the overseers have the same powers as the order keepers (as they are 5 called in Crete), except that the overseers are five in number and the order keepers ten. The senators correspond to the senators, whom the Cretans call the council. The Cretans at one time had a kingship, but later they did away with it, and the order keepers took over leadership in war. 10 All Cretans participate in the assembly, but its authority is limited to vot ing together for the resolutions of the senators and order keepers. Communal meals are better handled among the Cretans than among the Spartans. In Sparta, as we said earlier, 130 each person must con tribute a fixed amount per capita; if he does not, a law prevents him from 15 participating in the constitution. In Crete, on the other hand, things are done more communally. Out of all the public crops and livestock and the tributes paid by the subject peoples, one part is set aside for the gods 20 and for PUBLIC SERVICES, and another for the messes, so that all women and children and men-are fed at public expense. 131 The legisla tor regarded frugality as beneficial and gave much thought to securing it, and to the segregation of women, so as to prevent them from having many children, and to finding a place for sexual relations between men. There will be another opportunity to examine whether this was badly 25 done or not.132 It is evident, then, that the messes have been better orga nized by the Cretans than by the Spartans.
Matters relating to the order keepers, on the other hand, are even lesswell organized than those relating to the overseers. For the board oforder keepers shares the defect of the board of overseers (that it is composed of ordinary people), but the benefit to the constitution there is ab- 30sent here. For there the people participate in the most important office,and so wish the constitution to continue, because the election is fromall.133 But here the order keepers are elected not from all but from cer-tain families, and the senators are elected from those who have beenorder keepers. And the same remarks might be made about the senators 35as about those who become senators in Sparta: their exemption from inspection and their life tenure are greater prerogatives than they merit,and it is dangerous that they rule not in accordance with what is writtenbut according to their own opinion. The fact that the people remain quiescent even though they do notparticipate is no indication that it has been well organized. For unlike 40the overseers, the order keepers have no profit, because they live on anisland, far away, at least, from any who might corrupt them. The remedy !272hthey use for this offense is also strange, not political but characteristic ofa DYNASTY. For the order keepers are frequently expelled by a conspir-acy either of their colleagues themselves or of private individuals. Orderkeepers are also allowed to resign before their term has expired. But Ssurely it is better if all these things should take place according to LAWand not human wish, which is not a safe standard. Worst of all, however, is the suspension of order keepers, 134 oftenbrought about by the powerful, when they are unwilling to submit tojustice. For this makes it clear that whereas the organization has something of a constitution about it, yet it is not a constitution but more of adynasty. Their habit is to divide the people and their own friends, create !0anarchy, 135 form factions, and fight one another. Yet how does this sort ofthing differ from such a city-state ceasing temporarily to be a city-state,and the political community dissolving? A city-state in this condition isin danger, since those who wish to attack it are also able to so. But, as we ISsaid, Crete's location saves it, since its distance has served to keep foreigners out. 136 This is why the institution of subject peoples survives
among the Cretans, whereas the helots frequently revolt. For the Cre tans do not rule outside their borders-though a foreign war has recently 20 come to the island, which has made the weakness of its laws evident. 137 So much for this constitution.
Chapter 1 1 The Carthaginians also are thought to be well-governed, and in many 25 respects in an extraordinary way (compared to others), though in some respects closely resembling the Spartans. For these three constitutions, the Cretan, Spartan, and, third, the Carthaginian, are all in a way close to one another and very different from others. Many of their arrange ments work well for them, and it is an indication that their constitution 30 is well organized that the people willingly138 stick with the way the con stitution is organized, and that no faction even worth talking about has arisen among them, and no tyrant. Points of similarity to the Spartan constitution are these. The com panions' messes are like the phiditia; the office of the one-hundred- 35 and-four is like that of the overseers, except that it is not worse (for the overseers are drawn from ordinary people, whereas they elect to this of fice on the basis of merit). Their kings and senate are analogous to those of Sparta; but it is better that the kings are neither from the same family nor from a chance one; but if any family distinguishes itself, then the kings are elected from its members, rather than selected on the basis of 40 seniority. For they have authority in important matters, and if they are insignificant people, they do a lot of harm to the city-state (as they al-1273• ready have done to the city-state of the Spartans). Most of the criticisms one might make because of its deviations from the best constitution are actually common to all the constitutions we have discussed. But of those that are deviations from the fundamental principle of an aristocracy or a POLITY,139 some deviate more in the di- S rection of democracy, others more in the direction of oligarchy. For the kings and senators have authority over what to bring and what not to
1 37. Outside dominions involve foreign wars, which are one cause of serf re volts. See 1269bS-7. 1 38. Reading hekousion with Dreizehnter. 139. A polity is a mixed constitution ( 1 26Sb26-28). Aristotle usually uses the term "aristocracy" to refer to a single component of a mixed constitution. But here-as at 1 294bl 0-1 1-he treats it and "polity" as equivalents. Chapter 1 1 59
bring before the people, provided they all agree; but if they do not, thepeople have authority over these matters also. Moreover, when theymake proposals, the people not only are allowed to hear the officials' resolutions, but have the authority to decide them; and anyone who wishes 10may speak against the proposals being made. This does not exist in theother constitutions. On the other hand, it is oligarchic that the boards of five, which haveauthority over many important matters, elect themselves, and elect tothe office of one-hundred, 1 40 which is the most important office. More-over, it is also oligarchic that they hold office longer than the others (for 15they rule before taking office and after they have left it). But we must re-gard it as aristocratic that they are neither paid nor chosen by lot, or anything else of that sort. And also that all legal cases are decided by theboards of five, and not, as in Sparta, some by some and others by others.141 20 But the major deviation of the organization of the Carthaginians awayfrom aristocracy and toward oligarchy is their sharing a view that is heldalso by the many: that rulers should be chosen not solely on the basis oftheir merit but also on the basis of their wealth, since poor people can-not afford the leisure necessary to rule well. Hence, if indeed it is oli- 25garchic to choose rulers on the basis of their wealth, and aristocratic tochoose them on the basis of their merit, then this organization, accord-ing to which the Carthaginians have organized matters relating to theconstitution, will be a third sort. For they elect to office with an eye toboth qualities, especially in the case of the most important officials, thekings and the generals. 30 But this deviation from aristocracy should be regarded as an error onthe part of their legislator. For one of the most important things is to seeto it from the outset that the best people are able to be at leisure and donothing unseemly, not only when in office but in private life. But even ifone must look to wealth too, in order to ensure leisure, still it is bad that 35
the most important offices, those of king and general, should be for sale. For this law gives more esteem to wealth than to virtue, and makes the entire city-state love money. For whatever those in authority esteem, the 40 opinion of the other citizens too inevitably follows theirs. Hence when virtue is not esteemed more than everything else, the constitution can-1 27Jh not be securely governed as an aristocracy. It is reasonable to expect too that those who have bought office will become accustomed to making a profit from it, when they rule by having spent money. For if a poor but decent person will want to profit from office, it would certainly be odd if a worse one, who has already spent money, will not want to. Hence those S who are able to rule best should rule.142 And even if the legislator ne glected the wealth of the decent people, he had better look to their leisure, at least while they are ruling. It would also seem to be bad to allow the same person to hold several offices, a thing held in high esteem among the Carthaginians. For one 10 task is best performed by one person. The legislator should see to it that this happens, and not require the same person to play the flute and make shoes. So, where the city-state is not small, it is more political, 143 and more democratic, if more people participate in the offices. For it is more widely shared, as we said, and each of the offices144 is better carried out IS and more quickly. (This is clear in the case of military and naval affairs, since in both of them ruling and being ruled extend through practically speaking everyone.) But though their constitution is oligarchic, they are very good at es caping faction by from time to time sending some part of the people out to the city-states to get rich.145 In this way they effect a cure, and give 20 stability to their constitution. But this is the result of luck, whereas they ought to be free of faction thanks to their legislator. As things stand, however, if some misfortune occurs and the multitude of those who are ruled revolt, the laws provide no remedy for restoring peace. This, then, is the way things stand with the Spartan, Cretan, and 2S Carthaginian constitutions, which are rightly held in high esteem.
Chapter 1 2Some of those who have had something to say about a constitution tookno part in political actions, but always lived privately. About them prettymuch everything worth saying has been said. Others became legislators, 30engaging in politics themselves, some in their own city-states, others inforeign ones as well. Some of these men crafted LAWS only, whereas oth-ers, such as Lycurgus and Solon, crafted a CONSTITUTION too, for theyestablished both laws and constitutions. We have already discussed that of the Spartans.146 As for Solon, some 35think he was an excellent legislator because: he abolished an oligarchywhich had become too unmixed; he put an end to the slavery of the com-mon people; 147 and he established the ancestral democracy, by mixingthe constitution well. For they think the council of the Areopagus is oligarchic;148 the election of officials aristocratic; and the courts democra- 40tic. But it seems that the first two, the council and the election of offi- 1274acials, existed already, and Solon did not abolish them. On the otherhand, by making law courts open to all, he did set up the democracy.That, indeed, is why some people criticize him. They say that when hegave law courts selected by lot authority over all legal cases, he destroyedthe other things. For when this element became powerful, those who 5flattered the common people like a tyrant changed the constitution intothe democracy we have now: Ephialtes and Pericles149 curtailed thepower of the Areopagus, and Pericles introduced payment for jurors.150In this way, each popular leader enhanced the power of the people andled them on to the present democracy. 10 It seems that this did not come about through Solon's deliberatechoice, however, but rather more by accident. For the common peoplewere the cause of Athens's naval supremacy during the Persian wars. As
a result, they became arrogant, and chose inferior people as their popu lar leaders when decent people opposed their policies. 151 Solon, at any15 rate, seems to have given the people only the minimum power necessary, that of electing and INSPECTING officials (since if they did not even have authority in these, the people would have been enslaved and hostile). 152 But he drew all the officials from among the notable and rich: the pen-20 takosiomedimnoi, the zeugitai, and the third class, the so-called hippeis. But the fourth class, the thetes, did not participate in any office. 153 Zaleucus became a legislator for the Epizephyrian Locrians, and Charondas of Catana for his own citizens and for the other Chalcidian city-states in Italy and Sicily. (Some people actually try to establish con-25 nections by telling the following story: Onomacritus was the first person to become an expert in legislation. Though a Locrian, he trained in Crete while on a visit connected with his craft of divination. Thales was his companion; Lycurgus and Zaleucus were pupils of Thales; and Charondas was a pupil of Zaleucus. But when they say these things, they30 speak without regard to chronology.)154 There was also Philolaus of Corinth, 155 a member of the Bacchiad family, who became a legislator for the Thebans. He became the lover of Diodes, the victor in the Olympic games. Diodes left Corinth in disgust35 at the lust his mother, Alcyone, had for him, and went off to Thebes, where they both ended their days. Even now people point out their tombs, which are in full view of one another, although one is visible
from the land of the Corinthians and the other is not. The story goesthat they arranged to be buried in just this way, Diodes having the landof Corinth not be visible from his burial mound because of his loathingfor what he had experienced there, and Philolaus so that it might be vis- 40ible from his. It was for this sort of reason, then, that the two of themsettled among the Thebans. But Philolaus became legislator both on 1274hother matters and about procreation (which they call "the laws of adop-tion"). This is peculiar to his legislation, its purpose being to keep thenumber of estates fixed. 5 There is nothing peculiar to Charondas except lawsuits for perjury; hewas the first to introduce denunciations for perjury. But in the precisionof his laws, he is more polished than even present-day legislators. Thefeature peculiar to Phaleas is the leveling of property. And to Plato: thesharing of women, children, and property; 156 messes for women; the law 10about drinking, that the sober should preside at drinking parties;157 andthe one requiring ambidextrous training for soldiers, on the grounds thatone of the hands should not be useful and the other useless. There are also Draco's laws, 158 but Draco established his laws for anexisting constitution. There is nothing peculiar to his laws worth talking I5about, except the severity of the punishments. Pittacus too crafted laws,but not a constitution. A law peculiar to him requires a drunken personto be punished more severely for an offense than a sober one. For since 20more drunken people than sober ones commit acts of arrogance, Pitta-cus paid attention not to the greater indulgence one should show tothose who are drunk, but to what is beneficial.159 Androdamus of Rhe-
Chapter 1When investigating constitutions, and what each is and is like, prettywell the first subject of investigation concerns a city-state, to see whatthe city-state is. For as things stand now, there are disputes about this.Some people say, for example, that a city-state performed a certain ac-tion, whereas others say that it was not the city-state that performed theaction, but rather the oligarchy or the tyrant did. We see, too, that the 35entire occupation of statesmen and legislators concerns city-states.Moreover, a constitution is itself a certain organization of the inhabitants of a city-state. But since a city-state is a composite, one that is awhole and, like any other whole, constituted out of many parts,1 it isclear that we must first inquire into citizens. For a city-state is some sort 40of multitude of citizens. Hence we must investigate who should be calleda citizen, and who the citizen is. For there is often dispute about the cit- 1275•izen as well, since not everyone agrees that the same person is a citizen.For the sort of person who is a citizen in a democracy is often not one inan oligarchy. We should leave aside those who acquire the title of citizen in someexceptional way; for example, those who are made citizens.2 Nor is a cit- 5izen a citizen through residing in a place, for resident aliens and slavesshare the dwelling place with him. Again, those who participate in thejustice system, to the extent of prosecuting others in the courts or beingjudged there themselves, are not citizens: parties to treaties can also dothat (though in fact in many places the participation of resident aliens in 10the justice system is not even complete, but they need a sponsor, so thattheir participation in this sort of communal relationship is in a way
1 . Composites are always analyzed into their parts ( 1 252' 1 7-20). A whole (holon) is a composite that is a substance possessing an essence or nature (Metaph. 104 l b l l-33). See Introduction xxvii-xxxv.2. Presumably, honorary citizens and the like.
65 66 Politics III
incomplete).3 Like minors who are too young to be enrolled in the citi zen lists or old people who have been excused from their civic duties,4I5 they must be said to be citizens of a sort, but not UNQUALIFIED citizens. Instead, a qualification must be added, such as "incomplete" or "super annuated" or something else like that (it does not matter what, since what we are saying is clear). For we are looking for the unqualified citi zen, the one whose claim to citizenship has no defect of this sort that20 needs to be rectified (for one can raise and solve similar problems about those who have been disenfranchised or exiled). The unqualified citizen is defined by nothing else so much as by his participation in judgment and office. But some offices are of limited tenure, so they cannot be held twice by the same person at all, or can be25 held again only after a definite period. Another person, however, holds office indefinitely, such as the juror or assemblyman . Now someone might say that the latter sort are not officials at all, and do not, because of this, 5 participate in any office as such. Yet surely it would be absurd to deprive of office those who have the most authority.6 But let this make no difference, since the argument is only about a word. For what a juror30 and an assemblyman have in common lacks a name that one should call them both. For the sake of definition, let it be indefinite office. We take it, then, that those who participate in office in this way are citizens. And this is pretty much the definition that would best fit all those called citi zens. We must not forget, however, that in case of things in which what un-35 derlies differs in kind (one coming first, another second, and so on), a common element either is not present at all, insofar as these things are such, or only in some attenuated way.7 But we see that constitutions dif-
3. Resident aliens in Athens had to have a citizen "sponsor" (prostates), but they could represent themselves in legal proceedings. Elsewhere, it seems, their sponsor had to do this for them. 4. At the age of 18, young Athenians were enrolled in the citizen list kept by the leader of the deme. Older men were released from having to serve in the mili tary, and perhaps also from jury duty and attendance at meetings of the as sembly. 5 . Because of being jurors, assemblymen, and the like. 6. As jurors and members of the assembly do in certain sorts of democracies ( 1 27Jb4 1-1274" l l ) . 7 . Exercise is healthy, a complexion i s healthy, and a certain physical condition is healthy. Each of them underlies the property of being healthy, or is the sub ject of which that property is predicated. But exercise is healthy because it Chapter 2 67
fer in kind from one another, and that some are posterior and othersprior; for mistaken or deviant constitutions are necessarily posterior tothose that are not mistaken.8 (What we mean by "deviant" will be appar- 1275hent later.)9 Consequently, the citizen in each constitution must also bedifferent. That is precisely why the citizen that we defined is above all a citizenin a democracy, and may possibly be one in other constitutions, but notnecessarily. For some constitutions have no "the people" or assemblies 5they legally recognize, but only specially summoned councils and judi-cial cases decided by different bodies. In Sparta, for example, some casesconcerning contracts are tried by one overseer, others by another,whereas cases of homicide are judged by the senate, and other cases by 10perhaps some other official. It is the same way in Carthage, since therecertain officials decide all cases.10 None the less, our definition of a citi-zen admits of correction. For in the other constitutions, 11 it is not theholder of indefinite office who is assemblyman and juror, but someonewhose office is definite. For it is either to some or to all of the latter thatdeliberation and judgment either about some or about all matters is as- 15signed. It is evident from this who the citizen is. For we can now say thatsomeone who is eligible to participate in deliberative and judicial officeis a citizen in this city-state, and that a city-state, simply speaking, is amultitude of such people, adequate for life's self-sufficiency. 20
Chapter 2But the definition that gets used in practice is that a citizen is someonewho comes from citizens on both sides, and not on one only-for exam-
pie, that of father or of mother. Some people look for more here too, going back, for example, two or three or more generations of ancestors. But quick political definitions of this sort lead some people to raise the 25 problem of how these third- or fourth-generation ancestors will be citi zens. So Gorgias of Leontini, half perhaps to raise a real problem and half ironically, said that just as mortars are made by mortar makers, so Lariseans too are made by craftsmen, since some of them are Larisean 30 makersY But this is easy: if the ancestors participated in the constitu tion in the way that accords with the definition just given, 13 they were citizens. For "what comes from a citizen father and mother" cannot be applied to even the first inhabitants or founders. But perhaps a bigger problem is raised by the next case: those who come to participate in a constitution after a revolution, such as the citi- 35 zens created in Athens by Cleisthenes14 after the expulsion of the tyrants (for he enrolled many foreigners and alien slaves in the tribes). But the dispute in relation to these people is not which of them is a citizen, but whether they are rightly or wrongly so. And yet a further question might be raised as to whether one who is not rightly a citizen is a citizen at all,1276• as "wrong" and "false" seem to have the same force. But since we see that there are also some people holding office wrongly, whom we say are holding it though not rightly, and since a citizen is defined as someone who holds a sort of office (for someone who participates in such office is 5 a citizen, as we said), it is clear that these people too must be admitted to be citizens.
Chapter 3 The problem of rightly and not rightly is connected to the dispute we mentioned earlier. 15 For some people raise a problem about how to de termine whether a city-state has or has not performed an action, for ex ample, when an oligarchy or a tyranny is replaced by a democracy. At
12. Gorgias was a famous orator and sophist (c. 483-376) who visited Athens in 427. In Larissa, and other place, the word demiourgos, which means "crafts man," is also the title of a certain sort of public official. A Larisean is both a citizen of Larissa and a kind of pot made there. 1 3 . At 1 275b17- 2 1 . 1 4 . Cleisthenes was a sixth century Athenian statesman whose wide-ranging re form of the Athenian constitution was as significant and abiding as that of Solon. 1 5. At 1 274b34-36. Chapter 3 69
these times, some do not want to honor treaties, since it was not the city- 10state but its tyrant who entered into them, nor to do many other thingsof the same sort, on the grounds that some constitutions exist by forceand not for the common benefit.16 Accordingly, if indeed some democ-rats also rule in that way, it must be conceded that the acts of their constitution are the city-state's in just the same way as are those of the oli-garchy or the tyranny. 15 There seems to be a close relation between this argument and theproblem of when we ought to say that a city-state is the same, or not thesame but a different one.17 The most superficial way to investigate thisproblem is by looking to location and people. For a city-state's location 20and people can be split, and some can live in one place and some in another. Hence the problem must be regarded as a rather tame one. For thefact that a thing is said to be a city-state in many different ways makesthe investigation of such problems pretty easy.1 8 Things are similar if one asks when people inhabiting the same loca-tion should be considered a single city-state. Certainly not because it is 25enclosed by walls, since a single wall could be built around the Peloponnese. Perhaps Babylon is like that, or anywhere else that has the dimensions of a nation rather than a city-state. At any rate, they say that whenBabylon was captured, a part of the city-state was unaware of it for threedays. 19 But it will be useful to investigate this problem in another con- 30text. For the size of the city-state, both as regards numbers and as regards whether it is beneficial for it to be one or10 several, should not beoverlooked by the statesman. But when the same people are inhabiting the same place, is the city-state to be called the same as long as the inhabitants remain of the samestock, even though all the time some are dying and others being born 35(just as we are accustomed to say that rivers and springs remain the
same, even though all the time some water is flowing out and some flow ing in)? Or are we to say that human beings can remain the same for this 40 sort of reason, but the city-state is different? For if indeed a city-state is1276h a sort of community, a community of citizens sharing a constitution, then, when the constitution changes its form and becomes different, it would seem that the city-state too cannot remain the same. At any rate, a chorus that is at one time in a comedy and at another in a tragedy is said S to be two different choruses, even though the human beings in it are often the same. Similarly, with any other community or composite: we say it is different if the form of the composite is different. 21 For example, we call a melody composed of the same notes a different melody when it is played in the Dorian harmony than when it is played in the Phrygian. 10 But if this is so, it is evident that we must look to the constitution above all when saying that the city-state is the same. But the name to call it may be different or the same one whether its inhabitants are the same or completely different people.22 But whether it is just to honor or not to honor agreements when a 1S city-state changes to a different constitution requires another argument.
Chapter 4 The next thing to investigate after what we have j ust discussed is whether the virtue of a good man and of a good citizen should be re garded as the same, or not the same. But surely if we should indeed in vestigate this, the virtue of a citizen must first be grasped in some sort of outline. Just as a sailor is one of a number of members of a community, so, we 20 say, is a citizen. And though sailors differ in their capacities (for one is an oarsman, another a captain, another a lookout, and others have other sorts of titles), it is clear both that the most exact account of the virtue of each sort of sailor will be peculiar to him, and similarly that there will
also b e some common account that fits them all. For the safety o f the 25voyage is a task of all of them, since this is what each of the sailors strivesfor. In the same way, then, the citizens too, even though they are dissim-ilar, have the safety of the community as their task. But the communityis the constitution. Hence the virtue of a citizen must be suited to hisconstitution. Consequently, if indeed there are several kinds of constitu- 30tion, it is clear that there cannot be a single virtue that is the virtue-thecomplete virtue--of a good citizen. But the good man, we say, does express a single virtue: the complete one. Evidently, then, it is possible forsomeone to be a good citizen without having acquired the virtue ex-pressed by a good man. 35 By going through problems in a different way, the same argument canbe made about the best constitution. If it is impossible for a city-state toconsist entirely of good people, and if each must at least perform hisown task well, and this requires virtue, and if it is impossible for all thecitizens to be similar, then the virtue of a citizen and that of a good man 40cannot be a single virtue. For that of the good citizen must be had by all 1277•(since this is necessary if the city-state is to be best), but the virtue of agood man cannot be had by all, unless all the citizens of a good city-stateare necessarily good men. Again, since a city-state consists of dissimilarelements (I mean that just as an animal consists in the first instance of 5soul and body, a soul of reason and desire, a household of man andwoman, and property of master and slave, so a city-state, too, consists ofall these, and of other dissimilar kinds in addition), then the citizenscannot all have one virtue, any more than can the leader of a chorus and 10one of its ordinary members. 23 It is evident from these things, therefore, that the virtue of a man andof a citizen cannot be unqualifiedly the same. But will there, then, be anyone whose virtue is the same both as agood citizen and as a good man? We say, indeed, that an excellent ruler isgood and possesses practical wisdom, but that a citizen24 need not pos- 15sess practical wisdom. Some say, too, that the education of a ruler isdifferent right from the beginning, as is evident, indeed, from the sonsof kings being educated in horsemanship and warfare, and from Euripi-
23. The examples given are all of natural ruler-subject pairs. Aristotle has al ready shown in 1 . 1 3 that the virtues of natural rulers and subjects are differ ent.24. Reading politen with Ross and Dreizehnter. Alternatively (mss.): "but that a statesman (politikon) need not be practically-wise." 72 Politics III
des saying "No subtleties for me . . . but what the city-state needs,"25 (since this implies that rulers should get a special sort of education). But 20 if the virtue of a good ruler is the same as that of a good man, and if the man who is ruled is also a citizen, then the virtue of a citizen would not be unqualifiedly the same as the virtue of a man (though that of a certain sort of citizen would be), since the virtue of a ruler and that of a citizen would not be the same. Perhaps this is why Jason said that he went hun gry except when he was a tyrant.26 He meant that he did not know how to be a private individual. 25 Yet the capacity to rule and be ruled is at any rate praised, and being able to do both well is held to be the virtue of a citizen. 27 So if we take a good man's virtue to be that of a ruler, but a citizen's to consist in both, then the two virtues would not be equally praiseworthy. Since, then, both these views are sometimes accepted,28 that ruler and 30 ruled should learn different things and not the same ones, and that a cit izen should know and share in both, we may see what follows from that. For there is rule by a master, by which we mean the kind concerned with the necessities. The ruler does not need to know how to produce these, but rather how to make use of those who do. In fact, the former is 35 servile. (By "the former" I mean actually knowing how to perform the actions of a servant.) But there are several kinds of slaves, we say, since their tasks vary. One part consists of those tasks performed by manual laborers. As their very name implies, these are people who work with1 27Jb their hands. VULGAR CRAFTSMEN are included among them. That is why among some peoples in the distant past craftsmen did not participate in office until extreme democracy arose. Accordingly, the tasks performed by people ruled in this way should not be learned by a good person, nor by29 a statesman, nor by a good citizen, except perhaps to satisfy some 5 personal need of his own (for then it is no longer a case of one person becoming master and the other slave).30 But there is also a kind of rule exercised over those who are similar in birth and free. This we call "political" rule. A ruler must learn it by
25. From the lost play Aeolus (Nauck 367 fr. 16. 2-3). King Aeolus is apparently speaking about the education his sons are to receive. 26. Jason was tyrant of Pherae in Thessaly (c. 380-370). 27. See Plato, Laws 643e-644a. 28. Reading dokei amphO hetera with Dreizehnter. 29. Reading oude ton. 30. See 1 34 JbJ0- 1 5 . Chapter 5 73
Chapter 5But one of the problems about the citizen still remains. For is the citizenreally someone who is permitted to participate in office, or should vul-gar craftsmen also be regarded as citizens? If, indeed, those who do not 35share in office should be regarded as citizens, then this sort of virtue34cannot belong to every citizen (for these will then be citizens). On the
other hand, if none of this sort is a citizen, in what category should they each be put?-for they are neither resident aliens nor foreigners. Or shall we say that from this argument, at least, nothing absurd fol-1278• lows, since neither slaves nor freed slaves are in the aforementioned classes either? For the truth is that not everyone without whom there would not be a city-state is to be regarded as a citizen. For children are not citizens in the way men are. The latter are unqualified citizens, whereas the former are only citizens given certain assumptions: they are S citizens, but incomplete ones. Vulgar craftsmen were slaves or foreigners in some places long ago, which is why most of them still are even today. The best city-state will not confer citizenship on vulgar craftsmen, how ever; but if they too are citizens, then what we have characterized as a citizen's virtue cannot be ascribed to everyone, or even to all free people, 10 but only to those who are freed from necessary tasks. Those who per form necessary tasks for an individual are slaves; those who perform them for the community are vulgar craftsmen and hired laborers. If we carry our investigation a bit further, it will be evident how things stand in these cases. In fact, it is clear from what we have already said.35 For since there are several constitutions, there must also be sev- 1S eral kinds of citizens, particularly of citizens who are being ruled. Hence in some constitutions vulgar craftsmen and hired laborers must be citi zens, whereas in others it is impossible-for example, in any so-called aristocracy in which offices are awarded on the basis of virtue and merit. 20 For it is impossible to engage in virtuous pursuits while living the life of a vulgar craftsman or a hired laborer. 36 In oligarchies, however, while hired laborers could not be citizens (since participation in office is based on high property assessments), vulgar craftsmen could be, since in fact most craftsmen become rich (though in Thebes there used to be a law that anyone who had not kept 25 away from the market for ten years could not participate in office)Y In many constitutions, however, the law even goes so far as to admit some foreigners as citizens; for in some democracies the descendant of a citizen mother is a citizen, and in many places the same holds of bas tards too. Nevertheless, since it is because of a shortage of legitimate cit- 30 izens that they make such people citizens (for it is because of underpop-
35. At III. I . 36. Explained somewhat at 1 260'38-h l , 1 337h4-21 . 37. Aristotle thinks that oligarchies should impose restrictions of this sort on vulgar craftsmen (1321'26-29). Chapter 6 75
ulation that they employ laws in this way), when they are well suppliedwith a crowd of them, they gradually disqualify, first, those who have aslave as father or mother, then those with citizen mothers, until finallythey make citizens only of those who come from citizens on both sides. It is evident from these considerations, therefore, that there are sev-eral kinds of citizens, and that the one who participates in the offices is 35particularly said to be a citizen, as Homer too implied when he wrote:"like some disenfranchised alien."38 For people who do not participate inthe offices are like resident aliens. When this is concealed, it is for thesake of deceiving coinhabitants.39 As to whether the virtue expressed by a good man is to be regarded as 40the same as that of an excellent citizen or as different, it is clear from 1278"what has been said that in one sort of city-state both are the same per-son, while in another they are different. And that person is not just any-one, but the statesman, who has authority or is capable of exercising au-thority in the supervision of communal matters, either by himself orwith others. 5
Chapter 6Since these issues have been determined, the next thing to investigate iswhether we should suppose that there is just one kind of constitution orseveral, and, if there are several, what they are, how many they are, andhow they differ. A constitution is an organization of a city-state's various offices but,particularly, of the one that has authority over everything. For the governing class has authority in every city-state, and the governing class is 10the constitution.'�{) I mean, for example, that in democratic city-statesthe people have authority, whereas in oligarchic ones, by contrast, thefew have it, and we also say the constitutions of these are different. Andwe shall give the same account of the other constitutions as well. First, then, we must set down what it is that a city-state is constituted 15for, and how many kinds of rule deal with human beings and communallife. In our first discussions, indeed, where conclusions were reached
38. Iliad IX.648, XVI. 59. Achilles is complaining that this is how Agamemnon is treating him.39. See 1264'19-22.40. Aristotle is relying on his doctrine that "a city-state and every other com posite system is most of all the part of it that has the most authority" (NE 1 168h31-33). 76 Politics III
about household management and rule by a master, it was also said that a human being is by nature a political animal.41 That is why, even when 20 they do not need one another's help, people no less desire to live to gether, although it is also true that the common benefit brings them to gether, to the extent that it contributes some part of living well to each. This above all is the end, then, whether of everyone in common or of each separatelyY But human beings also join together and maintain po litical communities for the sake of life by itself. For there is perhaps 25 some share of what is NOBLE in life alone, as long as it is not too over burdened with the hardships of life. In any case, it is clear that most human beings are willing to endure much hardship in order to cling to life, as if it had a sort of joy inherent in it and a natural sweetness. But surely it is also easy to distinguish at least the kinds of rule people 30 talk about, since we too often discuss them in our own external works.43 For rule by a master, although in truth the same thing is beneficial for both natural masters and natural slaves, is nevertheless rule exercised 35 for the sake of the master's own benefit, and only coincidentally for that of the slave. 44 For rule by a master cannot be preserved if the slave is de stroyed. But rule over children, wife, and the household generally, which we call household management, is either for the sake of the ruled or for the sake of something common to both. Essentially, it is for the 40 sake of the ruled, as we see medicine, physical training, and the other1279" crafts to be, but coincidentally it might be for the sake of the rulers as well. For nothing prevents the trainer from sometimes being one of the athletes he is training, just as the captain of a ship is always one of the 5 sailors. Thus a trainer or a captain looks to the good of those he rules, but when he becomes one of them himself, he shares coincidentally in the benefit. For the captain is a sailor, and the trainer, though still a trainer, becomes one of the trained. Hence, in the case of political office too, where it has been established on the basis of equality and similarity among the citizens, they think it 10 right to take turns at ruling. In the past, as is natural, they thought it
right to perform public service when their turn came, and then to havesomeone look to their good, just as they had earlier looked to his benefitwhen they were in office. Nowadays, however, because of the profits tobe had from public funds and from office, people want to be in officecontinuously, as if they were sick and would be cured by being always inoffice. At any rate, perhaps the latter would pursue office in that way. 15 It is evident, then, that those constitutions that look to the commonbenefit turn out, according to what is unqualifiedly just, to be correct,whereas those which look only to the benefit of the rulers are mistakenand are deviations from the correct constitutions. For they are like rule 20by a master, whereas a city-state is a community of free people.
Chapter 7Now that these matters have been determined, we must next investigatehow many kinds of constitutions there are and what they are,45 startingfirst with the correct constitutions. For once they have been defined, thedeviant ones will also be made evident. Since "constitution" and "governing class" signify the same thing,46 25and the governing class is the authoritative element in any city-state, andthe authoritative element must be either one person, or few, or many,then whenever the one, the few, or the many rule for the common bene-fit, these constitutions must be correct. But if they aim at the privatebenefit, whether of the one or the few or the MULTITUDE, they are devi- 30ations (for either the participants47 should not be called citizens, or theyshould share in the benefits). A monarchy that looks to the common benefit we customarily call akingship; and rule by a few but more than one, an aristocracy (either be-cause the best people rule, or because they rule with a view to what is 35best for the city-state and those who share in it). But when the multitudegoverns for the common benefit, it is called by the name common to allCONSTITUTIONS, namely, politeia. Moreover, this happens reasonably.For while it is possible for one or a few to be outstandingly virtuous, it isdifficult for a larger number to be accomplished in every virtue, but it 40can be so in military virtue in particular. That is precisely why the class 12 7CJ'
of defensive soldiers, the ones who possess the weapons, has the most authority in this constitution.48 Deviations from these are tyranny from kingship, oligarchy from aris-5 tocracy, and democracy from polity. For tyranny is rule by one person for the benefit of the monarch, oligarchy is for the benefit of the rich, and democracy is for the benefit of the poor. But none is for their com mon profit.
Chapter 8I0 We should say a little more about what each of these constitutions is. For certain problems arise, and when one is carrying out any investigation in a philosophical manner, and not merely with a practical purpose in view, it is appropriate not to overlook or omit anything, but to make the truthI5 about each clear. A tyranny, as we said, exists when a monarchy rules the political com munity like a master; in an oligarchy those in authority in the constitu tion are the ones who have property. A democracy is the opposite; those who do not possess much property, and are poor, are in authority. The20 first problem concerns this definition. Suppose that the MAJORITY were rich and had authority in the city-state; yet there is a democracy when ever the majority has authority. Similarly, to take the opposite case, sup pose the poor were fewer in number than the rich, but were stronger and had authority in the constitution; yet when a small group has authority it is said to be an oligarchy. It would seem, then, that these constitutions25 have not been well defined. But even if one combines being few with being rich in one case, and being a majority with being poor in the other, and describes the constitutions accordingly (oligarchy as that in which the rich are few in number and hold the offices, and democracy as that in30 which the poor are many and hold them), another problem arises. For what are we to call the constitutions we just described, those where the rich are a majority and the poor a minority, but each has authority in its
Chapter 9The first thing one must grasp, however, is what people say the definingmarks of oligarchy and democracy are, and what oligarchic and democ-ratic justice are. For [1] they all grasp justice of a sort,51 but they go onlyto a certain point and do not discuss the whole of what is just in the mostauthoritative sense. For example, justice seems to be EQUALITY, and it is, 10but not for everyone, only fo r equals. Justice also seems to be inequality,since indeed it is, but not for everyone, only for unequalsY They disre-gard the "for whom," however, and judge badly. The reason is that thejudgment concerns themselves, and most people are pretty poor judgesabout what is their own.53 15 So since what is just is just for certain people, and consists in dividingthings and people in the same way (as we said earlier in the Ethics),54they agree about what constitutes equality in the thing but disagreeabout it in the people. This is largely because of what was just mentioned, that they judge badly about what concerns themselves, but also 20
I t i s evident that this is right. For even if [5] one were to bring theirterritories together into one, so that the city-state of the Megarians wasattached to that of the Corinthians by walls, it still would not be a singlecity-state. Nor would it be so if their citizens intermarried, even though ISthis is one of the forms of community characteristic of city-states. Similarly, if there were some who lived separately, yet not so separately as toshare nothing in common, and had laws against wronging one another intheir business transactions (for example, if one were a carpenter, anothera farmer, another a cobbler, another something else of that sort, and 20their number were ten thousand), yet they shared nothing else in common besides such things as exchange and alliance-not even in this casewould there be a city-state. What, then, is the reason for this? Surely, it is not because of the nonproximate nature of their community. For suppose they joined togetherwhile continuing to share in that way, but each nevertheless treated his 25own household like a city-state, and the others like a defensive allianceformed to provide aid against wrongdoers only. Even then this stillwould not be thought a city-state by those who make a precise study ofsuch things, if indeed they continued to associate with one another inthe same manner when together as when separated. Evidently, then, a city-state is not [5] a sharing of a common location,and does not exist for the purpose of [4] preventing mutual wrongdoing 30and [3] exchanging goods. Rather, while these must be present if indeedthere is to be a city-state, when all of them are present there is still notyet a city-state, but [2] only when households and families live well as acommunity whose end is a complete and self-sufficient life. But this willnot be possible unless they do inhabit one and the same location and 35practice intermarriage. That is why marriage connections arose in citystates, as well as brotherhoods, religious sacrifices, and the LEISUREDPURSUITS of living together. For things of this sort are the result offriendship, since the deliberative choice of living together constitutesfriendship. The end of the city-state is living well, then, but these otherthings are for the sake of the end . And a city-state is the community offamilies and villages in a complete and self-sufficient life, which we say 40is living happily and NOBLY. 128]• So political communities must be taken to exist for the sake of nobleactions, and not for the sake of living together. Hence those who contribute the most to this sort of community have a larger share in the citystate than those who are equal or superior in freedom or family but infe 5rior in political virtue, and those who surpass in wealth but aresurpassed in virtue. 82 Politics III
It is evident from what has been said, then, that [ 1 ] those who dispute10 about constitutions all speak about a part of justice.
Chapter 1 0 There is a problem as to what part of the state is to have authority, since surely it is either the multitude, or the rich, or decent people, or the one who is best of all, or a tyrant. But all of these apparently involve difficul ties. How so? If the poor, because they are the greater number, divide up15 the property of the rich, isn't that unjust? "No, by Zeus, it isn't, since it seemed just to those in authority." What, then, should we call extreme in justice? Again, if the majority, having seized everything, should divide up the property of the minority, they are evidently destroying the city-state. But virtue certainly does not ruin what has it, nor is justice something20 capable of destroying a city-state. So it is clear, then, that this law57 can not be just. Besides, everything done by a tyrant must be just as well; for he, being stronger, uses force, just as the multitude do against the rich.25 But is it just, then, for the rich minority to rule? If they too act in the same way, plundering and confiscating the property of the multitude, and this is just, then the other case is as well. It is evident, therefore, that all these things are bad and unjust. But should decent people rule and have authority over everything? In that case, everyone else must be deprived of honors by being excluded from30 political office. For offices are positions of honor, we say, and when the same people always rule, the rest must necessarily be deprived of honors. But is it better that the one who is best should rule? But this is even more oligarchic, since those deprived of honors are more numerous. Perhaps, however, someone might say that it is a bad thing in general35 for a human being to have authority and not the LAW, since he at any rate has the passions that beset the soul. But if law may be oligarchic or de mocratic, what difference will that make to our problems? For the things we have just described will happen just the same.
Chapter 1 1 As for the other cases, we may let them be the topic of a different dis cussion. 58 But the view that the multitude rather than the few best peo-
59. A panel chosen by lot selected the three best comedies and tragedies at the annual theater festivals in Athens. 84 Politics III
legislators arrange to have them elect and INSPECT officials, but prevent them from holding office alone. 6° For when they all come together their 35 perception is adequate, and, when mixed with their betters, they benefit their states, just as a mixture of roughage and pure food-concentrate is more useful than a little of the latter by itself. 61 Taken individually, how ever, each of them is an imperfect j udge. But this organization of the constitution raises problems itself. In the first place, it might be held that the same person is able to j udge whether 40 or not someone has treated a patient correctly, and to treat patients and cure them of disease when it is present-namely, the doctor. The same would also seem to hold in other areas of experience and other crafts.I282• Therefore, j ust as a doctor should be inspected by doctors, so others should also be inspected by their peers. But "doctor" applies to the or dinary practitioner of the craft, to a master craftsman, and thirdly, to someone with a general EDUCATION in the craft. For there are people of 5 this third sort in (practically speaking) all the crafts. And we assign the task of judging to generally educated people no less than to experts. Moreover, it might be held that election is the same way, since choos ing correctly is also a task for experts: choosing a geometer is a task for expert geometers, for example, and choosing a ship's captain is a task for IO expert captains. For even if some laymen are also involved in the choice of candidates in the case of some tasks and crafts, at least they do not play a larger role than the experts. According to this argument, then, the multitude should not be given authority over the election or inspection of officials. But perhaps not all of these things are correctly stated, both because I5 according to the earlier argument the multitude may not be too servile, since each may be a worse judge than those who know, but a better or no worse one when they all come together; and because there are some crafts in which the maker might not be either the only or the best judge-the ones where those who do not possess the craft nevertheless have knowledge of its products. For example, the maker of a house is not 20 the only one who has some knowledge about it; the one who uses it is an even better j udge (and the one who uses is the household manager). A captain, too, judges a rudder better than a carpenter, and a guest, rather than the cook, a feast. 62
Chapter 1 2Since in every science and craft the end is a good, the greatest and bestgood is the end of the science or craft that has the most authority of all 15
63. The one raised at 1281' 1 1 of who should have authority in the city-state.64. See 1281'34-39. 86 Politics III
of them, and this is the science of statesmanship. But the political good is justice, and justice is the common benefit. Now everyone holds that what is just is some sort of equality, and up to a point, at least, all agree with what has been determined in those philosophical works of ours 20 dealing with ethical issues.65 For justice is something to someone, and they say it should be something equal to those who are equal. But equal ity in what and inequality in what, should not be overlooked. For this in volves a problem and political philosophy. Someone might say, perhaps, that offices should be unequally distrib uted on the basis of superiority in any good whatsoever, provided the people did not differ in their remaining qualities but were exactly simi- 25 lar, since where people differ, so does what is just and what accords with merit. But if this is true, then those who are superior in complexion, or height, or any other good whatsoever will get more of the things with which political justice is concerned. And isn't that plainly false? The 30 matter is evident in the various sciences and capacities. For among flute players equally proficient in the craft, those who are of better birth do not get more or better flutes, since they will not play the flute any better if they do. It is the superior performers who should also get the superior 35 instruments. If what has been said is somehow not clear, it will become so if we take it still further. Suppose someone is superior in flute play ing, but is very inferior in birth or beauty; then, even if each of these (I mean birth and beauty) is a greater good than flute playing, and is pro- 40 portionately more superior to flute playing than he is superior in flute playing, he should still get the outstanding flutes. For the superiority in1283" wealth and birth would have to contribute to the performance, but in fact they contribute nothing to it. Besides, according to this argument every good would have to be commensurable with every other. For if being a certain height counted S more,66 height in general would be in competition with both wealth and freedom. So if one person is more outstanding in height than another is in virtue, and if height in general is of more weight than virtue, then all goods would be commensurable. For if a certain amount of size is better than a certain amount of virtue, it is clear that some amount of the one is equal to some amount of the other. Since this is impossible, it is clear 10 that in political matters, too, it is reasonable not to dispute over political office on the basis of just any sort of inequality. For if some are slow run-
ners and others fast, this is no reason for the latter to have more and theformer less: it is in athletic competitions that such a difference winshonor. The dispute must be based on the things from which a city-stateis constituted. Hence the well-born, the free, and the rich reasonably lay 15claim to office. For there must be both free people and those with assessed property, since a city-state cannot consist entirely of poor people,any more than of slaves. But if these things are needed in a city-state, sotoo, it is clear, are justice and political67 virtue, since a city-state cannotbe managed without these. Rather, without the former a city-state can- 20not exist, and without the latter it cannot be well managed.
Chapter 1 3As regards the existence of a city-state, all, or at any rate some, of thesewould seem to have a correct claim in the dispute. But as regards thegood life, education and virtue would seem to have the most just claimof all in the dispute, as was also said earlier.68 But since those equal in 25one thing only should not have equality in everything, nor inequality ifthey are unequal in only one thing, all constitutions of this sort must bedeviant. We said before69 that all dispute somewhat justly, but that not all do so 30in an unqualifiedly just way. The rich have a claim due to the fact thatthey own a larger share of the land, and the land is something common,and that, in addition, they are usually more trustworthy where treaties70are concerned. The FREE and the well-born have closely related claims,for those who are better born are more properly citizens than those ofignoble birth, and good birth is honored at home by everyone. Besides, 35they have a claim because better people are likely to come from betterpeople, since good birth is virtue of family.71 Similarly, then, we shall saythat virtue has a just claim in the dispute, since justice, we say, is a communal virtue, which all the other virtues necessarily accompany.72 Butthe majority too have a just claim against the minority, since they are 40
67. Reading politikis with Ross, Schiitrumpf, and some mss. Alternatively (Dreizehnter and some mss.): "military (polemikis)."68. At 128 1'1-8.69. At 1280'7-25.70. sumbolaia: or contracts.7 1 . A slightly different definition is given at 1 294'2 1 .72. Because justice is complete virtue i n relation t o another person (NE 1 129h2S-1 1 30'5). 88 Politics III
stronger, richer, and better, when taken as the majority in relation to the minority. If they were all present in a single city-state, therefore (I mean, for ex-1283b ample, the good, the rich, the well-born, and a political multitude in addition), will there be a dispute as to who should rule or not? Within each of the constitutions we have mentioned, to be sure, the decision as 5 to who should rule is indisputable, since these differ from one another because of what is in authority; for example, because in one the rich are in authority, in another the excellent men, and each of the others differs the same way. But be that as it may, we are investigating how the matter is to be determined when all these are present simultaneously. Suppose, 10 for example, that those who possess virtue are extremely few in number, how should the matter be settled? Should their fewness be considered in relation to the task? To whether they are able to manage the city-state? Or to whether there are enough of them to constitute a city-state by themselves? But there is a problem that faces all who dispute over political office. 15 Those who claim that they deserve to rule because of their wealth could be held to have no j ustice to their claim at all, and similarly those claim ing to do so because of their family. For it is clear that if someone is richer again than everyone else, then, on the basis of the same justice, this one person will have to rule them all . Similarly, it is clear that some one who is outstanding when it comes to good birth should rule those who dispute on the basis of freedom. Perhaps the same thing will also 20 occur in the case of virtue where aristocracies are concerned. For if one man were better than the others in the governing class, even though they were excellent men, then, on the basis of the same justice, this man should be in authority. So if the majority too should be in authority be cause they are superior to the few, then, if one person, or more than one 25 but fewer than the many, were superior to the others, these should be in authority rather than the multitude. All this seems to make it evident, then, that none of the definitions on the basis of which people claim that they themselves deserve to rule, whereas everyone else deserves to be ruled by them, is correct. For the multitude would have an argument of some justice even against those who claim that they deserve to have au- 30 thority over the governing class because of their virtue, and similarly against those who base their claim on wealth. For nothing prevents the multitude from being sometimes better and richer than the few, not as individuals but collectively. 35 Hence the problem that some people raise and investigate can also be Chapter 13 89
dealt with in this way. For they raise the problem of whether a legislatorwho wishes to establish the most correct laws should legislate for thebenefit of the better citizens or that of the majority, when the case justmentioned occurs. But what is correct must be taken to mean what isequitable; and what is equitable in relation to the benefit of the entire 40city-state, and the common benefit of the citizens. And a citizen gener-ally speaking is someone who participates in ruling and in being ruled,although in each constitution he is someone different. It is in the best 1284"one, however, that he is the one who has the power and who deliberatelychooses to be ruled and to rule with an eye to the virtuous life. But ifthere is one person or more than one (though not enough to make up acomplete city-state) who is so outstanding by reason of his superior Svirtue that neither the virtue nor the political power of all the others iscommensurable with his (if there is only one) or theirs (if there are anumber of them), then such men can no longer be regarded as part ofthe city-state. For they would be treated unjustly if they were thought tomerit equal shares, when they are so unequal in virtue and politicalpower. For anyone of that sort would reasonably be regarded as a god 10among human beings. Hence it is clear that legislation too must be con-cerned with those who are equals both in birth and in power, and that forthe other sort there is no law, since they themselves are law. For, indeed,anyone who attempted to legislate for them would be ridiculous, sincethey would presumably respond in the way Antisthenes tells us the lions 1Sdid when the hares acted like popular leaders and demanded equality foreveryone. 73 That is why, indeed, democratically governed city-states introduceostracism. For of all city-states these are held to pursue equality most,and so they ostracize those held to be outstandingly powerful (whetherbecause of their wealth, their many friends, or any other source of polit- 20ical power), banishing them from the city-state for fixed periods oftime.74 The story goes, too, that the Argonauts left Heracles behind forthis sort of reason: the Argo refused to carry him with the other sailorson the grounds that his weight greatly exceeded theirs.75 That is also 25
73. The lions' reply was: "Where are your claws and teeth?" See Aesop, Fables 241 . Antisthenes was a follower of Socrates and a founder of the school of philosophers known as the Cynics.74. Ostracism, or banishment without loss of property or citizenship for ten (later five) years, was introduced into Athens by Cleisthenes. See Ath. XXII.75. Athena had built a board into the Argo that enabled it to speak. 90 Politics III
why those who criticize tyranny or the advice that Periander gave Thrasybulus should not be considered to be unqualifiedly correct in their censure. For they say that Periander said nothing to the messenger who had been sent to him for advice, but leveled a cornfield by cutting 30 off the outstandingly tall ears. When the messenger, who did not know why Periander did this, reported what had happened, Thrasybulus un derstood that he was to get rid of the outstanding men. 76 This advice is not beneficial only to tyrants, however, nor are tyrants the only ones who follow it. The same situation holds too in oligarchies 35 and democracies. For ostracism has the same sort of effect as cutting down the outstanding people or sending them into exile. But those in control of power treat city-states and nations in the same way. For exam ple, as soon as Athens had a firm grip on its imperial rule, it humbled 40 Samos, Chios, and Lesbos,77 in violation of the treaties it had with them; and the king of the Persians often cut the Medes and Babylonians down1284b to size, as well as any others who had grown presumptuous because they had once ruled empires of their own. The problem is a general one that concerns all constitutions, even the correct ones. For though the deviant constitutions use such methods S with an eye to the private benefit, the position is the same with those that aim at the common good. But this is also clear in the case of the other crafts and sciences. For no painter would allow an animal to have a disproportionately large foot, not even if it were an outstandingly beau tiful one, nor would a shipbuilder allow this in the case of the stern or 10 any of the other parts of the ship, nor will a chorus master tolerate a member of the chorus who has a louder and more beautiful voice than the entire chorus. So, from this point of view, there is nothing to prevent monarchs from being in harmony with the city-state they rule when they resort to this sort of practice, provided their rule benefits their 15 city-states. Where acknowledged sorts of superiority are concerned, then, there is some political j ustice to the argument in favor of os tracism. It would be better, certainly, if the legislator established the constitu tion in the beginning so that it had no need for such a remedy. But the next best thing is to try to fix the constitution, should the need arise,
with a corrective of this sort. This is not what actually tended to happenin city-states, however. For they did not look to the benefit of their own 20constitutions, but used ostracism for purposes of faction. It is evident,then, that in each of the deviant constitutions ostracism is privately advantageous and just, but it is perhaps also evident that it is not unqualifiedly just. In the case of the best constitution, however, there is a considerable 25problem, not about superiority in other goods, such as power or wealthor having many friends, but when there happens to be someone who issuperior in virtue. For surely people would not say that such a personshould be expelled or banished, but neither would they say that theyshould rule over him. For that would be like claiming that they deserved 30to rule over Zeus, dividing the offices. 78 The remaining possibility-andit seems to be the natural one-is for everyone to obey such a persongladly, so that those like him will be permanent kings in their city-states.
Chapter 1 4After the matters just discussed, it may perhaps be well to change to an 35investigation of kingship, since we say that it is one of the correct constitutions. What we have to investigate is whether or not it is beneficial fora city-state or territory which is to be well managed to be under a king-ship, or under some other constitution instead, or whether it is benefi-cial for some but not for others. But first it must be determined whether 40there is one single type of kingship or several different varieties. In fact this is easy to see-that kingship includes several types, and 1285'that the manner of rule is not the same in all of them. For kingship inthe Spartan constitution, which is held to be the clearest example ofkingships based on law, does not have authority over everything, butwhen the king leaves the country, he does have leadership in military af- 5fairs. Moreover, matters relating to the gods are assigned to the kings.[ 1 ] This type of kingship, then, is a sort of permanent autocratic gener-alship. For the king does not have the power of life and death, exceptwhen exercising a certain sort of kingship/9 similar to that exercised inancient times on military expeditions, on the basis of the law of force.80Homer provides a clear example. Agamemnon put up with being abused 10
in the assemblies, but when they went out to fight he had the power even of life and death. At any rate, he says: ''Anyone I find far from the battle . . shall have no hope of escaping dogs and vultures, for I myself shall .·
8 1 . Iliad 11.391-393. The last line Aristotle quotes is not in our text. 82. See Plato, Republic 567a-568a. 83. On Pittacus, see 1274b18-23 and note. Alcaeus (born c. 620) was a lyric poet from Mytilene in Lesbos. Antimenides was his brother. 84. Diehl 1.427, fr. 87. 85. Some non-Greek kingships were also of this sort; see 1295•1 1-14. 86. The period described in the Homeric poems. Chapter IS 93
because the first of the line were benefactors of the multitude in thecrafts or war, or through bringing them together or providing them withland, they became kings over willing subjects, and their descendantstook over from them. They had authority in regard to leadership in war,and religious sacrifices not requiring priests. They also d ecided legal 10cases, some doing so under oath, and others not (the oath consisted inlifting up the scepter) . In ancient times, they ruled continuously overthe affairs of the city-state, both domestic and foreign. But later, whenthe kings themselves relinquished some of these prerogatives, and oth- 1Sers were taken away by the crowd in various city-states, only the sacri-fices were left to the kings, and even where there was a kingship worthyof the name, it was only leadership in military affairs conducted beyondthe frontiers that the king held on to. There are, then, these four kinds of kingship. One belongs to the 20heroic age: this was over willing subjects and served certain fixed purposes; the king was general and judge and had authority over matters todo with the gods. The second is the non-Greek kind, which is rule by amaster based on lineage and law. The third is so-called dictatorship, 25which is elective tyranny. Fourth among them is Spartan kingship,which, simply put, is permanent generalship based on lineage. These,then, differ from one another in this way. [5] But there is a fifth kind of kingship, when one person controlseverything in j ust the way that each nation and each city-state controls 30the affairs of the community. It is organized along the lines of householdmanagement. For j ust as household management is a sort of kingshipover a household, so this kingship is household management of one ormore city-states or nations.
Chapter 1 5Practically speaking, then, there are just two kinds of kingship to be examined, namely, the last one and the Spartan. For most of the others liein between them, since they control less than absolute kingship but 35more than Spartan kingship. So our investigation is pretty much abouttwo questions: First, whether or not it is beneficial for a city-state tohave a permanent general (whether chosen on the basis of family or byturns). Second, whether or not it is beneficial for one person to con-trol everything. In fact, however, the investigation of this sort of gener- 1 286"alship has the look of an investigation of LAWS rather than of constitu-tions, since this is something that can come to exist in any constitution. 94 Politics III
So the first question may be set aside. But the remaining sort of kingS ship is a kind of constitution. Hence we must study it and go through the problems it involves. The starting point of the investigation is this: whether it is more ben eficial to be ruled by the best man or by the best laws. Those who think it beneficial to be ruled by a king hold that laws speak only of the uni-10 versal, and do not prescribe with a view to actual circumstances. Conse quently, it is foolish to rule in accordance with written prescriptions in any craft, and doctors in Egypt are rightly allowed to change the treat ment after the fourth day (although, if they do so earlier, it is at their own risk). It is evident, for the same reason, therefore, that the best con-IS stitution is not one that follows written lawsY All the same, the rulers should possess the universal reason as well. And something to which the passionate element is entirely unattached is better than something in which it is innate. This element is not present in the law, whereas every20 human soul necessarily possesses it. But perhaps it ought to be said, to oppose this, that a human being will deliberate better about particulars. In that case, it is clear that the ruler must be a legislator, and that laws must be established, but they must not have authority insofar as they deviate from what is best, though they should certainly have authority everywhere else. As to what the law cannot decide either at all or well, should the one best person rule, or2S everyone? For as things stand now, people come together to hear cases, deliberate, and decide, and the decisions themselves all concern particu lars. Taken individually, any one of these people is perhaps inferior to the best person. But a city-state consists of many people, just like a feast to which many contribute, and is better than one that is a unity and sim-30 ple. That is why a crowd can also judge many things better than any sin gle individual. Besides, a large quantity is more incorruptible, so the multitude, like a larger quantity of water, are more incorruptible than the few. The judgment of an individual is inevitably corrupted when he is overcome by anger or some other passion of this sort, whereas in the same situation it is a task to get all the citizens to become angry and3S make mistakes at the same time. Let the multitude in question be the free, however, who do nothing outside the law, except about matters the law cannot cover-not an easy thing to arrange where numbers are large.88 But suppose there were a
number who were both good men and good citizens, which would bemore incorruptible-one ruler, or a larger number all of whom aregood? Isn't it clear that it would be the larger number? "But such agroup will split into factions, whereas the single person is free of fac- 1286htion." One should no doubt oppose this objection by pointing out thatthey may be excellent in soul just like the single person. So then, if the rule of a number of people, all of whom are good men,is to be considered an aristocracy, and the rule of a single person a king-ship, aristocracy would be more choiceworthy for city-states than king- 5ship (whether the rule is supported by force or not),89 provided that it ispossible to find a number of people who are similar. Perhaps this too isthe reason people were formerly under kingships-because it was rareto find men who were very outstanding in virtue, particularly as thecity-states they lived in at that time were small. Besides, men were madekings because of benefactions, which it is precisely the task of good men 10to confer. When there began to be many people who were similar invirtue, however, they no longer put up with kingship, but looked forsomething communal and established a polity. But when they began toacquire wealth from the common funds, they became less good, and itwas from some such source, so one might reasonably suppose, that oligarchies arose; for they made wealth a thing of honor. 90 Then from oli- 15garchies they changed first into tyrannies, and from tyrannies to democ-racy. For by concentrating power into ever fewer hands, because of ashameful desire for profit, they made the multitude stronger, with theresult that it revolted and democracies arose. Now that city-states havebecome even larger, it is perhaps no longer easy for any other constitu- 20tion to arise besides democracy. 91 But now if one does posit kingship as the best thing for a city-state,how is one to handle the matter of children? Are the descendants to ruleas kings too? If they turn out as some have, it would be harmful. "Butperhaps, because he is in control, he will not give it to his children." But 25this is hardly credible. For it is a difficult thing to do, and demandsgreater virtue than human nature allows.
89. The "force" in question is probably the citizen bodyguards, which Greek kings typically possessed ( 1 285'25-27, 1 286h27-40), and which could be used in a tyrannical fashion.90. Because the end that oligarchy sets for itself is wealth. See 1 3 1 1 '9-1 0; Plato, Republic 554a, Introduction, lxv-lxvi.9 1 . For somewhat different explanations of the changes constitutions undergo, see 1297b l 6-28, 1 3 1 6'1-b27. 96 Politics III
Chapter 1 6 Now that we have reached this point the next topic must be that of the1287• king who does everything according to his own wish, so we must investi gate this. For the so-called king according to law does not, as we said, amount to a kind of constitution, since a permanent generalship can 5 exist in any constitution (for example, in a democracy and an aristoc racy), and many places put one per�on in control of managing affairs. There is an office of this sort in Epidamnus, indeed, and to a lesser ex tent in Opus as well. But as regards so-called absolute kingship (which is where the king rules everything in accord with his own wish), some hold that it is not 10 even in accordance with nature for one person, from among all the citi zens, to be in control, when the city-state consists of similar people. For justice and merit must be by nature the same for those who are by nature similar. Hence, if indeed it is harmful to their bodies for equal people to have unequal food or clothing, the same holds, too, where offices are 15 concerned. The same also holds, therefore, when equal people have what is unequal. Which is precisely why it is j ust for them to rule no more than they are ruled, and, therefore, to do so in turn. But this is already law; for the organization is law.94 Thus it is more choiceworthy to have
law rule than any one of the citizens. And, by this same argument, evenif it is better to have certain people rule, they should be selected as 20guardians of and assistants to the laws. For there do have to be somerulers; although it is not just, they say, for there to be only one; at anyrate, not when all are similar. Moreover, the sort of things at least thatthe law seems unable to decide could not be discovered by a humanbeing either. But the law, having educated the rulers for this special purpose, hands over the rest to be decided and managed in accordance with 25the most just opinion of the rulers. Moreover, it allows them to make anycorrections by introducing anything found by experience to be an improvement on the existing laws. Anyone who instructs LAW to rule wouldseem to be asking GOD and the understanding alone to rule;95 whereassomeone who asks a human being asks a wild beast as well. For appetite 30is like a wild beast, and passion perverts rulers even when they are thebest men. That is precisely why law is understanding without desire. The comparison with the crafts, that it is bad to give medical treatment in accordance with written prescriptions and more choiceworthyto rely on those who possess the craft instead, would seem to be false.For doctors never do things contrary to reason because of friendship, 35but earn their pay by healing the sick. Those who hold political office,on the other hand, do many things out of spite or in order to win favor.And indeed if people suspected their doctors of having been bribed bytheir enemies to do away with them, they would prefer to seek treatmentderived from books. Moreover, doctors themselves call in other doctors 40to treat them when they are sick, and trainers call in other trainers when 128 7hthey are exercising, their assumption being that they are unable to judgetruly because they are judging about their own cases, and while in pain.So it is clear that in seeking what is just they are seeking the mean; forthe law is the mean.96 Again, laws based on custom are more authorita-tive and deal with matters that have more authority than do written laws, 5so that even if a human ruler is more reliable than written laws, he is notmore so than those based on custom. Yet, it is certainly not easy for a single ruler to oversee many things;hence there will have to be numerous officials appointed under him.Consequently, what difference is there between having them there fromthe beginning and having one person appoint them in this way? Besides, 10
as we said earlier,97 if it really is just for the excellent man to rule because he is better, well, two good ones are better than one. Hence the saying "When two go together . . . ," and Agamemnon's prayer, "May ten such counselors be mine. "98 IS Even nowadays, however, officials, such as jurors, have the authority to decide some things the law cannot determine. For, as regards those matters the law can determine, certainly no one disputes that the law it self would rule and decide best. But because some matters can be cov ered by the laws, while others cannot, the latter lead people to raise and 20 investigate the problem whether it is more choiceworthy for the best law to rule or the best man (since to legislate about matters that call for de liberation is impossible). The counterargument, therefore, is not that it is not necessary for a human being to decide such matters, but that there 25 should be many judges, not one only. For each official judges well if he has been educated by the law. And it would perhaps be accounted strange if someone, when judging with one pair of eyes and one pair of ears, and acting with one pair of feet and hands, could see better than many people with many pairs, since, as things stand, monarchs provide 30 themselves with many eyes, ears, hands, and feet. For they appoint those who are friendly to their rule and to themselves as co-rulers. Now if they are not friendly in this way, they will not do as the monarch chooses. But suppose they are friendly to him and his rule-well, a friend is someone similar and equal, so if he thinks they should rule, he must think that those who are equal and similar to him should rule in a similar fashion. These, then, are pretty much the arguments of those who dispute 35 against kingship.
Chapter 1 7 But perhaps these arguments hold in some cases and not in others. For what is by nature both just and beneficial is one thing in the case of rule by a master, another in the case of kingship, and another in the case of rule by a statesman (nothing is by nature both just and beneficial in the 40 case of a tyranny, however, nor in that of the other deviant constitutions, since they come about contrary to nature). But it is surely evident from what has been said that in a case where people are similar and equal, it is1288' neither beneficial nor just for one person to control everything. This
97. At 1 286b3-5. 98. Iliad X.224 and 11.372. Chapter 1 7 99
holds whether there are no laws except the king himself, or whetherthere are laws; whether he is a good person ruling good people, or a notgood one ruling not good ones; and even whether he is their superior invirtue--except in one set of circumstances. What these circumstancesare must now be stated-although we have in a way already stated it.99 5 First, we must determine what kind of people are suited to kingship,what to aristocracy, and what to polity. A multitude should be underkingship when it naturally produces a family that is superior in thevirtue appropriate to political leadership. A multitude is suited to aristocracy when it naturally produces a multitude100 capable of being ruled 10with the rule appropriate to free people by those who are qualified tolead by their possession of the virtue required for the rule of a statesman. And a multitude is suited to polity when there naturally arises in ita warrior multitude101 capable of ruling and being ruled, under a lawwhich distributes offices to the rich on the basis of merit. Whenever ithappens, then, that there is a whole family, or even some one individual I5among the rest, whose virtue is so superior as to exceed that of all theothers, it is just for this family to be the kingly family and to controleverything, and for this one individual to be king. For, as was said ear-lier, this not only accords with the kind of justice customarily put forward by those who establish constitutions, whether aristocratic, oli- 20garchic, or even democratic (for they all claim to merit rule on the basisof superiority in something, though not superiority in the same kind ofthing), but also with what was said earlier. 1 02 For it is surely not properto kill or to exile or to ostracize an individual of this sort, nor to claim 25that he deserves to be ruled in turn. For it is not natural for the part tobe greater than the whole, but this is what happens in the case of some-one who has this degree of superiority. So the only remaining option isfor such a person to be obeyed and to be in control not by turns but unqualifiedly.103 Kingship, then, and what its varieties are, and whether it is beneficial 30for city-states or not, and if so, for which and how, may be determined inthis way.
99. At 1 284'3-b35.100. Reading plethos with Dreizehnter and the mss.101. Reading plethos polemikon with Dreizehnter and the mss.102. At 1284h2S-34.103. The argument in this paragraph is discussed in the Introduction §8. 100 Politics III
Chapter 1 8 We say that there are three correct constitutions, and that the best of them must of necessity be the one managed by the best people. This is the sort of constitution in which there happens to be either one particu lar person or a whole family or a number of people whose virtue is supe- 35 rior to that of all the rest, and where the latter are capable of being ruled and the former of ruling with a view to the most choiceworthy life. Fur thermore, as we showed in our first discussions, 104 the virtue of a man must of necessity be identical to that of a citizen of the best city-state. Hence it is evident that the ways and means by which a man becomes ex- 40 cellent are the same as those by which one might establish a city-state ruled by an aristocracy or a king, and that the education and habits thatJ288h make a man excellent are pretty much the same as those that make him statesmanlike or kingly.1 05 Now that these matters have been determined, we must attempt to discuss the best constitution, the way it naturally arises and how it is es tablished. Anyone, then, who intends to do this must conduct the inves- 5 tigation in the appropriate way. 106
104. III.4-5. 105. See Introduction xxv-xxvi. 106. This sentence appears again in a slightly different form as part of the opening sentence of Book VII. It is bracketed as incomplete by Ross.Chapter 1Among all the crafts and sciences that are concerned not only with a 10part but that deal completely with some one type of thing, it belongs toa single one to study what is appropriate for each type. For example:what sort of physical training is beneficial for what sort of body, that is tosay, what sort is best (for the sort that is appropriate for the sort of bodythat is naturally best and best equipped is necessarily best), and whatsingle sort of training is appropriate for most bodies (since this too is a 15task for physical training). Further, if someone wants neither the condi-tion nor the knowledge required of those involved in competition, it belongs no less to coaches and physical trainers2 to provide this capacitytoo. We see a similar thing in medicine, ship building, clothing manufac-ture, and every other craft. 20 Consequently, it is clear that it belongs to the same science3 to study:[ I ] What the best constitution is, that is to say, what it must be like if it isto be most ideal, and if there were no external obstacles. Also [2] whichconstitution is appropriate for which city-states. For achieving the bestconstitution is perhaps impossible for many; and so neither the unquali- 25fiedly best constitution nor the one that is best in the circumstancesshould be neglected by the good legislator and true statesman. Further,[3] which constitution is best given certain assumptions. For a statesmanmust be able to study how any given constitution might initially come
1. The end of iii. l 8 prepares us for a discussion of the best constitution, but IV does not contain one. Indeed, the opening sentence of IV.2 seems to suggest that the best constitution has already been discussed. This is to some extent true, because much is said about the .best constitution in discussing both other people's candidates for that title and aristocracy and kingship ( 1 289h30-32). But Aristotle's own candidate is not formally discussed until VII-VIII.2. See 1 338b6-8.3. Namely, STATESMANSHIP.
101 102 Politics IV
into existence, and how, once in existence, it might be preserved for the 30 longest time. I mean, for example, when some city-state happens to be governed neither by the best constitution (not even having the necessary resources) nor by the best one possible in the existing circumstances, but by a worse one. Besides all these things, a statesman should know [4] which constitution is most appropriate for all city-states. Consequently, 35 those who have expressed views about constitutions, even if what they say is good in other respects, certainly fail when it comes to what is use ful. For one should not study only what is best, but also what is possible, and similarly what is easier and more attainable by all. As it is, however, some seek only the constitution that is highest and requires a lot of re- 40 sources, while others, though they discuss a more attainable sort, do away with the constitutions actually in place, and praise the Spartan or some other. But what should be done is to introduce the sort of organi-1289' zation that people will be easily persuaded to accept and be able to par ticipate in,4 given what they already have, as it is no less a task to reform a constitution than to establish one initially, just as it is no less a task to correct what we have learned than to learn it in the first place. That is S why, in addition to what has just been mentioned, a statesman should also be able to help existing constitutions, as was also said earlier.5 But this is impossible if he does not know [5] how many kinds of constitu tions there are. As things stand, however, some people think that there is just one kind of democracy and one of oligarchy. But this is not true. So 10 one must not overlook the varieties of each of the constitutions, how many they are and how many ways they can be combined.6 And [6] it is with this same practical wisdom7 that one should try to see both which laws are best and which are appropriate for each of the constitutions. For laws should be established, and all do establish them, to suit the consti tution and not the constitution to suit the laws. For a constitution is the IS organization of offices in city-states, the way they are distributed, what element is in authority in the constitution, and what the end is of each of the communities. 8 Laws, apart from those that reveal what the constitu-
tion is, are those by which the officials must rule, and must guard againstthose who transgress them. Clearly, then, a knowledge of the varieties of 20each constitution and of their number9 is also necessary for establishinglaws. For the same laws cannot be beneficial for all oligarchies or for alldemocracies-if indeed there are several kinds, and not one kind ofdemocracy nor one kind of oligarchy only. 25
Chapter 2Since our initial inquiry concerning constitutions, 1 0 we distinguishedthree correct constitutions (kingship, aristocracy, polity) and three deviations from them (tyranny from kingship, oligarchy from aristocracy,and democracy from polity), and since we have already discussed aristocracy and kingship, for studying the best constitution is the same as 30discussing these names, 11 since each of them tends to be established onthe basis of virtue furnished with resources; and since further, we havedetermined how aristocracy and kingship differ from one another, andwhen a constitution should be considered a kingship, 12 it remains to deal 35with the constitution that is called by the name common to all CONSTITUTIONS, and also with the others--oligarchy, democracy, and tyranny. It is also evident which of these deviations is worst and which secondworst. For the deviation from the first and most divine constitutionmust of necessity be the worst.13 But kingship either must be in name 40only and not in fact or must be based on the great superiority of the per-son ruling as king. Hence tyranny, being the worst, is furthest removed 1289"from being a constitution; oligarchy is second worst (since aristocracy isvery far removed from this constitution); and democracy the most mod-erate. An earlier thinker14 has already expressed this same view, though 5
he did not look to the same thing we do. For he judged that when all these constitutions are good (for example, when an oligarchy is good, and also the others), democracy is the worst of them, but that when they are bad, it is the best. But we say that these constitutions are all of them mistaken, and that it is not right to speak of one kind of oligarchy as bet-10 ter than another, but as less bad. But let us leave aside the judgment of this matter for the present. In stead, we must determine: [ I ] First, how many varieties of the constitu tions there are (if indeed there are several kinds of democracy and oli garchy). Next, [2] which kind is most attainable, and which most15 choiceworthy after the best constitution (if indeed there is some other constitution which, though aristocratic and well constituted, is at the same time appropriate for most city-states), and also which of the other constitutions is more choiceworthy for which people (for democracy is perhaps more necessary than oligarchy for some, whereas for others the20 reverse holds). After these things, [3] how someone who wishes to do so should establish these constitutions (I mean, each kind of democracy or oligarchy). Finally, when we have gone as far as we can to give a succinct account of each of these topics, [4] we must try to go through the ways in which constitutions are destroyed and those in which they are pre-25 served, both in general and in the case of each one separately, and through what causes these most naturally come about.
Chapter 3 The reason why there are several constitutions is that every city-state has several parts. 1 5 For in the first place, we see that all city-states are composed of households; and, next, that within this multitude there30 have to be some who are rich, some who are poor, and some who are in the middle; and that of the rich and of the poor, the one possessing weapons and the other without weapons. We also see that the people comprise a farming part, a trading part, and a vulgar craftsman part. And among the notables there are differences in wealth and in extent of their property-as, for example, in the breeding of horses, since this is35 not easy for those without wealth to do. (That is why, indeed, there were oligarchies among those city-states in ancient times whose power lay in
their cavalry, and who used horses in wars with their neighbors-as, forexample, the Eretrians did, and the Chalcidians, the Magnesians on theriver Menander, and many of the others in Asia.) There are also differ- 40ences based on birth, on virtue, and on everything else of the sort thatwe characterized as part of a city-state in our discussion of aristocracy, 1290"since there we distinguished the number of parts that are necessary toany city-state.16 For sometimes all of these parts participate in the constitution, sometimes fewer of them, sometimes more. It is evident, therefore, that there must be several constitutions that Sdiffer in kind from one another, since these parts themselves also differin kind. For a constitution is the organization of offices, and all consitutions distribute these either on the basis of the power of the participants, or on the basis of some sort of equality common to them (I mean,for example, of the poor or of the rich, or some equality common to 10both).17 Therefore, there must be as many constitutions as there areways of organizing offices on the basis of the superiority and varieties ofthe parts. But there are held to be mainly two constitutions: just as the windsare called north or south, and the others deviations from these, so thereare also said to be two constitutions, democracy and oligarchy. For aris- 15tocracy is regarded as a sort of oligarchy, on the grounds that it is a sortof rule by the few, whereas a so-called polity is regarded as a sort ofdemocracy, 18 just as the west wind is regarded as northerly, and the eastas southerly. 19 According to some people, the same thing also happens inthe case of harmonies, which are regarded as being of two kinds, the Do- 20rian and the Phrygian, and the other arrangements are called eitherPhrygian types or Dorian types. People are generally accustomed, then,to think of constitutions in this way. But it is truer and better to distinguish them, as we have, and say that two constitutions (or one) are wellformed, and that the others are deviations from them, some from the 25well-mixed "harmony," and others from the best constitution, the more
tightly controlled ones and those that are more like the rule of a master being more oligarchic, and the unrestrained and soft ones democratic.20
Chapter 4 30 One should not assert (as some are accustomed to do now)Z1 that democ racy is simply where the multitude are in authority (for both in oli garchies and everywhere else, the larger part is in authority). 22 Nor should an oligarchy be regarded as being where the few are in authority over the constitution. For if there were a total of thirteen hundred peo ple, out of which a thousand were rich people who give no share in office 35 to three hundred poor ones, no one would say that the latter were demo cratically governed even if they were free and otherwise similar to the rich. Similarly, if the poor were few, but stronger than the rich, who were a majority, no one would call such a constitution an oligarchy if the others, though rich, did not participate in office. Thus it is better to say 40 that a democracy exists when the free are in authority and an oligarchyJ29(J exists when the rich are; but it happens that the former are many and the latter few, since many are free but few are rich. Otherwise there would be an oligarchy if offices were distributed on the basis of height (as is 5 said to happen in Ethiopia) or on the basis of beauty, since beautiful peo ple and tall ones are both few in number. Yet these23 are not sufficient to distinguish these constitutions. Rather, since both democracy and oligarchy have a number of parts, we must further grasp that it is not a democracy if a few free people rule 10 over a majority who are not free, as, for example, in Apollonia on the Ionian Gulf and in Thera. For in each of these city-states the offices were held by the well born, the descendants of the first colonists, although they were few among many. Nor is it an oligarchy24 if the rich rule be 15 cause they are the multitude, as was formerly the case in Colophon, where the majority possessed large properties before the war against the
20. The example of music results in this extended musical metaphor in which "harmony" (harmonia) is used as a metaphor for a balanced mixture in a constitution. The well-mixed constitution is identified in IV.9. 21. See Plato, Statesman 29ld. 22. See 1 294•1 1-14 for an explanation. 23. Namely, wealth and freedom. 24. Reading oligarchia with Ross. Alternatively (Dreizehnter and the mss.): "democracy (demos)." Chapter 4 1 07
Lydians.25 Rather, it is a democracy when the free and the poor who area majority have the authority to rule, and an oligarchy when the rich andwell born, who are few, do. 26 20 It has been stated, then, that there are a number of constitutions andwhy this is so. But let us now say why there are more than the ones mentioned,27 what they are, and how they arise, taking as our starting pointwhat was agreed to earlier.28 For we are agreed that every city-state hasnot only one part but several. If we wanted to grasp the kinds of animals, we would first determine 25what it is necessary for every animal to have: for example, certain of thesense organs; something with which to work on and absorb food (such asa mouth and a stomach); and also parts by which it moves. If these werethe only parts, but they had varieties (I mean, for example, if there wereseveral types of mouths, stomachs, and sense organs, and also of loco- 30motive parts), then the number of ways of combining these would necessarily produce a number of types of animals. For the same animal can-not have mouths or ears of many different varieties. Hence, when thesehave been grasped, all the possible ways of pairing them together willproduce kinds of animals, that is to say, as many kinds of animals as 35there are combinations of the necessary parts.29 It is the same way withthe constitutions we have mentioned. For city-states are constituted notout of one but many parts, as we have often said . One of these parts is [ I ] the multitude concerned with food, the onescalled farmers. A second is [2] those called vulgar craftsman. They are 40concerned with the crafts without which a city-state cannot be managed 1291"(of these some are necessary, whereas others contribute to luxury or fineliving). A third is [3] the traders (by which I mean those engaged in sell-ing and buying, retail trade, and commerce) . A fourth is [4] the hired Ia- 5borers. A fifth is [5] the defensive warriors, which are no less necessarythan the others, if the inhabitants are not to become the slaves of any aggressor. For no city-state that is naturally slavish can possibly deserve to
30. At 369d-371e. 3 1 . See 1253'37-39, 1 328b l J-15. 32. The former are those that deal with our necessary needs; the latter, the war riors, etc. What is evident is that a city-state must at least have warriors among its parts. But it will often need a navy as well. See VII.S for further discussion. 33. The unidentified sixth part may be the class of priests (listed as an impor tant part of any city-state at 1328h 1 1-1 3). But it is also possible that the long aside about the Republic has caused Aristotle to go astray in his numbering. Chapter 4 1 09
34. Deliberating in a way that is noble and just requires practical wisdom, the virtue peculiar to a statesmen ( 1 277h2S-26, NE 1 14 l b23-24).35. Presumably, that of statesmen.36. A type (genus) is divided into kinds (species) on the basis of opposite vari eties (differentia). If these characteristics are themselves indivisible, there will then be just two kinds (species). See PA 643'3 1-b8, especially 643'7-8. The sorts of superiority claimed by the rich and the poor are wealth and freedom respectively.37. See VI. l-7.38. See 1 289h27-1290'1 3 . 1 10 Politics I V
other kind of multitude there may be. The notables are distinguished by wealth, good birth, virtue, education, and the other characteristics that are ascribed on the basis of the same sort of difference. 30 [ 1] The first democracy, then, is the one that is said to be most of all based on equality. For the law in this democracy says that there is equal ity when the poor enjoy no more superiority than the rich and neither is in authority but the two are similar. For if indeed freedom and equality are most of all present in a democracy, as some people suppose,39 this 35 would be most true in the constitution in which everyone participates in the most similar way. But since the people are the majority, and majority opinion has authority, this constitution is necessarily a democracy. This, then, is one kind of DEMOCRACY.40 [2] Another is where offices are filled on the basis of property assess ments, although these are low, and where anyone who acquires the req- 40 uisite amount may participate, whereas anyone who loses it may not. [3] Another kind of democracy is where all uncontested citizens41 partici-1292" pate, and the law rules. [4] Another kind of democracy is where everyone can participate in office merely by being a citizen,42 and the law rules. [5] Another kind of democracy is the same in other respects, but the 5 multitude has authority, not the law. This arises when DECREES have au thority instead of laws; and this happens because of POPULAR LEADERS. For in city-states that are under a democracy based on law, popular lead ers do not arise. Instead, the best citizens preside.43 Where the laws are 10 not in authority, however, popular leaders arise. For the people become a monarch, one person composed of many, since the many are in authority not as individuals, but all together. When Homer says that "many headed rule is not good,"44 it is not clear whether he means this kind of rule, or the kind where there are a number of individual rulers. In any 15 case, a people of this kind, since it is a monarchy, seeks to exercise monarchic rule through not being ruled by the law, and becomes a mas ter. The result is that flatterers are held in esteem, and that a democracy of this kind is the analog of tyranny among the monarchies. That is also why their characters are the same: both act like masters toward the bet-
ter people; the decrees of the one are like the edicts of the other; a pop-ular leader is either the same as a flatterer or analogous. Each of these 20has special power in his own sphere, flatterers with tyrants, popularleaders with a people of this kind. They are responsible for decreesbeing in authority rather than laws because they bring everything beforethe people. This results in their becoming powerful because the people 25have authority over everything, and popular leaders have it over the peo-ple's opinion, since the multitude are persuaded by them. Besides, thosewho make accusations against officials say that the people should decidethem. The suggestion is gladly accepted, with the result that all officesare destroyed. One might hold, however, that it is reasonable to object that this kind 30of democracy is not a CONSTITUTION at all, on the grounds that there isno constitution where the laws do not rule. For the law should rule universally over everything, while offices and the constitution45 should de-cide particular cases. So, since democracy is one of the constitutions, it 35is evident that this sort of arrangement, in which everything is managedby decree, is not even a democracy in the most authoritative sense, sinceno decree can possibly be universal.46 The kinds of democracy, then, should be distinguished in this way.
Chapter 5Of the kinds of oligarchy, [ 1 ] one has offices filled on the basis of such ahigh property assessment that the poor, even though they are the major- 40ity, do not participate, but anyone who does acquire the requisiteamount may participate in the constitution. [2] In another the offices arefilled on the basis of a high assessment and they themselves elect some- 1 292hone to fill any vacancy. If they elect from among all of these,47 it is heldto be more aristocratic; if from some specified people, oligarchic. 48 [3] In
45. Reading ten politeian with Dreizehnter and the mss. The oddity of the claim that the constitution decides particular cases is reduced if we remember that "the governing class is the constitution" ( 1 278b l l). In the kind of democ racy under discussion, the people are the governing class.46. With the explicable exception of absolute kingship (III. 17), a genuine CON STITUTION is defined by and governed in accordance with LAWS, which, un like DECREES, must be universal. Hence a democracy governed by decrees is arguably not a constitution.47. All who have the assessed amount of property.48. See 1 300'8-b7 for an explanation. 1 12 Politics IV
S another kind of oligarchy a son succeeds his father. [4] In a fourth what was just mentioned occurs, and not the law but the officials rule. This is to oligarchies what tyranny is to monarchies, and to the democracy we10 spoke of last among democracies. Such an oligarchy is called a dynasty. These, then, are the kinds of oligarchy and democracy. But one must not overlook the fact that it has happened in many places that constitu tions which are not democratic according to their laws are none the less governed democratically because of custom and training. Similarly, inIS other places, the reverse has happened: the constitution is more democ ratic in its laws, but is governed in a more oligarchic way as a result of custom and training. This happens especially after there has been a change of constitution. For the change is not immediate, but people are content at first to take from others in smaller ways. Hence the pre-exist-20 ing laws remain in effect, although those who have changed the consti tution are dominant.
Chapter 6 It is evident from what has been said that there are this many kinds of democracy and oligarchy. For either all of the aforementioned parts of the people must participate in the constitution, or some must and others25 not. ( 1 ] So when the part that farms and that owns a moderate amount of property has authority over the constitution, it is governed in accor dance with the laws. For they have enough to live on as long as they keep working, but they cannot afford any leisure time. So they put the law in charge and hold only such assemblies as are necessary. And the others may participate when they have acquired the property assessment de-30 fined by the laws. Hence all those who have acquired it may participate. For, generally speaking, it is oligarchic when not all of these may partic ipate, though not if what makes being at leisure impossible is the absence of revenues.49 This, then, is one kind of democracy and these are the rea sons for it. [2] Another kind arises through the following distinction. For it isJS possible for everyone of uncontested birth to participate, but for only those who have leisure actually to do so. Hence in this kind of democ racy the laws rule because there is no revenue. (3] A third kind is when
all who are free may participate in the constitution, but, for the reasonjust mentioned, they do not participate, so that law necessarily rules in 40this kind also. [4] A fourth kind of democracy was the last to arise incity-states. For because city-states have become much larger than the 1293"original ones and possess abundant sources of revenue, everyone sharesin the constitution, and so the multitude preponderates. And they all doparticipate and govern, because even the poor are able to be at leisure, 5since they get paid. A multitude of this sort is particularly leisured, in-deed, since care for their own property does not impede them. But itdoes impede the rich, who often fail to take part in the assembly or serveon juries as a result. Hence the multitude of poor citizens come to haveauthority over the constitution and not the laws. The kinds of democ- 10racy, then, are such and so many because of these necessities. As for the kinds of oligarchy, [ 1] when a number of people own prop-erty, but a smaller amount-not too much-this is the first kind of oligarchy. For anyone who acquires the amount may participate. And because of the multitude participating in the governing class, law is 15necessarily in authority, not human beings. For it is necessary for themto consent to having the law rule and not themselves, the more removedthey are from exercising monarchy, and the more they have neither somuch property that they can be at leisure without worrying nor so littlethat they need to be supported by the city-state. 20 [2] But if the property owners are fewer and their properties greaterthan those mentioned before, the second kind of oligarchy arises. For,being more powerful, the property owners expect to get more. Hencethey themselves elect from among the rest of the citizens those who areto enter the governing class. But as they are not yet powerful enough torule without law, they pass a law of this sort. 50 25 [3] But if they tighten this process by becoming fewer and owninglarger properties, the third stage of oligarchy is reached, where theykeep the offices in their own hands, but do so in accordance with a lawrequiring deceased members to be succeeded by their sons. [ 4] Butwhen they now tighten it excessively through their property holdingsand the number of their friends, a dynasty of this sort approximates a 30monarchy, and human beings are in authority, not law. This is the fourthkind of oligarchy, corresponding to the final kind of democracy.
50. Permitting already existing members of the ruling oligarchy to elect new members. 1 14 Politics IV
Chapter 7 35 There are also two constitutions besides democracy and oligarchy, one of which is mentioned by everyone and which we said was one of the four kinds of constitutions. The four they mention are monarchy, oligarchy, democracy, and, fourth, so-called aristocracy. There is a fifth, however, which is referred to by the name shared by all constitutions: the one 40 called a politeia (polity). But because it does not occur often, it gets over looked by those who try to enumerate the kinds of constitutions, and, like129Jh Plato, 51 list only the four in their discussion of constitutions. It is well to call the constitution we treated in our first discussions an aristocracy.52 For the only constitution that is rightly called an aristoc racy is the one that consists of those who are unqualifiedly best as regards virtue, and not of those who are good men only given a certain assump- 5 tion. For only here is it unqualifiedly the case that the same person is a good man and a good citizen. But those who are good in other constitu tions are so relative to their constitutions. Nevertheless, there are some constitutions that differ both from constitutions that are oligarchically governed and from so-called polity, and are called aristocracies. For a constitution where officials are elected not only on the basis of wealth 10 but also on the basis of merit differs from both of these and is called aris tocratic. For even in those constitutions where virtue is not a concern of the community, there are still some who are of good repute and held to be decent. Hence wherever a constitution looks to wealth, virtue, and the 15 people (as it does in Carthage), it is aristocratic, 53 as also are those, like the constitution of the Spartans, which look to only two, virtue and the people, and where there is a mixture of these two things, democracy and virtue. There are, then, these two kinds of aristocracy besides the first, which is the best constitution; and there is also a third, namely, [4] those 20 kinds of so-called polity that lean more toward oligarchy.
Chapter 8 It remains for us to speak about so-called polity and about tyranny. We have adopted this arrangement, even though neither polity nor the aris-
tocracies just mentioned are deviant, because in truth they all fall shortof the most correct constitution, and so are counted among the devia- 25tions, and these deviations are deviations from them, as we mentioned inthe beginning. 54 On the other hand, it is reasonable to treat tyranny last,since it is least of all a constitution, and our inquiry is about constitu-tions. So much for the reason for organizing things in this way. 30 But we must now set forth our views on polity. Its nature should bemore evident now that we have determined the facts about oligarchy anddemocracy. For polity, to put it simply, is a mixture of oligarchy anddemocracy. It is customary, however, to call those mixtures that lean toward democracy polities, and those that lean more toward oligarchy aris- 35tocracies, because education and good birth more commonly accompanythose who are richer. Besides, the rich are held to possess already whatunjust people commit injustice to get, which is why the rich are referredto as noble-and-good men, and as notables. So since aristocracies strive 40to give superiority to the best citizens, oligarchies too are said to consistprimarily of noble-and-good men. And it is held to be impossible for acity-state to be well governed if it is not governed aristocratically, but by 1294•bad people, and equally impossible for a city-state that is not well gov-erned to be governed aristocratically. But GOOD GOVERNMENT does notexist if the laws, though well established, are not obeyed. Hence we musttake good government to exist in one way when the established laws areobeyed, and in another when the laws that are in fact obeyed are well es- 5tablished (for even badly established laws can be obeyed). The secondsituation can come about in two ways: people may obey either the bestlaws possible for them, or the unqualifiedly best ones. Aristocracy is held most of all to exist when offices are distributed onthe basis of virtue. For virtue is the defining mark of aristocracy, wealth 10of oligarchy, and freedom of democracy. But MAJORITY opinion is foundin all of them. For in oligarchy and aristocracy and in democracies, theopinion of the major part of those who participate in the constitutionhas authority. Now in most city-states the kind of constitution iswrongly named, since the mixture aims only at the rich and the poor, at 15wealth and freedom. For among pretty much most people the rich aretaken to occupy the place of noble-and-good men. But there are in factthree grounds for claiming equal participation in the constitution: freedom, wealth, and virtue. (The fourth, which they call good birth, is a 20
Chapter 9 After what has been said, let us next discuss how, in addition to democ- 30 racy and oligarchy, so-called polity arises, and how it should be estab lished. At the same time, however, the defining principles of democracy and oligarchy will also become clear. For what we must do is get hold of the division of these, and then take as it were a token from each to put together. 55 35 There are three defining principles of the combination and mixture: [ 1 ) One is to take legislation from both constitutions. For example, in the case of deciding court cases, oligarchies impose a fine on the rich if they do not take part in deciding court cases, but provide no payment for 40 the poor, whereas democracies pay the poor but do not fine the rich. But what is common to both constitutions and a mean between them is doing both. And hence this is characteristic of a polity, which is a mix-/ 294h ture formed from both. This, then, is one way to conjoin them. [2] An other is to take the mean between the organizations of each. In democra cies, for example, membership in the assembly is either not based on a property assessment at all or on a very small one, whereas in oligarchies it is based on a large property assessment. The common position here is to require neither of these assessments but the one that is in a mean be- 5 tween the two of them. [3] A third is to take elements from both organi zations, some from oligarchic law and others from democratic law. I mean, for example, it is held to be democratic for officials to be chosen
Chapter 1 01295• It remained for us to speak about tyranny, not because there is much to say about it, but so that it can take its place in our inquiry, since we as sign it too a place among the constitutions. Now we dealt with kingship in our first discussions59 (when we investigated whether the kind of 5 kingship that is most particularly so called is beneficial for city-states or not beneficial, who and from what source should be established in it, and in what manner). And we distinguished two kinds of tyranny while we were investigating kingship, because their power somehow also overlaps 10 with kingship, owing to the fact that both are based on law. For some non-Greeks choose [ 1 ] autocratic monarchs, and in former times among the ancient Greeks there were [2] people called dictators who became monarchs in this way. There are, however, certain differences between 15 these; but both were kingly in as much as they were based on law, and in volved monarchical rule over willing subjects; but both were tyrannical, in as much as the monarchs ruled like masters in accordance with their own judgment.60 But [3] there is also a third kind of tyranny, which is held to be tyranny in the highest degree, being a counterpart to absolute kingship. Any monarchy is necessarily a tyranny of this kind if the monarch rules in an unaccountable fashion over people who are similar 20 to him or better than him, with an eye to his own benefit, not that of the ruled. It is therefore rule over unwilling people, since no free person willingly endures such rule. The kinds of tyranny are these and this many, then, for the aforemen tioned reasons.
Chapter 1 1 25 What is the best constitution, and what is the best life for most city states and most human beings, judging neither by a virtue that is beyond the reach of ordinary people, nor by a kind of education that requires natural gifts and resources that depend on luck, nor by the ideal consti tution, but by a life that most people can share and a constitution in 30 which most city-states can participate? For the constitutions called aris tocracies, which we discussed just now,61 either fall outside the reach of
59. At III.l4-17. 60. See III.l4. 6 1 . At 1 29Jb7- 2 1 . Chapter 11 1 19
most city-states or border on so-called polities (that is why the two haveto spoken about as one). Decision about all these matters depends on the same elements. For if 35what is said in the Ethics is right, and a happy life is the one that expresses virtue and is without impediment, and virtue is a mean, then themiddle life, the mean that each sort of person can actually achieve, mustbe best.62 These same defining principles must also hold of the virtueand vice of a city-state or a constitution, since a constitution is a sort of 40life of city-state. In all city-states, there are three parts of the city-state: the very rich, 1295'the very poor; and, third, those in between these. So, since it is agreedthat what is moderate and in a mean is best, it is evident that possessinga middle amount of the GOODS of luck is also best. For it most readily 5obeys reason, whereas whatever is exceedingly beautiful, strong, wellborn, or wealthy, or conversely whatever is exceedingly poor, weak, orlacking in honor, has a hard time obeying reason. For the former sorttend more toward ARROGANCE and major vice, whereas the latter tendtoo much toward malice and petty vice; and wrongdoing is caused in the 10one case by arrogance and in the other by malice.63 Besides, the middleclasses are least inclined either to avoid ruling or to pursue it, both ofwhich are harmful to city-states. Furthermore, those who are superior in the goods of luck (strength,wealth, friends, and other such things) neither wish to be ruled nor 15know how to be ruled (and this is a characteristic they acquire right fromthe start at home while they are still children; for because of their luxurious lifestyle they are not accustomed to being ruled, even in school).Those, on the other hand, who are exceedingly deprived of such goodsare too humble. Hence the latter do not know how to rule, but only howto be ruled in the way slaves are ruled, whereas the former do not knowhow to be ruled in any way, but only how to rule as masters rule. The re- 20suit is a city-state consisting not of free people but of slaves and masters,the one group full of envy and the other full of arrogance. Nothing isfurther removed from a friendship and a community that is political. Forcommunity involves friendship, since enemies do not wish to share evena journey in common. But a city-state, at least, tends to consist as muchas possible of people who are equal and similar, and this condition be- 25longs particularly to those in the middle. Consequently, this city-state,
the one constituted out of those from which we say the city-state is nat urally constituted, must of necessity be best governed. Moreover, of all citizens, those in the middle survive best in city-states. For neither do 30 they desire other people's property as the poor do, nor do other people desire theirs, as the poor desire that of the rich. And because they are neither plotted against nor engage in plotting, they live out their lives free from danger. That is why Phocylides did well to pray: "Many things are best for those in the middle. I want to be in the middle in a city state."64 It is clear, therefore, that the political community that depends on 35 those in the middle is best too, and that city-states can be well governed where those in the middle are numerous and stronger, preferably than both of the others, or, failing that, than one of them. For it will tip the balance when added to either and prevent the opposing extremes from arising.65 That is precisely why it is the height of good luck if those who 40 are governing own a middle or adequate amount of property, because1296• when some people own an excessive amount and the rest own nothing, either extreme democracy arises or unmixed oligarchy or, as a result of both excesses, tyranny. For tyranny arises from the most vigorous kind of democracy and oligarchy,66 but much less often from middle constitu- 5 tions or those close to them. We will give the reason for this later when we discuss changes in constitutions.67 That the middle constitution is best is evident, since it alone is free from faction. For conflicts and dissensions seldom occur among the cit izens where there are many in the middle. Large city-states are also freer from faction for the same reason, namely, that more are many in the 10 middle. In small city-states, on the other hand, it is easy to divide all the citizens into two, so that no middle is left and pretty well everyone is ei ther poor or rich. Democracies are also more stable and longer lasting than oligarchies because of those in the middle (for they are more nu- 15 merous in democracies than in oligarchies and participate in office more), since when the poor predominate without these, failure sets in and they are quickly ruined. The fact that the best legislators have come from the middle citizens should be regarded as evidence of this. For
64. Diehl I.SO, fr. 1 0. Phocylides was a sixth century poet from Miletus. 65. By joining the poor it prevents extreme oligarchy; by joining the rich it pre vents extreme democracy. 66. See 1 3 1 2b34-38, 1 3 1 0b3-4. 67. Perhaps a reference to 1 308"18-24. Chapter l2 121
Solon was one of these, as is clear from his poems, as were Lycurgus (forhe was not a king), Charondas, and pretty well most of the others. 20 It is also evident from these considerations why most constitutionsare either democratic or oligarchic. For because the middle class in themis often small, whichever of the others preponderates (whether theproperty owners or the people), those who overstep the middle way con- 25duct the constitution to suit themselves, so that it becomes either ademocracy or an oligarchy. In addition to this, because of the conflictsand fights that occur between the people and the rich, whenever oneside or the other happens to gain more power than its opponents, theyestablish neither a common constitution nor an equal one, but take their 30superiority in the constitution as a reward of their victory and make inthe one case a democracy and in the other an oligarchy. Then too each ofthose who achieved leadership in Greece68 has looked to their own constitutions and established either democracies or oligarchies in citystates, aiming not at the benefit of these city-states but at their own. As a 35consequence of all this, the middle constitution either never comes intoexistence or does so rarely and in few places. For among those who havepreviously held positions of leadership, only one man69 has ever beenpersuaded to introduce this kind of organization, and it has now becomecustomary for those in city-states not even to wish for equality, but ei- 40ther to seek rule or to put up with being dominated . 1296b What the best constitution is, then, and why it is so is evident fromthese considerations. As for the other constitutions (for there are, as wesay, several kinds of democracies and of oligarchies), which of them is tobe put first, which second, and so on in the same way, according to 5whether it is better or worse, is not hard to see now that the best hasbeen determined. For the one nearest to this must of necessity always bebetter and one further from the middle worse-provided one is notjudging on the basis of certain assumptions. I say "on the basis of certain assumptions," because it often happens that, while one constitutionis more choiceworthy, nothing prevents a different one from being more 10beneficial for some.
Chapter 1 2The next thing to go through after what has been said is which constitution and which kind of it is beneficial for which and which kind of peo-
pie. First, though, a general point must be grasped about all of them, namely, that the part of a city-state that wishes the constitution to con- IS tinue must be stronger than any part that does not.7° Every city-state is made up of both quality and quantity. By "quality," I mean FREEDOM, wealth, education, and good birth; by "quantity," I mean the superiority of size. But it is possible that the quality belongs to one of the parts of 20 which a city-state is constituted, whereas the quantity belongs to an other. For example, the low-born may be more numerous than the well born or the poor more numerous than the rich, but yet the one may not be as superior in quantity as it is inferior in quality. Hence these have to be judged in relation to one another. Where the multitude of poor peo- 25 ple is superior in the proportion mentioned,71 there it is natural for a democracy to exist, with each particular kind of democracy correspond ing to the superiority of each particular kind of the people. For example, if the multitude of farmers is predominant, it will be the first kind of democracy; if the vulgar craftsmen and wage earners are, the last kind; 30 and similarly for the others in between these. But where the multitude of those who are rich and notable is more superior in quality than it is inferior in quantity, there an oligarchy is natural, with each particular kind of oligarchy corresponding to the superiority of the multitude of oligarchs, in the same way as before. 72 But the legislator should always include the middle in his constitu- 35 tion: if he is establishing oligarchic laws, he should aim at those in the middle, and if democratic ones, he must bring them in by these laws. And where the multitude of those in the middle outweighs either both of the extremes together, or even only one of them, it is possible to have 40 a stable constitution. For there is no fear that the rich and the poor will1297" conspire together against these, since neither will ever want to serve as slaves to the other; and if they look for a constitution that is more com mon than this, they will find none. For they would not put up with rul ing in turn, because they distrust one another; and an ARBITRATOR is 5 most trusted everywhere, and the middle person is an arbitrator. The better mixed a constitution is, the more stable it is. But many of those who wish to establish aristocratic constitutions make the mistake not
only of granting more to the rich, but also of deceiving the people. Forsooner or later, false goods inevitably give rise to a true evil; for the ac- 10quisitive behavior of the rich does more to destroy the constitution thanthat of the poor. 73
Chapter 1 3The devices used in constitutions to deceive the people are five in num-ber, and concern the assembly, offices, the courts, weapons, and physical 15training. [ 1 ] As regards the assembly: allowing all citizens to attend assemblies, but either imposing a fine only on the rich for not attending, ora much heavier one on them. [2] As regards offices: not allowing thosewith an assessed amount of property to swear off,74 but allowing the poor 20to do so. [3] As regards the courts: fining the rich for not serving on ju-ries, but not the poor, or else imposing a large fine on the former and asmall one on the latter, as in the laws of Charondas. In some places,everyone who has enrolled may attend the assembly and serve on juries,but once they have enrolled, if they do not attend or serve, they are 25heavily fined. The aim is to get people to avoid enrolling because of thefine, and not to serve or to attend because of not being enrolled. Theylegislate in the same way where possessing hoplite arms and physicaltraining are concerned. [4] For the poor are permitted not to possess 30weapons, but the rich are fined if they do not; [5] and if they do nottrain, there is no fine for the former, but the latter are fined. That waythe rich will participate because of the fine, whereas the poor, not beingin danger of it, will not participate. These legislative devices are oligarchic; in democracies there are op- 35posite devices. For the poor are paid to attend the assembly and serve onjuries, and the rich are not fined for failing to. If one wants to mix justly,then, it is evident that one must combine elements from either side, andpay the poor while fining the rich. For in this way everyone would par- 40ticipate, whereas in the other way the constitution comes to belong toone side alone. The constitution should consist only of those who 1297bpossess weapons; but it is impossible unqualifiedly to define the size ofthe relevant property assessment, and say that it must be so much. One
should instead look for what amount15 is the highest that would let thoseS who participate in the constitution outnumber those who do not, and fix on that. For the poor are willing to keep quiet even when they do not participate in office, provided no one treats them arrogantly or takes away any of their property (not an easy thing, however, since those who10 do participate in the governing class are not always cultivated people). People are also in the habit of shirking in time of war if they are poor and do not receive provisions; but if food is provided, they will fight. 76 In some places, the constitution consists not only of those who are serving as hoplites but also of those who have served as hoplites in the past. In Malea, the constitution consisted of both, although the officialsIS were elected from among the active soldiers. Also the first constitution that arose among the Greeks after kingships also consisted of the defen sive warriors.77 Initially, it consisted of the cavalrymen, since strength and superiority in war lay in them. For a hoplite force is useless without20 organized formations, and experience in such things and organizations did not exist among the ancients. Hence their strength lay in their cav alry. But as city-states grew larger and those with hoplite weapons be came a stronger force, more people came to participate in the constitu tion. That is precisely why what we now call polities used to be called25 democracies. But the ancient constitutions were oligarchic and kingly, and quite understandably so. For because of their small population they did not have much of a middle class, so that, being small in number and poor in organization, the people put up with being ruled. We have said, then, [ 1 ] why there are several constitutions-[1 . 1] why30 there are others besides those spoken of (for democracy is not one in number, and similarly with the others), [ 1 .2] what their varieties are, and [ 1 .3] why they arise. In addition, [2] we have said which constitution is best, for the majority of cases, and [3] among the other constitutions which suits which sort of people.
Chapter 1 4 As regards what comes next, let us once again discuss constitutions gen-35 erally and each one separately, taking the starting point that is appropri-
82. Democratic constitutions favored election by lot, but were willing to make an exception when the office (for example, a generalship) required expert knowledge ( 1 3 17h20-21). 83. See 1 292'4-30. 84. Alternatively (Dreizehnter and the mss.): "elected or (e) chosen by lot." 85. Reading e with Dreizehnter. Chapter 15 127
to the courts. For they establish a fine for those people they want to haveon juries to ensure that they serve (whereas democrats pay the poor).The same should be done in the case of assemblies too, for they will deliberate better if they all deliberate together, the people with the nota- 20bles, and the latter with the multitude. It is beneficial too if those who dothe deliberating are elected, or chosen by lot, in equal numbers fromthese parts. And even if the democrats among the citizens86 are greatlysuperior in numbers, it is beneficial not to provide pay for all of them,but only for a number to balance the number of notables, or to exclude 25the excess by lot. In oligarchies, however, it is beneficial either to select some additionalpeople from the multitude of citizens to serve as officials or to establisha board of officials like the so-called preliminary councilors or lawguardians that exist in some constitutions, and then have the assemblydeal only with issues that have been considered by this board. In thisway, the people will share in deliberation, but will not be able to abolish 30anything connected to the constitution. It is also beneficial to have thepeople vote only on decrees brought before them that have already undergone preliminary deliberation, or on nothing contrary to them, orelse to let all advise and have only officials deliberate. One should in factdo the opposite of what happens in polities. 87 For the multitude should 35have authority when vetoing measures but not when approving them; inthe latter case, they should be referred back to the officials instead. Forin polities, they do the contrary, since the few have authority when veto-ing decrees but not when passing them; decrees of the latter sort are al-ways referred to the majority instead. 40 This, then, is the way the deliberative part, the part that has authorityover the constitution, should be determined. 88 1299"
Chapter 1 5[2] Next after these things comes the division of the offices. 89 For thispart of a constitution too has many varieties: how many offices there are;with authority over what things; with regard to time: how long each 5
86. Reading politon with Ross rather than politikon ("statesmen") with Dreizehnter and the mss.87. Or constitutions generally.88. Reading dei . . . di0risthai with Dreizehnter.89. This topic is further discussed in Vl.8. 128 Politics IV
office is to last (some make it six months, some less, some make it a year, some a longer period); and whether they are to be held permanently or for a long time, or neither of these, but instead to be held by the same person several times, or not even twice but only once; and further, as re-10 gards the selection of officials: from whom they should come, by whom, and how. For one should be able to determine how many ways all these can be handled, and then fit the kinds of offices to the kinds of constitu tions for which they are beneficial.I5 But even to determine what should be called an office is not easy. For a political community needs many sorts of supervisors, so that not everyone who is selected by vote or by lot can be regarded as an official. In the first place, for example, there are the priests: for a priesthood must be regarded as something other than and apart from the political offices. Besides, patrons of the theater and heralds are elected, ambas-20 sadors too. But some sorts of supervision are political, either concerned with all the citizens involved in a certain activity (as a general supervises those who are serving as soldiers) or some part of them (for example, the supervisors of women or children). Some are related to household man agement (for corn rationers are often elected),90 while others are subor dinate, and are of the sort that, when there are the resources, are as signed to slaves. Simply speaking, however, the offices most properly so called are25 those to which are assigned deliberation, decision, and issuing orders about certain matters, especially the latter, since issuing orders is most characteristic of office. This problem makes scarcely any difference in practice, but since terminological disputes have not been resolved, there30 is some theoretical work yet to be done. One might rather raise a problem with regard to any constitution about what sorts of offices and how many of them are necessary for the existence of a city-state,91 and which sorts, though not necessary, are yet useful with a view to an excellent constitution, but one might particu larly raise it with regard to constitutions in small city-states. For in large35 city-states one can and should assign a single office to a single task. For because there are many citizens, there are many people to take up office, so that some offices are held again only after a long interval and others are held only once. Also every task is better performed when its supervi-
90. In times of scarcity or when a gift of corn had been given to the city-state, a corn rationer (sitometres) was elected to distribute it among the citizens. 9 1 . Listed in VI.8. Chapter IS 1 29
92. A common claim, see 1 252h l -5, 127Jh9-15; also Plato, Republic 370a-b, 374a-c, 394e, 423c-d, 433a, 443b-c, 453b.93. A spit-lamp (obeliskoluchnion) was a military tool which could be used either as a roasting spit or as a lamp holder.94. See 1 298h26-1299'2. 1 30 Politics IV
In the case o f each o f these varieties, there are four99 different ways toproceed. Either all select from all by election or all select from all bylot100 (and101 from all either by sections-by tribe, for example, or bydeme or clan, until all the citizens have been gone through---{)r from all 25on every occasion); or from some by election or from some by lot;102 orpartly in the first way and partly in the second. Again, if only some dothe selecting, they may do so either from all by election or from all bylot; or from some by election or from some by lot; or partly in the firstway and partly in the second-that is to say, for some from all by elec-tion and for some by lot. 103 This gives rise to twelve ways, setting aside 30two of the combinations. 104 Three of these ways of selecting are democratic, namely, when all select from all by election, by lot, or by both (thatis, for some offices by election and for some by lot). But when not all se-lect at the same time, but do so for all from all or from some, whether byelection, lot, or both, or from all for some offices and from some for oth- 35ers, whether by election, lot, or both (by "both," I mean some by lot andothers by election)-it is characteristic of a polity. When some appointfrom all, whether by election, lot, or both (for some offices by lot forothers by vote), it is oligarchic-although it is more oligarchic to do soby both. But when some offices are selected for from all and others from 40some or when some are selected for by election and some by vote, this is
some are selectable, (2.2.3) all are selectable for some offices and some are selectable for others; (2.3 . 1) selection is by lot, (2.3.2) selection is by elec tion, (2.3.3) selection is by lot for some offices and by election for others. 99. Reading tettares with the mss in place of Ross's conjectural hex. The text of this entire paragraph is difficult, and many reorganizations and emenda tions have been proposed.100. Deleting the material added by Ross.101. Deleting ei, which Newman brackets.102. Adding e ek tinon hairesei e ek tiniin klero{i), which also appears at •28-29.103. Deleting the material added by Ross.104. The twelve ways referred to are: ( 1 ) all select from all by election; (2) all se lect from all by lot; (3) all select from some by election; (4) all select from some by lot; (5) all select from all partly by election and partly by lot; (6) all select from some partly by election and partly by lot; (7) some select from all by election; (8) some select from all by lot; (9) some select from some by election; ( 10) some select from some by lot; ( 1 1 ) some select from all partly by election and partly by lot; ( 1 2) some select from some partly by election and partly by lot. The two omitted combinations are: (2. 1 .3) all select for some offices and some select for others, and (2.2.3) all are selectable for some offices and some are selectable for others. 132 Politics IV
Chapter 1 6 Of the three parts, 105 it remains to speak about [3] the judicial. And we must grasp the ways that it can be organized by following the same sup position as before. The differences between courts are found in three 15 defining principles: from whom; about what; and how. From whom: I mean whether they are selected from all or from some. About what: how many kinds of courts are there. How: whether by lot or by election. First, then, let us distinguish how many kinds of courts there are. They are eight in number. One is [i] concerned with inspection. Another 20 [ii] deals with anyone who wrongs the community. 106 Another [iii] with matters that affect the constitution. A fourth [iv] deals with officials and private individuals in disputes about fines. A fifth [v] deals with private transactions of some magnitude. Besides these there is [vi] a court that deals with homicide and [vii] one that deals with aliens. The kinds of homicide court, whether having the same juries or not, are: [vi. l ] that 25 concerned with premeditated homicide, [ vi.l] that concerned with in voluntary homicide, [vi.3] that concerned with cases where there is agreement on the fact of homicide but the justice of it disputed, and a fourth [ vi.4] concerned with charges brought against those who have been exiled for homicide after their return (the court of Phreatto in
Athens107 is said to be an example), but such cases are rare at any timeeven in large city-states. The aliens' court has [ vii.l] a part for aliens dis- 30puting with aliens and [ vii.2] a part for aliens disputing with citizens.Besides all these, there is [viii] a court that deals with petty transactions:those involving one drachma, five drachmas, or a little more (for judgment must be given in these cases too, but it should not fall to a multi-tude of jurors to give it). 35 But let us set aside these courts as well as the homicide and aliens'courts and talk about the political ones, which, when not well managed,give rise to factions and constitutional changes. Of necessity, there arejust the following possibilities: [3 . 1] All decide all the cases just distinguished, and are selected either [3 . 1 . 1 ] by lot or [3 . 1 .2] by election; or[3 . 1 ] all decide all of them, and [3.1 .3] some are selected by lot and some 40by election; or, [3 . 1 .4] although dealing with the same case, some jurorsmay be selected by lot and some by election. Thus these ways are four innumber. [3.2] There are as many again when selection is from only some 1301•of the citizens. For here again either [3.2. 1] the juries are selected fromsome by election and decide all cases; or [3.2.2] they are selected fromsome by lot and decide all cases; or [3 .2.3] some may be selected by lotand some by election; or [3.2.4] some courts dealing with the same casesmay be composed of both members selected by lot and elected members. 5These ways, as we said, are the counterparts of the ones we mentionedearlier. [3.3] Furthermore, these same ones may be conjoined-! mean,for example, some may be selected from all, others from some, and oth-ers from both (as for example if the same court had juries selected partlyfrom all and partly from some); and the selection may be either by lot orby election or by both. We have now listed the possible ways the courts can be organized. Of 10these the first, [3 . 1 ] those which are selected from all and decide allcases, are democratic. The second [3 .2], those which are selected fromsome and decide all cases, are oligarchic. The third [3.3], those whichare partly selected from all and partly from some, are aristocratic orcharacteristic of a polity. 15
107. If someone exiled for involuntary homicide was charged with a second vol untary homicide, he could not enter Attica for trial, but he could offer his defense from a boat offshore at Phreatto, on the east side of Piraeus. B OOK V
Chapter 120 Pretty well all the other topics we intended to treat have been discussed. Next, after what has been said, we should investigate: [ I ] the sources of change in constitutions, how many they are and of what sort; [2] what things destroy each constitution; [3] from what sort into what sort they principally change; further, [ 4] the ways to preserve constitutions in general and each constitution in particular; and, finally, [5] the means by which each constitution is principally preserved. 125 We should take as our initial starting point that many constitutions have come into existence because, though everyone agrees about justice (that is to say, proportional EQUALITY), they are mistaken about it, as we also mentioned earlier.2 For democracy arose from those who are equal in some respect thinking themselves to be unqualifiedly equal; for be-30 cause they are equally free, they think they are unqualifiedly equal. Oli garchy, on the other hand, arose from those who are unequaP in some respect taking themselves to be wholly unequal; for being unequal in property, they take themselves to be unqualifiedly unequal. The result is that the former claim to merit an equal share of everything, on the grounds that they are all equal, whereas the latter, being unequal, seek to35 get more (for a bigger share is an unequal one). All these constitutions possess justice of a sort, then, although unqualifiedly speaking they are mistaken. And this is why, when one or another of them does not partic ipate in the constitution in accordance with their assumption,4 they start faction. However, those who would be most justified in starting faction,
1 . (4) The ways to preserve a constitution; ( 5) the steps or devices needed to im- plement them. See 1 3 1 3'34-b32, 1 3 1 9b37-1 320b l 7 . 2. A t III.9. 3 . Specifically, superior ( 1 302b26-27). 4. About the nature of proportional equality.
134 Chapter 1 135
namely, those who are outstandingly virtuous, are the least likely to do 40so.5 For they alone are the ones it is most reasonable to regard as unqual- JJ01bifiedly unequal. There are also certain people, those of good birth, whosuppose that they do not merit a merely equal share because they are un-equal in this way. For people are thought to be noble when they have an-cestral wealth and virtue behind them. These, practically speaking, are the origins and sources of factions, 5the factors that lead people to start it. Hence the changes that are due tofaction are also of two kinds. [ 1 ] For sometimes people aim to change theestablished constitution to one of another kind-for example, fromdemocracy to oligarchy, or from oligarchy to democracy, or from theseto polity or aristocracy, or the latter into the former. [2] But sometimesinstead of trying to change the established constitution (for example, an 10oligarchy or a monarchy), they deliberately choose to keep it, but [2. 1 ]want to have it i n their own hands. Again, [2.2] it may be a question ofdegree: where there is an oligarchy, the aim may be to make the govern-ing class more oligarchic or less so; where there is a democracy, the aim 15may be to make it more democratic or less so; and similarly, in the case ofthe remaining constitutions, the aim may be to tighten or loosen them. 6Again, [2.3] the aim may be to change a certain part of the constitution,for example, to establish or abolish a certain office, as some say Lysandertried to abolish the kingship in Sparta, and King Pausanias the overseer- 20ship.7 In Epidamnus too the constitution was partially altered, since acouncil replaced the tribal rulers, though it is still the case that onlythose members of the governing class who actually hold office areobliged to attend the public assembly when election to office is takingplace. 8 (Having a single supreme official was also an oligarchic feature ofthis constitution.) 25 For faction is everywhere due to inequality, when unequals do not receive proportionately unequal things (for example, a permanent kingship is unequal if it exists among equals). For people generally engage infaction in pursuit of equality. But equality is of two sorts: numerical
Chapter 2 Since we are investigating the sources from which both factions and changes arise in constitutions, we must first grasp their general origins and causes. There are, roughly speaking, three of these, each of which 20 must first be determined in outline by itself. We must grasp [ 1 ] the con dition people are in when they start faction, [2] for the sake of what, and,
9. At III.9. 10. The basis of aristocracy. 11. Omitting kai aporoi ("and poor ones") with Dreizehnter and the mss. 12. See 1296'13-18, where a somewhat different explanation is offered. Chapter 3 137
third, [3] what the origins are of political disturbances and factionsamong people. [ 1] The principal general cause of people being in some way disposedto change their constitution is the one we have in fact already mentioned. For those who desire equality start faction when they believethat they are getting less, even though they are the equals of those who 25are getting more; whereas those who desire inequality (that is to say, superiority) do so when they believe that, though they are unequal, theyare not getting more but the same or less. (Sometimes these desires arejust, sometimes unjust.) For inferiors start factions in order to be equal, 30and equals do so in order to be superior. So much for the condition ofthose who start faction. [2] The things over which they start such faction are profit, honor,and their opposites. For people also start faction in city-states to avoiddishonor and fines, either for themselves or for their friends. [3] The causes and origins of the changes, in the sense of the factorsthat dispose people to feel the way we described about the issues we 35mentioned, are from one point of view seven in number and from another more. Two are the same as those just mentioned, but not in theirmanner of operation. For people are also stirred up by profit and honornot simply in order to get them for themselves, which is what we said be-fore, but because they see others, whether justly or unjustly, getting more. 40Other causes are: ARROGANCE, fear, superiority, contempt, and dispropor- 13026tionate growth. Still other ones, although operating in another way, areelectioneering, carelessness, gradual alteration, and dissimilarity. 13
Chapter 3The effect of arrogance and profit, and the way the two operate, are 5pretty much evident. For when officials behave arrogantly and become
1 3 . The seven causes mentioned at '36-37 are profit, honor, arrogance, fear, su periority, contempt, and disproportionate growth in power. The two points of view are: ( l ) treating profit and honor as two causes each of which oper ates in two ways and (2) treating these two ways of operating as distinct causes. If (2) is adopted, there are then more than seven causes. Of the four causes mentioned in the final sentence, the first three (electioneering, care lessness, and gradual alteration) cause political change, but not by giving rise to faction in the way the initial seven (or nine) do (1 303' 1 3 -1 4) . The fourth (dissimilarity) also gives rise to faction, at least "until people learn to pull together" ( 1 303'25-26). 138 Politics V
acquisitive, people start faction with one another and with the constitu tions that gave the officials authority. (Sometimes their ACQUISITIVE NESS is at the expense of private properties, sometimes at that of public funds.)10 It is also clear what honor is capable of, and how it causes faction. For people start faction both when they themselves are dishonored and when they see others being honored. This occurs unjustly when people are honored or dishonored contrary to their merit; justly, when it ac cords with merit. Superiority causes faction when some individual or group of individ-1S uals is too powerful for the city-state and for the power of the governing class. For the usual outcome of such a situation is a monarchy or a dy nasty. That is why some places, such as Argos and Athens, have a prac tice of ostracism. Yet it is better to see to it from the beginning that no one can emerge whose superiority is so great than to supply a remedy af-20 terwards. 14 People start faction through fear both when they have committed in justice and are afraid of punishment and when they think they are about to suffer an injustice and wish to avoid becoming its victims. The latter occurred in Rhodes when the notables united against the people because of the lawsuits being brought against them.1525 People also start faction and hostilities because of contempt. For ex- ample, this occurs in oligarchies when those who do not participate in the constitution are in a majority (since they consider themselves the stronger party), 16 and in democracies, when the rich are contemptuous of the disorganization and anarchy. Thus the democracy in Thebes col lapsed because they were badly governed after the battle of Oenophyta, 1730 as was the democracy of the Megarians when they were defeated be cause of disorganization and anarchy. 18 The same happened to the democracy in Syracuse before the tyranny of Gelon,19 and to the one in Rhodes prior to the revolt. 20 Changes also occur in constitutions because of disproportionate
growth. For just as a body is composed of parts which must grow in pro- 35portion if balance is to be maintained (since otherwise it will be destroyed, as when a foot is four cubits [six feet] long, for example, and therest of the body two spans [fifteen inches]; or, if the disproportionategrowth is not only quantitative but also qualitative, its shape mightchange to that of another animal), 21 so a city-state too is composed of 40parts, one of which often grows without being noticed-for example, 1303"the multitude of the poor in democracies or polities. This sometimesalso happens because of luck. Thus a democracy took the place of apolity in Tarentum when many notables were killed by the lapygiansshortly after the Persian wars. 22 In Argos too, after the death of those cit- Sizens killed on the seventh23 by the Spartan Cleomenes, the notableswere forced to admit some of their SUBJECT PEOPLES to citizenship; andin Athens, when they had bad luck fighting on land, the notables werereduced in number, because at the time of the war against Sparta thoseserving in the army were drawn from the citizen service-list.24 This sort 10of change also occurs in democracies, though to a lesser extent. Forwhen the rich become more numerous or their properties increase insize, democracies change into oligarchies or polities. But constitutions also change without the occurrence of faction, bothbecause of electioneering, as happened in Heraea (for they replacedelection with selection by lot for this reason, that those who election- 1Seered were elected), and also because of carelessness, when people whoare not friendly to the constitution are allowed to occupy the offices withsupreme authority. Thus the oligarchy in Oreus was overthrown when
24. Lists were kept of those citizens eligible for service in the cavalry, hoplites, or navy. During the Peloponnesian war (43 1-404), the army was recruited from the wealthier citizens, whereas in Aristotle's day it often consisted of mercenaries. 140 Politics V
25. The events in Heraea are otherwise unknown. The changes in Oreus, also called Hestiaea ( 1303h33), occurred in 377 when it revolted from the Spar tans and joined the Athenian Confederacy. 26. See 1290h38-1291 b 1 3, 1326' 16-25, 1328b 16-17. 27. The expelled Troezenians were received at Croton, which destroyed Sybaris in 510. The precise nature of the curse is unknown, but to drive out fellow colonists would have been viewed as a great sacrilege. 28. Nothing is known about this conflict, or about the one in Antissa mentioned in the next sentence. 29. The conflict at Zancle is described in Herodotus VI.22-24. 30. That is to say, after the fall ofThrasybulus in 467. 3 1 . Also referred to at 1 306'2-4. The original Athenian settlers were driven out and Amphipolis was incorporated into the powerful Chalcidian Confeder acy in around 370. Chapter 4 141
that they are treated unjustly because they do not participate equally, inspite of being equal. In democracies, the notables do so because they do Sparticipate equally, in spite of not being equal Y City-states also occasionally become factionalized because of their location, when their territory is not naturally suitable for a city-state thatis a unity. In Clazomenae, for example, the inhabitants of Chytrus cameinto conflict with those on the island, as did the inhabitants of Colophonand those of Notium.33 At Athens, too, the people are not all similar, but 10those in Piraeus are more democratic than those in the town. For just asin battles, where crossing even small ditches breaks up the phalanx, soevery difference seems to result in factional division. The greatest factional division is probably between virtue and vice; next that between 1Swealth and poverty; and so on for the others, including the one we havejust discussed, with each one greater than the next.
Chapter 4Factions arise from small issues, then, but not over them; it is over important issues that people start faction. Even small factions gain greaterpower, however, when they arise among those in authority,34 as happenedin Syracuse in ancient times. For the constitution underwent change be- 20cause two young men in office started a faction about a love affair. 35While the first was away, the second, though his comrade, seduced hisboyfriend. The first, enraged at him, retaliated by inducing the second'swife to commit adultery. The upshot was that they drew the entire gov- 25erning class into their quarrel and split it into factions. That is preciselywhy one should be circumspect when such things are beginning, andbreak up the factions of leaders and powerful men. For the error arises atthe beginning, and "well begun is half done," as the saying goes. Consequently, even a small error at the beginning is comparable in effect to all 30the errors made at the later stages. 36
37. Referred to as Oreus at 1303•1 8 . Nothing else is known about this event, which must have occurred prior to the absorption of Hestiaea by Athens in 446. 38. See Thucydides III.Z-50. 39. An agent (proxenos), like a consul or ambassador, was the representative of one city-state to another, but he was a citizen of the latter, not the former. 40. With Thebes (355-347), relating to control of the temple of Apollo at Del phi, which was situated on Phocian territory. The War was ended by Philip of Macedon. Mnason seems to have been a friend of Aristotle's. Chapter 4 143
tighter;41 in return, the seafaring crowd, who were responsible for vic-tory at Salamis, and so for hegemony based on sea power, made thedemocracy more powerful.42 In Argos the notables, having acquiredprestige in connection with the battle against the Spartans at Mantinea, 25undertook to overthrow the democracy. In Syracuse the people, havingbeen responsible for victory in the war against the Athenians, changedthe constitution from a polity to a democracy. In Chalcis the people,with the aid of the notables, overthrew the tyrant Phoxus, and then immediately took control of the constitution. Similarly, in Ambracia the 30people joined with the opponents of Periander to expel him and afterwards took the constitution into their own hands.43 Generally speaking,then, this should not be overlooked-that the people responsible for acity-state's power, whether private individuals, officials, tribes, or, in aword, a part or multitude of any sort, start faction. For either those who 35envy them for being honored start a faction, or they themselves, becauseof their superior achievement, are unwilling to remain as mere equals. Constitutions also undergo change when parts of a city-state that areheld to be opposed, such as the rich and the people, become equal to oneanother, and there is little or no middle class. For if either of the parts J304bbecomes greatly superior, the other will be unwilling to risk going upagainst their manifestly superior strength. That is why those who areoutstandingly virtuous do not cause any faction, practically speaking, forthey are few against many. 5 In general, then, the origins and causes of conflict and change are ofthis sort in all constitutions. But people change constitutions sometimesthrough force, sometimes through deceit. Force may be used right at thebeginning or later on. Deceit is also employed in two ways. Sometimesthey first deceive the others into consenting to a change in the constitu- 10tion and then later keep hold of it by force when the others no longerconsent. Thus the Four Hundred44 deceived the Athenian people bytelling them that the King of Persia would provide money for the war
4 1 . That is to say, less democratic ( 1290•22-29). Prior to the mid fifth century the Areopagus consisted of wealthy citizens of noble birth and was a power fully oligarchic component of the Athenian constitution.42. The navy was recruited from the poorest classes and was a powerfully de mocratic force in Athenian politics. See 1321'1 3-14; Plato, Republic 396a-b, Laws 707b-c.43. In c. 580. Further details are given at 1 3 1 1'39-b l .44. The oligarchy which replaced the democracy at Athens in 4 1 1 , described in Thucydides VIII.45-98. 144 Politics V
against the Spartans, and, having deceived them, tried to keep the conIS stitution in their own hands. At other times, they persuade them at the beginning, and continue to persuade them later on and rule with their consent. Simply stated, then, changes generally occur in all constitutions as a result of the factors that have been stated.
Chapter 5 We must now take each kind of constitution separately and study what happens to it as a result of these factors.20 Democracies undergo change principally because of the wanton be- havior of popular leaders,45 who sometimes bring malicious lawsuits against individual property owners, causing them to join forces (for a shared fear unites even the bitterest enemies), and at others, openly egg on the multitude against them. One may see this sort of thing happening25 in many instances. In Cos the democracy was overthrown when evil pop ular leaders arose (for the notables banded together),46 and also in Rhodes. For the popular leaders provided pay for public service and pre vented the naval officials from getting what they were owed; the latter were then forced to unite and overthrow the democracy because of the30 lawsuits brought against them.47 Right after the colony was settled, the democracy in Heraclea was also overthrown because of its popular lead ers. For the notables were treated unjustly by them and went into exile. Later the exiles united, returned home, and overthrew the democracy.35 The democracy in Megara48 was overthrown in a somewhat similar way. For the popular leaders expelled many of the notables in order to declare the latters' wealth public property, until they made numerous exiles. The exiles then returned, defeated the people in battle, and established an oligarchy.49 A similar thing happened to the democracy in Cyme,
Democracies also change from the traditional kind to the newest kind. For when officials are elected, but not on the basis of a property assess- 30 ment, and the people do the electing, those seeking office, in order to curry favor, bring matters to this point, that the people have authority even over the laws. A remedy that prevents this, or diminishes its effect, is to have the tribes nominate the officials rather than the people as a whole. Pretty well all the changes in democracies, then, happen for these rea- 40 sons.
Chapter 6 Oligarchies principally undergo change in two ways that are most evi dent. [ 1 . 1 ] The first is when they treat the multitude unjustly. 57 For any leader is adequate for the task when that happens, particularly if he comes from the ranks of the oligarchs themselves, like Lygdamis of Naxos, who actually became tyrant of the Naxians later on. 58 There are130Sb also several other varieties of faction that originate with other people. 59 [ 1 .2] For sometimes the overthrow comes from the rich themselves, though not the ones in office, when those holding the offices are very S few. This occurred in Massilia, lstrus, Heraclea, and other city-states, where those who did not participate in office agitated until first elder brothers and then younger ones were admitted. (For in some city-states, a father and son, and in others, an elder and younger brother, may not hold office simultaneously.) In Massilia, the oligarchy became more like 10 a polity; the one in Istrus ended in a democracy; and the one in Heraclea went from a small number to six hundred. [ 1 .3] The oligarchy in Cnidus also changed when the notables became factionalized because so few participated in office, and, as was mentioned, if a father participated, his 1S son could not, nor, if there were several brothers, could any but the el dest alone. For while they were engaged in faction, the people inter vened in the conflict, picked one of the notables as their leader, attacked, and were victorious (for what is factionalized is weak). And in Erythrae in ancient times, during the oligarchy of the Basilids, even though those with authority over the constitution governed well, the people neverthe- 20 less resented being ruled by a few and changed the constitution.60
6 1 . The oligarchy of the Thirty Tyrants, of which Charicles was a member, was in control of Athens for a brief period in 404/3. The oligarchy of the Four Hundred gained control there in 41 1 . See Ath. XXVIII-XXXVIII.62. See 1 268'22, note.63. Nothing is known about this event.64. In 406-405.65. Nothing is known about this event.66. Chares was an Athenian general at the head of a troop of mercenaries sta tioned in Corinth in 367 (a likely date for his negotiations). 148 Politics V
67. The thieves attack the oligarchs to avoid punishment; their opponents do so if they sanction the theft of publilfunds. Nothing is known about the event referred to. 68. Nothing is known about this oligarchy. 69. See 1271'9-18. 70. Timophanes became tyrant in 350, during the war with Argos, and was later killed by his brother Timolean. See Plutarch, Timoleon IV.4-8. 7 1 . The Aleuds were a great Thessalian family. The Simus referred to is most probably the one who helped bring Thessaly into subjection to Philip of Macedon in 342. Nothing is know about the events in Abydos. 72. At 1 303b37-1304' 17. Chapter 7 1 49
Chapter 7[ I ] In aristocracies factions arise because few people participate in of-fice, which is just what is said to change oligarchies as well, 76 becausearistocracy too is oligarchy of a sort. For the rulers are few in both,though not for the same reason. At any rate, that is why an aristocracy 25too is thought to be a kind of oligarchy. [ 1 . 1 ] Such conflict is particularlyinevitable [ 1 . 1 . 1 ] when there is a group of people who consider themselves equal in virtue to the ruling few-for example, the so-called Sons
73. Nothing is known about these events. Pillory was not a punishment com- monly inflicted on notables.74. See l 3QSh l 2-18. Nothing is known about the events in Chios.75. See 1 292'4-6 (democracies), 1292hS-10 (oligarchies).76. At 1 306'13-22. I SO Politics V
30 of the Maidens at Sparta (for they were descended from the Equals), who were discovered in a conspiracy and sent off to colonize Taren tum;77 or [ 1 . 1 .2] when powerful men who are inferior to no one in virtue are dishonored by others who are more esteemed, as Lysander was by the kings; or [ 1 . 1 .3] when a man of courage does not participate in office, like Cinadon, who instigated the rebellion against the Spartiates in the 35 reign of Agesilaus;78 or, again, [ 1 .2] when some people are very poor and others very rich, a situation which is particularly prevalent in wartime, and also happened in Sparta at the time of the Messenian war (this is clear from the poem of Tyrtaeus called "Good Government"), 79 for1307" those who were hard pressed because of the war demanded a redistribu tion of the land; or, again, [ 1 .3] when there is a powerful man capable of becoming still more powerful, who instigates conflict in order to become sole ruler, as Pausanias (who was general during the Persian war) is held S to have done in Sparta, and Annan in Carthage. 80 [2] Polities and aristocracies are principally overthrown, however, be cause of a deviation from justice within the constitution itself. For what begins the process in a polity is failing to get a good mixture of democ racy and oligarchy, and in an aristocracy, failing to get a good mixture of these and virtue as well, but particularly the two. I mean by the two 10 democracy and oligarchy, since these are what polities and most so called aristocracies try to mix. For aristocracies differ from what are termed polities in this,81 and this is why the former of them are less and
77. The Equals (homoioi) were Spartan citizens, born of citizen parents, who possessed sufficient wealth to enable them to participate in the communal meals (see 127 1'25-37). Various ancient accounts are given of the Sons of the Maidens: they were the offspring of Spartans degraded to the rank of helots for failing to serve in the First Messanian War; they were the illegiti mate sons of young unmarried Spartan women who were encouraged to in crease the population during that war; or they were the sons of adulterous Spartan women conceived while their husbands were fighting in that war. They founded Tarentum in 708. 78. Lysander was a Spartan general whose plans were thwarted by king Pausa nius in 403, and later by king Agesilaus. Cinadon's rebellion of 398 was dis covered and he was executed. See Xenophon, Hellenica 11.4.29; Plutarch, Lysander XXIII. 79. See Diehl l.7-9, fr. 2-5 . Tyrtaeus was a seventh century Spartan elegiac poet. 80. Annon's identity is uncertain. He may be the Carthaginian general of that name who fought against Dionysius II in Sicily, c. 400. 8 1 . In their way of mixing democracy and oligarchy. Chapter 7 151
the latter more stable. For those constitutions that lean more toward oligarchy get called aristocracies, whereas those that lean more toward the 15multitude get called polities. That is why, indeed, the latter sort are moresecure than the former. For the majority of citizens are the more power-ful party and they are quite content with an equal share; whereas if therich are granted superiority by the constitution, they act arrogantly andtry to get even more for themselves. Generally speaking, whichever direction a constitution leans is the di- 20rection in which it changes when either party grows in power, for exam-ple, polity into democracy and aristocracy into oligarchy. Or it changesin the opposite direction; for example, aristocracy changes into democ-racy (when the poorer people pull it toward its opposite because they arebeing unjustly treated), and polity changes into oligarchy. For the only 25stable thing is equality in accordance with merit and the possession ofprivate property. The aforementioned change82 occurred at Thurii. Because the property assessment for holding office was rather high, achange was made to a smaller one and to a larger number of offices. Butbecause the notables illegally acquired all the land (for the constitution 30was still too oligarchic), they were able as a result to get more. But thepeople, who had received military training during the war, provedstronger than the garrison troops, and forced those who had more thantheir fair share of the land to give it up. Moreover, [3] because all aristocratic constitutions are oligarchic incharacter, the notables in them tend to get more. Even in Sparta, for ex- 35ample, properties keep passing into fewer and fewer hands. The notablesare also freer to do as they please and make marriage alliances as theyplease. The city-state of the Locrians was ruined, indeed, because amarriage alliance was formed with the tyrant Dionysius, something thatwould not have occurred in a democracy or a well-mixed aristocracy. 83 [4] Aristocracies are particularly apt to change imperceptibly by being 40overturned little by little. This is precisely what was said earlier as a gen- 1307hera! point about all constitutions,84 namely, that even a small thing cancause them to change. For once one thing relating to the constitution is
82. From aristocracy to democracy. Nothing is known for certain about the events referred to.83. Locri accepted a marriage alliance with Dionysius I, who was tyrant of Syracuse 367-356, 346-343. Later (starting in 3 56) it suffered under the oppressive tyranny of the offspring of this marriage, Dionysius II.84. At 1 303'20-1304h 1 8. 152 Politics V
Chapter 8 Our next topic is the preservation of constitutions generally and each kind of constitution separately. [ I ] It is clear, in the first place, that if we know what destroys a constitution, we also know what preserves it. For opposites are productive of opposite things, and destruction is opposite30 to preservation. In well-mixed constitutions, then, if care should be taken to ensure that no one breaks the law in other ways, small violations should be particularly guarded against. For illegality creeps in unno ticed, in just the way that property gets used up by frequent small ex penditures: the expense goes unnoticed because it does not occur all at35 once. For the mind is led to reason fallaciously by them, as in the so-
phistical argument "if each is small, all are also." In one way this is true;in another false: the whole composed of all the parts is not small, but itis composed of small parts. One thing to guard against, then, is destruction that has a starting point of this sort. [2] Secondly, we must not put our faith in the devices that are designed to deceive the multitude, since they are shown to be useless by 40the facts. (I mean the sort of devices used in constitutions that we dis 1308"cussed earlier. )87 [3) Next, we should notice that not only some aristocracies but alsosome oligarchies survive, not because their constitutions are secure, butbecause those in office treat well both those outside the constitution and sthose in the governing class. They do this by not being unjust to thenonparticipants and by bringing their leading men into the constitution;by not being unjust to those who love honor by depriving them of honor,or to the many by depriving them of profit; and by treating each other,the ones who do participate, in a democratic manner. For what democ 10rats seek to extend to the multitude, namely, equality, is not only just forthose who are similar but also beneficial. That is why, if the governingclass is large, many democratic legislative measures prove beneficial, forexample, having offices be tenable for six months in order that all thosewho are similar can participate in them. For those who are similar are al JSready a people of a sort, which is why popular leaders arise even amongthem, as we mentioned earlier. 88 Furthermore, oligarchies and aristocracies of this sort are less likely to fall into the hands of dynasties. For officials who rule a short time cannot so easily do wrong as those who rule along time. For this is what causes tyrannies to arise in oligarchies and 20democracies, since in both constitutions, the ones who attempt to establish a tyranny are either the most powerful (popular leaders in democracies, dynasts in oligarchies) or those who hold the most important offices, and hold them for a long time. [4) Constitutions are preserved not only because of being far awayfrom what destroys them, but sometimes too because they are nearby.89 25For fear makes people keep a firmer grip on the constitution. Hencethose who are concerned about their constitution should excite fears andmake faraway dangers seem close at hand, so that the citizens will de-
fend the constitution and, like sentries on night-duty, never relax their 30 guard. [5] Moreover, one should try to guard against the rivalries and fac tions of the notables, both by means of the laws and by preventing those who are not involved in the rivalry from getting caught up in it them selves. For it takes no ordinary person to recognize an evil right from the beginning but a man who is a statesman. [6] As for change from an oligarchy or a polity because of property as- 35 sessments-if it occurs while the assessments remain the same but money becomes more plentiful, it is beneficial to discover what the total communal assessment is compared with that of the past; with that of last 40 year's in city-states with annual assessment, with that of three or five130!Jb years ago in larger city-states. If the total is many times greater or many times less than it was when the rates qualifying someone to participate in the constitution were established, it is beneficial to have a law that tightens or relaxes the assessment; tightening it in proportion to the in- S crease if the total has increased, relaxing it or making it less if the total has decreased. For when oligarchies and polities do not do this, the re sult is that if the total has decreased, an oligarchy arises from the latter and a dynasty from the former, and if it has increased, a democracy 10 arises from a polity and either a polity or a democracy from an oligarchy. [7] It is a rule common to democracy, oligarchy, monarchy, and every constitution not to allow anyone to grow too great or out of all due pro portion, but to try to give small honors over a long period of time rather than large ones quickly. For people are corrupted by major honors, and not every man can handle good luck.9° Failing that, constitutions should at least try not to take away all at once honors that have been awarded all 1S at once, but to do so gradually. They should try to regulate matters by means of the laws, indeed, so as to ensure that no one arises who is far superior in power because of his friends or wealth. Failing that, they should ensure that such men are removed from the city-state by being ostracized.9 1 [8] But since people also attempt to stir up change because of their 20 private lives, an office should be set up to keep an eye on those whose lifestyles are not beneficial to the constitution, whether to the democ racy in a democracy, to the oligarchy in an oligarchy, or similarly for
each of the other constitutions. For the same reasons, one must guardagainst the prospering of the city-state one part at a time. 92 A remedy for 25this is always to place the conduct of affairs and the offices in the handsof opposite parts. (I mean that the decent are opposite to the multitude,the poor to the rich.) Another remedy is to try to mix the multitude ofthe poor with that of the rich or to increase the middle class, since thisdissolves faction caused by inequality. 30 [9] But the most important thing in every constitution is for it havethe laws and the management of other matters organized in such a waythat it is impossible to make a profit from holding office.93 One shouldpay particular heed to this in oligarchies. For the many are not as resent-ful at being excluded from office-they are even glad to be given the 35leisure to attend to their private affairs-as they are when they thinkthat officials are stealing public funds. At any rate, they are then painedboth at not sharing in office and at not sharing in its profits. Indeed, theonly way it is possible for democracy and aristocracy to coexist is ifsomeone instituted this,94 since it would then be possible for both the 40notables and the multitude to have what they want. For allowing every- 1309"one to hold office is democratic, but having the notables actually holdthe offices is aristocratic. But this is what will happen if it is impossibleto profit from office. For the poor will not want to hold office, becausethere is no profit in it, but will prefer to attend to their private affairs, 5whereas the rich will be able to hold it, because they need no supportfrom public funds. The result will be that the poor will become richthrough spending their time working, and the notables will not have tobe ruled by anybody and everybody. But to prevent public funds frombeing stolen, the transfer of the money95 should take place in the pres- 10ence of all citizens, and copies of the accounts should be deposited witheach clan, company,96 and tribe. And to ensure that people will hold of-fice without seeking profit, there should be a law that assigns honors toreputable officials.
Chapter 9 Those who are to hold the offices with supreme authority should pos sess three qualities: first, friendship for the established constitution; 35 next, the greatest possible capacity for the tasks of office; third, in each constitution the sort of virtue or justice that is suited to the constitution (for if what is just is not the same in all constitutions, there must be dif ferences in the virtue of justice as well). But there is a problem. When all of these qualities are not found in the same person, how is the choice to 40 be made? For example, if one man is an expert general but is vicious and1301Jh no friend to the constitution, whereas another is just and friendly to it, how should the choice be made? It seems that one should consider two things: which quality does everyone have a larger share in, and which a smaller one? That is why, in the case of a generalship, one should con sider experience more than virtue. For everyone shares in generalship 5 less, but in decency more. In the case of guardianship or stewardship, on the other hand, the opposite holds. For these require more virtue than the many possess, but the knowledge they require is common to all. One might also raise the following problem. If someone has the capacity for the tasks of office as well as friendship for the constitution, why does he Chapter 9 157
also need virtue, since even the first two will produce beneficial results? 10Or is it possible for someone who possesses these two qualities to beweak-willed, so that just as people can fail to serve their own interestswell even though they have the knowledge and are friendly to themselves, so nothing prevents them from behaving in the same way wherethe common interest is concerned? Simply speaking, everything in laws that we say is beneficial to constitutions also preserves those constitutions, as does the most important 1Sfundamental principle, so often mentioned, of keeping watch to ensurethat the multitude that wants the constitution is stronger than the multitude that does not.97 In addition to all this, one thing must not be overlooked, which is infact overlooked by deviant constitutions: the mean. For many of thethings that are held to be democratic destroy democracies, and many 20that are held to be oligarchic destroy oligarchies. But those who thinkthat this98 is the only kind of virtue push the constitution to extremes.They do not know that constitutions are just like parts of the body. Astraight nose is the most beautiful, but one that deviates from beingstraight and tends toward being hooked or snub can nevertheless still bebeautiful to look at. Yet if it is tightened still more toward the extreme, 2Sthe part will first be thrown out of due proportion, and in the end it willcease to look like a nose at all, because it has too much of one and too lit-tle of the other of these opposites. The same holds of the other parts aswell. This can also happen in the case of the constitutions. For it is pos- 30sible for an oligarchy or a democracy to be adequate even though it hasdiverged from the best organization. But if someone tightens either ofthem more, he will first make the constitution worse, and in the end itwill not be a constitution at all. That is why legislators and statesmen JSshould not be ignorant about which democratic features preserve ademocracy and which destroy it, or which oligarchic features have theseeffects on an oligarchy. For neither of these constitutions can exist andsurvive without rich people and the multitude, but when a leveling ofproperty occurs, the resulting constitution is necessarily of a differentkind. Hence by destroying these classes through extreme legislation, 40they destroy their constitution. 131()' A mistake is made in both democracies and oligarchies. In democra-cies popular leaders make it where the multitude have authority over the
laws. For they divide the city-state in two by always fighting with theS rich, yet they should do the opposite, and always be regarded as spokes men for the rich. In oligarchies, the oligarchs should be regarded as spokesmen for the people, and should take oaths that are the opposite of the ones they take nowadays. For in some oligarchies, they now swear "and I will be hostile to the people and will plan whatever wrongs I can10 against them." But they ought to hold and to seem to hold the opposite view, and declare in their oaths that "I will not wrong the people."99 But of all the ways that are mentioned to make a constitution last, the most important one, which everyone now despises, is for citizens to be educated in a way that suits their constitutions. For the most beneficialIS laws, even when ratified by all who are engaged in politics, are of no use if people are not habituated and educated in accord with the constitu tion-democratically if the laws are democratic and oligarchically if they are oligarchic. For if weakness of will indeed exists in a single indi vidual, it also exists in a city-state. But being educated in a way that suits20 the constitution does not mean doing whatever pleases the oligarchs or those who want a democracy. Rather, it means doing the things that will enable the former to govern oligarchically and the latter to have a demo cratic constitution. In present-day oligarchies, however, the sons of the rulers live in luxury, whereas the sons of the poor are hardened by exer cise and toil, so that the poor are more inclined to stir up change and are2S better able to do so. In those democracies that are held to be particularly democratic, the very opposite of what is beneficial has become estab lished. The reason for this is that they define freedom incorrectly. For there are two things by which democracy is held to be defined: by the majority being in supreme authority and by freedom. For justice is held30 to be equality; equality is for the opinion of the multitude to be in au thority; and freedom is doing whatever one likes. So in democracies of this sort everyone lives as he likes, and "according to his fancy," as Eu ripides says. 100 But this is bad. For living in a way that suits the constitu-35 tion should be considered not slavery, but salvation.10 1 Such, then, simply speaking, are the sources of change and destruc tion in constitutions, and the factors through which they are preserved and maintained.
Chapter 1 0It remains to go through monarchy too, both the sources of its destruc-tion and the means by which it is naturally preserved. What happens in 40the case of kingships and tyrannies is pretty much similar to what wesaid happens in constitutions. For kingship is akin to aristocracy, and 131(/tyranny is a combination of ultimate oligarchy and ultimate democ-racy. 1 02 That is why, indeed, tyranny is also the most harmful to those itrules, seeing that it is composed of two bad constitutions and involves 5the deviations and errors of both. Each of these kinds of monarchy comes to be from directly oppositecircumstances. For kingship came into existence to help the decentagainst the people, 103 and a king is selected from among the decent men 10on the basis of a superiority in virtue, or in the actions that spring fromvirtue, or on the basis of a superiority of family of this sort. A tyrant, onthe other hand, comes from the people (that is to say, the multitude) tooppose the notables, so that the people may suffer no injustice at theirhands. This is evident from what has happened. For almost all tyrantsbegan as popular leaders who were trusted because they abused the no- 15tables. For some tyrannies were established in this way in city-states thathad already grown large. Other earlier ones arose when kings departedfrom ancestral customs and sought to rule more in the manner of a mas-ter. Others were established by people elected to the offices that havesupreme authority; for in ancient times, the people appointed "doers of 20the people's business" and "sacred ambassadors" to serve for long peri-ods of time. 104 Still others arose in oligarchies that gave a single electedofficial authority over the most important offices. For in all these wayspeople could easily become tyrants if only they wished, because of thepower they already possessed through the kingship or through other 25
high office. Thus Pheidon of Argos and others became tyrants having al ready ruled as kings; the Ionian tyrants and Phalaris as a result of their high office; and Panaetius in Leontini, Cypselus in Corinth, Pisistratus 30 in Athens, Dionysius in Syracuse, and likewise others, from having been popular leaders. 105 Kingship is, then, as we said, 106 an organization like aristocracy, since it is based on merit, whether individual or familial virtue, or on benefac tions, or on these together with the capacity to perform them. For all those who obtained this office either had benefited or were capable of 35 benefiting their city-states or nations. Some, like Codrus, saved their people from enslavement in war; others, like Cyrus, set them free; oth ers acquired or settled territory, like the kings of the Spartans, Macedo- 40 nians, and Molossians. 107 A king tends to be a guardian, seeing to it that1311• property owners suffer no injustice and the people no arrogance. But tyranny, as has often been said, 108 never looks to the common benefit ex cept for the sake of private profit. A tyrant aims at what is pleasant; a king at what is noble; and that is why it is characteristic of a tyrant to be 5 most acquisitive of wealth 109 and of a king to be most acquisitive of what is noble. Also, a king's bodyguard consists of citizens, whereas a tyrant's consists of foreigners. 1 10 That tyranny has the vices of both democracy and oligarchy is evi- 10 dent. From oligarchy comes its taking wealth to be its end (for, indeed, only in this way can the tyrant possibly maintain his bodyguard and his luxury), and its mistrust of the multitude (which is why, indeed, tyrants deprive them of weapons). It is common to both constitutions (oligarchy and tyranny) to ill-treat the multitude, drive them out of the town, and 15 disperse them. From democracy, on the other hand, comes its hostility
1 05. Pheidon as tyrant in the middle of the seventh century. Phalaris was a no toriously cruel sixth-century tyrant of Agrigentum in Sicily. For Pisistra tus, see 1 305'23-24 note. Cypselus was tyrant of Corinth c. 655-625. Dionysius is Dionysius I. 1 06. At 1 3 1 0b2-3. 1 07. Codrus was a legendary early king of Athens. According to one traditional account he was already king when he gave his life to prevent Athens from Dorian invasion. Cyrus was the first ruler of the Persian empire (559-529); he freed Persia from the Medes in 559. Neoptolemus, the son of Achilles, conquered the Molossians and became their king. 1 08. For example, at 1279h6-1 0, 1295' 1 7-22. 109. On the connection between wealth and the pursuit of pleasure, see 1257h40-1258'5. l lO. See 1285'24-29. Chapter 10 161
t o the notables, its destruction o f them both b y covert and overt means,and its exiling of them as rivals in the craft of ruling and impediments toits rule. For it is from the notables that conspiracies arise, since some ofthem wish to rule themselves, and others not to be enslaved. Hence toothe advice that Periander gave to Thrasybulus when he cut down the 20tallest ears of corn, namely, that it is always necessary to do away withthe outstanding citizens. 1 1 1 A s has pretty much been said, then, one should consider the sourcesof change both in CONSTITUTIONS and in monarchies to be the same.For it is because of injustice, fear, and contemptuous treatment that 25many subjects attack monarchies. In the case of injustice, arrogance isthe principal cause, but sometimes too the seizure of private property.The ends sought are also the same there as in tyrannies and kingships,since monarchs possess the great wealth and high office that everyone 30desires. In some cases, attack is directed against the person of the rulers; inothers, against their office. Those caused by arrogance are directedagainst the person. Arrogance has many forms, but each of them is acause of anger; and most angry people act out of revenge, not ambition. 35For example, the attack on the Pisistratids took place because theyabused Harmodius' sister and showed contempt for Harmodius himself(for Harmodius attacked because of his sister, and Aristogeiton becauseof Harmodius). 112 People plotted against Periander, tyrant of Ambracia,because once when he was drinking with his boyfriend, he asked 40whether he was pregnant by him yet. Philip was attacked by Pausanias 131 Jhbecause he allowed him to be treated arrogantly by Attalus and his co-terie.113 Amyntas the Little was attacked by Derdas because he boastedof having deflowered him. 1 14 The same is true of the attack on Evagorasof Cyprus by a eunuch;115 he felt arrogantly treated because Evagoras' 5son had taken away his wife. Many attacks have also occurred because of the shameful treatment ofother people's bodies by certain monarchs. The attack on Archelaus116
1 1 1 . See 1284'26-33.1 12. The attack on the Athenian Pisistratid tyranny in 5 14 is discussed in Ath. XVIII, Herodotus V.55-65, Thucydides VI.54-9.1 13 . Philip of Macedon was murdered by Pausanius (a young Macedonian) in 330.1 14. Amyntas and Dardas are otherwise unknown.1 1 5. Evagoras ruled Salamis in Cyprus from 41 1 until his death in 374.1 16. King of Macedon 4 13-399. See Plutarch, Amatorius 23. 1 62 Politics V
30 monarchy but fame. Nevertheless, very few people are impelled by this sort of motive, since it presupposes a total disregard for their own safety in the event that the action is not successful. They must be guided by the same fundamental principle as Dion (something that is not easy for most people). For Dion accompanied by a small force marched against 35 Dionysius, saying that whatever point he was able to reach, he would be satisfied to have completed that much of the enterprise, and that if, for example, he were killed after having just set foot on land, he would have a noble death. Like each of the other constitutions, one way a tyranny is destroyed is 40 from the outside, if there is a more powerful constitution opposed toJ]J2b it.126 For the wish to destroy a tyranny will clearly be present, because the deliberate choices of the two are opposed; and people always do what they wish when they have the power. The constitutions opposed to tyranny are democracy, kingship, and aristocracy. Democracy is opposed to it as "potter to potter" (as Hesiod puts it), 127 since the extreme sort of S democracy is also a tyranny. 128 Kingship and aristocracy are opposed to it because of opposition of constitution. That is why the Spartans over threw a large number of tyrannies, as did the Syracusans while they were well governed . Another way a tyranny is destroyed is from within, when those partic ipating in it start a faction. This happened in the tyranny of the family of 10 Gelon and, in our own time, in that of the family of Dionysius. The tyranny of Gelon was destroyed when Thrasyboulus, the brother of Hiero, curried favor with Gelon's son and led him into a life of sensual pleasure, in order that he himself might rule. The family got together to destroy not the entire tyranny, but Thrasyboulus. 129 But those who 1S joined them seized the opportunity and expelled all of them. Dion, who was related by marriage to Dionysius, marched against him, won over the people, and expelled him, but was himself killed afterwards. The two principal motives people have for attacking tyrannies are ha tred and contempt. Of them, hatred always attaches to tyrants, but many
overthrows are due to contempt. Evidence of this is the fact that most of 20those who won the office of tyrant held onto it, whereas their successorsalmost all lost it right away. For living lives of indulgence, they easily became contemptible and gave others ample opportunity to attack them. 25Anger must also be considered a part of the hatred, since in a way itgives rise to the same sorts of actions. Often, in fact, it is more conducive to action than hatred. For angry people attack more vehementlybecause passion does not employ rational calculation. People are particularly apt to be led by their angry spirit on account of arrogant treatment. This was the cause of both the overthrow of the Pisistratid 30tyranny and that of many others. But hatred employs calculation morethan anger does. For anger involves pain, and pain makes rational calculation difficult; but hatred does not involve pain. To speak summarily, however, the causes that we said destroy unmixed or extreme oligarchies and extreme democracies should also be 35regarded as destroying tyranny. For these are in fact divided tyrannies. 1 30 Kingship is destroyed least by outside factors, which is also why it islong-lasting. The sources of its destruction generally come from within.It is destroyed in two ways: first, when those who participate in the king-ship start faction, and, second, when the kings try to manage affairs in a 1313•more tyrannical fashion, claiming that they deserve to have authorityover more areas than is customary, and to be beyond the law. Kingshipsno longer arise nowadays, but if any do happen to occur, they tend moreto be tyrannical monarchies. 1 3 1 This is because kingship is rule over will-ing subjects and has authority over more important matters. But nowa- 5days there are numerous men of equal quality, although none so outstanding as to measure up to the magnitude and dignity of the office ofking. Hence people are unwilling to put up with this sort of rule. And ifsomeone comes to exercise it, whether through force or deceit, this isimmediately held to be a tyranny. In the case of kingships based on lineage, there is something besides 10the factors already mentioned that should be considered a cause of theirdestruction, namely, the fact that many kings easily become objects ofcontempt and behave arrogantly, even though they exercise kingly office,not tyrannical power. For then overthrow is easy. For a king whose sub-
Chapter 1 1 It is clear, to put it simply, that monarchies are preserved by the opposite causes.132 But kingships in particular are preserved by being made more 20 moderate. For the fewer areas over which kings have authority, the longer must their office remain intact. For they themselves become less like masters, more equal in their characters, and less envied by those they rule. That is also why the kingships of the Molossians lasted a long time, and that of the Spartans as well. In the latter case it was because 25 the office was divided into two parts from the beginning, and again be cause Theopompus, besides moderating it in other ways, instituted the office of the overseers. 133 By diminishing the power of the kingship he increased its duration, so that in a way he made it greater, not lesser. He is supposed to have given precisely this answer, indeed, when his wife 30 asked him whether he was not ashamed to hand over a lesser kingship to his sons than the one he had inherited from his father: "Certainly not," he said, "for I am handing over one that will be longer lasting. " Tyrannies134 are preserved in two quite opposite ways. One of them is 35 traditional and is the way most tyrants exercise their rule. Periander of Corinth is said to have instituted most of its devices, but many may also be seen in the Persian empire. These include the device we mentioned some time ago135 as tending to preserve a tyranny (to the extent that it 40 can be preserved): [ I ] cutting down the outstanding men and eliminat ing the high-minded ones. Others are: [2] Prohibiting messes, clubs, ed-13131 ucation, and other things of that sort. [3] Keeping an eye on anything that typically engenders two things: high-mindedness and mutual trust. [4] Prohibiting schools and other gatherings connected with learning,136
and doing everything to ensure that people are as ignorant of one another as possible, since knowledge tends to give rise to mutual trust. [5] 5Requiring the residents to be always in public view and to pass theirtime at the palace gates. 137 For their activities will then be hard to keepsecret and they will become humble-minded from always acting likeslaves. [6] Imposing all the other restrictions of a similar nature that arefound in Persian and non-Greek tyrannies (for they are all capable ofproducing the same effect). 10 [7] Another is trying to let nothing done or said by any of his subjectsescape notice, but to retain spies, like the so-called women informers ofSyracuse, or the eavesdroppers that Hiero138 sent to every meeting orgathering. For people speak less freely when they fear the presence ofsuch spies, and if they do speak freely, they are less likely to go unno- 15ticed. [8] Another is to slander people to one another, setting friendagainst friend, the people against the notables, and the rich againstthemselves. [9] It is also tyrannical to impoverish the people, so thatthey cannot afford a militia and are so occupied with their daily workthat they lack the leisure for plotting. The pyramids of Egypt, the 20Cypselid monuments, the construction of the temple of Olympian Zeusby the Pisistratids, and the works on Samos commissioned by Polycratesare all examples of this. 139 For all these things have the same result, lackof leisure and poverty for the ruled. [ 1 0] And there is taxation, as in 25Syracuse, when, during the reign of Dionysius, 140 taxation ate up a person's entire estate in five years. [ 1 1 ] A tyrant also engages in warmonger-ing in order that his subjects will lack leisure and be perpetually in needof a leader. And while a kingship is preserved by its friends, it is themark of a tyrant to distrust his friends, on the grounds that while all his 30subjects wish to overthrow him, these are particularly capable of doingso.l41 All the practices found in the extreme kind of democracy are alsocharacteristic of a tyranny: [ 1 2] the dominance of women in the household, in order that they may report on the men, and [ 1 3] the license ofslaves for the same reason. For slaves and women not only do not plot 35against tyrants but, because they prosper under them, are inevitably well
disposed toward tyrannies and toward democracies as well (for the peo ple too aspire to be a monarch). That is why a flatterer is honored in both constitutions-in democracies, the popular leader (for the popular 40 leader is a flatterer of the people), in tyrannies, those who are obse quious in their dealings with the tyrant, which is precisely a task for flat-1314• tery. For that is also why tyranny loves vice. For tyrants delight in being flattered. But no free-minded person would flatter them. On the con trary, decent people act out of friendship, not flattery. 142 The vicious are 5 also useful for vicious tasks-"nail to nail," as the saying goes.143 And it is characteristic of a tyrant not to delight in anyone who is dignified or free-minded. For a tyrant thinks that he alone deserves to be like that. But anyone who is a rival in dignity or free-mindedness robs tyranny of its superiority and its status as a master of slaves, and so tyrants hate him as a threat to their rule. And it is also characteristic of a tyrant to have foreigners rather than people from the city-state as dinner guests and 10 companions, on the grounds that the former are hostile to him, whereas the latter oppose him in nothing. These devices are characteristic of tyrants and help preserve their rule, but there is no vice they leave out. They all fall into three cate- J5 gories, broadly speaking. For tyranny aims at three things: first, that the ruled think small, for a pusillanimous person would plot against no one;144 second, that they distrust one another, for a tyranny will not be overthrown until some people trust each other. This is also why tyrants attack decent people. They view them as harmful to their rule not only 20 because they refuse to be ruled as by a master, but also because they command trust among both themselves and others, and do not inform on one another or on anyone else. Third, that the ruled be powerless to act. For no one tries to do what is impossible, and so no one tries to over- 25 throw a tyranny if he lacks the power. Thus the wishes of tyrants may be reduced in fact to these three defining principles, since all tyrannical aims might be reduced to these three tenets: that the ruled not trust one another; that they be powerless; that they think small.
142. A true friend loves one for one's own qualities; a flatterer is someone who seems to do this but does not. If decent people seem friendly it will be be cause they are so, not because they are engaging in flattery (Rh. 1371'17-24). 143. More usually, "nail is driven out by nail," but here something like "it takes a nail to do a nail's work." 144. See NE 1 123b9-26, 1 1 25'19-27. Chapter 11 169
145. Since tyranny differs from kingship in being rule over unwilling subjects.146. Of rendering public accounts and seeming to take care of public funds.147. The mss. have "political virtue (politike areti)." 170 Politics V
2S jects, but neither should any of his followers. The women of his house hold should also be similarly respectful toward other women, as the ar rogant behavior of women has caused the downfall of many tyrannies. Where bodily pleasures are concerned, the tyrant should do the oppo site of what some in fact do. For they not only begin their debaucheries 30 at dawn and continue them for days on end, but they also wish to be seen doing so by others, in order that they may be admired as happy and blessed. But above all the tyrant should be moderate in such matters, or failing that, he should at least avoid exhibiting his indulgence to others. For it is not easy to attack or despise a sober or wakeful man, but it is 3S easy to attack or despise a drunk or drowsy one. [4] A tyrant must do the opposite of pretty well all the things we men tioned a while back. 148 For he must lay out and beautify the city-state as if he were a household steward rather than a tyrant. Again, [5] a tyrant should always be seen to be very zealous about matters concerning the gods, but without appearing foolish in the process. For people are less afraid of suffering illegal treatment at the 40 hands of such people. And if they regard their ruler as a god-fearing131 s• man who pays heed to the gods, they plot against him less, since they think that he has the gods on his side. [6] A tyrant should so honor those who prove to be good in any area S that they do not expect that they would be more honored by citizens liv ing under their own laws. He should bestow such honors himself, but punishments should be administered by other officials and by the courts. But it is a precaution common to every sort of monarchy not to make any one man important, but where necessary to elevate several, so that they will keep an eye on one another. If it happens to be necessary to make one man important, however, at all events it should not be some- 10 one of courageous character. For men of this sort are the most enterpris ing in any sphere of action. And if it is considered necessary to remove someone from power, his prerogatives should be taken away gradually, not all at once. [7] A tyrant should refrain from all forms of arrogance, and from two IS in particular: corporal punishment and arrogance toward adolescents. This is particularly true where those who love honor are concerned. For while lovers of money resent contemptuous acts affecting their prop erty, honor lovers and decent human beings resent those involving dis-
honor. Hence either he should not treat people in these ways or else he 20should appear to punish like a father, not out of contempt; and to engagein sexual relations with young people out of sexual desire, and not as if itwere a prerogative of his office. And as a general rule, he should compensate apparent dishonors with yet greater honors. Of those who makeattempts on his life, a tyrant should most fear and take the greatest pre- 25cautions against those who are ready to sacrifice their own lives to destroy him. Hence he should be particularly wary of people who thinkthat he has behaved arrogantly toward them or those they happen tocherish. For people who attack out of anger are careless of themselves.As Heraclitus said, "Anger is a hard enemy to combat, because it pays 30for what it wants with life."149 [8] Since city-states consist of two parts, poor and rich, it is best ifboth believe that they owe their safety to the tyrant's rule, and that neither is unjustly treated by the other because of it. But whichever of themis the stronger should be particularly attached to his rule, so that with JShis power thus increased he will not need to free slaves or confiscateweapons. For the latter of the two parts added to his force will be enoughto make them stronger than attackers. But it is superfluous to discuss all such measures in detail. For their 40aim is evident. A tyrant should appear to his subjects not as a tyrant butas a head of household and a kingly man, not as an embezzler but as a 131Sbsteward. He should also pursue the moderate things in life, not excess,maintaining close relations with the notables, while playing the popularleader with the many. For as a result, not only will his rule necessarily benobler and more enviable, but since he rules better people who have notbeen humiliated he will not end up being hated and feared. And his rule Swill be longer lasting, and his character will either be nobly disposed tovirtue or else half good, not vicious but half vicious. 10
Chapter 1 2Yet, the shortest-lived of all constitutions are oligarchy and tyranny. Forthe longest lasting tyranny was that of Orthagoras and his sons inSicyon. It lasted a hundred years. 150 This was because they treated their
149. Diels-Kranz B85. Heraclitus of Ephesus (c. 540-480) was one of the greatest of the Presocratic philosophers.1 50. The tyranny was founded in 670. Cleisthenes was grandson of Orthagoras and grandfather of the Athenian reformer of the same name. 172 Politics V
not become good men. But how could this sort of change be any morepeculiar to the constitution he says is best than common to all the othersand to everything that comes into existence? Yes, and is it during this pe-riod of time, 155 due to which, as he says, everything changes, that eventhings that did not begin to exist at the same time change at the same 1Stime? If something comes into existence on the day before the comple-tion of the cycle, for example, does it still change at the same time aseverything else? Furthermore, why does the best constitution changeinto a constitution of the Spartan sort? For all constitutions more oftenchange into their opposites than into the neighboring one. 156 The sameremark also applies to the other changes. For he says that the Spartan 20constitution changes to an oligarchy, then to a democracy, then to atyranny. Yet change may also occur in the opposite direction. For exam-ple, from democracy to oligarchy, and to it more than to monarchy. Moreover, he does not tell us whether tyranny undergoes change, or 25what causes it to change, if it does. Nor does he tell us what sort of constitution it changes into. The reason for this is that he could not easilyhave told us, since the matter is undecidable, although according to himit should change into his first or best constitution, since that wouldmake the cycle continuous. But in fact tyranny can also change into another tyranny, as the constitution at Sicyon changed from the tyranny ofMyron to that of Cleisthenes; into oligarchy, like that of Antileon in 30Chalcis; into democracy, like that of Gelon and his family at Syracuse;and into aristocracy, like that of Charillus in Sparta [or the one inCarthage]. 1 57 Change also occurs from oligarchy to tyranny, as happened in most of JSthe ancient oligarchies in Sicily: in Leontini, it was to the tyranny ofPanaetius; in Gela, to that of Cleander; in Rhegium, to that of Anaxi-laus; and similarly in many other city-states. 158 It is also absurd to holdthat a constitution changes into an oligarchy because the office holdersare money lovers and acquirers of wealth, 159 and not because those who 40are far superior in property holdings think it unjust for those who do not 1316b
own anything to participate equally in the city-state with those who do. And in many oligarchies office holders are not only not allowed to ac quire wealth, but there are laws to prevent it. On the other hand, in5 Carthage, which is governed timocratically, 160 the officials do engage in acquiring wealth, and it has not yet undergone change. It is also absurd to claim that an oligarchic city-state is really two city states, one of the rich and one of the poor. 161 For why is this any more true of it than of the Spartan constitution, or any other constitution where the citizens do not all own an equal amount of property or are not10 all similarly good men? And even when no one becomes any poorer than he was, constitutions still undergo change from oligarchy to democracy, if the poor become a majority, or from democracy to oligarchy, if the rich happen to be more powerful than the multitude, and the latter are careless, while the former set their mind to change. Also, though there are many reasons why oligarchies change into democracies, Socrates15 mentions but one: poverty caused by riotous living and paying interest on loans162-as if all or most of the citizens were rich at the start. But this is false. Rather, when some of the leading men lose their properties, they stir up change; but when some of the others do so, nothing terrible happens. And even when change does occur, it is no more likely to result20 in a democracy than in some other constitution. Besides, if people have no share in office or are treated unjustly or arrogantly, they start factions and change constitutions, even if they have not squandered all their property through being free to do whatever they like (the cause of which, Socrates says, is too much freedom). 16325 Although there are many kinds of oligarchies and democracies, Socrates discusses their changes as if there were only one of each.
Chapter 1We have already discussed 1 the number and varieties of the deliberative 30and authoritative elements of constitutions, the ways of organizing of-fices and courts, which is suited to which constitution, and also what theorigins and causes are of the destruction and preservation of constitutions.2 But since it turned out that there are several kinds of democra- 35cies, and similarly of the other constitutions, we would do well to consider whatever remains to be said about these, and to determine whichways of organizing things are appropriate for and beneficial to each ofthem. Moreover, we have to investigate the combinations of all the ways of 40organizing the things we mentioned. For these, when coupled, causeconstitutions to overlap, resulting in oligarchic aristocracies and democ- 1317•ratically inclined polities. I mean those couplings which should be inves-tigated but at present have not been. For example, where the deliberativepart and the part that deals with the choice of officials are organized oligarchically, but the part that deals with the courts is aristocratic; or 5where the part that deals with the courts and the deliberative part areoligarchic, and the part that deals with the choice of officials is aristo-cratic; or where, in some other way, not all the parts appropriate to theconstitution are combined.3 We have already discussed4 the question of which kind of democracyis suited to which kind of city-state; similarly, which kind of oligarchy is 10suited to which kind of people; and which of the remaining constitutions is beneficial for which. Still, since we should make clear not onlywhich kind of constitution is best for a city-state, but also how it and the
1. At IV. 14-16.2. AtV. 1-12.3. These combinations are not discussed in the Politics as we have it.4. At IV. 12.
175 176 Politics VI
Chapter 2 40 The fundamental principle of the democratic constitution is freedom. For it is commonly asserted that freedom is shared only in this sort of13J7b constitution, since it is said that all democracies have it as their aim. One component of freedom is ruling and being ruled in turn. For democratic justice is based on numerical equality, not on merit.7 But if this is what 5 justice is, then of necessity the multitude must be in authority, and
whatever seems right to the majority, this is what is final and this is whatis just, since they say that each of the citizens should have an equalshare. The result is that the poor have more authority than the rich indemocracies. For they are the majority, and majority opinion is in authority. This, then, is one mark of freedom which all democrats take as a 10goal of their constitution. Another is to live as one likes. This, they say, isthe result of freedom, since that of slavery is not to live as one likes.This, then, is the second goal of democracy. From it arises the demandnot to be ruled by anyone, or failing that, to rule and be ruled in turn. In I5this way the second goal contributes to freedom based on equality. From these presuppositions and this sort of principle arise the following democratic features: [ I ] Having all choose officials from all. [2] Hav-ing all rule each and each in turn rule all. [3] Having all offices, or all 20that do not require experience or skill, filled by lot. [4] Having no prop-erty assessment for office, or one as low as possible. [5] Having no office,or few besides military ones, held twice or more than a few times by thesame person. [6] Having all offices or as many as possible be short-term.[7] Having all, or bodies selected from all, decide all cases, or most of 25them, and the ones that are most important and involve the most author-ity, such as those having to do with the inspection of officials, the constitution, or private contracts. [8] Having the assembly have authority overeverything or over all the important things, but having no office with authority over anything or over as little as possible. The council is the most 30democratic office in city-states that lack adequate resources to payeveryone, but where such resources exist even this office is stripped ofits power. For when the people are well paid, they take all decisions intotheir own hands (as we said in the inquiry preceding this one).8 [9] Hav-ing pay provided, preferably for everyone, for the assembly, courts, and 35public offices, or failing that, for service in the offices, courts, council,and assemblies that are in authority, or for those offices that require theirholders to share a mess. Besides, since oligarchy is defined by family,wealth, and education, their opposites (low birth, poverty, and vulgarity) 40are held to be characteristically democratic.9 [ 1 0] Furthermore, it is democratic to have no office be permanent; and if such an office happens
1318" to survive an ancient change, to strip it of its power, at least, and have it filled by lot rather than by election. These, then, are the features commonly found in democracies. And from the type of justice that is agreed to be democratic, which consists in everyone having numerical equality, comes what is held to be most of S all a democracy and a rule by the people, since equality consists in the poor neither ruling more than the rich nor being alone in authority, but in all ruling equally on the basis of numerical equality, since in that way they would consider equality and freedom to be present in the constitu- 10 tion.
Chapter 3 The next problem that arises is how they will achieve this equality. Should they divide assessed property so that the property of five hun dred citizens equals that of a thousand others, and then give equal power to the thousand as to the five hundred?10 Or is this not the way to pro duce numerical equality? Should they instead divide as before, then take IS an equal number of citizens from the five hundred as from the thousand and give them authority over the elections and the courts? Is this the constitution that is most just from the point of view of democratic jus tice? Or is it the one based on quantity? For democrats say that whatever seems just to the greater number constitutes justice, 1 1 whereas oligarchs say that it is whatever seems just to those with the most property. For 20 they say that quantity of property should be the deciding factor. But both views are unequal and unjust. For if justice is whatever the few de cide, we have tyranny, since if one person has more than the others who are rich, then, from the point of view of oligarchic justice, it is just for him alone to rule. 12 On the other hand, if justice is what the numerical 25 majority decide, they will commit injustice by confiscating the property of the wealthy few (as we said earlier). 1 3 What sort of equality there might be, then, that both would agree on is something we must investigate in light of the definitions of justice
1 0. We have two groups, one of five hundred (the rich), another of one thou sand (the poor), each of which has the same amount of property. If we so distribute political power that each group has the same amount, have we treated both the rich and the poor as numerical equality demands? 1 1 . See 1 3 1 7bS-7 12. See 1 283h13 -27. 13. At 1281'14-28. Chapter 4 1 79
they both give. For they both say that the opinion of the MAJORITY of thecitizens should be in authority. So let this stand, though not fully. Instead, since there are in fact two classes in a city-state, the rich and the 30poor, whatever is the opinion of both or of a majority of each shouldhave authority. But if they are opposed, the opinion of the majority (thatis to say, the group whose assessed property is greater) should prevail.Suppose, for example, that there are ten rich citizens and twenty poorones, and that six of the rich have voted against fifteen of the poorerones, whereas four of the rich have sided with the poor, and five of the JSpoor with the rich. When the assessed properties of both the rich andthe poor on each side are added together, the side whose assessed prop-erty is greater should have authority. If the amounts happen to be equal,this should be considered a failure for both sides, as it is at present whenthe assembly or the court is split, and the question must be decided by 40lot or something else of that sort. 131Sb Even if it is very difficult to discover the truth about what equalityand justice demand, however, it is still easier than to persuade people ofit when they have the power to be ACQUISITIVE. For equality and justiceare always sought by the weaker party; the strong pay no heed to them. S
Chapter 4Of the four kinds of democracy, the first in order is the best, as we saidin the discussions before these. 14 It is also the oldest of them all. But Icall it first as one might distinguish people. For the first or best kind ofpeople is the farming kind, and so it is also possible to create a democ-racy where the multitude live by cultivating the land or herding flocks. 10For because they do not have much property, they lack leisure and can-not attend meetings of the assembly frequently. And because they donot15 have the necessities, they are busy at their tasks and do not desireother people's property. Indeed, they find working more pleasant thanengaging in politics and holding office, where no great profit is to be had 1Sfrom office, since the many seek money more than honor. Evidence ofthis is that they even put up with the ancient tyrannies, and continue toput up with oligarchies, so long as no one prevents them from workingor takes anything away from them. For in no time some of them become
20 rich, while the others at least escape poverty. Besides, having authority over the election and inspection of officials will give them what they need, if they do have any love of honor. In fact, in some democracies, the multitude do not participate in the election of officials; instead, electors are selected from all the citizens by turns, as in Mantinea; yet if they 25 have authority over deliberation, they are content. (This arrangement too should be regarded as a form of democracy, as it was at Mantinea.) That is why, indeed, in the aforementioned kind of democracy, it is both beneficial and customary for all the citizens to elect and inspect of ficials and sit on juries, but for the holders of the most important offices 30 to be elected from those with a certain amount of assessed property (the higher the office, the higher the assessment), or alternatively for officials not to be elected on the basis of property assessments at all, but on the basis of ability. People governed in this way are necessarily governed well; the offices will always be in the hands of the best, while the people will consent and will not envy the decent; and this organization is neces- 35 sarily satisfactory to the decent and reputable people, since they will not be ruled by their inferiors, and will rule justly because the others have authority over the inspection of officials. For to be under constraint, and not to be able to do whatever seems good, is beneficial, since freedom to 40 do whatever one likes leaves one defenseless against the bad things that131 Ci' exist in every human being. So the necessary result, which is the very one most beneficial in constitutions, is that the decent people rule with out falling into wrongdoing and the multitude are in no way short changed. It is evident, then, that this is the best of the democracies, and also the 5 reason why: that it is because the people are of a certain kind. And for the purpose of establishing a farming people, some of the laws that ex isted in many city-states in ancient times are extremely useful, for exam ple, prohibiting the ownership of more than a certain amount of land under any circumstances, or else more than a certain amount situated between a given place and the city-state's town. And there used to be a 10 law in many city-states (at any rate, in ancient times) forbidding even the sale of the original allotments of land, 16 and also one, said to derive from Oxylus, 17 with a similar sort of effect, forbidding lending against more than a certain portion of each person's land. Nowadays, however, one should also attempt reform by using the law of the Aphytaeans, as it too
is useful for the purpose under discussion. For though the citizens of 15Aphytis are numerous and have little land, they all engage in farming,because property assessments are based not on whole estates18 but onsuch small subdivisions of them that even the poor can exceed the assessment. After the multitude of farmers, the best sort of people consists ofherdsmen, who get their living from livestock. For herding is in many 20respects similar to farming, and where military activities are concerned,they are particularly well prepared, because they are physically fit andable to live in the open. The other multitudes, of which the remainingkinds of democracies are composed, are almost all very inferior to these. 25For their way of life is bad, and there is no element of virtue involved inthe task to which the multitude of vulgar craftsmen, tradesmen, and laborers put their hand. 19 Furthermore, because they wander around themarketplace and town, practically speaking this entire class can easily at-tend the assembly. Farmers, on the other hand, because they are scat- 30tered throughout the countryside, neither attend so readily nor have thesame need for this sort of meeting. But where the lay of the land is suchthat the countryside is widely separated from the CITY-STATE, it is eveneasier to create a democracy that is serviceable and a CONSTITUTION. For 35the multitude are forced to make their settlements out in the countryareas, so that, even if there is a whole crowd that frequents the marketplace, one should simply not hold assemblies in democracies without themultitude from the country. How, then, the best or first kind of democracy should be establishedhas been described. But how the others should be established is also evident. For they should deviate in order from the best kind, always ex- 40eluding a worse multitude.20 The ultimate democracy, because everyone participates in it, is not 131CJhone that every city-state can afford;21 nor can it easily endure, if its lawsand customs are not well put together. (The factors that cause the de-
struction of this and other constitutions have pretty well all been dis- 5 cussed earlier.)22 With a view to establishing this sort of democracy and making the people powerful, the leaders usually admit as many as possi ble to citizenship, including not only the legitimate children of citizens but even the illegitimate ones, and those descended from citizens on only one side (I mean their mother's or their father's). For this whole10 class are particularly at home in this sort of democracy. This, then, is how popular leaders usually establish such a constitution; yet they should add citizens only up to the point where the multitude outnumber the notables and middle classes, and not go beyond this. For when they do overshoot it, they make the constitution more disorderly and provoke15 the notables to such an extent that they find the democracy hard to en dure (which was in fact the cause of the faction at Cyrene).23 For a small class of worthless people gets overlooked, but as it grows larger it gets more noticed.20 Also useful to a democracy of this kind are the sorts of institutions that Cleisthenes used in Athens when he wanted to increase the power of the democracy, and that those setting up the democracy used at Cyrene.24 For different and more numerous tribes and clans should be created, private cults should be absorbed into a few public ones, and25 every device should be used to mix everyone together as much as possi ble and break up their previous associations. Furthermore, all tyrannical institutions are held to be democratic. I mean, for example, the lack of supervision of slaves (which may really be beneficial to a democracy up to a certain point), or of women or children,25 and allowing everyone to30 live as he likes. For many people will support a constitution of this sort, since for the many it is more pleasant to live in a disorderly fashion than in a temperate one.
Chapter 5 For a legislator, however, or for those seeking to establish a constitution of this kind, setting it up is not the most important task nor indeed the
22. In V.S . 2 3 . Perhaps the revolution o f 401 i n which five hundred rich people were put to death. 24. The reforms of Cleisthenes are described in Ath. XXI. The reference to the democracy at Cyrene may be to the one established there in 462. 25. On this sort of supervision, see 1 300'4-8, 1 322b37-1 323'6. The advantage of not having it in a democracy is explained at 1 3 1 3b32-39, 1 323'3-6. Chapter 5 1 83
only one, but rather ensuring its preservation. For it is not difficult for 35those who govern themselves in any old way to continue for a day oreven for two or three days. That is why legislators should make use ofour earlier studies of what causes the preservation and destruction ofconstitutions, and from them try to institute stability, carefully avoidingthe causes of destruction, while establishing the sort of LAWS, both writ-ten and unwritten, which best encompass the features that preserve con- 40 stitutions. They should consider a measure to be democratic or oli- 132(1'garchic not if it will make the city-state be as democratically governed oras oligarchically governed as possible, but if it will make it be so for thelongest time. Popular leaders nowadays, however, in their efforts to curry favor withthe people, confiscate a lot of property by means of the courts. That is 5why those who care about the constitution should counteract this bypassing a law that nothing confiscated from a condemned person shouldbecome common property, but sacred property instead. For wrongdoerswill be no less deterred, since they will be fined in the same way as be-fore, whereas the crowd will less frequently condemn defendants, since 10they will gain nothing by doing so. Public lawsuits too should always bekept to an absolute minimum, and those who bring frivolous o nesshould be deterred by large fines.26 For they are usually brought againstnotables, not democrats; but all the citizens should be well disposed toward the constitution, or, failing that, they should at least not regard 15those in authority as their enemiesY Since the ultimate democracies have large populations that cannot eas-ily attend the assembly without wages, where they also happen to have adearth of revenues, this is hostile to the notables. For the wages have to beobtained from taxes, confiscations of property, and corrupt courts- 20things that have already brought down many democracies. Where revenues are lacking, then, few assemblies should be held, and courts withmany jurors should be in session for only a few days. For this helps reducethe fears of the notables about expense, provided the rich are not paid for 25jury service but only the poor. It also greatly improves the quality of decisions in lawsuits; for the rich are unwilling to be away from their privateaffairs for many days, but are willing to be so for brief periods. Where there are revenues, however, one should not do what popularleaders do nowadays. For they distribute any surplus, but people no 30
sooner get it than they want the same again. Helping the poor in this way, indeed, is like pouring water into the proverbial leaking jug.28 But the truly democratic man should see to it that the multitude are not too poor (since this is a cause of the democracy's being a corrupt one). Mea sures must, therefore, be devised to ensure long-term prosperity. And, 35 since this is also beneficial to the rich, whatever is left over from the rev enues should be collected together and distributed in lump sums to the poor, particularly if enough can be accumulated for the acquisition of a plot of land, or failing that, for a start in trade or farming. And if this cannot be done for all, distribution should instead be by turns on the132rJ basis of tribe or some other part. In the meantime the rich should be taxed to provide pay for necessary meetings of the assembly, while being released from useless sorts of public service. It is by governing in this sort of way that the Carthaginians have won 5 the friendship of their people, since they are always sending some of them out to their subject city-states to become rich. 29 But it is also char acteristic of notables who are cultivated and sensible to divide the poor amongst themselves and give them a start in some line of work. It is a good thing too to imitate the policy of the Tarentines, who retain the goodwill of the multitude by giving communal use of their property to 10 the poor.30 They also divide all their offices into two classes, those that are elected and those chosen by lot: those by lot, so the people partici pate; those elected, so they are governed better. But this can also be done by dividing the same office between those people chosen by lot and 15 those elected. We have said, then, how democracies should be established.
Chapter 6 It is also pretty well evident from these remarks how oligarchies should be established. For each oligarchy should be assembled from its oppo- 20 sites, by analogy with the opposite democracy, as in the case of the best mixed and first of the oligarchies. This is the one very close to so-called
28. See 1267bl-5. Forty-nine of Danaus' fifty daughters murdered their hus bands on their wedding night and were punished in Hades by having end lessly to fill leaking jugs with water. 29. Compare l 273b l 8 -24. 30. See 1263'35-40 where this policy is attributed to the Spartans, who were the ancestors of the Tarentines. Chapter 7 185
Chapter 7Since there are four principal parts of the multitude (farmers, vulgar 5craftsmen, tradesmen, and hired laborers), and four useful in war (cav-alry, HOPLITES, light infantry, and naval forces), where the country hap-pens to be suitable for cavalry, natural conditions favor the establishment of a powerful oligarchy. For the security of the inhabitantsdepends on horse power, and horse breeding is the privilege of those 10who own large estates.34 Where the country is suitable for hoplites, onthe other hand, conditions favor the next kind of oligarchy, since hoplites are more often rich than poor. 35
3 1 . Those required for the very existence of a city-state ( 1 283'1 7-22, VI. 9).32. From the farmers first, then from the herdsmen, then from the artisans, and so on. See 1 3 1 9'39-h1 and note.33. See 1 290'22-29 and note.34. See 1 289h33-40.35. Since heavy armor is expensive. 1 86 Politics VI
36. At 1320b2S-29. 37. See 1278'25-26. 38. "Small": because ruled by the few instead of the many; "democracies": be cause the few pursue money just like the many (see 1 3 1 8b16-17). Chapter 8 1 87
Chapter 8After what has just been said, the next topic, as was mentioned earlier,39is the matter of correctly distinguishing what pertains to the offices, howmany they are, what they are, and what they are concerned with. For 5without the necessary offices a city-state cannot exist, and without thoseconcerned with proper organization and order it cannot be well managed. Furthermore, in small city-states the offices are inevitably fewer,while in larger ones they are more numerous, as was also said earlier.40 10Consequently, the question of which offices it is appropriate to combineand which to keep separate should not be overlooked. The first of the necessary offices, then, deals with [ 1 ] the supervisionof the market, where there must be some office to supervise contractsand maintain good order. For in almost all city-states people have to beable to buy and sell in order to satisfy each other's necessary needs. This 15is also the readiest way to achieve self-sufficiency, which is thought to bewhat leads people to join together in one constitutionY Another kind of supervision, connected to this one and close to it, is[2] the supervision of public and private property within the town, sothat it may be kept in good order; also, the preservation and repair of decaying buildings and roads, the supervision of property boundaries, so 20that disputes do not arise over them, and all other sorts of supervisionsimilar to these. Most people call this sort of office town management,though its parts are more than one in number. More populous citystates assign different officials to these; for example, wall repairers, well 25supervisors, and harbor guards. Another office is also necessary and closely akin to this one, since itdeals with [3] the same areas, though it concerns the country and matters outside the town. In some places its holders are called country managers, in others foresters. These, then, are three kinds of supervision that deal with necessities. 30Another is [4] the office that receives public funds, safeguards them, anddistributes them to the various branches of the administration. Its hold-ers are called receivers or treasurers. Another office is [5] that where private contracts and the decisions of
avoid it, however, and giving bad ones authority over it is not safe, sincethey are more in need of guarding than capable of guarding others. That 25is why there should not be a single office in charge of guarding prison-ers, nor the same office continuously. Instead, prisoners should be supervised by different people in turn, chosen from among the youngmen, in places where there is a regiment of cadets or guards,45 or fromthe other officials. These offices must be put first, then, as the most necessary. After 30these are others that are no less necessary, but ranked higher in dignity,since they require much experience and trustworthiness. The offices [7]that deal with the defense of the city-state are of this sort, and any thatare organized to meet its wartime needs. In peacetime and wartime alikethere should be people to supervise the defense of the gates and walls, 35and the inspection and organizing of the citizens. In some places thereare more offices assigned to all these areas, in others there are fewer (insmall city-states, for example, a single office deals with all of them).Such people are called generals or warlords. Furthermore, if there is acavalry, a light infantry, archers, or a navy, an office is sometimes estab- 1322blished for each of them. They are called admirals, cavalry commanders,or regimental commanders, whereas those in charge of the units underthese are called warship commanders, company commanders, or triballeaders, and so on for their subunits. But all of these together constitute 5a single kind, namely, supervision of military affairs. This, then, is theway things stand with regard to this office. But since some if not all of the offices handle large sums of publicmoney, there must be [8] a different office to receive and examine theiraccounts which does not itself handle any other matters. Some call these 10inspectors, accountants, auditors, or advocates. Besides all these offices, there is [9] the one with the most authorityover everything; for the same office often has authority over both implementing and introducing a measure, or presides over the multitudewhere the people have authority. For there must be some body to con-vene the body that has authority over the constitution. In some places, 15they are called preliminary councilors, because they prepare businessfor the assembly. 46 But where the multitude are in authority they areusually called a council instead.
45. In Athens and other city-states young men served from the time they were eighteen until they were twenty in such regiments, which acted as police or civic guards.46. See 1 298b26-34. 1 90 Politics VI
This, then, is pretty much the number of offices that are political. But another kind of supervision is [ 1 0] that concerned with the worship of the gods: for example, priests, supervisors of matters relating to the 20 temples (such as the preservation of existing buildings, the restoration of decaying ones), and all other duties concerning the gods. Sometimes it happens, for example, in small city-states, that a single office super vises all this, but sometimes, apart from the priests, there are a number of others, such as supervisors of sacrifices, temple guardians, and sacred 25 treasurers. Next after this is the office specializing in the public sacri fices that the law does not assign to the priests; instead, the holders have the office from the communal hearth.47 These officials are called archons by some, kings or presidents by others. To sum up, then, the necessary kinds of supervision deal with the fol- 30 lowing: religious matters, military matters, revenues and expenditures, the market, town, harbors, and country; also matters relating to the courts, such as registering contracts, collecting fines, carrying out of 35 sentences, keeping prisoners in custody, receiving accounts, and in specting and examining officials; and, finally, matters relating to the body that deliberates about public affairs. On the other hand, peculiar to city-states that enjoy greater leisure and prosperity and that also pay attention to good order are [ 1 1 ] the offices dealing with the supervision of women, [ 12] the guardianship of the laws, [ 1 3 ] the supervision of children, [ 1 4] authority over the gymnasia, and1323• also [ 1 5] the supervision of gymnastic or Dionysiac contests,48 as well as of any other such public spectacles there may happen to be. Some of these are obviously not democratic, for example, the supervision of women and that of children, for the poor have to employ their women 5 and children as servants, because of their lack of slaves. There are three offices that city-states use to supervise the selection of the officials who are in authority: [ 1 6] the office of law guardian, [ 17] that of preliminary councilor, and [ 1 8] the council. The office of law guardian is aristocratic, that of preliminary councilor oligarchic, and a council, democratic. 10 Pretty well all the offices have now been discussed in outline.
47. The communal hearth (koine hestia) derives from the hearth in the king's palace which had both a practical and a magico-religious significance. 48. The dramatic festivals in which tragic and comedic poets competed. B oo K V I I
Chapter 1Anyone who intends to investigate the best constitution in the properway must first determine which life is most choiceworthy, since if this 15remains unclear, what the best constitution is must also remain unclear.For it is appropriate for those to fare best who live in the best constitu-tion their circumstances allow-provided nothing contrary to reason-able expectation occurs. That is why we should first come to some agreement about what the most choiceworthy life is for practically speakingeveryone,1 and then determine whether it is the same for an individual as 20for a community, or different. Since, then, I consider that I have already expressed much that is adequate about the best life in the "external" works,2 I propose to make useof them here as well. For since, in the case of one division at least, thereare three groups--external GOODS, goods of the body, and goods of the 25soul-surely no one would raise a dispute and say that not all of themneed be possessed by those who are BLESSEDLY HAPPY. For no one wouldcall a person blessedly happy who has no shred of courage, temperance,j ustice, or practical wisdom, but is afraid of the flies buzzing aroundhim, stops at nothing to gratify his appetite for food or drink, betrays his 30dearest friends for a pittance, and has a mind as foolish and prone toerror as a child's or a madman's. But while almost all accept theseclaims, they disagree about quantity and relative superiority. For they 35consider any amount of virtue, however small, to be sufficient, but seekan unlimitedly excessive amount of wealth, possessions, power, reputa-tion, and the like. We, however, will say to them that it is easy to reach a reliable conclusion on these matters even from the facts themselves. For we see that the
191 1 92 Politics VII
40 virtues are not acquired and preserved by means of external goods, but the other way around,3 and we see that a happy life for human beings,132Jh whether it consists in pleasure or virtue or both, is possessed more often by those who have cultivated their characters and minds to an excessive degree, but have been moderate in their acquisition of external goods, than by those who have acquired more of the latter than they can possi- 5 bly use, but are deficient in the former. Moreover, if we investigate the matter on the basis of argument, it is plain to see. For external goods have a limit, as does any tool, and all useful things are useful for some thing; so excessive amounts of them must harm or bring no benefit to their possessors. 4 In the case of each of the goods of the soul, however, 10 the more excessive it is, the more useful it is (if these goods too should be thought of as useful, and not simply as noble). It is generally clear too, we shall say, that the relation of superiority holding between the best condition of each thing and that of others cor responds to that holding between the things whose conditions we say 15 they are. So since the soul is UNQUALIFIEDLY more valuable, and also more valuable to us, than possessions or the body, its best states must be proportionally better than theirs. Besides, it is for the sake of the soul that these things are naturally choiceworthy, and every sensible person 20 should choose them for its sake, not the soul for theirs. We may take it as agreed, then, that each person has just as much hap piness as he has virtue, practical wisdom, and the action that expresses them. We may use GOD as evidence of this. For he is blessedly happy, not because of any external goods but because of himself and a certain qual- 25 ity in his nature.5 This is also the reason that good luck and happiness are necessarily different. For chance or luck produces goods external to the soul, but no one is just or temperate as a result of luck or because of luck. 6 30 The next point depends on the same arguments. The happy city-state is the one that is best and acts nobly. It is impossible for those who do not do noble deeds to act nobly; and no action, whether a man's or a city state's, is noble when separate from virtue and practical wisdom. But the
3. The point is probably not that virtue invariably makes you rich, but that, without virtue, wealth and the rest can do you as much harm as good. 4. See 1256b3 5-36, 1 257h28. 5. See Introduction xliii-xlv. Luck (tuche) and chance (to automaton) and the difference between them are discussed in Ph. Il.4-6. 6. See NE 1 1 53bJ9-25. Chapter 2 193
courage, justice, and practical wisdom of a city-state have the same capacity and are of the same kind as those possessed by each human being JSwho is said to be just, practically wise, and temperate. So much, then, for the preface to our discussion.7 For we cannot avoidtalking about these issues altogether, but neither can we go through allthe arguments pertaining to them, since that is a task for another type ofstudy.8 But for now, let us assume this much, that the best life, both for 40individuals separately and for city-states collectively, is a life of virtuesufficiently equipped with the resources9 needed to take part in virtuousactions. With regard to those who dispute this, if any happen not to be 1324"persuaded by what has been said, we must ignore them in our presentstudy, but investigate them later.
Chapter 2It remains to say whether the happiness of each individual human being Sis the same as that of a city-state or not. But here too the answer is evident, since everyone would agree that they are the same. For those whosuppose that living well for an individual consists in wealth will also calla whole city-state blessedly happy if it happens to be wealthy. And thosewho honor the tyrannical life above all would claim that the city-state 10that rules the greatest number10 is happiest. And if someone approves ofan individual because of his virtue, he will also say that the more excel-lent city-state is happier. Two questions need to be investigated, however. First, which life ismore choiceworthy, the one that involves taking part in politics withother people and participating in a city-state, or the life of an alien cut 1Soff from the political community? Second, and regardless of whetherparticipating in a city-state is more choiceworthy for everyone or formost but not for all, which constitution, which condition of the citystate, is best? This second question, and not the one about what is 20choiceworthy for the individual, is a task for political thought or theory.And since that is the investigation we are now engaged in, whereas theformer is a further task, our task is the second question. l l
8. Namely, ethics. 9. That is, external GOODS.10. Presumably, the greatest number of other city-states.11. See Introduction xlvi-xlviii. 194 Politics VII
Chapter 3 We must now reply to the two sides who agree that the virtuous life is most choiceworthy, but disagree about how to practice it. For some rule out the holding of political office and consider that the life of a free per son is both different from that of a statesman and the most choiceworthy 20 one of all. But others consider that the political life is best, since it is im possible for someone inactive to do or act well, and that doing well and happiness are the same. We must reply that they are both partly right and partly wrong. On the one hand, it is true to say that the life of a free person is better than that of a master. For there is certainly nothing 25 grand about using a slave as a slave, since ordering people to do neces sary tasks is in no way noble. None the less, it is wrong to consider that every kind of rule is rule by a master. For the difference between rule over free people and over slaves is no smaller than the difference be tween being naturally free and being a natural slave. We have adequately 30 distinguished them in our first discussions. 15 On the other hand, to praise inaction more than action is not correct either. For happiness is ACTION, and many noble things reach their end in the actions of those who are just and temperate. Perhaps someone will take these conclusions to imply, however, that 35 having authority over everyone is what is best. For in that way one would have authority over the greatest number of the very noblest actions. It would follow that someone who has the power to rule should not surren der it to his neighbor but take it away from him, and that a father should disregard his children, a child his father, a friend his friend, and pay no attention to anything except ruling. For what is best is most choicewor- 40 thy, and doing well is best. What they say is perhaps true, if indeed those who use force and com-1325b mit robbery will come to possess the most choiceworthy thing there is. But perhaps they cannot come to possess it, and the underlying assump tion here is false. For someone cannot do noble actions if he is not as su perior to those he rules as a husband is to his wife, a father to his chil- 5 dren, or a master to his slaves. Therefore, a transgressor could never make up later for his deviation from virtue. For among those who are similar, ruling and being ruled in turn is just and noble, since this is equal or similar treatment. But unequal shares for equals or dissimilar ones for similars is contrary to nature; and nothing contrary to nature is
1 5 . 1.4-7. Chapter 4 197
noble. Hence when someone else has superior virtue and his power to do 10the best things is also superior, it is noble to follow and just to obey him.But he should possess not virtue alone, but also the power he needs to dothese things. If these claims are correct, and we should assume that happiness isdoing well, then the best life, whether for a whole city-state collectivelyor for an individual, would be a life of action. Yet it is not necessary, as I5some suppose, for a life of action to involve relations with other people,nor are those thoughts alone active which we engage in for the sake ofaction's consequences; the study and thought that are their own endsand are engaged in for their own sake are much more so. For to do or act 20well is the end, so that ACTION of a sort is the end too. And even in thecase of actions involving external objects, the one who does them mostfully is, strictly speaking, the master craftsman who directs them bymeans of his thought. 16 Moreover, city-states situated by themselves, which have deliberatelychosen to live that way, do not necessarily have to be inactive, since activity can take place even among their parts. For the parts of a city-state 25have many sorts of communal relationships with one another. 17 Similarly, this holds for any human being taken singly. For otherwise GODand the entire universe could hardly be in a fine condition; for they haveno external actions, only the internal ones proper to them. It is evident, then, that the same life is necessarily best both for each 30human being and for city-states and human beings collectively.
Chapter 4Since what has just been said about these matters was by way of a pref-ace, and since we studied the various constitutions earlier, 18 the startingpoint for the remainder of our investigation is first to discuss the condi- 35tions that should be presupposed to exist by the ideal city-state we areabout to construct. For the best constitution cannot come into existencewithout commensurate resources. Hence we should presuppose thatmany circumstances are as ideal as we could wish, although none should
would be a task for a divine power, the sort that holds the entire universetogether. For beauty is usually found in number and magnitude. Hence acity-state whose size is fixed by the aforementioned limit must also bethe most beautiful. But the size of city-state, like everything else, has a 35certain scale: animals, plants, and tools. For when each of them is nei-ther too small nor too excessively large, it will have its own proper capacity; otherwise, it will either be wholly deprived of its nature or be inpoor condition. For example, a ship that is one span [seven and a halfinches] long will not be a ship at all, nor will one of two stades [twelve 40hundred feet]; and as it approaches a certain size, it will sail badly, be-cause it either is still too small or still too large. Similarly for a city-state: 13266one that consists of too few people is not SELF-SUFFICIENT (whereas acity-state is self-sufficient), but one that consists of too many, while it isself-sufficient in the necessities, the way a nation is, is still no city-state,since it is not easy for it to have a constitution. For who will be the gen-eral of its excessively large multitude, and who, unless he has the voice 5of Stentor, will serve as its herald?24 Hence the first city-state to arise is the one composed of the first multitude large enough to be self-sufficient with regard to living the goodlife as a political community. It is also possible for a city-state that exceeds this one in number to be a greater city-state, but, as we said, this is 10not possible indefinitely. The limit to its expansion can easily be seenfrom the facts. For a city-state's actions are either those of the rulers orthose of the ruled. And a ruler's task is to issue orders and decide. But inorder to decide lawsuits and distribute offices on the basis of merit, each I5citizen must know what sorts of people the other citizens are. For wherethey do not know this, the business of electing officials and decidinglawsuits must go badly, since to act haphazardly is unjust in both theseproceedings. But this is plainly what occurs in an overly populated citystate. Besides, it is easy for resident aliens and foreigners to participate 20in the constitution, since the excessive size of the population makesescaping detection easy. It is clear, then, that the best limit for a city-state is this: it is the greatest size of multitude that promotes life's selfsufficiency and that can be easily surveyed as a whole. The size of thecity-state, then, should be determined in this way. 25
24. Stentor was a Homeric hero gifted with a very powerful voice. 200 Politics VII
Chapter 5 Similar things hold in the case of territory. For, as far as its quality is concerned, it is clear that everyone would praise the most self-sufficient. And as such it must produce everything, for self-sufficiency is having everything and needing nothing. In size or extent, it should be large 30 enough to enable the inhabitants to live a life of leisure in a way that is generous and at the same time temperate.25 But whether this defining principle is rightly or wrongly formulated is something that must be in vestigated with greater precision later on, when we come to discuss the question of possessions generally-what it is to be well off where prop- 35 erty is concerned, and how and in what way this is related to its use. For there are many disputes about this question raised by those who urge us to adopt one extreme form of life or the other: penury in the one case, luxury in the other.26 The layout of the territory is not difficult to describe (although on 40 some points the advice of military experts should also be taken): it should be difficult for enemies to invade and easy for the citizens to get out to. 27 Moreover, just as the multitude of people should, as we said, be1327" easy to survey as a whole, the same holds of the territory. For a territory easy to survey as a whole is easy to defend. If the CITY-STATE is to be ideally sited, it is appropriate for it to be well situated in relation to the sea and the surrounding territory. One S defining principle was mentioned above: defensive troops should have access to all parts of the territory. The remaining defining principle is that the city-state should be accessible to transportation, so that crops, timber, and any other such materials the surrounding territory happens to possess can be easily transported to it.
Chapter 6 There is much dispute about whether access to the sea is beneficial or harmful to well-governed city-states. For it is said that entertaining for-
Chapter 7 We spoke earlier about what limit there should be on the number of cit izens.30 Let us now discuss what sort of natural qualities they should have.20 One may pretty much grasp what these qualities are by looking at those Greek city-states that have a good reputation, and at the way the entire inhabited world is divided into nations. The nations in cold re gions, particularly Europe, are full of spirit but somewhat deficient in intelligence and craft knowledge. That is precisely why they remain25 comparatively free, but are apolitical and incapable of ruling their neigh bors. Those in Asia, on the other hand, have souls endowed with intelli gence and craft knowledge, but they lack spirit. That is precisely why they are ruled and enslaved. The Greek race, however, occupies an in termediate position geographically, and so shares in both sets of charac-30 teristics. For it is both spirited and intelligent. That is precisely why it remains free, governed in the best way, and capable, if it chances upon a single constitution, of ruling all the others.31 Greek nations also differ from one another in these ways. For some have a nature that is one-35 sided, whereas in others both of these capacities are well blended. It is evident, then, that both spirit and intelligence should be present in the natures of people if they are to be easily guided to virtue by the legislator. Some say that guardians should have precisely this quality: they must be friendly to those they know and fierce to those they do not,32 and that40 spirit is what makes them be friendly. For spirit is the capacity of the soul by which we feel friendship. A sign of this is that our spirit is roused
30. In VII.4. 3 1 . Aristotle cannot be supposing that all of Greece might form a single city state; it was.
|
https://ru.scribd.com/document/384249201/Aristotle-Politics-Hackett-1998-pdf
|
CC-MAIN-2020-10
|
refinedweb
| 80,674
| 57.3
|
Python - Switch Case Implementation
Unlike C++/Java, Python does not have a built-in switch case statement. Due to this, it is quite common to think of using if-elif-else control statement for each switch cases. But there is a other way around to implement switch statement in Python. The powerful dictionary mapping which provides unique key-value mapping can be efficiently used to create such implementation.
Example:
The example below illustrates how to implement switch case in Python. Inside the function called MySwitchCases, the dictionary called MyDict is created with key-value pairs representing respective switch-case scenarios. When the function MySwitchCases is called, it uses dictionary get() method to find the value of the specified key. If the key is not present in the dictionary, it returns default value which is "Not Found" in this particular example.
def MySwitchCases(case): MyDict = { 1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI', 6: 'SAT', 7: 'SUN' } return MyDict.get(case, 'Mapping not found') print("3 is Mapped to:", MySwitchCases(3)) print("9 is Mapped to:", MySwitchCases(9))
The output of the above code will be:
3 is Mapped to: WED 9 is Mapped to: Mapping not found
❮ Python - Dictionary
|
https://www.alphacodingskills.com/python/notes/python-switch-case-implementation.php
|
CC-MAIN-2021-31
|
refinedweb
| 201
| 60.95
|
374 votes
1 answers
just getting started using shopify js api and getting an error when trying to run my angular application
I'm getting this error in the console.
__WEBPACK_IMPORTED_MODULE_1_shopify_buy___default.a is not a constructor
import Client, {Config} from 'shopify-buy'; const config = new Config({ domain: 'something.myshopify.com', accessToken: 'xxxxxxxxxxxxxxxxxxx', appId : x }); const client = new Client(config);
Seems to be yelling at "const client = new Client(config);".... But that's what they have in their documentation. Am I doing something wrong? If so, how can I fix it?
Undefined asked
56
votes
Answer
Solution:
I haven't tested this but from their documentation you can do something like following.
import ShopifyBuy from 'shopify-buy'; const shopClient = ShopifyBuy.buildClient({ apiKey: 'xxxxxxxxxxxxxxxxxxxx1403c107adc7e', domain: 'xxxxxxxxxxxxxxxx.myshopify.com', appId: '6', }); export function fetchAllProducts() { return new Promise((resolve, reject) => { shopClient.fetchAllProducts() .then((data) => { console.log('shopClient.fetchAllProducts', data); resolve(data); }).catch((error) => { console.error(new Error('Fetching products error!')); reject(error); }); }); }
Undefined answered
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
544 javascript - Getting Status: "Not Acceptable" while trying to update a variant price form Rest API Admin Shopify in Airtable Scripts
715 javascript - Make Shopify API Post Request using Next.js and Koa Router (405 Method not allowed)
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
|
https://e1commerce.com/items/just-getting-started-using-shopify-js-api-and-getting-an-error-when-trying-to-ru
|
CC-MAIN-2022-40
|
refinedweb
| 263
| 51.04
|
Make a Twitter Clone With This Flask TutorialYamil Asusta Technical
Flask is a lightweight Python micro framework. And by micro, they mean it’s super easy to use. Batteries are not included. (But you can inject batteries as you go!) This tutorial will show you how to use Flask to create a Twitter clone. Most of my tutorials are based on Twitter since most people are familiar with it. So, let’s get started.
Prepare Your Environment
You should have either pip or easy_install. For the sake of versioning we will use virtualenv.
$ pip install virtualenv // or $ easy_install virtualenv
You may or may not need to use sudo when running that. Let’s follow up by creating a virtualenv for a project called TweetBot.
$ virtualenv tweetbot $ cd tweetbot $ source bin/activate $ pip install flask sendgrid
Small recap of the commands. Source will actually activate the virtualenv in order for us to have a contained Python version. Everything we do now will be contained to this virtual python environment. Whenever you want to exit the virtualenv, just write deactivate.
Boilerplate Your Flask Application
Like previously mentioned, we are going to be building a Twitter clone. Flask let’s your start really simple, so in this case we’re simply building a RESTful API.
The starting boilerplate will look like the following:
from flask import Flask, request, jsonify from random import randint from sendgrid import Mail, SendGridClient app = Flask(__name__) app.debug = True tweets = [] #put code here if __name__ == '__main__': app.run()
If you notice, Flask contains everything we need out of the box.
Add Routes for the API
The POST endpoint will be used to save our tweets. Quick note, our database for this example is an array–so nothing fancy. On the other hand, the GET where no parameters are included, will return a list of all tweets.
@app.route('/tweet', methods=['POST', 'GET']) def handle_create(): if request.method == 'POST': new_tweet = {"id": randint(), "text": request.form['tweet']} tweets.append(newtweet) return jsonify(newtweet) else: return jsonify({"tweets": tweets})
Now, let’s handle tweets individually. Either return a specific tweet (GET),
modify a tweet (PUT), or delete a tweet (DELETE).
@app.route('/tweet/<int:id>', methods=['PUT', 'GET', 'DELETE']) def handle_single_tweet(id): for tweet in tweets: if tweet['id'] == id: if request.method == 'GET': return jsonify(tweet) elif request.method == 'PUT': tweet['text'] = request.form('text') return jsonify(tweet) else: removed = tweet tweets.remove(tweet) return jsonify(removed) return jsonify({"error": "Not found"})
Notice this can be organized in a cleaner way, but for the sake of showing everything step by step, I made this a little verbose.
Now we have a way to create, view, edit, and delete tweets! Start playing around! This was initially built for a workshop I’ve been giving as practice for Puerto Rico’s upcoming hackathon, hackPR. If you want me to drop by and give this workshop for your peeps, I’d be more than glad to do so! Send me a tweet @elbuo8 and we can sort it out
Bonus: Add Tweets Via Email
You can use SendGrid’s Inbound
Parse API to accept incoming email. Why not point it to your Flash application?
Add the following route:
@app.route('/tweet/emailhook', methods=['POST']) def email_tweet(): new_tweet = {'id': randint(), 'text': request.form['subject']} tweets.append(new_tweet) return jsonify(new_tweet)
This will receive a POST request and add the text within the subject to your Twitter clone.
The full source code for this Twitter clone tutorial is available on GitHub.
For more details about receiving email in Flask applications, see Elmer’s tutorial, Collect Inbound Email Using Python and Flask.
|
https://sendgrid.com/blog/make-twitter-clone-flask-tutorial/
|
CC-MAIN-2016-18
|
refinedweb
| 606
| 66.84
|
On Wed, 2005-01-26 at 08:44 -0800, Casey Schaufler wrote: > --- "Timothy R. Chavez" <chavezt gmail com> wrote: > > > Ok, if you're watching /home/casey/viruses and you > > mv/rename() > > viruses/ to fuzzybunnys/, you will lose the watch. > > That is not what I would expect from an object > standpoint. I specified the object that I wanted > to watch and the rename did not change the object. In the case of shadow all you care about is the new object. You have a log entry saying that the object was moved, now you wait for a new one to be created. You care about who is writing to the pathname which will be used for authentication. The case you're mentioning is when we're more concerned about protecting the data itself. We've talked about supporting this, but it would have to be very clear to the user which type of audit watch is being requested. One of the main reasons we've not addressed the issue yet is because in order for this type of tracking to survive a reboot, we would have to either make use of extended attributes, or have the kernel append to the list of audit rules stored in the config file. The latter is clearly unacceptable, and the former would be nice to avoid if possible. > Make no mistake. The stated and genuine purpose > of an audit trail is to track the changes to the > security state of the system and the access control > decisions made by the system. Yes, and so when we know that login will check whatever object happens to be located at /etc/shadow, then the object which can be reached through /etc/shadow, whatever dentry it was actually reached through, must be audited. Note that the case you mention of mv filename tempfile mv tempfile filename would result in filename being audited again after the second mv under the current behavior. But any access to tempfile between the two moves would not be audited. (At least this is the intent. I'm not yet convinced that renames and unlinks are all currently correctly handled, only because I haven't had time to look for that yet) > This requires that > it be 100% unambiguous what it means to specify > a watched object. Absolutely. > # watch dev=8,9 inode=8776 > > that would be reliable, unambiguous, and > painful. Reliable depends on what you're trying to accomplish. It would be worthless for the shadow case, because after the next run of passwd, inode 8776 is no longer useful. > If you want to audit by pathname attaching > the audit watch to the inode is not right > because the two are not connected in any > real way. Attaching to the inode is necessary because it is the only way to catch every access to the object attached to this dentry, regardless of which dentry (in whatever namespace) was used to access the inode. -- Serge Hallyn <serue us ibm com>
|
https://www.redhat.com/archives/linux-audit/2005-January/msg00251.html
|
CC-MAIN-2015-18
|
refinedweb
| 496
| 68.2
|
Java theory and practice
Going wild with generics, Part 1
Understanding wildcard capture
Content series:
This content is part # of # in the series: Java theory and practice
This content is part of the series:Java theory and practice
Stay tuned for additional content in this series.. We've all had a few head-scratching moments with generics, but far and away the trickiest part of generics is wildcards.
Wildcard basics
Generics are a means of expressing type constraints on the
behavior of a class or method in terms of unknown types, such as
"whatever the types of parameters
x and
y of
this method are, they must be the same type," "you must provide a
parameter of the same type to both of these methods," or "the return
value of
foo() is the same type as the parameter of
bar()."
Wildcards — the funky question marks where a type parameter should go — are a means of expressing a type constraint in terms of an unknown type. They were not part of the original design for generics (derived from the Generic Java (GJ) project); they were added as the design process played out over the five years between the formation of JSR 14 and its final release.
Wildcards play an important role in the type system; they
provide a useful type bound for the family of types specified by a
generic class. For the generic class
ArrayList, the type
ArrayList<?> is a supertype of
ArrayList<T>
for any (reference) type
T (as are the raw type
ArrayList and the root type
Object, but
these supertypes are far less useful for performing type inference).
The wildcard type
List<?> is different from both the
raw type
List and the concrete type
List<Object>. To say a variable
x has type
List<?> means that there exists some type
T
for which
x is of type
List<T>, that
x is homogeneous even though we don't know what
particular type its elements have. It's not that the contents can be
anything, it's that we don't know what the type constraints on the
contents are — but we know that there is a constraint. On the other
hand, the raw type
List is heterogeneous; we are not able
to place any type constraints on its elements, and the concrete type
List<Object> means that we explicitly know that it can
contain any object. (Of course, the generic type system has no concept
of "the contents of a list," but it is easiest to understand generics
in terms of collection types like
List.)
The utility of wildcards in the type system comes partially from the
fact that generic types are not covariant. Arrays are covariant;
because
Integer is a subtype of
Number, the
array type
Integer[] is a subtype of
Number[], and therefore an
Integer[] value
can be supplied wherever a value of
Number[] is
required. On the other hand, generics are not covariant;
List<Integer> is not a subtype of
List<Number>, and attempting to supply a
List<Integer> where a
List<Number> is
demanded is a type error. This was not an accident — nor necessarily
the error that everyone assumes it to be — but the different behavior
of generics vs. arrays does cause a great deal of confusion.
I got dealt a wildcard — now what?
Listing 1 shows a simple container type,
Box, which
supports
put and
get
operations.
Box is parameterized by a type parameter
T, which signifies the type of the contents of the box; a
Box<String> can contain only elements of type
String.
Listing 1. Simple generic Box type
public interface Box<T> { public T get(); public void put(T element); }
One benefit of wildcards is that they allow you to write code that can
operate on variables of generic types without knowing their exact type
bound. For example, suppose you have a variable of type
Box<?>, such as the
box parameter in the
method
unbox() in Listing 2. What can
unbox() do with the box that it's been handed?
Listing 2. Unbox method with wildcard parameter
public void unbox(Box<?> box) { System.out.println(box.get()); }
It turns out it can do quite a lot: it can call the
get() method, and it can call any of the methods
inherited from
Object (such as
hashCode()). The only thing it cannot do is call the
put() method, and this is because it cannot verify the
safety of such an operation without knowing the type parameter
T for this
Box instance. Because
box is a
Box<?>, and not a raw
Box, the compiler knows that there is some
T
that serves as a type parameter for
box, but because it doesn't
know what that
T is, it will not let you call
put() because it cannot verify that doing so will not violate
the type safety constraints for
Box. (Actually, you can
call
put() in one special case: when you pass the
null literal. We may not know what type
T
represents, but we know that the
null literal is a valid
value for any reference type.)
What does
unbox() know about the return type of
box.get()? It knows that it is
T for some
unknown
T, so the best it can do is conclude that the
return type of
get() is the erasure of the unknown type
T, which in the case of an unbounded wildcard is
Object. So the expression
box.get() in Listing 2 has type
Object.
Wildcard capture
Listing 3 shows some code that seems like it should work,
but doesn't. It takes a generic
Box, extracts the value,
and tries to put the value back into the same
Box.
Listing 3. Once you take it out of the box, you can't put it back
public void rebox(Box<?> box) { box.put(box.get()); } Rebox.java:8: put(capture#337 of ?) in Box<capture#337 of ?> cannot be applied to (java.lang.Object) box.put(box.get()); ^ 1 error
This code looks like it should work because the value that came out is
the right type to go back in, but instead the compiler produces the
(very confusing) error message about "capture#337 of ?" not being
compatible with
Object.
What on earth does "capture#337 of ?" mean? When the compiler
encounters a variable with a wildcard in its type, such as the
box parameter of
rebox(), it knows that
there must have been some
T for which
box is
a
Box<T>. It does not know what type
T
represents, but it can create a placeholder for that type to refer to
the type that
T must be. That placeholder is called the
capture of that particular wildcard. In this case, the compiler
has assigned the name "capture#337 of ?" to the wildcard in the type
of
box. Each occurrence of a wildcard in each variable declaration
gets a different capture, so in the generic declaration
foo(Pair<?,?> x, Pair<?,?> y), the compiler would assign
a different name to the capture of each of the four wildcards because
there is no relationship between any of the unknown type parameters.
What this error message is telling us is that we can't call
put() because it can't verify that the type of the actual
parameter to
put() is compatible with the type of its
formal parameter — because the type of its formal parameter is
unknown. In this case, because
? essentially means "?
extends Object," the compiler has already concluded that the type of
box.get() is
Object, not "capture#337 of ?,"
and it can't statically verify that an
Object is an
acceptable value for the type identified by the placeholder "capture#337 of ?."
Capture helpers
While it looks like the compiler has thrown away some useful
information, there's a trick that we can use to get the compiler to
reconstitute that information and go along with us here, which is to
give a name to the unknown wildcard type. Listing 4 shows an
implementation of
rebox(), along with a generic helper
method, that does the trick:
Listing 4. The "capture helper" idiom
public void rebox(Box<?> box) { reboxHelper(box); } private<V> void reboxHelper(Box<V> box) { box.put(box.get()); }
The helper method
reboxHelper() is a generic method;
generic methods introduce additional type parameters (placed in angle
brackets before the return type), which are usually used to formulate
type constraints between the parameters and/or return value of the
method. In the case of
reboxHelper(), however, the
generic method does not use the type parameter to specify a type
constraint; it allows the compiler (through type inference) to give a
name to the type parameter of box's type.
The capture helper trick allows us to work around the compiler's
limitations in dealing with wildcards. When
rebox() calls
reboxHelper(), it knows that doing so is safe because its
own
box parameter must be a
Box<T> for some
unknown
T. Because the type parameter
V is
introduced in the method signature and not tied to any other type
parameter, it can stand for any unknown type as well, so a
Box<T> for some unknown
T might as well be a
Box<V> for some unknown
V. (This is similar to the principle of alpha reduction in the lambda calculus, which allows you to rename bound variables.)Now the
expression
box.get() in
reboxHelper() no
longer has type
Object, it has type
V— and it
is allowable to pass a
V to
Box<V>.put().
We could have declared
rebox() as a generic method in
the first place, like
reboxHelper(), but that is
considered bad API design style. The governing design principle here
is "don't give something a name if you're never going to refer to it
by name." In the case of generic methods, if a type parameter appears
only once in the method signature, then it probably should be a
wildcard rather than a named type parameter. In general, APIs with
wildcards are simpler than APIs with generic methods, and the
proliferation of type names in a more complicated method declaration
would likely make the declaration less readable. Because the name can
always be resurrected with a private capture helper if needed, this
approach gives you the opportunity to keep APIs clean without throwing
useful information away.
Type inference
The capture-helper trick depends on several things: type inference and capture conversion. The Java compiler doesn't perform type inference in very many places, but one place it does is in inferring the type parameter for generic methods. (Other languages depend much more heavily on type inference, and we may see additional type inference features added to the Java language in the future.) You are allowed to specify the value of the type parameter if you like, but only if you can name the type — and the capture types are not denotable. So the only way this trick could work is if the compiler infers the type for you. Capture conversion is what allows the compiler to manufacture a placeholder type name for the captured wildcard, so that type inference can infer it to be that type.
The compiler will try and infer the most specific type it can for the type parameters when resolving a call to a generic method. For example, with this generic method:
public static<T> T identity(T arg) { return arg };
and this call:
Integer i = 3; System.out.println(identity(i));
the compiler could infer that
T is
Integer,
Number, Serializable, or
Object, but
it chooses
Integer as that is the most specific type that
fits the constraints.
You can use type inference to reduce some of the redundancy when
constructing generic instances. For example, using our
Box class, creating a
Box<String> requires
you to specify the type parameter
String twice:
Box<String> box = new BoxImpl<String>();
This violation of the DRY principle (Don't Repeat Yourself) here
can be irksome, even when IDEs are able to do some of the work for
you. However, if the implementation class
BoxImpl
provides a generic factory method as in Listing 5 (which is a good
idea anyway), you can reduce this redundancy in client code:
Listing 5. A generic factory method that allows you to avoid redundantly specifying type parameters
public class BoxImpl<T> implements Box<T> { public static<V> Box<V> make() { return new BoxImpl<V>(); } ... }
If you instantiate a
Box using the
BoxImpl.make() factory, you need only specify the type
parameter once:
Box<String> myBox = BoxImpl.make();
The generic
make() method returns a
Box<V>
for some type
V, and the return value is being used in a
context that requires a
Box<String>. The compiler
determines that
String is the most specific type that
V could take on that satisfies the type constraints, and
so infers
V to be
String here. You still
have the option of manually specifying the value of
V as
follows:
Box<String> myBox = BoxImpl.<String>make();
In addition to saving some keystrokes, the factory method technique illustrated here has other advantages over constructors: you can give them more descriptive names, they can return subtypes of the named return type, and they are not necessarily required to create a new instance for each invocation, enabling sharing of immutable instances. (See Effective Java, Item #1 in the Related topics for more on the benefits of static factories.)
Conclusion
Wildcards can definitely be tricky; some of the most confusing error messages that come out of the Java compiler have to do with wildcards, and some of the most complex sections of the Java Language Specification have to do with wildcards. However, when used properly, they can be extremely powerful. The two tricks shown here — the capture helper trick and the generic factory trick — both take advantage of generic methods and type inference, which, when used properly, can hide much of the complexity.
Downloadable resources
Related topics
- "Generics gotchas" (Brian Goetz, developerWorks, January 2005): Learn how to identify and avoid some of the pitfalls in learning to use generics.
- Introduction to generic types in JDK 5 (Brian Goetz, developerWorks, December 2004): Follow along with frequent developerWorks contributor and Java programming expert Brian Goetz, as he explains the motivation for adding generics to the Java language, details the syntax and semantics of generic types, and provides an introduction to using generics in your classes.
- JSR 14: Added generics to the Java programming language. The early specification was derived from GJ. Wildcards were added later.
- Java Generics and Collections: Offers a comprehensive treatment of generics.
- Effective Java: Item 1 contains further exploration of the benefits of static factory methods.
- Generics FAQ: Angelika Langer has created a comprehensive FAQ on generics.
- Java Concurrency in Practice: The how-to manual for developing concurrent programs in Java code, including constructing and composing thread-safe classes and programs, avoiding liveness hazards, managing performance, and testing concurrent applications.
|
https://www.ibm.com/developerworks/java/library/j-jtp04298/index.html
|
CC-MAIN-2019-22
|
refinedweb
| 2,486
| 57.5
|
Add item to java array
Here is the layout
index num 0 [10] 1 [20] 2 [30] 35 here) 3 [40] Move elements down 4 [50] 5 [60] 6 [70]
then my method is
public static void method(int[] num, int index, int addnum) { }
How can I add 35?
Tried this:
public static void method(int[] num, int index, int addnum) { int index = 10; for(int k = num.length k>3; k++) { Num[k]=num[k++] } Num[3] = 35;
source to share
Since this is something you have to accomplish yourself, I will only suggest his method, not the code:
If you set a number at a position
index
, you must overwrite the value that was there previously. So what you need to do is move each element one position at a time to the end of the array, starting at
index
:
num[x]
becomes
num[x+1]
, etc.
You will find out that you need to do it in reverse order, otherwise you will fill your array with a value in
num[index]
.
During this process, you will need to decide what to do with the last entry of the array (
num[num.length - 1]
):
- You can just overwrite it by dropping the value
- You can return it from your function
- You can throw an exception if it is nonzero.
- You can create a new array that will contain 1 entry more than the current array to keep all values
- and etc.
After that, you duplicate
num[index]
: this value is also present in
num[index+1]
, since you deleted it.
Now you can write the new value to the desired position without overriding the existing value.
EDIT
There are several errors in the code:
- You increase
k
, you need to decrease it (
k--
, not
k++
)
- You are changing again
k
in your loop body: it is updated twice in every loop
- If you start with
k = num.length
, you try to write in
num[num.length + 1]
, which is impossible
source to share
You need
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy all the elements and leave some space for pasting.
for (int i = 0; i < newArray.length - 1; i++) newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the blank space.
newArray[insertIndex] = numberToInsert;
Note that this is not possible in a method like this:
public static void method(int[] num, int index, int addnum) ^^^^
since you cannot change the length
num
.
You need to allocate a new array, which means you need to return a new array:
public static int[] method(int[] num, int index, int addnum) ^^^^^
and then call the method like this:
myArr = method(myArr, 3, 35);
source to share
Very roughly, you want to do something like this:
public static void(int[] num, int index, int addnum) { // initialize new array with size of current array plus room for new element int[] newArray = new int[num.length + 1]; // loop until we reach point of insertion of new element // copy the value from the same position in old array over to // same position in new array for(int i = 0; i < index; i++) { newArray[i] = num[i]; } i = i + 1; // move to position to insert new value newArray[i] = addnum; // insert the value // loop until you reach the length of the old array while(i < num.length) { newArray[i] = num[i-1]; } // finally copy last value over newArray[i + 1] = num[i]; }
source to share
Well, you can't if you don't have "extra space" in your array, and then you can shift all elements [starting from
index
] one element to the right and add 35 [
num
] to the appropriate place.
[what actually happens is that the last element is discarded].
However, the best solution would probably be to use ArrayList and use the method
myArrayList.add(index,element)
source to share
Since this closely resembles homework, you need to understand that you cannot dynamically increase the size of an array. So in your function:
public static void(int[] num, int index, int addnum) { int[] temp = new int[num.length *2]; for(int i = 0; i < index; i++) copy num[i] into temp[i] insert addnum into temp[index] fill temp with remaining num values }
This pseudocode above should get you started.
source to share
What you are looking for is a sort insert .
This is a cool job, so you need to figure out the correct code.
source to share
How about this?
public class test { public static void main(String[] arg) throws IOException { int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4 int[] temp_myarray=myarray;//take a temp array myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end for(int i=0;i<myarray.length;i++) { if(i==3) //becaues I want to add the value 4 in 4th place myarray[i]=4; else if(i>3) myarray[i]=temp_myarray[i-1]; else myarray[i]=temp_myarray[i]; } for(int i=0;i<myarray.length;i++) System.out.print(myarray[i]);//Print new array } static int[] addElement(int[] arr, int elem) { arr = Arrays.copyOf(arr, arr.length + 1); arr[arr.length - 1] = elem; return arr; } }
source to share
|
https://daily-blog.netlify.app/questions/1894652/index.html
|
CC-MAIN-2021-21
|
refinedweb
| 884
| 65.86
|
Posted 12 Jan 2011
Link to this post
Hi,
I want to create a unit test for the CheckUser method presented below... In that method we create a new instance of a class named LoginService. Inside my unit test, I know how to arrange my LoginService instance so that the mocking framework will replace the original call to ValidateUser with a simple "Return 1". That is not my problem.... My problem is that the parameterless constructor of the LoginService class used in CheckUser does a couple things I'd prefer not to do in my unit test like (as an example) connect to an Active Directory. Of course, if my unit test tries systematically to create a REAL LoginService then it will always fail as I have no active directory ready for my tests... Is there a way with JustMock to tell the mocking infrastructure that whenever my code tries to instanciate a class of type LoginService then I want a MOCK (or proxy) of LoginService to be created instead? On this mock I would of course have set arrange statements to have it behave like I want, let's say, Return 1 when ValidateUser is invoked on the Mock (or proxy)...
public class LegacyCode
{
public int CheckUser(string userName, string password)
{
----> LoginService _service = new LoginService();
[some code ommited here]
return _service.ValidateUser(userName, password);
}
}
I know some other mocking products out there support such a feature and I want to know if JustMock supports it also?
Thanks for your time.
Posted 13 Jan 2011
Link to this post
|
http://www.telerik.com/forums/mocking-an-object-instanciation
|
CC-MAIN-2017-22
|
refinedweb
| 259
| 58.42
|
What no-one tells you about getting started with BenchmarkDotNet
BenchmarkDotNet is a package for benchmarking (timing) .Net routines. It does correctly what you would do wrong if you were trying to time code yourself using
System.Diagnostics.Stopwatch and gaffer tape. Like, it does timed rounds of volume testing, warmups, and JIT gymnastics all to make sure that the timings you get back are accurate. Pretty cool.
The samples are wilfully naive; they make it sound like all you do is throw in this
[Benchmark] annotation but they don’t discuss what kind of project you’re supposed to use, what setup and config you need… so let me be honest with you:
It only works on optimized code (Release mode)
Set your Configuration to ‘Release’, or any other configuration which you have created which has ‘Optimize code’ turned on.
Without this, Benchmark will refuse to start.
It works best without the debugger attached
Ctrl+F5 starts your project without the debugger
You need a Program entry point which runs Benchmark
I had a Console project, for example, which kicks off like this:
using BenchmarkDotNet.Running; ... static void Main(string[] args) { var summary = BenchmarkRunner.Run<DynamicBenchmarks>(); Console.WriteLine("End"); Console.ReadLine(); }
…and that was my startup project, because all I was doing in it was benchmarking (there was no working program in the solution).
Instead, you could have multiple startup projects or just choose to run your Benchmark project ad-hoc using right-click, Debug, ‘Start new instance’.
You don’t have to do anything in your program with the returned result from
.Run<>()
The output goes to the bin folder in three formats
The results files go to:
{YourProject}\bin\Release\BenchmarkDotNet.Artifacts\results, and you will get, for each benchmarking project:
{Project}-report.csv- A comma-separated CSV
{Project}-report.html- Minimally-formatted HTML
{Project}-report-github.md- GitHub Flavoured Markdown
Don’t keep the report web page open in browser when running another attempt, or Benchmark will fail to write it and will throw a deathwailing exception.
Now you’re ready
Happy benchmarking! Hmu on twitter @SteGriff if you have more questions.
|
https://stegriff.co.uk/upblog/what-no-one-tells-you-about-getting-started-with-benchmarkdotnet/
|
CC-MAIN-2022-05
|
refinedweb
| 356
| 61.67
|
Jupyter to load, explore, and transform some data. After the data has been prepared, we will train a model.
From the project menu, click Workspaces.
Click Open Last Workspace or Open in the workspace created in Step 3. In
/mnt, you can see
data.csv. If not, go to Step 4 to download the dataset.
Use the New menu to create a Python notebook.
Starting in the first cell, enter these lines to import some packages. After each line, press
Shift+Enterto execute:
%matplotlib inline import pandas as pd import datetime
Next, read the file you downloaded into a pandas dataframe:
df = pd.read_csv('data.csv', skiprows=1, skipfooter=1, header=None, engine='python')
Rename the columns according to information on the column headers at and display the first five rows of the dataset using
df.head().
df.columns = ['HDF', 'date', 'half_hour_increment', 'CCGT', 'OIL', 'COAL', 'NUCLEAR', 'WIND', 'PS', 'NPSHYD', 'OCGT', 'OTHER', 'INTFR', 'INTIRL', 'INTNED', 'INTEW', 'BIOMASS', 'INTEM','INTEL', 'INTIFA2', 'INTNSL'] df.head()
We can see that this is a time series dataset. Each row is a successive half hour increment during the day that details the amount of energy generated by fuel type. Time is specified by the
dateand
half_hour_incrementcolumns.
Create a new column named
datetimethat represents the starting datetime of the measured increment. For example, a
20190930date and
2half hour increment means that the time period specified is September 19, 2019 from 12:30am to 12:59am.
df['datetime'] = pd.to_datetime(df['date'], format="%Y%m%d") df['datetime'] = df.apply(lambda x:x['datetime']+ datetime.timedelta(minutes=30*(int(x['half_hour_increment'])-1)), axis = 1)
Visualize the data to see how each fuel type is used during the day by plotting the data.
df.drop( ['HDF', 'date', 'half_hour_increment'], axis = 1 ).set_index('datetime').plot(figsize=(15,8))
The CCGT column, representing combined-cycle gas turbines, generates a lot of energy and is volatile.
We will concentrate on this column and try to predict the power generation from this fuel source.
Data scientists have access to many libraries and packages that help with model development. Some of the most common for Python are XGBoost, Keras and scikit-learn. These packages are already installed in the Domino Analytics Distribution (DAD) . However, there might be times when you want to experiment with a package that the next Jupyter cell, install Facebook Prophet and its dependencies, including PyStan (a slightly older version of Plotly, which is compatible with Prophet), and Cufflinks. PyStan requires 4 GB of RAM to be installed. Make sure your workspace is set to use a large enough hardware tier:
!pip install cufflinks==0.16.0 !sudo -H pip install -q --disable-pip-version-check "pystan==2.17.1.0" "plotly<4.0.0" !pip install -qqq --disable-pip-version-check fbprophet==0.6
For Facebook Prophet, the time series data needs to be in a DataFrame with 2 columns named
dsand
y:
df_for_prophet = df[['datetime', 'CCGT']].rename(columns = {'datetime':'ds', 'CCGT':'y'})
Split the dataset into train and test sets:
X = df_for_prophet.copy() y = df_for_prophet['y'] proportion_in_training = 0.8 split_index = int(proportion_in_training*len(y)) X_train, y_train = X.iloc[:split_index], y.iloc[:split_index] X_test, y_test = X.iloc[split_index:], y.iloc[split_index:]
Import Facebook Prophet and fit a model:
from fbprophet import Prophet m = Prophet() m.fit(X_train)
If you encounter an error when running this cell, you may need to downgrade your pandas version first. In that case you would run
!sudo pip install pandas==0.23.4
and then
from fbprophet import Prophet m = Prophet() m.fit(X_train)
After running the code above, you may encounter a warning about code deprecation. The warning can be ignored for the purposes of this walkthrough.
Make a DataFrame to hold prediction and predict future values of CCGT power generation:
future = m.make_future_dataframe(periods=int(len(y_test)/2), freq='H') forecast = m.predict(future) # forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail() #uncomment to inspect the DataFrame
Plot the fitted line with the training and test data:
import matplotlib.pyplot as plt plt.gcf() fig = m.plot(forecast) plt.plot(X_test['ds'].dt.to_pydatetime(), X_test['y'], 'r', linewidth = 1, linestyle = '--', label = 'real') plt.legend()
Rename the notebook to be
Forecast_Power_Generation
Save the notebook.
Trained models are meant to be used. There is no reason to re-train the
model each time you use the model. Export or serialize the model to a
file to load and reuse the model later. In Python, the
pickle module
implements protocols for serializing and de-serializing objects. In R,
you can commonly use the
serialize command to create RDS files.
Export the trained model as a pickle file for later use:
import pickle # m.stan_backend.logger = None #uncomment if using Python 3.6 and fbprophet==0.6 with open("model.pkl", "wb") as f: pickle.dump(m, f)
|
https://admin.dominodatalab.com/en/3.6/user_guide/288e42/step-5--develop-your-model/
|
CC-MAIN-2022-27
|
refinedweb
| 798
| 60.21
|
Documentation
Using Shotgun Pipeline Toolkit Actions
Developing Apps for Shotgun
Installation, Updates and Development
Configuration Options
Release Notes History
The Shotgun Engine makes it possible to integrate Shotgun Pipeline Toolkit Apps right into Shotgun. These will appear inside of Shotgun on the Action menu and can be attached to most project-centric entities. You can, for example, launch an application straight from a task, or launch apps that handle deliveries of Review Versions, Summaries or reports for Shots or Notes.
Documentation
The Shotgun engine manages apps that can be launched from within Shotgun. Sometimes we refer to these Toolkit Apps as Actions. They typically appear as items on menus inside of Shotgun.
Using Shotgun Pipeline Toolkit Actions for Shotgun!
As of Core v0.13, you can use all the multi apps with the Shotgun Engine. Technically speaking there is little difference between the Shotgun engine and other engines. There are, however, some subtle differences:
You will need to manually install PySide or PyQt into your standard python environment if you want to execute QT based apps in the Shotgun Engine.
It is possible in the Shotgun engine to make an action visible to a user depending on which permissions group they belong to. This is useful if you want example want to add a command to the Shotgun Action menu and you only want admins to see it.
A hello-world style Shotgun App, only visible to admins, would look something like this:
from tank.platform import Application class LaunchPublish(Application): def init_app(self): """ Register menu items with Shotgun """ params = { "title": "Hello, World!", "deny_permissions": ["Artist"], } self.engine.register_command("hello_world_cmd", self.do_stuff, params) def do_stuff(self, entity_type, entity_ids): # this message will be displayed to the user self.engine.log_info("Hello, World!")
Installation and Updates
Adding this Engine to the Shotgun Pipeline Toolkit
If you want to add this engine to Project XYZ, and an environment named asset, execute the following command:
> tank Project XYZ install_engine asset tk-shotgun.24.8.2
2018-May-10
Updated to require core 18.24 for QT5 compatibility.
v0.8.1
2018-Apr-13
Improvements to PySide2 Support.
v0.8.0
2017-April-13
Added support for Pyside2.
v0.7.0
2017-Nov-08
Updated for use with new core metrics
v0.6.0
2017-Sep-01
Allows on-the-fly context changes.
v0.5.5
2017-Jul-31
Adds back in Qt library path clearing, but only for KDE Linux.
v0.5.4
2017-Jul-26
Removes the clearing of Qt library paths introduced in v0.5.3.
Details:
This has been removed in favor of a safer and more-targeted implementation of the same in tk-multi-launchapp.
v0.5.3
2017-Jun-06
Fixes crashes on multiple Linux distributions when QT_PLUGINS_PATH is set.
v0.5.2
2016-Nov-08
Updated Shotgun icon
v0.5.1
Improved logic for indication of a UI present
Details:
This changes the meaning of the has_ui property so that it is consistent with other engines. Previously has_ui would return True as soon as a valid pyside/pyqt4 was detected. This is inconsistent with other engines, where has_ui indicates that an active UI is present and running. This pull request adjusts the shotgun engine so that has_ui only returns true when a QApplication is actually active in the system.
v0.5.0
Updated visual style to better match Maya.
Details: This change affects the visual appearance of all apps running in the engine, making their visual appearance much more consistent with the look and feel that you would get inside Maya. Please note that after this upgrade, app UIs will look slightly different.
v0.4.2
Updated PySide version handling to support very old versions!
v0.4.1
Updated engine icon.
v0.4.0
Added support for multi-select style UI apps.
v0.3.6
Updated PyQt compatibility
v0.3.5
Now uses the built in QT stylesheet introduced in Core v0.14.28.
v0.3.4
Updated QT Style Sheet to include a border around text input elements.
v0.3.3
Better Support for unicode.
v0.3.2
Fixed a bug where debug logging was supressed from the output despite the debug flag being set.
v0.3.1
Renames and support for the new name Sgtk.
v0.3.0.
v0.2.3
Fixed a bug which could cause apps raising Exceptions to be stuck in a loop.
v0.2.2
Minor adjustments to PyQt4
v0.2.1
Better QT App Support.
v0.1.4
Added icon.
v0.1.3
Updated manifest to require core v0.12.5
v0.1.2
Fixed formatting bugs related to html characters and certain exceptions being raised.
v0.1.1
Bug 19097: < and > Characters are now html escaped and no longer swallowed in the output.
v0.1.0
First Release with the new Tank API.
v0.0.1
Initial release to the App Store.
|
https://support.shotgunsoftware.com/hc/en-us/articles/219032918-Shotgun-Integration
|
CC-MAIN-2019-26
|
refinedweb
| 811
| 58.28
|
:
To make the changes described above double click on each entry to bring up the “Template Information” dialog seen below, or its counterpart the “Stencil Information” dialog. =).
If.
using System;
using System.Collections.Generic;
using System.Text;
using IVisio = Microsoft.Office.Interop.Visio;
public class TextUtilities
{.
A.
This post will be a little experiment to try out file attachments on the blog.
When customers send files to us, we often want to get a general understanding about the drawing contents. This is common in scenarios where customers are concerned about performance or file size. Visio drawings may be carrying some excess baggage along.
In addition to shapes on the page, a Visio document contains information about master shapes, styles, layers, fonts, colors, data and other items. These collections of information are used to accurately present the shapes on the page. However, they do not automatically get purged when shapes are deleted from the diagram.
Take the simple example of a flowchart. If you drag a Process shape onto the drawing page, Visio adds a copy of the Process master shape to the document and places an instance of this master shape on the page. If you delete the Process shape from the page, the master shape remains. Over time unused master shapes pile up. Normally this is no big deal, but some shapes contain large bitmaps or other complex information that will quickly increase file size.
Before you go out and delete every master shape from your document, keep in mind that master shapes are highly efficient when they are actually used in the drawing. If you took a drawing with many copies of the same shapes and then deleted the master, you would find the resulting document much larger and slower.
The attached DrawingAnalyzer.vsd document is a handy little tool written in VBA for counting the shapes in a drawing and determining whether there are unused master shapes. Also the tool counts shapes on the page with no master shape, and it keeps track of the level of grouping among shapes. More nested groups mean much slower performance.
To use the tool, open the file in Visio along with any other document you want to analyze. Make sure the document to be analyzed is in the active window. Then go to Tools > Macro > DrawingAnalyzer > ThisDocument > GetDrawingStats. Then open the VBA Editor (Alt+F11) and look in the Immediate Window (Ctrl+G) at the output. Here's a sample result:
Total Pages: 3 Total Shapes: 495
Top Level Shapes: 11 Group Shapes: 92 Max Nesting Depth: 3 Total Masters: 13 Unused Masters: 0 Shapes w/o Masters: 36 Total Patterns: 0 Unused Patterns: 0 Total Styles: 9
A top level shape is a shape directly on the page. All other shapes are found inside of groups. In this example, there are only 11 shapes spread across the 3 pages in the drawing. However, the total number of shapes is 495, meaning there are lots of shapes inside groups. There are even groups inside groups inside groups as evidenced by the maximum nesting depth of 3. This is not terribly efficient. All 13 master shapes in the document are used in the drawing, so that is good. 36 shapes have no master. If any of these shapes are similar, it would be more efficient to create a master shape for them.
The DrawingAnalyzer.vsd file is saved in Visio 2000/2002 format. Please post a comment if you have difficulties getting the file. As we said, this is a test..
|
http://blogs.msdn.com/b/visio/archive/2006/08.aspx?PostSortBy=MostViewed&PageIndex=1
|
CC-MAIN-2014-15
|
refinedweb
| 590
| 64.91
|
IRC log of tagmem on 2004-11-22
Timestamps are in UTC.
20:07:46 [RRSAgent]
RRSAgent has joined #tagmem
20:08:31 [Chris]
Meeting: tag f2f
20:08:37 [Chris]
Chair: Norm
20:08:42 [Chris]
Scribe: TimBL
20:08:50 [timbl_]
Norm: Next meeting is f2f next week. i can't come the second day (Tuesday)
20:08:50 [Chris]
Agenda:
20:09:24 [timbl_]
Paul: See email frpm email for details on meeting location (Stata center, >1 room)
20:09:36 [timbl_]
Today is the 22nd November.
20:09:41 [timbl_]
Zakim, who is on the call?
20:09:41 [Zakim]
On the phone I see TimBL, Chris, paulc, Roy, Noah, Norm
20:10:16 [timbl_]
Tim: Seocnd day oif f2f - regrets - conflict with W3C Steering Committee.
20:10:51 [timbl_]
Chis: Also I have a conflict with Interraction Domain meeting, on Tuesday 30th all day, but not clear which meeting I will go to
20:11:11 [Chris]
minutes:
20:11:20 [timbl_]
Norm: Anyone looked at the minues?
20:11:44 [Chris]
"TimBL: WebDAV works on bits, including a filename, no metadata is transferred"
20:11:46 [timbl_]
I didn't recognize "TimBL: WebDAV works on bits, including a filename, no metadata is transferred" from previous minutes
20:11:54 [Chris]
incorrectly attributed to TimBL
20:12:09 [timbl_]
s/timbl/____?/
20:12:40 [timbl_]
RESOLVED Minutes accepted with that ammendment
20:12:45 [timbl_]
____________
20:12:49 [timbl_]
AC Meeting Prep:
20:13:48 [timbl_]
Chris: Ian asked about TAG participation, DanC suggested none, Ian pushed back and so did Steve Bratt.
20:14:00 [Chris]
I'm happy to do a talk if required; mainly to point to existing PR and to ask for scope of next version
20:14:34 [Chris]
timbl: talk about how to prioritize things for next version
20:14:37 [timbl_]
Tim: Yes, it was felt we couldn't go to PR after all this time without comment.
20:14:53 [timbl_]
Paul: There were suggestions form IAn on what we could do.
20:15:31 [timbl_]
.... The excitemnt of reaching PR, te csope, of it, the priorities, summizing of last 3 years.
20:16:55 [paulc]
20:17:08 [timbl_]
tx
20:17:25 [timbl_]
Paul: We are onthe agenda and we should discuss what to say at hte face-face meeting.
20:19:00 [timbl_]
[discussion of format]
20:19:18 [timbl_]
Anyone who is at the meeting will be at the front.
20:19:21 [timbl_]
_______________________
20:19:29 [timbl_]
Technical Plenary meeting
20:19:48 [timbl_]
Section 1.2
20:20:10 [timbl_]
Stuart is stick handling here. Ongoing, Stuart to report at face-face.
20:21:08 [timbl_]
Noah: During the non-meeting last week I agreed to get schema folks to participate, David Orchard may contribute, David Ezell as chair may both be involved.
20:21:09 [paulc]
WS-Addressing liaison at TP:
20:21:25 [timbl_]
Norm: re face-face next week or TP?
20:21:41 [timbl_]
Noah: sorry, f2f next week.
20:21:58 [timbl_]
...ikn case we want to go further with Schema.
20:25:17 [timbl_]
Paul: Noah, be aware that before you joined, we used to use less AC meeting and mor TP time, and specifically for tech stuff including versioning.
20:25:47 [timbl_]
Noah: Sounds aas though there is serious work on versioning on both sides, and so liaison good.
20:26:05 [timbl_]
Paul: We are open to any laiision on this --- open to any form of response.
20:26:08 [timbl_]
___________________
20:26:15 [timbl_]
Item 1.3 TAG charter
20:26:28 [timbl_]
Norm: Reviews are open till Dec 3.
20:26:32 [timbl_]
Any comment?
20:26:47 [timbl_]
[no]
20:26:51 [timbl_]
_____________________
20:27:08 [timbl_]
Inserted agenda item 1.4
20:27:24 [timbl_]
Setting the face-face agenda.
20:27:41 [timbl_]
Paul: Can we please discuss this
20:27:56 [Norm]
Draft agenda:
20:27:59 [timbl_]
...; We are planning a video conf with Stuart in the morning only, so we will start promptly at 9am.
20:28:24 [timbl_]
lunch has been arranged, and whiteboard and video projectors, zakim bridge number, video conference number.
20:28:38 [timbl_]
Zakim will be ususal passcode, 4 lines all day.
20:28:57 [timbl_]
...Two outstanding options.
20:29:04 [timbl_]
... Dinner Monday night?
20:29:15 [timbl_]
... (ask for reservation?)
20:29:19 [Chris]
+1 for dinner
20:30:14 [timbl_]
... Lets. go with the flow and reserev on the fly prob fo 5-6 on Monday.
20:30:16 [Chris]
no advannce reservation
20:30:19 [timbl_]
RESOLVED.
20:30:42 [timbl_]
Paul: Will we need speakerphoine for Tuesday pm?
20:30:46 [timbl_]
Norm: Yes
20:31:16 [timbl_]
______________________
20:31:27 [timbl_]
DARFT Agenda
20:31:44 [timbl_]
20:32:15 [DanC-AIM]
DanC-AIM has joined #tagmem
20:32:39 [timbl_]
Norm: To construct slides, we will need 45-90 mins for AC meeting prep.
20:33:25 [timbl_]
Norm: [discusses darft agenda 0101.html]
20:33:55 [paulc]
F2F rooms:
20:34:20 [paulc]
F2F: Monday, November 28th, Stata Center, Room 262 [1] (video teleconference
20:34:47 [timbl_]
Norm: Clusetring of items has been sent out -- see 2.3 on this agenda
20:36:22 [Chris]
Do we plan to approve any draft findings?
20:36:49 [Chris]
Or find which ones are not moving and decide what do do about that (action, drop, etc)
20:37:50 [Chris]
Paul said, a bit of both I think
20:38:10 [timbl_]
Paul: I don't think we will approve any draft findings, only current ones really are
20:38:27 [timbl_]
... the one Chris is working on and teh one Norm did.
20:38:35 [timbl_]
... We haev only reposted one draft finding.
20:39:40 [paulc]
F2F is to attack both issues and findings to determine our future work.
20:40:12 [Chris]
q+ to talk about that
20:40:16 [paulc]
We will have to decide which issues are the most important post-Rec and also decide which findings we want to do more work on.
20:40:27 [Norm]
ack chris
20:40:27 [Zakim]
Chris, you wanted to talk about that
20:40:31 [timbl_]
Meeting room, by the way:
20:41:07 [timbl_]
Chris: They are confused because we are trying to say stg different. His points are good -- however those points were supposed to convey tsg diffrent.
20:41:33 [timbl_]
That is, fi you have a choice of representations, you can either select on the server or on teh client.
20:41:50 [timbl_]
We should say that they are correct and that we were talking about something different.
20:42:14 [timbl_]
That means that the finding means to be improved, as that is how we clarify things.
20:42:17 [timbl_]
Norm:
20:42:24 [Chris]
we were talking about the DIselect type content adaptation
20:42:37 [timbl_]
>... i agree tha ta ddressing eth finding would be good but we have to address the comment too.
20:42:52 [timbl_]
ACTION Chris repsond to Hakon by the face-face meeting
20:44:13 [timbl_]
ACTION Chris propose improved text for the document by the face-face.
20:44:14 [Chris]
a) talk with Hakon about what we meant
20:44:37 [Chris]
b) propose text for AWWW for agreement at f2f
20:45:35 [timbl_]
_______________
20:45:55 [timbl_]
Norm: Second comment is editorial - the glossay definition of Namespeace Dcouemnt is bogus
20:46:00 [Chris]
do we agree his example is valid
20:46:01 [Chris]
<foo xmlns="
mailto:patrick.stickler@nokia.com
">...</foo>
20:46:24 [Chris]
its a URI
20:46:27 [timbl_]
...This is a URI
20:46:38 [timbl_]
.... Is the rqeuiremnt aht it has to be a URI
20:46:39 [Chris]
so, it seems correct per spec. unusual, but not incorrect
20:46:45 [Chris]
20:47:57 [Noah]
FWIW: As a matter of definition from XML Namespaces 1.1 (
)
20:48:02 [timbl_]
Raoy: I think he means that if theer is an information resource then it is a namespaec dcoument.
20:48:04 [Noah]
[Definition: An XML namespace is identified by an IRI reference; element and attribute names may be placed in an XML namespace using the mechanisms described in this specification. ]
20:49:08 [timbl_]
[discussion]
20:49:12 [Chris]
wondering .... xmlns:="about:"
20:49:16 [timbl_]
Norm: NS spec doesn't precldue mailto here
20:50:27 [Chris]
response: example its a valid but stupid thing to do ...
20:51:10 [timbl_]
Noah: One could imagine being tempted to use a NS URI which is a mailbox if one had a system with one ns per mailbx , ....
20:51:37 [timbl_]
Norm: It is not good to do that, and we do say that it is godo to have a NS document. We say HHTP URIs are good for this.
20:51:44 [Noah]
Agreed.
20:53:10 [Chris]
xmln="tel:+33123456789"
20:54:11 [Noah]
...which gets you a fax machine that sends you the namespace document? :-)
20:54:35 [timbl_]
RESOLVED change workding as Roy recommended, vix that if the NS URI identifies and Information Resource, then that IR is the NS document.
20:54:55 [timbl_]
RESOLVED that disposes of that comment
20:55:10 [timbl_]
ACTION Norm respond to that.
20:55:16 [Chris]
per the spec, its valid if it gets you a 'this number is not in service' voice message .....
20:56:05 [timbl_]
Tim: NO, just because a phone number results in a message does NOT mean the phione number is an identifier of a messgae. it still identifies a PSTN end point.
20:56:10 [timbl_]
__________________________________
20:56:18 [Noah]
I thought you'd say that...
20:57:02 [timbl_]
Norm: Last up we have some push back from Steve Bratt COO on the use of "edition" as the XML and NS documents have used it in a different spirit.
20:57:14 [timbl_]
... In message 0090 he and Steve discuss this.
20:58:23 [timbl_]
Roy: Why not use "Edition"?
20:58:36 [timbl_]
Tim: "Edition" in W3C is a specific term.
20:59:09 [Chris]
Some specifications use 'Level' for different versions of a spec where level n+1
20:59:28 [Chris]
has more stuff than Level n
20:59:37 [timbl_]
Tim: We didn't want to do levels as it isn't l;evels of the technoolgy, only of the document.
21:00:13 [timbl_]
Chris: Will the next editiion be a superset?
21:00:32 [timbl_]
Norm: I said I don't mind being "first edition" as on fact we can change the title.
21:00:44 [timbl_]
.... Shjoudl we call it "edition 2004"?
21:01:00 [timbl_]
Tim: Does that avoid "Edition".
21:01:35 [Zakim]
-paulc
21:01:42 [timbl_]
Paul: I must leave, ay be late on Monday morning for the face-face.
21:02:39 [timbl_]
Norm: I assumed: "the Architectrue of the WWW" "The architecture of the WS" " "ASW"
21:02:52 [timbl_]
Tim: [surprised] you mean no content from this one in next one?
21:03:07 [timbl_]
Noah: But is we feel we could improve on this document's scope?
21:03:19 [timbl_]
... like XMLns going from 1.0 to 1.1
21:04:11 [timbl_]
Tim: Agreed .. but we can still rename it even if it has large overlap.
21:05:06 [timbl_]
Noah: But we really might eant to rev this document.... and rev it incompatibly ... we may have made a mistake, we may decide.
21:05:28 [timbl_]
Noah: If XMLNS 1.1 brought in IRIs etc.
21:05:53 [timbl_]
... Maybe this is "AWWW v1 edition1"
21:06:42 [timbl_]
Chris: Maybe we want to be able to revise some little bits without putting in the new document.
21:06:44 [Chris]
we might want to to an AWWW2 that references AWWW1, and also might want to do an AWWW second edition that lightly revs the original AWWW
21:07:04 [timbl_]
Tim: Is the proposal then to drop "First Edition"?
21:07:08 [timbl_]
Chris: OK
21:07:11 [Noah]
+1
21:07:13 [timbl_]
Roy: OK
21:07:18 [Norm]
+1
21:07:35 [timbl_]
Paul had said that he would concur for the rest of the meeting.
21:07:53 [timbl_]
Norm: He agrees anyway.
21:08:10 [timbl_]
RESOLVED: We drop the "First Edition" part of the title.
21:08:37 [timbl_]
_____________________________
21:09:04 [timbl_]
2.2 Versioning and Extensabbility
21:09:05 [timbl_]
Norm:
21:09:36 [timbl_]
We have an existing finding and a bunch of wor from David orchard, and DO and I have talked about updating the document with some of those ideas.
21:10:13 [timbl_]
... i agreed to produce a new draft by the end of tomorrow or early on Wednesdya, for sending on Thursdaay, forgetting atht Thursday was Thanksgiving, so that may not happen.
21:10:23 [timbl_]
... I don't know who will have read it.
21:10:31 [timbl_]
Chris: I will be able to read it.
21:10:50 [Chris]
Chris, Paul, Stuart might not be affected by US thanksgiving
21:10:55 [timbl_]
... and paul may be able to
21:11:34 [timbl_]
____________________________
21:11:37 [timbl_]
TAG ISSUES
21:12:00 [timbl_]
Norm: can we have an update please?
21:12:26 [timbl_]
Chris: re putMediaTypes, sorry I haven't sent in my work on that.
21:12:46 [Chris]
there has been some discussion on
as well
21:12:51 [timbl_]
Roy: To soem extentthe fidning on Metadata incorporates both directions and so may end up answering this issue
21:14:07 [timbl_]
Chris: The charset issue has attarcted some criticsm on public-www-tag and some IETF lists, saying we conflict with RFC____
21:15:06 [DanC]
DanC has joined #tagmem
21:15:14 [timbl_]
Re finding on message metadata ...
21:16:10 [Noah]
21:16:32 [Chris]
q+
21:16:43 [timbl_]
Authoritative Metadata
21:16:43 [timbl_]
TAG Finding 25 February 2004
21:17:57 [timbl_]
Noah: MediaType management 45 -- was that addressed last meeting?
21:18:23 [Norm]
s/Noah:/Norm:/ :-)
21:18:40 [timbl_]
Chris: It wasn't last meeting, but uit has come up in the community recently, specifically different XML document types such as XSLT and XForms
21:20:20 [timbl_]
ADJOURNED
21:20:29 [Zakim]
-Roy
21:20:38 [Zakim]
-TimBL
21:20:39 [Zakim]
-Norm
21:20:39 [Zakim]
-Chris
21:20:40 [Zakim]
-Noah
21:20:41 [Zakim]
TAG_Weekly()2:30PM has ended
21:20:42 [Zakim]
Attendees were TimBL, Chris, +1.732.962.aaaa, Roy, Norm, Noah, paulc
21:26:10 [DanC]
DanC has left #tagmem
23:11:49 [Chris]
Chris has left #tagmem
23:35:44 [Zakim]
Zakim has left #tagmem
|
http://www.w3.org/2004/11/22-tagmem-irc
|
CC-MAIN-2017-04
|
refinedweb
| 2,518
| 70.13
|
I would like to concatenate multiple string variables in BPMN inside 'Input Data Mapping' using expression, but so far it doesn't work. It always interprets the whole expression as string and does not apply any operators or methods. I have tried:
"bla" + variable
return ("bla" + variable);
getProcessVariable(variable)
Do I make something wrong, or is the Expression for Input Data Mappings buggy?
Is there any workaround? E.g. using a script task?
Hi Giorgi
As this is specific to how to define a BPMN process within jBPM (the BPMN2 engine we use), you will probably have better luck getting an answer by posting the question to the jBPM forum - can be found here: jBPM - Open Source Business Process Management - Process engine
Regards
Gary
Found it:
<bpmn2:from xsi:<![CDATA[You need to evaluate #{employee}.]]></bpmn2:from>
this is equivalent to
“You need to evaluate” + processInstance.getVariable(“employee”)
#{employee} was what I was looking for.
|
https://developer.jboss.org/thread/250327
|
CC-MAIN-2019-30
|
refinedweb
| 155
| 55.13
|
This is your resource to discuss support topics with your peers, and learn from each other.
09-07-2012 10:41 AM
I am instantiating MyNetwork class on a button click in my app class.
Hence constructor in MyNetwork class is called in which i am checking network availability.
Once a network is found available, a sendRequest() method is called in which a get request is initiated.
And the QNetworkAccessManager object emits finished(QNetworkReply *) signal is connected with a slot (requestFinished(QNetworkReply *reply)) of this MyNetwork class.
When the button in app.cpp file is clicked , an object of MyNetwork class is created and inside its constructor network availability check is working.
also connect() method returns true but it never enters slot (requestFinished(QNetworkReply *reply)) method where i am handling my response.
mynetwork.hpp
#ifndef MYNETWORK_HPP_ #define MYNETWORK_HPP_ #include<QObject> #include <QtNetwork/qnetworkaccessmanager.h> #include<QtNetwork/qnetworkreply.h> #include<QtNetwork/qnetworkrequest.h> #include<QtNetwork/qnetworksession.h> #include <QtNetwork/qnetworkconfiguration.h> #include <QtNetwork/qnetworkconfigmanager.h> #include<QtNetwork/qnetworkinterface.h> /*! * @brief Network Connection Implementation */ class MyNetwork:public QObject { Q_OBJECT; public : MyNetwork(); /*! * @brief Method to create and send request */ void sendRequest(); /*! * @brief Method to check if network is available */ bool isNetworkAvailable(); private slots: void requestFinished(QNetworkReply *reply); }; #endif /* MYNETWORK_HPP_ */
mynetwork.cpp
#include<mynetwork.hpp> #include<QtNetwork/qnetworkconfigmanager.h> #include<QtNetwork/qnetworkconfiguration.h> #include<QList> QNetworkAccessManager *mNetworkMgr; MyNetwork::MyNetwork() { if (isNetworkAvailable()) { sendRequest(); } } void MyNetwork::sendRequest() { mNetworkMgr = new QNetworkAccessManager(this); QNetworkReply *reply = mNetworkMgr->get( QNetworkRequest( QUrl( ") {
if (reply) { if (reply->error() == QNetworkReply::NoError) { qDebug() << "No Error"; } else { int httpStatus = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute).toInt(); qDebug() << "Error and the code is " << httpStatus; } reply->deleteLater(); } else { qDebug() << "Reply comes out to be null"; } } bool MyNetwork::isNetworkAvailable() { QNetworkConfigurationManager netMgr; QList<QNetworkConfiguration> mNetList = netMgr.allConfigurations( QNetworkConfiguration::Active); if (mNetList.count() > 0) { if (netMgr.isOnline()) { return true; } else { return false; } } else { return false; } }
Solved! Go to Solution.
09-10-2012 10:32 AM
This superficially looks about right to me.
A few comments:
1. Do you get a reply object?
2. There is a window between getting the reply object and the connect where a background thread could finish before the connect is made. Try moving the connect to before the get. (I haven't tried this but I expect background threads are involved)
3. The global variable mNetworkMgr is misleading. Looks like you create an object of this type for each MyNetwork created and never release it. Better is to either make the a true member of MyNetwork; better yet is to just have it a variable in the sendRequest routine and set up appropriate connects to ensure it is eventually deleted. (Don't delete it too early)
Stuart
09-11-2012 07:23 AM - edited 09-11-2012 07:24 AM
Thanks for your reply.
1. Yes I am receiving the reply object but that the slot function is never invoked.
2. Yes connect() method was moved before the request (Get) invocation.
3. Well control never reaches the slot at all. How would the delete statement get executed earlier as in the slot the very first statement is qDebug() that's not printing at all.
I made the amendments you asked for but no change in the result. The slot is not being invoked.
One more thing that I am not running my project on simulator.
I am receiving this output :
Connection is success : ? : true
Reply from server is QNetworkReplyImpl(0x87b36b0)
09-11-2012 12:17 PM
Can you try to move
bool resFromServer = connect(mNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*))); qDebug() << "Connection is success : ? : " << resFromServer;
before
QNetworkReply *reply = mNetworkMgr->get( QNetworkRequest( QUrl( "
umentation/device_platform/networking/model.xml")));umentation/device_platform/networking/model.xml")));
You might have a network faster than the device/simulator your app was running on, e.g.: signal might have emitted before the slot got connected.
09-12-2012 01:10 AM
Yes I did. But no change in result.
09-12-2012 11:57 AM
hmm. I just did quick test for the you network code.
I moved
bool resFromServer = connect(mNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*))); to be before QNetworkReply *reply = mNetworkMgr->get( QNetworkRequest( QUrl( "
umentation/device_platform/networking/model.xml")));umentation/device_platform/networking/model.xml")));
in my test.
As I mentioned that we need to connect the signal before we trigger sending network request.
I got "No Error" in the log which seemed have indicated that the signal/slot was triggerred properly in my case.
Question for u:
how did u create your "MyNetwork" object?
is the object still alive when the network request signal is triggerred?
maybe the code segment for creating/destorying your "MyNetwork" object will be helpful
09-13-2012 02:03 AM
Yes you are right. The error was in instantiation of the MyNetwork object. That was a silly mistake, else code was correct.
Thanks linkBB10Dev for your reply.
11-22-2012 05:06 AM
Hi ,
Please tell me what was mistake . i want know because i am using your code but it is not working in my project
please help me
11-26-2012 02:23 AM
Hi Farhan,
I was creating MyNetwok object as
MyNetwork *object;
and due to this before background thread provide me response from server, the object was destroyed.
Correction :
MyNetwork *object=new MyNetwork();
Now this object will remain through out the app life.
This was error in my case.
02-27-2013 10:36 AM
Hello,
I have a question about your function isNetworkAvailable().
I'm using it to check if the network is available and it works great.
However, there is this one case when it doesn't give me the right answser.
Indeed, if, at first, I have network, isNetworkAvailable() will return true.
Then, if I switch off the Wifi, isNetworkAvailable() will return false which is OK.
But then, if I switch on the Wifi again, isNetworkAvailable() still returns false which is non OK this time.
Have you seen this problem ?
Thank you!
|
http://supportforums.blackberry.com/t5/Native-Development/Error-while-establishing-a-Http-connection-Once-request-finished/m-p/1902655
|
CC-MAIN-2015-48
|
refinedweb
| 986
| 50.02
|
User Name:
Published: 25 Aug 2008
By: Dino Esposito
Dino Esposito talks about idiomatic design and some potential issues with the List type.
Let me start from a blog post that Krzysztof Cwalina—a prominent member of the .NET Framework team—made some time ago. You find it at. In the post, Krzysztof doesn’t recommend using List<T> in the signature of public members of custom classes. I’ll get to the details of the post in a moment. Before going any further, though, I want to introduce idiomatic design.
When it comes to designing software, general principles of object-oriented design as well as basic and fundamental principles such as low coupling and high cohesion are always valid and should always be taken into due consideration.
However, when you step inside the design, at some point you meet the technology. When this happens, you may need to review the way you apply principles and aim at them in the context of the specific technology or platform you’re using. This is called idiomatic design. Simply put, it is design when you conceptually envision a class and its attribute; it is idiomatic design when you know you will actually be using the .NET Framework (or any other framework) and adapt your decisions to the context.
As far as the .NET Framework is concerned, a set of idiomatic design rules exists under the name of Framework Design Guidelines. You can access them online from the following URL:. The Framework Design Guidelines also exists as a book written by Microsoft’s Krzysztof Cwalina and Brad Abrams.
The advice of not using List<T> in a public API is definitely an example of an idiomatic design rule. Let’s briefly recap why List<T> is not recommended in a public signature and from there I’ll take on the more general theme of code reusability.
According to Cwalina, two are the reasons for not using List<T> publicly. One is that List<T> is a rather bloated type with many members not relevant in many scenarios. The other reason is that the class is unsealed, but not specifically designed to be extended. Let’s have a look at the class signature:
The class is designed to be a strongly typed list of objects that can be accessed by index. The class also provides methods to search, sort, and manipulate lists. If you look at the methods on the implemented interfaces, you obtain the following list of members, subdivided by interface:
In addition, the class List<T> counts a similar set of methods but non-generic. If you look at the actual list of members, you find many more methods: BinarySearch, Reverse, Sort, a variety of Find methods, and a bunch of predicate-based methods including ForEach and TrueForAll.
In a nutshell, List<T> is not merely a class that implements the IList<T> interface. It’s, instead, quite a large object. Hence, it is preferable that you use simpler and thinner lists in your public APIs.
Behind the aforementioned idiomatic design rule, a couple of general principles of (object-oriented) software design can be recognized. One is the Single Responsibility Principle (SRP).
SRP states that each class should have only one reason to change. In other words, a class should expose a cohesive and anyway limited set of functionality. Bloated classes with methods that range from search to I/O, from manipulation to index-based access are hard to classify as SRP-safe classes.
Breaking the SRP principle is not per se a bad statement and doesn’t affect in any way the working of the code based on such a class. It is simply a sign that confirms you have a lot of room left for improving the design of the class.
Using the List<T> class internally is absolutely fine and, in fact, the class is really helpful and performs optimally. When it comes to interfacing other layers and classes, though, a bit of attention is required. Full respect of the SRP principle ensures maintainability and readability of the code.
Let’s move to the second motivation for not using List<T> in public signatures—the class is further inheritable, but it is not designed for being extended.
In .NET coding, leaving a class unsealed (which is the default setting indeed) is, well, a responsibility you take on your own. If you leave a class unsealed around your code you expose yourself to the possibility that others will inherit from that. What if at some point you have to trace back and seal a previously unsealed class that was inherited? In software development, changes of requirements are the rule, not the exception. For this reason, it would be preferable to seal as many classes as possible unless a strong reason exists to further inherit.
Using unsealed classes in public signatures may expose your code to a subtle issue that is well summarized by the Liskov Substitution Principle (LSP).
When a new class is derived from an existing one, the derived class can be used in any place where the parent class is accepted. This is just polymorphism, isn’t it? Well, the LSP principle just recalls that polymorphism is a great feature, but it doesn’t come for free by simply inheriting a class. The principle says:
Subclasses should be substitutable for their base classes.
Apparently, you get this free of charge from just using an object-oriented language. It is not always as simple as you may think, though.
If the base class has virtual methods, and through virtual methods you make access to internal, hidden members, what would happen to overrides? Are these methods guaranteed to verify the same preconditions of overridden methods? If a virtual method accesses a private member, there’s no possibility for an override to fulfill the same precondition—the override can’t just access the private member which would make it unfit as an override. As a result, the override may alter the expected behavior of the base class thus potentially breaking polymorphism.
Now does this mean that the List<T> is not LSP-safe? I wouldn’t say so, but for sure the class is not designed with inheritance in mind. From a coding perspective, using List<T> doesn’t enable a great deal of polymorphism, but doesn’t break (not even potentially) any code if used. The two points made by Cwalina are, of course, tightly related: the class is per se bloated and there’s no clear polymorphism benefit in using List<T> in public APIs. In other words, you can; but you shouldn’t.
Let’s see why List<T> is still LSP-safe, but not really beneficial for further inheritance.
The first key point is that the class has no virtual methods. And virtual methods are just the means through which inheritance delivers benefits—by overriding methods you can alter the behavior of the class and bend it to your needs. Having no virtual methods in derivable class reduces the risk of breaking LSP, but at the cost of not making inheritance attractive and beneficial. List<T> has no protected members either. This means that when you derive a class from it all that you can do is adding new methods. New methods, however, have no privileged access to internal members, because when not public they are private. You can’t really specialize the class behavior; you can only extend it in way that resembles composition rather than inheritance.
When you design a class for inheritance, you make available some virtual methods, either public or protected. These methods should be LSP-safe meaning that they only access protected or public members of the class and never private members. Access to private members can’t be replicated by overrides which will make base and derived classes not semantically equivalent from the perspective of a caller. This is key point to keep in mind when considering inheritance in an object-oriented world.
In his aforementioned post and book, Cwalina recommends that you avoid List<T> in public APIs. What is the alternative? You should use a simpler list-based type such as Collection<T> or ReadOnlyCollection<T> for outputs and class properties. You should go for IEnumerable<T>, ICollection<T>, IList<T> for input parameters.
Are these guidelines valid in general and beyond the specific case of the List<T> class? The SRP principle comes handy again. Each class you design should take care of the smallest possible set of responsibilities. If you need to pass in a list of objects, then you should start with IEnumerable and increase the amount of responsibilities only when necessary.
When you return an object from a method, you should return the simplest possible object that works in the scenario. In the unfortunate case that no predefined classes match your needs, you should consider creating a custom class that implements a given set of interfaces. You should try to program to interfaces as much as possible. After all, “Program to an interface, not to an implementation” is the first principle of object-oriented design.
This author has published 53 articles on DotNetSlackers. View other articles or the complete profile here.
In case readers need an easier refactoring then abandoning the List<T> utterly (and therefore having to address all the code that might be using the described bloated violations of single responsibility in List<T> by downstream consumers - although pain is perhaps unavoidable due to the nature of generics without constraints applied) I believe most would find it an acceptable compromise to do the following: 1) Refactor by creating a new collection class which will replace as needed your use of List<T> in your public API2) inherit from List<T> on each new class (which is driven by domain specifics in name and purpose) where necessary (where you cannot use an as described 'better' set or indeed just implement an interface yourself such as ICollection<T>)3) Make your new exposed type NON-GENERIC as a rule (in general this is good advice as it's very hard to test generic types in exposed APIs. On one extreme a case could be made that you would need to test with a wide variety of different types. Only the most 'generic' (sorry) code with wide application (such as Linq and IEnumerable<T>) should leverage generics.Thoughts?4) Ensure they are sealed if indeed using List<T> as base classFor example:public sealed class CustomerSet : List<Customer> then:public interface ISalesRepresentative {........CustomerSet KeyCustomers {get; }....}5) Even better? Create an abstract base for all your List<T> occurances as such (as this addresses co-variance)
public abstract class DomainSet<TSet, TContained> : List<TContained>where TSet : DomainSet<TSet, TContained>, IList<TContained> {}
public sealed class CustomerDefaults : DomainSet<CustomerDefaults, Customer> {}
public sealed class CustomerTargets : DomainSet<CustomerTargets, Customer> {}
public class Customer {
private static int _counter;
public Customer() {
Id = Interlocked.Increment(ref _counter);
}
public int Id { get; private set; }
public class startup {
private static IEnumerable<Customer> Get100Customers {get { return Enumerable.Repeat(1, 100).Select(i => new Customer()); }
public static void Main(string[] args) {
var defaults = new CustomerDefaults();
defaults.AddRange(Get100Customers);
var targets = new CustomerTargets();
targets.AddRange(Get100Customers);
var allCustomers =
defaults.Join(targets,
c => c.Id,
cInner => cInner.Id - 100,
(c, cInner) => new[] {c, cInner}).SelectMany(customers => customers).
ToList();
Debug.Assert(allCustomers.Count() == 200);}
Kind Regards,Damon Wilder Carr
Reply
|
Permanent
link
Please login to rate or to leave a comment.
Link to us
All material is copyrighted by its respective authors. Site design and layout
is copyrighted by DotNetSlackers.
Advertising Software by Ban Man Pro
|
http://dotnetslackers.com/articles/net/List-and-Object-oriented-Design-Principles.aspx
|
crawl-003
|
refinedweb
| 1,934
| 53.81
|
A model backed by a QgsVectorLayerCache which is able to provide feature/attribute information to a QAbstractItemView. More...
#include <qgsattributetablemodel.h>.
Constructor.
Launched when attribute value has been changed.
Returns the number of columns.
Returns data on the given index.
Returns the context in which this table is shown.
Will be forwarded to any editor widget created when editing data on this model.
Execute an action.
Execute a QgsMapLayerAction.
Return the feature attributes at given model index.
Launched when a feature has been added.
Launched when a feature has been deleted.
get column from field index
get field index from column
Returns item flags for the index.
Returns header data.
Maps feature id to table row.
Returns the layer this model uses as backend.
Retrieved from the layer cache.
Returns the layer cache this model uses as backend.
Launched when layer has been deleted.
Gets mFieldCount, mAttributes and mValueMaps.
Loads the layer into the model Preferably to be called, before basing any other models on this model.
Model has been changed.
Caches the entire data for one column.
This should be called prior to sorting, so the data does not have to be fetched for every single comparison. Specify -1 as column to invalidate the cache
Reloads the model data between indices.
Remove rows.
Resets the model.
Returns the number of rows.
Maps row to feature id.
Updates data on given index.
Sets the context in which this table is shown.
Will be forwarded to any editor widget created when editing data on this model.
Set a request that will be used to fill this attribute table model.
In contrast to a filter, the request will constrain the data shown without the possibility to dynamically adjust it.
Swaps two rows.
|
http://www.qgis.org/api/classQgsAttributeTableModel.html
|
CC-MAIN-2014-42
|
refinedweb
| 290
| 62.64
|
33 parameters for a function?! Seriously!?
#21 Members - Reputation: 1685
Posted 09 January 2009 - 06:00 PM
A few cases we have some strange stuff because we init classes only using the
classA foo = {...}
syntax instead of
classA foo(...);
and so there are wrapper macros that EMULATE the constructor format and thus can have tonnes of parameters.
#22 Members - Reputation: 925
Posted 09 January 2009 - 08:20 PM
Quote:
o_O
For purely educational purposes, why would you do such a thing?
#23 Members - Reputation: 174
Posted 09 January 2009 - 08:56 PM
Quote:
And even then, the more recent standards of FORTRAN (e.g. 2003) contain support for object-oriented programming, so even the good old grand daddy of programming languages should be able to handle passing a struct or an object through the parameter list :-)
#24 Members - Reputation: 143
Posted 09 January 2009 - 09:37 PM
#25 Members - Reputation: 618
Posted 09 January 2009 - 09:38 PM
Quote:On the contrary, he must be quite good at typing, you noticed 100 lines were removed from the declaration right :)
#26 Members - Reputation: 1583
Posted 09 January 2009 - 10:38 PM
#27 Crossbones+ - Reputation: 2805
Posted 09 January 2009 - 10:51 PM
Quote:Yes. It is quite common that people who take decisions have no flipping clue what they are talking about. However, they are still the ones who decide.
This is where corporate branding and FUD have their base. It is what influencer marketing aims at too. Big companies have been successful selling inferior goods and services with that strategy for decades.
In other words, executives will rather spend 250,000 for something that works less efficient and has higher maintenance cost than something they could get for free or nearly so based on the fact that some guy they play golf with says it's what people use, or because it has a big name.
It looks like your boss has a great career as executive ahead. :-)
#28 Members - Reputation: 313
Posted 10 January 2009 - 02:10 AM
Quote:
There is no need for functions like that. Really.
#29 Members - Reputation: 618
Posted 10 January 2009 - 03:23 AM
Quote:It's also common for technical people to think their bosses are stupid because they are less technically able than they are. This is logically ridiculous. Your boss has to manage people, organise schedules and budgets, keep clients happy etc, which all take time and require knowledge and skills. Only a very special person can do all that and still know as much as his development team. In fact even if he is a coder by trade, a good boss would be hiring coders who were better than him.
Expecting your boss to be at the same level as you on your specialty is unreasonable. Programmers need to learn not to feel superior to people who aren't great programmers, and how to communicate with less technical people.
#30 Members - Reputation: 948
Posted 10 January 2009 - 08:50 AM
#31 Members - Reputation: 304
Posted 10 January 2009 - 11:15 AM
#32 Members - Reputation: 100
Posted 10 January 2009 - 01:32 PM
Quote:
I agree. Unless the function is called very frequently (in which case maintaining a struct with configuration information would be far more efficient), creating another layer of abstraction seems rather pointless.
Is this,
params.a = 1.0;
...
params.z = 26.0;
Init(¶ms);
really any better than
Init(1.0,
...,
26.0);
?
I submit that it is not. The only advantage of the first is that it is clear which argument corresponds to which parameter. It's not immediately obvious from the latter, although that could be rectified with comments.
Init(1.0, // a
...
26.0); // z
#33 GDNet+ - Reputation: 1958
Posted 10 January 2009 - 02:27 PM
Quote:Or, indeed, if a lot of parameters have default values - but this is better resolved with named/optional parameters.
#34 Members - Reputation: 272
Posted 10 January 2009 - 03:03 PM
Quote:
When you make a function which takes 33 parameters, you (I'm taking the role of the processor here, bear with me) have to fill in each and every one of those variables on to the stack when the function is called. This comes at a cost, especially if the function is called a lot. By passing a reference/pointer instead of 33 parameters, you'll only need 4 bytes on the stack, as opposed to 132.
#35 Members - Reputation: 744
Posted 10 January 2009 - 03:28 PM
Quote:
Right, it probably wouldn't help matters to just dump all the parameters in one struct. What you'd want to do is group similar parameters into different structs to make the mess of 33 parameters conceptually simpler to someone reading the code. It'd make it faster to locate the parameter of interest.
And, looking at the bit that was posted, I'd probably have to be tearing apart an object to pass it to that function.
namespace Application {
struct Application {
ApplicationType type;
std::string version;
};
}
namespace Asset {
struct Video {
int width;
int height;
float duration;
std::string frameRate;
std::string dataRate;
Asset::VideoBitRateMode videoBitRateMode;
std::string codec;
};
struct Audio {
std::string dataRate;
Asset::AudioBitRateMode audioBitRateMode;
std::string codec;
};
struct Asset {
std::string shortName;
std::string description;
std::string authorName;
std::string fileName;
std::string fileType;
Video video;
Audio audio;
};
struct Paths {
std::string asset;
std::string shortPreview;
std::string mainThumbnail;
std::string summaryThumbnails;
};
}
void myUploadAsset(
const Application::Application& application,
const Asset::Paths& pathTo,
const Asset::Asset& asset,
const Asset::Asset& source,
const std::string& presetXML,
const std::string& filter,
bool (*progressCallback)(float)
) {
uploadAsset(
applicaiton.type, application.version,
pathTo.asset, pathTo.shortPreview,
pathTo.mainThumbnail, pathTo.summaryThumbnails,
asset.shortName, asset.description,
asset.video.frameRate, asset.video.width, asset.video.height,
asset.audio.dateRate, asset.video.dataRate,
asset.audio.bitRateMode, asset.video.bitRateMode,
asset.video.duration,
presetXML,
asset.fileType,
filter,
asset.audio.codec, asset.video.codec,
asset.authorName,
source.fileName, source.fileType,
source.audio.codec, source.video.codec,
source.video.frameRate, source.video.width, source.video.height,
source.audio.dataRate, source.video.dataRate,
source.audio.bitRateMode, source.video.bitRateMode,
progressCallback
);
}
#36 Members - Reputation: 100
Posted 10 January 2009 - 10:44 PM
Quote:
I mentioned that it doesn't matter for functions which are called infrequently (such as initialization functions, which may be called once or only a few times per program session.) In that case, pushing things on the stack is no big deal. If you had to set up all the parameters in a struct each time, you wouldn't save anything, because you would still be making just as many memory writes as pushing everything on the stack.
#37 Members - Reputation: 1144
Posted 11 January 2009 - 06:49 AM
Quote:
its actually fairy common to pass tens or hundreds of arguments to function.... that's called OOP and arguments are called "members" or "fields" :P It also has nicer syntax than just listing them in the (,,,,) list.
(joking of course.)
More seriously though. I never seen a function taking many arguments, which are so unrelated as that you couldn't group them into classes. Example, a function that takes 2 3-d vectors... of course you should make 3d vector a class.
[Edited by - Dmytry on January 11, 2009 1:49:40 PM]
#38 Crossbones+ - Reputation: 6807
Posted 11 January 2009 - 08:36 AM
Quote:I don't get why you had to use 81 parameters. Seems like there would be a cleaner, less error prone solution.
Quote:I beg to differ. The difference is readability. Intellisense makes it really easy to build a struct like that, because each time you access a member with '.', you get a nice, readable list of members. If you're trying to call the function with 34 arguments, when you write '(' intellisense is going to give you a boat load of parameters, many of which look like this: const std::string& parameterName. The const std::string& kills readability. And it's easy to forget which parameter your on, so one mistake can cause a huge ripple effect. You also suggest using comments to clarify the 34 parameters. Not only does that take time, but it requires the programmer to know exactly what all 34 parameters are and (here's the hard part) exactly what order they're in. With a struct, you can fill them in whatever order you like, and the member names are named reasonably so you shouldn't need any comments. Hence increasing productivity and readability.
Quote:I actually really like that solution. Cramming all 34 parameters into an object does seem messy. Splitting them up into coherent objects like that makes a lot of sense. I'll suggest something like that.
Quote:I hope you weren't targeting me in that. My boss is a programmer/software engineer and mostly works in Java. The reason the function grew to 34 parameters is because it started out with about 5 parameters (we hardcoded the rest of the values into the function while testing), but when we removed those hardcoded testing values, we had to suddenly expand the function to take all the values we needed. It just hadn't been planned out (not that that's a good excuse, we should have planned it out long ago). Anyway, that's how it evolved from a 5ish parameter function into a 34 parameter beast.
#39 Members - Reputation: 486
Posted 11 January 2009 - 08:38 AM
#40 Members - Reputation: 92
Posted 11 January 2009 - 11:50 AM
Quote:
Thank you sir , never laughed so hard in my life
seriously
|
http://www.gamedev.net/topic/520322-33-parameters-for-a-function-seriously/page-2
|
CC-MAIN-2013-48
|
refinedweb
| 1,599
| 51.28
|
Is it true that we cannot use Composite Primary key when we opt for EJB 1.1 & Weblogic 5.1 as the development platform. If it is possible would anyone help in providing some direction to achieve my goal in developing a system, my database system would be on SQL.
Murali Thantry
Discussions
EJB programming & troubleshooting: Composite Primary Key in EJB 1.1 & Weblogic 5.1
Composite Primary Key in EJB 1.1 & Weblogic 5.1 (1 messages)
- Posted by: Murali Thantry
- Posted on: March 26 2001 05:54 EST
Threaded Messages (1)
- Composite Primary Key in EJB 1.1 & Weblogic 5.1 by Somil Nanda on March 26 2001 17:09 EST
Composite Primary Key in EJB 1.1 & Weblogic 5.1[ Go to top ]
It is possible to have a composite key in weblogic 5.1
- Posted by: Somil Nanda
- Posted on: March 26 2001 17:09 EST
- in response to Murali Thantry
here is an example
package com.whatever.whatever
import java.io.Serializable;
public class CompositePK implements java.io.Serializable {
public int firstID;
public int secondID;
public CompositePK(){}
public CompositePK( int firstID, int secondID ){
this.firstID = firstID;
this.secondID = secondID;
}
public boolean equals(Object obj){
if (obj == null || !(obj instanceof CompositePK))
return false;
else if ( (((CompositePK)obj).firstID == firstID) &&
(((CompositePK)obj).secondID == secondID) )
return true;
else
return false;
}
public int hashCode(){
return toString().hashCode();
}
public String toString(){
return firstID+""+secondID;
}
}
|
http://www.theserverside.com/discussions/thread.tss?thread_id=5269
|
CC-MAIN-2014-15
|
refinedweb
| 234
| 53.98
|
If you are reading the book, you can get the notebooks by cloning this repository on GitHub and running the notebooks on your computer. Or you can read (but not run) the notebooks on GitHub:
Chapter 7 Notebook (Chapter 7 Solutions)
Chapter 8 Notebook (Chapter 8 Solutions)
Chapter 9 Notebook (Chapter 9 Solutions)
I'll post the next batch soon; in the meantime, here are some of the examples from Chapter 7, demonstrating the surprising difficulty of making an effective scatter plot, especially with large datasets (in this example, I use data from the Behavioral Risk Factor Surveillance System, which includes data from more than 300,000 respondents).
In [2]:
df = brfss.ReadBrfss(nrows=None)
The following function selects a random subset of a
DataFrame.
In [3]:
def SampleRows(df, nrows, replace=False): indices = np.random.choice(df.index, nrows, replace=replace) sample = df.loc[indices] return sample
I'll extract the height in cm and the weight in kg of the respondents in the sample.
In [4]:
sample = SampleRows(df, 5000) heights, weights = sample.htm3, sample.wtkg2
Here's a simple scatter plot with
alpha=1, so each data point is fully saturated.
In [5]:
thinkplot.Scatter(heights, weights, alpha=1) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False)
/>
The data fall in obvious columns because they were rounded off. We can reduce this visual artifact by adding some random noice to the data.
NOTE: The version of
NOTE: The version of
Jitterin the book uses noise with a uniform distribution. Here I am using a normal distribution. The normal distribution does a better job of blurring artifacts, but the uniform distribution might be more true to the data.
In [6]:
def Jitter(values, jitter=0.5): n = len(values) return np.random.normal(0, jitter, n) + values
Heights were probably rounded off to the nearest inch, which is 2.8 cm, so I'll add random values from -1.4 to 1.4.
In [7]:
heights = Jitter(heights, 1.4) weights = Jitter(weights, 0.5)
And here's what the jittered data look like.
In [8]:
thinkplot.Scatter(heights, weights, alpha=1.0) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False)
/>
The columns are gone, but now we have a different problem: saturation. Where there are many overlapping points, the plot is not as dark as it should be, which means that the outliers are darker than they should be, which gives the impression that the data are more scattered than they actually are.
This is a surprisingly common problem, even in papers published in peer-reviewed journals.
We can usually solve the saturation problem by adjusting
This is a surprisingly common problem, even in papers published in peer-reviewed journals.
We can usually solve the saturation problem by adjusting
alphaand the size of the markers,
s.
In [9]:
thinkplot.Scatter(heights, weights, alpha=0.1, s=10) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False)
/>
That's better. This version of the figure shows the location and shape of the distribution most accurately. There are still some apparent columns and rows where, most likely, people reported their height and weight using rounded values. If that effect is important, this figure makes it apparent; if it is not important, we could use more aggressive jittering to minimize it.
An alternative to a scatter plot is something like a
HexBinplot, which breaks the plane into bins, counts the number of respondents in each bin, and colors each bin in proportion to its count.
In [10]:
thinkplot.HexBin(heights, weights) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False)
/>
In this case the binned plot does a pretty good job of showing the location and shape of the distribution. It obscures the row and column effects, which may or may not be a good thing.
Exercise: So far we have been working with a subset of only 5000 respondents. When we include the entire dataset, making an effective scatterplot can be tricky. As an exercise, experiment with
Scatterand
HexBinto make a plot that represents the entire dataset well.
In [11]:
# Solution # With smaller markers, I needed more aggressive jittering to # blur the measurement artifacts # With this dataset, using all of the rows might be more trouble # than it's worth. Visualizing a subset of the data might be # more practical and more effective. heights = Jitter(df.htm3, 2.8) weights = Jitter(df.wtkg2, 1.0) thinkplot.Scatter(heights, weights, alpha=0.01, s=2) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False)
/>
In [12]:
cleaned = df.dropna(subset=['htm3', 'wtkg2'])
Then I'll divide the dataset into groups by height.
In [13]:
bins = np.arange(135, 210, 5) indices = np.digitize(cleaned.htm3, bins) groups = cleaned.groupby(indices)
Here are the number of respondents in each group:
In [14]:
for i, group in groups: print(i, len(group))
0 305 1 228 2 477 3 2162 4 18759 5 45761 6 70610 7 72138 8 61725 9 49938 10 43555 11 20077 12 7784 13 1777 14 405 15 131
Now we can compute the CDF of weight within each group.
In [15]:
mean_heights = [group.htm3.mean() for i, group in groups] cdfs = [thinkstats2.Cdf(group.wtkg2) for i, group in groups]
And then extract the 25th, 50th, and 75th percentile from each group.
In [16]:
for percent in [75, 50, 25]: weight_percentiles = [cdf.Percentile(percent) for cdf in cdfs] label = '%dth' % percent thinkplot.Plot(mean_heights, weight_percentiles, label=label) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False)
/>
Exercise: Yet another option is to divide the dataset into groups and then plot the CDF for each group. As an exercise, divide the dataset into a smaller number of groups and plot the CDF for each group.
In [17]:
# Solution bins = np.arange(140, 210, 10) indices = np.digitize(cleaned.htm3, bins) groups = cleaned.groupby(indices) cdfs = [thinkstats2.Cdf(group.wtkg2) for i, group in groups] thinkplot.PrePlot(len(cdfs)) thinkplot.Cdfs(cdfs) thinkplot.Config(xlabel='Weight (kg)', ylabel='CDF', axis=[20, 200, 0, 1], legend=False)
/>
The following function computes the covariance of two variables using NumPy's
dotfunction.
In [18]:
And here's an example:
In [19]:
heights, weights = cleaned.htm3, cleaned.wtkg2 Cov(heights, weights)
Out[19]:
103.33290857697797
Covariance is useful for some calculations, but it doesn't mean much by itself. The coefficient of correlation is a standardized version of covariance that is easier to interpret.
In [20]:
def Corr(xs, ys): xs = np.asarray(xs) ys = np.asarray(ys) meanx, varx = thinkstats2.MeanVar(xs) meany, vary = thinkstats2.MeanVar(ys) corr = Cov(xs, ys, meanx, meany) / np.sqrt(varx * vary) return corr
The correlation of height and weight is about 0.51, which is a moderately strong correlation.
In [21]:
Corr(heights, weights)
Out[21]:
0.50873647897347707
NumPy provides a function that computes correlations, too:
In [22]:
np.corrcoef(heights, weights)
Out[22]:
array([[ 1. , 0.50873648], [ 0.50873648, 1. ]])
The result is a matrix with self-correlations on the diagonal (which are always 1), and cross-correlations on the off-diagonals (which are always symmetric).
Pearson's correlation is not robust in the presence of outliers, and it tends to underestimate the strength of non-linear relationships.
Spearman's correlation is more robust, and it can handle non-linear relationships as long as they are monotonic. Here's a function that computes Spearman's correlation:
Spearman's correlation is more robust, and it can handle non-linear relationships as long as they are monotonic. Here's a function that computes Spearman's correlation:
In [23]:
import pandas as pd def SpearmanCorr(xs, ys): xranks = pd.Series(xs).rank() yranks = pd.Series(ys).rank() return Corr(xranks, yranks)
For heights and weights, Spearman's correlation is a little higher:
In [24]:
SpearmanCorr(heights, weights)
Out[24]:
0.54058462623204762
A Pandas
Seriesprovides a method that computes correlations, and it offers
spearmanas one of the options.
In [25]:
def SpearmanCorr(xs, ys): xs = pd.Series(xs) ys = pd.Series(ys) return xs.corr(ys, method='spearman')
The result is the same as for the one we wrote.
In [26]:
SpearmanCorr(heights, weights)
Out[26]:
0.54058462623204839
An alternative to Spearman's correlation is to transform one or both of the variables in a way that makes the relationship closer to linear, and the compute Pearson's correlation.
In [27]:
Corr(cleaned.htm3, np.log(cleaned.wtkg2))
Out[27]:
0.53172826059834655
Using data from the NSFG, make a scatter plot of birth weight versus mother’s age. Plot percentiles of birth weight versus mother’s age. Compute Pearson’s and Spearman’s correlations. How would you characterize the relationship between these variables?
In [28]:
import first live, firsts, others = first.MakeFrames() live = live.dropna(subset=['agepreg', 'totalwgt_lb'])
In [29]:
# Solution ages = live.agepreg weights = live.totalwgt_lb print('Corr', Corr(ages, weights)) print('SpearmanCorr', SpearmanCorr(ages, weights))
Corr 0.0688339703541 SpearmanCorr 0.0946100410966
In [30]:
# Solution def BinnedPercentiles(df): """Bin the data by age and plot percentiles of weight for each bin. df: DataFrame """ bins = np.arange(10, 48, 3) indices = np.digitize(df.agepreg, bins) groups = df.groupby(indices) ages = [group.agepreg.mean() for i, group in groups][1:-1] cdfs = [thinkstats2.Cdf(group.totalwgt_lb) for i, group in groups][1:-1] thinkplot.PrePlot(3) for percent in [75, 50, 25]: weights = [cdf.Percentile(percent) for cdf in cdfs] label = '%dth' % percent thinkplot.Plot(ages, weights, label=label) thinkplot.Config(xlabel="Mother's age (years)", ylabel='Birth weight (lbs)', xlim=[14, 45], legend=True) BinnedPercentiles(live)
/>
In [31]:
# Solution def ScatterPlot(ages, weights, alpha=1.0, s=20): """Make a scatter plot and save it. ages: sequence of float weights: sequence of float alpha: float """ thinkplot.Scatter(ages, weights, alpha=alpha) thinkplot.Config(xlabel='Age (years)', ylabel='Birth weight (lbs)', xlim=[10, 45], ylim=[0, 15], legend=False) ScatterPlot(ages, weights, alpha=0.05, s=10)
/>
In [32]:
# Solution # My conclusions: # 1) The scatterplot shows a weak relationship between the variables but # it is hard to see clearly. # 2) The correlations support this. Pearson's is around 0.07, Spearman's # is around 0.09. The difference between them suggests some influence # of outliers or a non-linear relationsip. # 3) Plotting percentiles of weight versus age suggests that the # relationship is non-linear. Birth weight increases more quickly # in the range of mother's age from 15 to 25. After that, the effect # is weaker.
In [ ]:
|
https://allendowney.blogspot.com/2017/01/third-batch-of-notebooks-for-think-stats.html
|
CC-MAIN-2018-51
|
refinedweb
| 1,777
| 60.21
|
Contents
This document is an introduction to how you can extend paster and Paste Script for your system – be it a framework, server setup, or whatever else you want to do.
paster is a two-level command, where the second level (e.g., paster help, paster create, etc) is pluggable.
Commands are attached to Python Eggs, i.e., to the package you distribute and someone installs. The commands are identified using entry points.
To make your command available do something like this in your setup.py file:
from setuptools import setup setup(... entry_points=""" [paste.paster_command] mycommand = mypackage.mycommand:MyCommand [paste.global_paster_command] myglobal = mypackage.myglobal:MyGlobalCommand """)
This means that paster mycommand will run the MyCommand command located in the mypackage.mycommand module. Similarly with paster myglobal. The distinction between these two entry points is that the first will only be usable when paster is run inside a project that is identified as using your project, while the second will be globally available as a command as soon as your package is installed.
So if you have a local command, how does it get enabled? If the person is running paster inside their project directory, paster will look in Project_Name.egg-info/paster_plugins.txt which is a list of project names (the name of your package) whose commands should be made available.
This is for frameworks, so frameworks can add commands to paster that only apply to projects that use that framework.
The command objects (like MyCommand) are subclasses of paste.script.command.Command. You can look at that class to get an idea, but a basic outline looks like this:
max_args and min_args are used to give error messages. You can also raise command.BadCommand(msg) if the arguments are incorrect in some way. (Use None here to give no restriction)
The usage variable means paster mycommand -h will give a usage of paster mycommand [options] NAME. summary is used with paster help (describing your command in a short form). group_name is used to group commands together for paste help under that title.
The parser object is an optparse <> OptionParser object. Command.standard_parser is a class method that creates normal options, and enables options based on these keyword (boolean) arguments: verbose, interactive, no_interactive (if interactive is the default), simulate, quiet (undoes verbose), and overwrite. You can create the parser however you want, but using standard_parser() encourages a consistent set of shared options across commands.
When your command is run, .command() is called. As you can see, the options are in self.options and the positional arguments are in self.args. Some options are turned into instance variables – especially self.verbose and self.simulate (even if you haven’t chosen to use those options, many methods expect to find some value there, which is why they are turned into instance variables).
There are quite a few useful methods you can use in your command. See the Command class for a complete list. Some particulars:
run_command(cmd, arg1, arg2, ..., cwd=os.getcwd(), capture_stderr=False):
Runs the command, respecting verbosity and simulation. Will raise an error if the command doesn’t exit with a 0 code.
insert_into_file(filename, marker_name, text, indent=False):
Inserts a line of text into the file, looking for a marker like -*- marker_name -*- (and inserting just after it). If indent=True, then the line will be indented at the same level as the marker line.
ensure_dir(dir, svn_add=True):
Ensures that the directory exists. If svn_add is true and the parent directory has an .svn directory, add the new directory to Subversion.
ensure_file(filename, content, svn_add=True):
Ensure the file exists with the given content. Will ask the user before overwriting a file if --interactive has been given.
The other pluggable part is “templates”. These are used to create new projects. Paste Script includes one template itself: basic_package which creates a new setuptools package.
To enable, add to setup.py:
setup(... entry_points=""" [paste.paster_create_template] framework = framework.templates:FrameworkTemplate """)
FrameworkTemplate should be a subclass of paste.script.templates.Template. An easy way to do this is simply with:
from paste.script import templates class FrameworkTemplate(templates.Template): egg_plugins = ['Framework'] summary = 'Template for creating a basic Framework package' required_templates = ['basic_package'] _template_dir = 'template' use_cheetah = True
egg_plugins will add Framework to paste_plugins.txt in the package. required_template means those template will be run before this one (so in this case you’ll have a complete package ready, and you can just write your framework files to it). _template_dir is a module-relative directory to find your source files.
The source files are just a directory of files that will be copied into place, potentially with variable substitutions. Three variables are expected: project is the project name (e.g., Project-Name), package is the Python package in that project (e.g., projectname) and egg is the project’s egg name as generated by setuptools (e.g., Project_Name). Users can add other variables by adding foo=bar arguments to paster create.
Filenames are substituted with +var_name+, e.g., +package+ is the package directory.
If a file in the template directory ends in _tmpl then it will be substituted. If use_cheetah is true, then it’s treated as a Cheetah template. Otherwise string.Template is used, though full expressions are allowed in ${expr} instead of just variables.
See the templates module for more.
|
http://pythonpaste.org/script/developer?highlight=paster%20create
|
CC-MAIN-2015-27
|
refinedweb
| 885
| 59.3
|
qt-opengl is a missing dependency for x11-libs/qt-webkit.
With qt-opengl installed, emerge qt-webkit is successful.
Reproducible: Always
make[2]: Leaving directory '/var/tmp/portage/dev-qt/qtwebkit-5.2.1/work/qtwebkit-opensource-src-5.2.1_build/Source'
cd WebKit2/ && ( test -e Makefile.WebProcess || /var/tmp/portage/dev-qt/qtwebkit-5.2.1/work/qtwebkit-opensource-src-5.2.1_build/bin/qmake /var/tmp/portage/dev-qt/qtwebkit-5.2.1/work/qtwebkit-opensource-src-5.2.1/Source/WebKit2/WebProcess.pro -o Makefile.WebProcess ) && make -f Makefile.WebProcess
Project ERROR: Unknown module(s) in QT: webkitwidgets
Makefile.QtWebKit:68: recipe for target 'sub-WebKit2-WebProcess-pro-make_first-ordered' failed
make[1]: *** [sub-WebKit2-WebProcess-pro-make_first-ordered] Error 3
make[1]: Leaving directory '/var/tmp/portage/dev-qt/qtwebkit-5.2.1/work/qtwebkit-opensource-src-5.2.1_build/Source'
Makefile:303: recipe for target 'sub-Source-QtWebKit-pro-make_first-ordered' failed
make: *** [sub-Source-QtWebKit-pro-make_first-ordered] Error 2
* ERROR: dev-qt/qtwebkit-5.2.1::gentoo failed (compile phase):
* emake failed
Just ran into this. Was able to work around it with USE="widgets" for this package.
*** Bug 512274 has been marked as a duplicate of this bug. ***
(In reply to Kelly Price from comment #2)
> Just ran into this. Was able to work around it with USE="widgets" for this
> package.
+1
We can get a bit further with ' qt_use_disable_mod widgets widgets Source/WebKit2/WebProcess.pro' but in Source/WebKit2/qt/MainQt.cpp:
#if defined(QT_NO_WIDGETS)
#include <QGuiApplication>
typedef QGuiApplication ApplicationType;
#else
#include <QApplication>
typedef QApplication ApplicationType;
#endif
Is there any way to handle this, or should we just drop the widgets USE flag?
(In reply to Michael Palimaka (kensington) from comment #5)
> Is there any way to handle this, or should we just drop the widgets USE flag?
No, at least not in a sane way. It's much easier and safer to just drop USE=widgets and always require it. We can revisit this later if needed.
USE flag removed in overlay, will push to the tree if it looks sane.
LGTM, please proceed. (don't bother to revbump...)
What about the opengl part of this bug?
Thanks, fixed in CVS.
I tried a few things but wasn't able to reproduce any opengl issue (and haven't heard anything about it lately either). Please reopen with a build log if that issue persists.
+ 25 Sep 2014; Michael Palimaka <kensington@gentoo.org> qtwebkit-5.3.2.ebuild:
+ Remove widgets USE flag wrt bug #448178 as it causes build failure when
+ disabled.
|
https://bugs.gentoo.org/show_bug.cgi?id=448178
|
CC-MAIN-2021-10
|
refinedweb
| 433
| 52.76
|
You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org
Obsolete talk:Media server/Distributed File Storage choices
I haven't been closely involved with this, and don't have a ton of time to devote to this over the next couple of days, but just a couple of questions:
- The requirements are expressed in terms of software libraries, but do we have any requirements about...
- Requirements are stated more verbosely in Obsolete:Media server/2011_Media_Storage_plans. RussNelson 00:59, 1 December 2010 (UTC)
- consistency or availability, particularly cross-colo?
- performance?
- scaling?
- horizontally -- we add a new server, what happens to all the old files?
- I believe that the presumption is that the new server takes over its fair share. It's mine, anyway. RussNelson 00:59, 1 December 2010 (UTC)
- "diagonally" -- we want to add some servers with newer hardware, what's the procedure for balancing faster and slower machines?
- Not planning to do this automatically, because I don't think we understand that problem yet. There will be a manual procedure for storing more or less files on each machine. RussNelson 00:59, 1 December 2010 (UTC)
- How is this handled by existing third party code? -- ArielGlenn 20:28, 5 December 2010 (UTC)
- In my survey of DFSs, I didn't see anybody claim to have solved that problem. RussNelson 15:58, 8 December 2010 (UTC)
- I assume that vertical scaling is right out. :)
- Gosh, it's worked so far! RussNelson 00:59, 1 December 2010 (UTC)
- Or is it just that all the options here are roughly the same?
- MogileFS is listed as not having files available over HTTP, but why? Doesn't it run over HTTP?
- I strongly disagree with the requirement that files should be stored in the physical filesystem under a name similar to their title. I realize this is how MediaWiki works, but I would rather not have this baked into our systems going forward.
- That was listed as a Want, not a Need, but I get your point. RussNelson 00:59, 1 December 2010 (UTC)
- Ariel seems to believe this offers some sysadmin convenience, but I think that comes at a HUGE penalty for the application design. When it comes to media uploads, many files could legitimately have the same title, and we also have the issue of the file extension to deal with (as a wart on the title). Media files should be stored under guaranteed unique ids or an id generated from a content hash. Titles should be stored in a secondary place such as a database.
- The namespace is flat (AFAIK) and so no, they can't have the same title. RussNelson 00:59, 1 December 2010 (UTC)
IMO Mogile ought to be an acceptable alternative (since I disagree with the two strikes it has against it in your current matrix). LiveJournal uses it for relatively similar use cases, and it is what everybody in the Web 2.0 space copied, including Flickr.
I'd like to hear a bit more about the "Homebrew" solution as it seems to rely on DNS and does not allow arbitrary files to be associated with arbitrary hosts. Maybe we can get away with this, as, unlike the Web 2.0 world, we don't have to do complex lookups related to permissions or other user characteristics just to serve a file. But I confess I am a bit skeptical that we've come up with something that the rest of the industry has missed, unless it can be shown to flow directly from our more relaxed requirements about (for instance) affiliating a file with a user, checking privacy, licensing, etc.
- Groups of files (which have the same hash) are associated with arbitrary hosts. Currently, we have 13TB. Spread over a 256 hash, that's 19GB per file group. It's straightforward to scale that to 65536 hosts by using the secondary hash. RussNelson 00:59, 1 December 2010 (UTC)
The title->hostname hashing algorithm I see discussed there seems to suggest that all servers ought to be of equal performance characteristics too, which won't be the case. Unless we have 256 "virtual" servers that may not map to the exact set of machines. How does this work if we have more than 256 machines?
- Yes, that's exactly how it works. We apportion the file groups to servers as their performance dictates. Once we have more than 256 machines, we expand the hostname to include the secondary hash. We can roll out all of these changes on the fly by ensuring that both systems work and are coherent. In fact, we can probably go from having the existing Solaris machines to the cluster on the fly. As we go, adding machines, we copy files off the Solaris machines. Adding the 1st machine in the cluster should work identically to adding the Nth machine into it. RussNelson 00:59, 1 December 2010 (UTC)
NeilK 22:47, 29 November 2010 (UTC)
- I'd like to know more about what pieces would need to be written for the "homebrew" solution also. At least a repo method for uploads would have to be done. Also I'd like to know what varnish url rewriting capabilities exist. If the rewriting piece turns out to hamper our choices for caching in any way, I would be opposed to that on principle. We would want to think about workarounds.
- Homebrew pieces: 1) replication and migration tools. 2) We actually need to shuffle up the existing system, because we need to do scaling without NFS mounts of a central computer. I think we should do scaling on the cluster hosts themselves. We didn't do that in the past because the central big machine needed to stick to its knitting. But with clustered machines they can serve multiple functions. Scale by adding more.
- I agree that being able to rewrite is an absolute requirement for Homebrew. Once I finish editing this (and sleep) it will be the first thing I look at tomorrow. RussNelson 00:59, 1 December 2010 (UTC)
- As to filenames that can be humanly read, I have as a want that the filename on wiki be similar to (= embedded in, for example, as we do for the archived filenames) the filename as stored. Why? Because if we ever have buggy mapping (and believe me we have had all kinds of bizarre bugs with the current system) then we will be in a world of hurt trying to sort out what files go to what. But if the filename is at least a part of the file as stored, we have a fighting chance of finding things gone missing or straightening them out. I would like to build in robustness of this sort wherever possible. Having said that I listed it as a "want" because it's up for discussion, not set in stone. -- ArielGlenn 23:18, 29 November 2010 (UTC)
- I see the problem with remapping, but that's only because MediaWiki thinks that the primary key is the title. It really should be the other way around, we map the file id to a title. Then again we have to deal with the system as it is. NeilK 23:22, 29 November 2010 (UTC)
- Ariel noted to me that we need to preserve the existing project/hash/2ndhash/Title.jpg and thumbs/project/hash/2ndhash/Title.jpg/px-Title.jpg URLs. If we give up on titles in filenames and actually store them in arbitrary tokens, then we need to have an index which maps those names into the tokens. RussNelson 00:59, 1 December 2010 (UTC)
Notes on homebrew
Looking more closely at the existing URLs, they contain the first, and then first two digits of the md5sum of the filename. Thus, we have at most a 256-way split with the existing filename structure. If we have machines with, say, 4TB on them, then we can serve up at most a petabyte. Given that we have 13TB now, a petabyte is only an 64X expansion. I don't think a design which only supports a 64X expansion is reasonable.
One of the constraints is to preserve these URLs. There are two sources of the URLs, however: our own, which we hand out on the fly (which we are free to change), and URLs presented to us from an external page. We only really need to preserve those URLs. Depending on how many there are, it's possible that we could get away with a machine or two rewriting the URLs and re-presenting them to the caches.
If we're then handing out a new kind of permalink, we can create one which scales between machines better. For example, we could take the first three digits of the md5sum (256*16 or 4096 unique values) and put them into hostnames. Those hostnames would map into a relatively small set of servers which would serve up the file in the usual manner. For reliability, we could keep duplicate copies of each of these 4096 bins of files, and resolve the hostname into multiple IP addresses.
- One of my hesitations about the homebrew solution, besides that then we do wind up maintaining another non-trivial piece of code, is that as it is described it won't be general purpose, so we will have spent a decent chunk of time developing something that is useful pretty much for us only. If we put in work making one of the third-party options work for us, that work can go back to the upstream project, at least in theory, and benefit other folks. I realize that's a bit of a meta reason to favor one choice over another, but I think we should keep it in mind anyways. Another point is that a third party project with a decent community behind it has exactly that: a decent community of developers. If we go with homebrew, we'll have 1, maybe 2 people who know the code well, and who are probably immediately booked on other things once it's deployed. -- ArielGlenn 20:28, 5 December 2010 (UTC)
- I agree with this concern 100%. Maybe 101%. Or more. The only only reason I'm taking Homebrew seriously is because we have four choices:
- Use somebody's DFS with POSIX semantics using FUSE,
- a DFS mounted via NFS,
- Write PHP code that talks to a DFS API, or
- Write PHP code to a REST API that implements our Repo modification needs.
I'm eliminating #1 because I'm dubious of putting FUSE into a production path. There's a REASON why you do some things in the kernel. I'm eliminating #2 because NFS has always had reliability problems which I think are inherent in the design. Both of these solutions are code-free. We just configure the DFS to put files where we have always been mounting them. I don't believe this is the correct path. Requirements and capabilities change over time, which mean that a newly-implemented solution will make different trade-offs between requirements and capabilities. Trying to preserve existing capabilities in the face of different requirements just pushes changes off into the future. Sometimes this is the right thing to do when you don't understand the problem well enough. I think that right now, we do understand the problem of a bigger Media Server. Thus, it's time to write code.
By the previous paragraph's reasoning, we are writing code. To address your concern, we should try to write the simplest, most understandable, most reusable code possible. On the one hand, that could be something like Domas' PHP interface to Mogile (proven to be reusable since somebody already IS reusing it). On the other hand, that could be extending the FileRepo code so that it splits the store over different machines, but preserves the structure of the local store, thus eliminating entities and configuration. I think that the Homebrew solution will result in our taking away configuration variables and code that (already) we are the only user of. RussNelson 15:58, 8 December 2010 (UTC)
|
https://wikitech-static.wikimedia.org/wiki/Obsolete_talk:Media_server/Distributed_File_Storage_choices
|
CC-MAIN-2022-33
|
refinedweb
| 2,034
| 70.13
|
Quokka Clone In 10 Minutes - VSCode Extention Tutorial
July 22, 2019
In this tutorial, we’ll learn how to create a VSCode extension that will communicate with Node Inspector to collect execution data - basically a Quokka.js clone.
For those who don’t know what Quokka.js is - it’s a live scratchpad for Javascript/Typescript that allows you to see the results of code execution right in your editor.
The extension that we’ll build will be called Wombat.js because wombats are cool and they poop cubes.
I’ll be using Typescript because I like to have type annotations and smart code completion when I work with unfamiliar modules/libs.
Bootstrap New VSCode Extention
We’ll start by creating our VSCode extension first.
VSCode provides a Yeoman generator to bootstrap new extensions.
Make sure you have Yeoman installed globally.
npm i -g yeoman
Run vscode extention generator:
yo code .
It will ask you a bunch of questions about your project. Answer them and it will create the file structure.
Here I will assume that you’ll also choose Typescript as the preferred language.
Open the project in VSCode:
code <project name>
Here you need to put your actual project name instead of
<project name>.
Here I assume that you have a console command installed that allows you to launch VSCode from your terminal. If not - do this:
- Launch VSCode regular way.
- Open the Command Palette (
⇧⌘Pon Mac) and type
shell commandto find the Shell Command: Install ‘code’ command in PATH command.
Change command title in
package.json. It is located in
contributes.commandsblock.
"contributes": { "commands": [ { "command": "extension.<your extension name>", "title": "Run wombat" } ] },
Get Data From Node Inspector
Since version 6.3 node provides a built-in inspector which API we are gonna use to get runtime information about our code.
Open the file
src/extention.tsand add the following imports:
import * as path from "path"; import * as util from "util"; import * as inspector from "inspector";
Make the activation function asynchronous we’ll need this to use promises and
async/awaitinstead of callback API that
inspectorprovides by default.
export async function activate(context: vscode.ExtensionContext) { // ...
Launch inspector:
export async function activate(context: vscode.ExtensionContext) { inspector.open(); // ...
This is an equivalent of running
node --inspector somefile.js.
Start new client session. Add these lines after you activate the
inspector.
const session = new inspector.Session(); session.connect();
Wrap
session.postinto
promisify.
const post = <any>util.promisify(session.post).bind(session);
Unfortunately, we’ll have to use type
anyhere. Usually, I avoid using
anyas much as I can, but here it will use the wrong type because of how
session.postfunction is typed.
This is because
session.postis overloaded and has different arity for different actions it calls and the fact that by default typescript will pick the last function definition it finds.
In the case with
post- it would be:
post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void;
As you can see this type allows only
HeapProfiler.stopSamplingas
method, and we want to use just regular
stringtype.
I didn’t want to deal with complex type annotations in this tutorial. Alternatively, you could create your custom
promisifyfunction that will overcome that limitation.
Make the
registedCommandcallback - asynchronous.
To do this search for
vscode.commands.registerCommandand add
asyncbefore callback definition.
let disposable = vscode.commands.registerCommand( "extension.wombat", async () => { // ...
Our app will need to get the text from the currently open file, so get the
activeTextEditorinstance.
const activeEditor = vscode!.window!.activeTextEditor; if (!activeEditor) { return; }
We instantly stop the execution if we can’t get the editor instance.
Here is the second time I cut the corners with Typescript here.
See those
!.- it tells Typescript that there definitely, 100% certainly, I swear by god is a be a value in the previous field.
It is called non-null assertion operator. It’s important that it is not the same as
?.that is optional chaining operator (that might be familiar to Ruby, C# and probably other language users) and is not currently available neither in Typescript nor in Javascript.
Get
documentand
fileNamefor later use:
const document = activeEditor!.document; const fileName = path.basename(document.uri.toString())
Compile the script from the editor:
const { scriptId } = await post("Runtime.compileScript", { expression: document.getText(), sourceURL: fileName, persistScript: true });
Here we use
document.getText()to obtain the source code. We get
scriptIdthat we will need in the next step.
Run the script:
await post("Runtime.runScript", { scriptId });
Get all the variables in global namespace:
const data = await post("Runtime.globalLexicalScopeNames", { executionContextId: 1 });
Here I’ve hardcoded the
executionContextId. Alternatively, you could get it by subscribing to
Runtime.executionContextCreatedevent.
It will return an array with a list of
var,
letor
constdefinitions available in the global namespace.
In the next steps, we’ll get their values.
Of course, this is not how Quokka.js does that, but for this tutorial, it’s just enough.
Map through the variable names and get their values:
data.names.map(async (expression: string) => { const { result: { value } } = await post("Runtime.evaluate", { expression, contextId: 1 }); })
We do it by executing variable names as expressions in the same context we run our script.
Get variable locations. Add this to
mapfunction.
const { result } = await post("Debugger.searchInContent", { scriptId, query: expression });
Display Info In UI
Now we need to display this information somehow.
I wanted to find out how did Quokka.js do it.
It was surprisingly cumbersome to find the API that allows you to display info on top of the text in VSCode because it wasn’t mentioned in the
API section among the capabilities. So I had to jump directly to the
references section.
It was mentioned in the API docs as
decorators, which I find a bit non-intuitive name. I was looking for something like “overlay API” - of course with zero success.
Back to the tutorial:
Define the
addDecorationWithTextfunction:
const addDecorationWithText = ( contentText: string, line: number, column: number, activeEditor: vscode.TextEditor ) => { const decorationType = vscode.window.createTextEditorDecorationType({ after: { contentText, margin: "20px" } }); const range = new vscode.Range( new vscode.Position(line, column), new vscode.Position(line, column) ); activeEditor.setDecorations(decorationType, [{ range }]); };
Due to how those decorations work we need to create a separate
decorationTypefor each case because we want to have different
contextTextvalues.
Then we define range - in our case, it’s just one line so start and end sections of this range are the same.
And finally, we apply created a decoration to the
activeEditor.
Time to use
addDecorationWithText. Call this function inside of the names
mapwe’ve defined earlier:
addDecorationWithText( `${value}`, result[0].lineNumber, result[0].lineContent.length, activeEditor );
Add it at the end of that function.
Launch The Extention
Time to check how our extension works.
F5or
Debug -> Start Debugging.
It will launch a new VSCode window in debug mode.
Open some simple Javascript file:
const x = 10; let y = x; let z = 2 + 2; let foo = 'bar'; const test = 42;
This is the file that I’ve used.
Run the
wombatcommand.
Open
Command Pallete(
⇧⌘Pon Mac) and type
wombat. Then press enter.
Publishing Your Extention
Publishing VSCode extensions is done using
vsce tool.
There is a guide in VSCode docs that explains how to do that.
You’ll need to obtain your personal
publishedID and then just run
vsce publish.
Final Words
Of course, this extension we’ve made is very basic and is missing 99.9999999% functionality that is needed to use it for real.
In reality, I believe you would have to also get the AST tree of the script to know exact locations of all the variables you want to track.
Also, you would have to have some state management to store values along with the script execution.
I believe that you also would have to pause the execution in the beginning and then execute the script step by step, recording current state on every iteration.
But all that wasn’t the point of this tutorial. I wanted to play around with the available APIs and make a fun project.
The source code is available on github. The extension itself is available in VSCode marketplace. Ping me on telegram if you have any questions.
|
https://maksimivanov.com/posts/quokka-clone/
|
CC-MAIN-2019-43
|
refinedweb
| 1,357
| 51.95
|
import "github.com/spf13/hugo/hugolib"
alias.go author.go config.go gitinfo.go handler_base.go handler_file.go handler_meta.go handler_page.go hugo_info.go hugo_sites.go hugo_sites_build.go media.go menu.go multilingual.go page.go pageCache.go pageGroup.go pageSort.go page_collections.go page_output.go page_paths.go pagesPrevNext.go pagination.go permalinker.go permalinks.go scratch.go shortcode.go shortcodeparser.go site.go site_output.go site_render.go sitemap.go taxonomy.go translations.go
const ( KindPage = "page" // The rest are node types; home page, sections etc. KindHome = "home" KindSection = "section" KindTaxonomy = "taxonomy" KindTaxonomyTerm = "taxonomyTerm" )
var ( // CommitHash contains the current Git revision. Use make to build to make // sure this gets set. CommitHash string // BuildDate contains the date of the current build. BuildDate string )
var ErrHasDraftAndPublished = errors.New("both draft and published parameters were found in page's frontmatter")
LoadConfig loads Hugo configuration into a new Viper and then adds a set of defaults.
type Author struct { GivenName string FamilyName string DisplayName string Thumbnail string Image string ShortBio string LongBio string Email string Social AuthorSocial }
Author contains details about the author of a page.
AuthorList is a list of all authors and their metadata.
AuthorSocial is a place to put social details per author. These are the standard keys that themes will expect to have available, but can be expanded to any others on a per site basis - website - github - facebook - twitter - googleplus - pinterest - instagram - youtube - linkedin - skype
type BuildCfg struct { // Whether we are in watch (server) mode Watching bool // Print build stats at the end of a build PrintStats bool // Reset site state before build. Use to force full rebuilds. ResetState bool // Re-creates the sites from configuration before a build. // This is needed if new languages are added. CreateSitesFromConfig bool // Skip rendering. Useful for testing. SkipRender bool // contains filtered or unexported fields }
BuildCfg holds build options used to, as an example, skip the render step.
type HandleResults chan<- HandledResult
func (h HandledResult) Error() string
HandledResult is an error
func (h HandledResult) Page() *Page
func (h HandledResult) String() string
type Handler interface { FileConvert(*source.File, *Site) HandledResult PageConvert(*Page) HandledResult Read(*source.File, *Site) HandledResult Extensions() []string }
HugoInfo contains information about the current Hugo environment
HugoSites represents the sites to build. Each site represents a language.
NewHugoSites creates HugoSites from the given config.
Build builds all sites. If filesystem events are provided, this is considered to be a potential partial rebuild.
Pages returns all pages for all sites.
type Image struct { // The URL of the image. In some cases, the image URL may not be on the // same domain as your main site. This is fine, as long as both domains // are verified in Webmaster Tools. If, for example, you use a // content delivery network (CDN) to host your images, make sure that the // hosting site is verified in Webmaster Tools OR that you submit your // sitemap using robots.txt. In addition, make sure that your robots.txt // file doesn’t disallow the crawling of any content you want indexed. URL string Title string Caption string AltText string // The geographic location of the image. For example, // <image:geo_location>Limerick, Ireland</image:geo_location>. GeoLocation string // A URL to the license of the image. License string }
An Image contains metadata for images + image sitemaps
Menu is a collection of menu entries.
ByName sorts the menu by the name defined in the menu configuration.
ByWeight sorts the menu by the weight defined in the menu configuration.
Limit limits the returned menu to n entries.
Reverse reverses the order of the menu entries.
Sort sorts the menu by weight, name and then by identifier.
type MenuEntry struct { URL string Name string Menu string Identifier string Pre template.HTML Post template.HTML Weight int Parent string Children Menu }
MenuEntry represents a menu item defined in either Page front matter or in the site config.
HasChildren returns whether this menu item has any children.
IsEqual returns whether the two menu entries represents the same menu entry.
IsSameResource returns whether the two menu entries points to the same resource (URL).
KeyName returns the key used to identify this menu entry.
Menus is a dictionary of menus.
func NewMetaHandler(in string) *MetaHandle
func (mh *MetaHandle) Convert(i interface{}, s *Site, results HandleResults)
func (mh *MetaHandle) Handler() Handler
func (mh *MetaHandle) Read(f *source.File, s *Site, results HandleResults)
type MetaHandler interface { // Read the Files in and register Read(*source.File, *Site, HandleResults) // Generic Convert Function with coordination Convert(interface{}, *Site, HandleResults) Handle() Handler }
type Multilingual struct { Languages helpers.Languages DefaultLang *helpers.Language // contains filtered or unexported fields }
func (ml *Multilingual) Language(lang string) *helpers.Language
type OrderedTaxonomy []OrderedTaxonomyEntry
OrderedTaxonomy is another representation of an Taxonomy using an array rather than a map. Important because you can't order a map.
func (t OrderedTaxonomy) Reverse() OrderedTaxonomy
Reverse reverses the order of the entries in this taxonomy.
type OrderedTaxonomyEntry struct { Name string WeightedPages WeightedPages }
OrderedTaxonomyEntry is similar to an element of a Taxonomy, but with the key embedded (as name) e.g: {Name: Technology, WeightedPages: Taxonomyedpages}
func (ie OrderedTaxonomyEntry) Count() int
Count returns the count the pages in this taxonomy.
func (ie OrderedTaxonomyEntry) Pages() Pages
Pages returns the Pages for this taxonomy.
func (ie OrderedTaxonomyEntry) Term() string
Term returns the name given to this taxonomy.
type OutputFormat struct { // Rel constains a value that can be used to construct a rel link. // This is value is fetched from the output format definition. // Note that for pages with only one output format, // this method will always return "canonical". // As an example, the AMP output format will, by default, return "amphtml". // // See: // // // Most other output formats will have "alternate" as value for this. Rel string // contains filtered or unexported fields }
And OutputFormat links to a representation of a resource.
func (o OutputFormat) MediaType() media.Type
MediaType returns this OutputFormat's MediaType (MIME type).
func (o OutputFormat) Name() string
Name returns this OutputFormat's name, i.e. HTML, AMP, JSON etc.
func (o *OutputFormat) Permalink() string
Permalink returns the absolute permalink to this output format.
func (o *OutputFormat) RelPermalink() string
Permalink returns the relative permalink to this output format.
type OutputFormats []*OutputFormat
OutputFormats holds a list of the relevant output formats for a given resource.
func (o OutputFormats) Get(name string) *OutputFormat
Get gets a OutputFormat given its name, i.e. json, html etc. It returns nil if not found.
type Page struct { // Kind is the discriminator that identifies the different page types // in the different page collections. This can, as an example, be used // to to filter regular pages, find sections etc. // Kind will, for the pages available to the templates, be one of: // page, home, section, taxonomy and taxonomyTerm. // It is of string type to make it easy to reason about in // the templates. Kind string // Since Hugo 0.18 we got rid of the Node type. So now all pages are ... // pages (regular pages, home page, sections etc.). // Sections etc. will have child pages. These were earlier placed in .Data.Pages, // but can now be more intuitively also be fetched directly from .Pages. // This collection will be nil for regular pages. Pages Pages // Params contains configuration defined in the params section of page frontmatter. Params map[string]interface{} // Content sections Content template.HTML Summary template.HTML TableOfContents template.HTML Aliases []string Images []Image Videos []Video Truncated bool Draft bool Status string PublishDate time.Time ExpiryDate time.Time // PageMeta contains page stats such as word count etc. PageMeta // Markup contains the markup type for the content. Markup string Layout string Source Position `json:"-"` GitInfo *gitmap.GitInfo Site *SiteInfo `json:"-"` Title string Description string Keywords []string Data map[string]interface{} Date time.Time Lastmod time.Time Sitemap Sitemap URLPath // contains filtered or unexported fields }
AllTranslations returns all translations, including the current Page.
func (p *Page) AlternativeOutputFormats() (OutputFormats, error)
AlternativeOutputFormats is only available on the top level rendering entry point, and not inside range loops on the Page collections. This method is just here to inform users of that restriction.
func (p *Page) Authors() AuthorList
IsHome returns whether this is the home page.
IsNode returns whether this is an item of one of the list types in Hugo, i.e. not a regular content page.
IsPage returns whether this is a regular content page.
IsTranslated returns whether this content file is translated to other language(s).
func (p *Page) OutputFormats() OutputFormats
OutputFormats gives the output formats for this Page.
Paginate invokes this Page's main output's Paginate method.
Paginator get this Page's main output's paginator.
Param is a convenience method to do lookups in Page's and Site's Params map, in that order.
This method is also implemented on Node and SiteInfo.
Permalink returns the absolute URL to this Page.
RelPermalink gets a URL to the resource relative to the host.
Scratch returns the writable context associated with this Page.
Translations returns the translations excluding the current Page.
type PageCollections struct { // Includes only pages of all types, and only pages in the current language. Pages Pages // Includes all pages in all languages, including the current one. // Includes pages of all types. AllPages Pages // A convenience cache for the regular pages. // This is for the current language only. RegularPages Pages // A convenience cache for the all the regular pages. AllRegularPages Pages // contains filtered or unexported fields }
PageCollections contains the page collections for a site.
PageGroup represents a group of pages, grouped by the key. The key is typically a year or similar.
PageMenus is a dictionary of menus defined in the Pages.
PageOutput represents one of potentially many output formats of a given Page.
func (p *PageOutput) AlternativeOutputFormats() (OutputFormats, error)
OutputFormats gives the alternative output formats for this PageOutput. Note that we use the term "alternative" and not "alternate" here, as it does not necessarily replace the other format, it is an alternative representation.
func (p *PageOutput) Paginate(seq interface{}, options ...interface{}) (*Pager, error)
Paginate gets this PageOutput's paginator if it's already created. If it's not, one will be created with the qiven sequence. Note that repeated calls will return the same result, even if the sequence is different.
func (p *PageOutput) Paginator(options ...interface{}) (*Pager, error)
Paginator gets this PageOutput's paginator if it's already created. If it's not, one will be created with all pages in Data["Pages"].
func (p *PageOutput) Render(layout ...string) template.HTML
Pager represents one of the elements in a paginator. The number, starting on 1, represents its place.
First returns the pager for the first page.
HasNext tests whether there are page(s) after the current.
HasPrev tests whether there are page(s) before the current.
Last returns the pager for the last page.
Next returns the pager for the next page.
NumberOfElements gets the number of elements on this page.
func (p *Pager) PageGroups() PagesGroup
PageGroups return Page groups for this page. Note: If this return non-empty result, then Pages() will return empty.
PageNumber returns the current page's number in the pager sequence.
PageSize returns the size of each paginator page.
Pagers returns a list of pagers that can be used to build a pagination menu.
Pages returns the Pages on this page. Note: If this return a non-empty result, then PageGroups() will return empty.
Prev returns the pager for the previous page.
TotalNumberOfElements returns the number of elements on all pages in this paginator.
TotalPages returns the number of pages in the paginator.
URL returns the URL to the current page.
ByDate sorts the Pages by date and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByExpiryDate sorts the Pages by publish date and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByLanguage sorts the Pages by the language's Weight.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByLastmod sorts the Pages by the last modification date and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByLength sorts the Pages by length and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByLinkTitle sorts the Pages by link title and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByPublishDate sorts the Pages by publish date and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByTitle sorts the Pages by title and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
ByWeight sorts the Pages by weight and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
FindPagePos Given a page, it will find the position in Pages will return -1 if not found
GroupBy groups by the value in the given field or method name and with the given order. Valid values for order is asc, desc, rev and reverse.
GroupByDate groups by the given page's Date value in the given format and with the given order. Valid values for order is asc, desc, rev and reverse. For valid format strings, see
GroupByExpiryDate groups by the given page's ExpireDate value in the given format and with the given order. Valid values for order is asc, desc, rev and reverse. For valid format strings, see
GroupByParam groups by the given page parameter key's value and with the given order. Valid values for order is asc, desc, rev and reverse.
GroupByParamDate groups by a date set as a param on the page in the given format and with the given order. Valid values for order is asc, desc, rev and reverse. For valid format strings, see
GroupByPublishDate groups by the given page's PublishDate value in the given format and with the given order. Valid values for order is asc, desc, rev and reverse. For valid format strings, see
Len returns the number of pages in the list.
Limit limits the number of pages returned to n.
Next returns the next page reletive to the given page.
Prev returns the previous page reletive to the given page.
Reverse reverses the order in Pages and returns a copy.
Adjacent invocations on the same receiver will return a cached result.
This may safely be executed in parallel.
Sort sorts the pages by the default sort order defined: Order by Weight, Date, LinkTitle and then full file path.
PagesGroup represents a list of page groups. This is what you get when doing page grouping in the templates.
func (psg PagesGroup) Len() int
Len returns the number of pages in the page group.
func (p PagesGroup) Reverse() PagesGroup
Reverse reverses the order of this list of page groups.
PermalinkOverrides maps a section name to a PathPattern
Permalinker provides permalinks of both the relative and absolute kind.
Scratch is a writable context used for stateful operations in Page/Node rendering.
Add will, for single values, add (using the + operator) the addend to the existing addend (if found). Supports numeric values and strings.
If the first add for a key is an array or slice, then the next value(s) will be appended.
Get returns a value previously set by Add or Set
GetSortedMapValues returns a sorted map previously filled with SetInMap
Set stores a value with the given key in the Node context. This value can later be retrieved with Get.
SetInMap stores a value to a map with the given key in the Node context. This map can later be retrieved with GetSortedMapValues.
type ShortcodeWithPage struct { Params interface{} Inner template.HTML Page *Page Parent *ShortcodeWithPage IsNamedParams bool // contains filtered or unexported fields }
ShortcodeWithPage is the "." context in a shortcode template.
func (scp *ShortcodeWithPage) Get(key interface{}) interface{}
Get is a convenience method to look up shortcode parameters by its key.
func (scp *ShortcodeWithPage) Ref(ref string) (string, error)
Ref is a shortcut to the Ref method on Page.
func (scp *ShortcodeWithPage) RelRef(ref string) (string, error)
RelRef is a shortcut to the RelRef method on Page.
func (scp *ShortcodeWithPage) Scratch() *Scratch
Scratch returns a scratch-pad scoped for this shortcode. This can be used as a temporary storage for variables, counters etc.
func (scp *ShortcodeWithPage) Site() *SiteInfo
Site returns information about the current site.
type Site struct { *PageCollections Files []*source.File Taxonomies TaxonomyList Source source.Input Sections Taxonomy Info SiteInfo Menus Menus Data map[string]interface{} Language *helpers.Language // Logger etc. *deps.Deps `json:"-"` // contains filtered or unexported fields }
Site contains all the information relevant for constructing a static site. The basic flow of information is as follows:
1. A list of Files is parsed and then converted into Pages.
2. Pages contain sections (based on the file they were generated from),
aliases and slugs (included in a pages frontmatter) which are the various targets that will get generated. There will be canonical listing. The canonical path can be overruled based on a pattern.
3. Taxonomies are created via configuration and will present some aspect of
the final page and typically a perm url.
4. All Pages are passed through a template based on their desired
layout based on numerous different elements.
5. The entire collection of files is written to disk.
NewEnglishSite creates a new site in English language. The site will have a template system loaded and ready to use. Note: This is mainly used in single site tests.
NewSite creates a new site with the given dependency configuration. The site will have a template system loaded and ready to use. Note: This is mainly used in single site tests.
NewSiteDefaultLang creates a new site in the default language. The site will have a template system loaded and ready to use. Note: This is mainly used in single site tests.
NewSiteForCfg creates a new site for the given configuration. The site will have a template system loaded and ready to use. Note: This is mainly used in single site tests.
RegisterMediaTypes will register the Site's media types in the mime package, so it will behave correctly with Hugo's built-in server.
Stats prints Hugo builds stats to the console. This is what you see after a successful hugo build.
type SiteInfo struct { Taxonomies TaxonomyList Authors AuthorList Social SiteSocial Sections Taxonomy *PageCollections Files *[]*source.File Menus *Menus Hugo *HugoInfo Title string RSSLink string Author map[string]interface{} LanguageCode string DisqusShortname string GoogleAnalytics string Copyright string LastChange time.Time Permalinks PermalinkOverrides Params map[string]interface{} BuildDrafts bool Data *map[string]interface{} Language *helpers.Language LanguagePrefix string Languages helpers.Languages // contains filtered or unexported fields }
GetPage looks up a index page of a given type in the path given. This method may support regular pages in the future, but currently it is a convenient way of getting the home page or a section from a template:
{{ with .Site.GetPage "section" "blog" }}{{ .Title }}{{ end }}
This will return nil when no page could be found.
The valid page types are: home, section, taxonomy and taxonomyTerm
HomeAbsURL is a convenience method giving the absolute URL to the home page.
Param is a convenience method to do lookups in SiteInfo's Params map.
This method is also implemented on Page and Node.
Ref will give an absolute URL to ref in the given Page.
RelRef will give an relative URL to ref in the given Page.
SitemapAbsURL is a convenience method giving the absolute URL to the sitemap.
SourceRelativeLink attempts to convert any source page relative links (like [../another.md]) into absolute links
SourceRelativeLinkFile attempts to convert any non-md source relative links (like [../another.gif]) into absolute links
SiteSocial is a place to put social details on a site level. These are the standard keys that themes will expect to have available, but can be expanded to any others on a per site basis github facebook facebook_admin twitter twitter_domain googleplus pinterest instagram youtube linkedin
type Taxonomy map[string]WeightedPages
A Taxonomy is a map of keywords to a list of pages. For example
TagTaxonomy['technology'] = WeightedPages TagTaxonomy['go'] = WeightedPages2
func (i Taxonomy) Alphabetical() OrderedTaxonomy
Alphabetical returns an ordered taxonomy sorted by key name.
func (i Taxonomy) ByCount() OrderedTaxonomy
ByCount returns an ordered taxonomy sorted by # of pages per key. If taxonomies have the same # of pages, sort them alphabetical
Count the weighted pages for the given key.
func (i Taxonomy) Get(key string) WeightedPages
Get the weighted pages for the given key.
func (i Taxonomy) TaxonomyArray() OrderedTaxonomy
TaxonomyArray returns an ordered taxonomy with a non defined order.
The TaxonomyList is a list of all taxonomies and their values e.g. List['tags'] => TagTaxonomy (from above)
func (tl TaxonomyList) String() string
Translations represent the other translations for a given page. The string here is the language code, as affected by the `post.LANG.md` filename.
type Video struct { ThumbnailLoc string Title string Description string ContentLoc string PlayerLoc string Duration string ExpirationDate string Rating string ViewCount string PublicationDate string FamilyFriendly string Restriction string GalleryLoc string Price string RequiresSubscription string Uploader string Live string }
A Video contains metadata for videos + video sitemaps
A WeightedPage is a Page with a weight.
func (w WeightedPage) String() string
type WeightedPages []WeightedPage
WeightedPages is a list of Pages with their corresponding (and relative) weight [{Weight: 30, Page: *1}, {Weight: 40, Page: *2}]
func (wp WeightedPages) Count() int
Count returns the number of pages in this weighted page set.
func (wp WeightedPages) Len() int
func (wp WeightedPages) Less(i, j int) bool
func (wp WeightedPages) Next(cur *Page) *Page
Next returns the next Page relative to the given Page in this weighted page set.
func (wp WeightedPages) Pages() Pages
Pages returns the Pages in this weighted page set.
func (wp WeightedPages) Prev(cur *Page) *Page
Prev returns the previous Page relative to the given Page in this weighted page set.
func (wp WeightedPages) Sort()
Sort stable sorts this weighted page set.
func (wp WeightedPages) Swap(i, j int)
Package hugolib imports 45 packages (graph) and is imported by 181 packages. Updated 2017-05-17. Refresh now. Tools for package owners.
|
https://godoc.org/github.com/spf13/hugo/hugolib
|
CC-MAIN-2017-22
|
refinedweb
| 3,715
| 58.89
|
Bonjour,
After updating my laptop system to the latest update (OS X 10.11.5) today, I’ve “lost” the XQuartz display … !
So I’ve decided to re-build root from scratch.
It worked without problems BUT I’m still “missing” the graphic display when I run a python script !!!
Here is the simplest example :
from ROOT import * MYS = TFile("SIGN.root") H_NbVert.Draw()
If the ultra-simple script above is called “plot.py”, then, when running it with : python -i plot.py ,
I should get the plot on a separate (XQuartz window) and then the python prompt.
Indeed, I get the python prompt BUT XQuartz is not launched and instead, a “Python” application icon appears in the Dock.
If now, I start python interactively and then type the 3 lines above one after the other :
- after
from ROOT import *, the “Python” application icon appears in the Dock
- after
H_NbVert.Draw(), the “Python” application icon is replaced by a Tree (ROOT ???) icon AND I get a graphic window with my plot !!!
Can someone tell me what to do ?
(I, of course, suspect something wrong with the graphic window assignment, but don’t know how to change this)
Thanks a lot in advance for your help !
– filip (Philippe Ghez LAPP-IN2P3-CNRS / LHCb)
|
https://root-forum.cern.ch/t/strange-behavior-of-graphic-display-with-latest-os-x/21153
|
CC-MAIN-2022-27
|
refinedweb
| 212
| 75.1
|
This post is meant for new and or aspiring data scientists trying to decide what model to use for a problem.
This post will not be going over data wrangling. Which hopefully, you know, is the majority of the work a data scientist does. I’m assuming you have some data ready, and you want to see how you can make some predictions.
Simple Models
There are many models to choose from with seemingly endless variants.
There are usually only slight alterations needed to change a regression model into a classification model and vice versa. Luckily this work has already been done for you with the standard python supervised learning packages. So you only need to select what option you want.
There are a lot of models to choose from:
- Decision trees
- Support vector machines (SVM)
- Naive Bayes
- K-Nearest Neighbors
- Neural Networks
- Gradient Boosting
- Random Forests
The list goes on and on, but consider starting with one of two.
Linear regression & Logistic regression
Photo by iMattSmart on Unsplash
Yes, fancy models like xgboost, BERT, and GPT-3 exist, but start with these two.
Note: logistic regression has an unfortunate name. The model is used for classification, but the name persists due to historical reasons.
I would suggest changing the name to something straightforward like linear classification to remove this confusion. But, I don’t have that kind of leverage in the industry yet.
Linear Regression
from sklearn.linear_model import LinearRegression import numpy as npX = np.array([[2, 3], [5, 6], [8,9], [10, 11]]) y = np.dot(X, np.array([1, 2])) + 1 reg = LinearRegression().fit(X, y) reg.score(X, y)
Logistic Regression
from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_breast_cancer X, y = load_breast_cancer(return_X_y=True) clf = LogisticRegression(solver='liblinear', random_state=10).fit(X, y) clf.score(X,y)
Why These Models?
Why should you start with these simple models? Because likely, your problem doesn’t need anything fancy.
Busting out some deep learning model and spending hundreds on AWS fees to get only a slight accuracy bump is not worth it.
Submit Guest Post Data Analytics
These two models have been studied for decades and are some of the most well-understood models in machine learning.
They are easily interpretable. Both models are linear, so their inputs translate to their output in a way that you could calculate by hand.
Save yourself some headache.
Even if you are an experienced data scientist, you should know the performance of these models on your problem, mainly because they are so effortless to implement and test.
I’ve been guilty of this. I’ve dived straight in and built complex models before. Thinking the xgboost model I’m using is overall superior, so it should be my starting model. Only to find out that a linear regression model performs with a few percentage points. And linear regression was used because it is more straightforward and more interpretable.
There is an element of ego at play here.
Photo by Sebastian Herrmann on Unsplash
You may want to show that you understand these complex models and how to use them. But they’re just sometimes not practical to set up, train and maintain. Just because a model can be used does not mean that model should be used.
Don’t waste your time. Something good enough and gets used is always better than something intricate, but no one uses or understands.
So hopefully, now you start simple and start with one of these models.
The First Question
Is my problem a classification problem or a regression problem?
Is your problem a regression problem?
Are you trying to predict a continuous output?
Linear Regression (Photo by Author)
The price of something like a house, a product, or a stock? Regression.
How long will something last, like flight duration, manufacturing time, or time a user spends on your blog? Regression.
Start with linear regression. Plot your linear regression and evaluate this model.
Save the performance here. If it is already good enough for your problem, then go with it. Otherwise, now you can start experimenting with other models.
Is your problem a classification problem?
Are you trying to predict a binary output or multiple unique and discrete outputs?
Logistic Regression (Photo by Author)
Are you trying to determine if someone will buy something from your store or win a game? Classification.
Does a yes or no answer the question you have? Classification.
Start with logistic regression, make a scatter plot of your data or a subset of it and color the classes. Maybe there is already a clear pattern.
Again, evaluate the model and use this as your baseline if you still need to improve your performance. But start here.
Conclusion
Likely, those who have read through this will find themselves in a similar situation, selecting what model to use. And then deciding your problem is perfect for this new model from a paper you read. As a result, spending hours fine-tuning this complex model only to have a more straightforward model win in the end.
Not necessarily by performance, but because precisely because they are simple and easy to interpret.
Save yourself some time and energy. Just start with linear regression and logistic regression.
|
https://www.thinkdataanalytics.com/how-to-select-an-initial-model-for-your-data-science-problem/
|
CC-MAIN-2021-49
|
refinedweb
| 874
| 58.99
|
A lot of people aren't aware that you can combine Microsoft's .NET Framework with the Linux operating system by using the Open Source mono project. This article will get you started on installing mono and running basic .NET applications on Linux.
Two of the most popular topics on Builder AU, and indeed in the wider industry, is Microsoft's .NET framework and Linux development and administration.
Most of the time the two are in conflict, and it's rare to find a developer who needs to know about both. A lot of people aren't aware that you can combine the two, however, by using the Open Source mono project. This article will get you started on installing mono and running basic .NET applications on Linux
Firstly you'll need to install the base
mono package using
apt-get. It is a good idea to install two other packages at this point:
monodevelop — an interactive mono development environment similar in some ways to Visual Studio .NET (although nowhere near as sophisticated), and
monodoc which provides help and technical documentation.
Just start up a root terminal and type:
% apt-get install mono monodevelop monodoc
When that's finished you've got a mono implementation ready to go, but while you're at it, you may as well include some of the add ons you'll need.
% apt-get install mono-utils mono-xsp monodoc-http
mono-utils provides some command line utilities that are useful if you'll be doing part of your development from the terminal.
monodoc-http provides the monodoc manuals as a Web service, which requires the
mono-xsp standalone Web server to operate. mono contains
mcs the mono C# compiler, but it only compiles .NET 1.1 code, if you want to use the features of .NET 2.0 C# (such as the extremely helpful generics) then you'll need
gmcs:
% apt-get install mono-gmcs
If you're planning to use monodevelop to write your code, then you can install a few more packages for SVN, Java, NUnit, Boo and MonoQuery support:
% apt-get install monodevelop-versioncontrol monodevelop-java monodevelop-nunit monodevelop-boo monodevelop-query
Likewise, if you're planning to use monodoc (strongly recommended) you can install manuals for whichever toolkits you'll be using:
% apt-get install monodoc-nunit-manual monodoc-ipod-manual monodoc-gtk2.0-manual
Before we get started on the code, let's take a look at some of the tools we've just installed. The monodoc browser lets you view the mono related manuals you have installed, including the useful C# language specification reference.
Or, if you'd prefer, you can read the documentation in your Web browser. The
monodoc-http program starts up an XSP server that runs locally, allowing you to connect to it in any Web browser:
You can also start up the monodevelop IDE now if you wish, although you won't need anything that powerful for the examples we'll be looking at.
Now let's check that the whole thing is working by trying out some code. Take the standard C# Hello World program:
using System; namespace Hello { class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
Compile it using
mcs and run it with the command
mono. And the result:
That works, but it's a completely trivial example, and it doesn't include the most used part of .NET: Windows Forms. Let's see if a simple Windows Forms application will work. First make sure that you've got the relevant libraries installed:
% apt-get install libmono-winforms1.0-cil libmono-winforms2.0-cil
Now the source code:
using System; using System.Windows.Forms; namespace HelloClickWorld { public class Hello : Form { public static void Main (string[] args) { Application.Run (new Hello ()); } public Hello () { Button button = new Button (); button.Text = "Click..."; button.Click += new EventHandler (Button_Click); Controls.Add (button); } private void Button_Click (object sender, EventArgs e) { MessageBox.Show ("Hello Click World!"); } } }
Compiling to assembly this time is a little more complicated, since you need to tell the C# compiler to include the library for Windows Forms:
% mcs -r:System.Windows.Forms hiclickworld.cs % mono hiclickworld.exe
Finally we need to make sure ASP.NET will work just as well. Save the following as
index.aspx:
<%@ Page void Button1_Click(object sender, EventArgs e) { Label1. <asp:Button <asp:Label </form> </body> </html>
Then start an xsp server in that directory.
Finally, point your Web browser at and check out your brand new Linux-built ASP.NET site:
If everything is working so far you've got a completely functioning mono installation, and you should be able to build applications on either Linux or Windows and deploy them on either system.
Be warned, mono is not a perfect replacement, there are parts of the .NET framework currently not implemented, particularly in the area of Windows Forms, so be very careful if you're looking to implement something complicated in mono, or migrate an existing .NET project.
|
https://www.techrepublic.com/article/gallery-installing-and-using-mono-on-ubuntu/
|
CC-MAIN-2019-18
|
refinedweb
| 834
| 54.93
|
Created on 2011-04-26.14:11:01 by geoffbache, last changed 2014-09-17.02:20:34 by zyasoft.
sys.meta_path is documented as for CPython, but it only seems to work for imports of Python modules. For example, if you run this code:
import sys
class MyFinder:
def find_module(self, name, *args):
print "Checking", name
sys.meta_path = [ MyFinder() ]
print "Importing xml.sax.handler..."
import xml.sax.handler
print "Importing javax.swing..."
import javax.swing
and note that when importing the Python module xml.sax.handler,
"find_module" gets called for every submodule as expected. When
importing javax.swing, it is called only once, on "javax", despite
"javax.swing" also being added to sys.modules. This seems to be the
case for any java package, i.e. only the top level interacts with
sys.meta_path, which as it's usually something like "org" or "com"
makes it not very useful.
This should either work (preferably) or be documented as not working.
|
http://bugs.jython.org/issue1742
|
CC-MAIN-2015-22
|
refinedweb
| 161
| 62.95
|
I want to determine the minimum bandwidth required for my J2EE Application (Struts & Hibernate) . I have deployed it in JBoss Server . I am running / accessing the application in a distributed...
Type: Posts; User: rameshiit19
I want to determine the minimum bandwidth required for my J2EE Application (Struts & Hibernate) . I have deployed it in JBoss Server . I am running / accessing the application in a distributed...
Hi,
I have hosted my J2EE application in my JBoss Server (Consider IP as , 172.20.91.64) . I am unable to hit it from a particular remote PC . When I hit ,...
I am creating a new Session in LoginAction.java while the user logs in as ,
HttpSession session = request.getSession(true);
Some values are being set in the session from my Login class as,
...
:(
I will try the same in some other PC where the firewall is not blocking it . Thanks a lot for your detailed explanations . :)
Thanks for the detailed reply.
I can access the site whatismyipaddress.com through my browser and I am unable to ping the same with the java program (PingIP) .My user account does not have...
I have tried to export my content to the text file using Jasper but only a empty text file is getting generated. All other formats such as pdf,xls,csv & rtf are getting generated properly. My code is...
I have tried pinging the Public IP , Localhost (127.0.0.1) and whats my IP Address but I am getting errors . I have added e.printStackTrace(); in catch block of the Program provided by you. I have...
Thank you for the detailed explanation .I have tried to ping my own Public IP address shown in What Is My IP Address? Lookup IP, Hide IP, Change IP, Trace IP and more... but I am getting error as...
I have referred Sourparno'd thread RMI Interface server. It was very useful . I am able to find out available sockets in same LAN but I am unable to ping the IP of remote PC , which is there in...
I meant Remote PC as PC which is in some other network. Both PCs are connected only through internet and I want to know whether it is possible to access that remote PC & make some processes / tasks...
Is it possible to access remote PC in a different network with my Java Application ? How can I achieve the same ? Please give me some suggestions.
Thanks !
Hi,
Can any one please tell me where can I get SCJP 1.6 Dumps ?? Will the dumps change year by year ?
Please help !
Thanks !!
You can remove jxl package and the associated lines because I have added those for future use to write the filetypes to excel file !
Thanks !
Hi,
I have written the following code to extract the names of directories/files & their extensions to text files.I am using it to find out the number of files/directories in my eclipse workspace...
Thanks for the reply !
I am using jboss-4.0.5 server . I have installed jdk1.6.0_22 now and my error message is getting displayed as ,
When I run my Java application (Eclipse) , I am getting error in Java Console as follows :
I tried Googling for the solution , it's mentioned like JRE Version error.
My Command prompt...
Finally I have solved it ...
I have added the following line in Java/jre6/lib/security/Java.policy , by specifying the folder where the JAR and DLL exists ...
grant codeBase "file:/C:/PATH/*"...
That was the requirement I got :( Not they have accepted in making two independent jars and is working fine . Thanks !
Sample class is simply a dependant class of SampleApplet class and returns some string from a function !
/ means that the dependant jar is in a different directory.I have read it in a forum and have implemented it here !
This is my exact problem.I have tried the same with the sample code as Posted above.
We are trying to access JNative.jar from our TestApplet.jar. We have downloaded JNative.jar form some site....
When ever I run my Applet , I am getting error as ,
SampleApplet.Jar contains,
SampleApplet.java
Manifest.MF
Sample.jar contains,
Found the bug.It's in manifest file.
Specified Class-Path: C:/Sample.jar as . It's working fine now.
Thanks !
I have modified my HTML code as follows,
<html>
<head>
<title>Sample Applet</title>
</head>
<body>
<applet name="sampleapplet" code="SampleApplet" archive="SampleApplet.jar" height="80"...
Hi,
I have created an Applet as follows and made it into a jar file (SampleApplet.jar).
import java.applet.Applet;
import java.awt.Graphics;
public class SampleApplet extends Applet
{
public...
|
http://www.javaprogrammingforums.com/search.php?s=02777deae04ac56e54f8aa21890931c4&searchid=1075596
|
CC-MAIN-2014-41
|
refinedweb
| 775
| 69.68
|
Step 3.1: Create a Jupyter Notebook and Initialize Variables
In this section, you create a Jupyter notebook in your Amazon SageMaker notebook instance and initialize variables.
To create a Jupyter notebook
Create the notebook.
Open the notebook instance, by choosing Open next to its name. The Jupyter notebook server page appears:
To create a notebook, in the Files tab, choose New, and conda_python3. This pre-installed environment includes the default Anaconda installation and Python 3.
Name the notebook.
Copy the following Python code and paste it into your notebook. Add the name of the S3 bucket that you created in Step 1: Setting Up, and run the code. The
get_execution_rolefunction retrieves the IAM role you created at the time of creating your notebook instance.
from sagemaker import get_execution_role role = get_execution_role() bucket = '
bucket-name' # Use the name of your s3 bucket here
Next Step
Step 3.2: Download, Explore, and Transform the Training Data
|
https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-prepare.html
|
CC-MAIN-2019-04
|
refinedweb
| 154
| 66.13
|
Scala vs. F#: Comparing Functional Programming Features
F# and Scala, two relatively recent programming languages, provide most .NET and Java software developers with new functional programming features that are worth understanding and evaluating. (Read a Short Briefing on Functional Programming for a primer on how functional programming works.)
Scala is a Java-based, general-purpose language that is intended to appeal to both adherents of functional programming as well as devotees of more mainstream imperative and object-oriented programming. It compiles into Java bytecode and runs on top of the Java Virtual Machine (JVM).
While Scala is fundamentally a functional language, it also embodies all the elements of imperative and object-oriented languages, which gives it the promise of introducing functional programming features to a broader programming community.
F# is a general-purpose programming language developed by Microsoft to run as part of .NET's Common Language Runtime (CLR). It is based on another, orthodox functional language, Ocaml. Microsoft introduced F# into the .NET platform because of, among other reasons, the increased interest in functional programming and functional programming's suitability to high-performance computing and parallelism.
Although its syntax is distinctly functional, F# actually is a hybrid functional/imperative/object-oriented language. Its object-oriented and imperative features are present mostly for compatibility with the .NET platform, but F#'s tripartite nature is also pragmatic -- it allows programmers who use any or all of the three programming paradigms to program exclusively in one or to combine all three.
In this article, I will compare and contrast the functional features and related syntax of F# and Scala.
F# vs. Scala: First Order Functions
Functions in F# and Scala are treated as first order types. They can be passed in as arguments, returned from other functions, or assigned to a variable.
In this F# code snippet, I first define a function (
increment) that adds 1 to a passed value, and then I define the function
handler, which takes type
myfunc and applies 2 to it as a parameter. Finally, I invoke the function handler with a parameter incremented to it. The function
incrementis passed as a regular value, hence the function is being treated as a first order type:
let increment x = x + 1 let handler myfunc = (myfunc 2) printfn "%A" (handler increment)
Notice the type inference in the example above. F# will infer that
x is an integer because I add 1 to it, and so
x will be treated as an integer
(Int) type.
Here is the same example in Scala:
def increment(x:Int) = x + 1 def handler( f:Int => Int) = f(2) println( handler( increment ))
Currying is an essential feature of functional programming that allows for the partial application of functions and functional composition. F# supports currying. Here is an example of the curried function
add in F#:
Declaration:
val add : int -> int -> int
Implementation:
let add = (fun x -> (fun y -> x + y) )
In Scala, the curried function
add looks like this:
def add(x:Int)(y:Int) = x + y
F# vs. Scala: Lambda Expressions
F# also supports Lambda expressions (anonymous functions). In F#, lambda expressions are declared with the keyword
fun. In the example below (adopted from F# documentation), an anonymous function is applied to a list of numbers to increment each number in the list and return a new, incremented list:
let list = List.map (fun i -> i + 1) [1;2;3] printfn "%A" list
Lambda expressions in Scala are defined in a very succinct fashion. This is how you would increment a function with a Lambda expression (
x=>x+1) on a list of numbers (1,2,3) in Scala:
val list = List(1,2,3).map( x => x + 1 ) println( list )
F# vs. Scala: Pattern Matching
Pattern matching is a powerful feature of functional programming languages that allows blocks of code within the function to be 'activated' depending on the type of a value or an expression. (Think of pattern matching as a more powerful variation of the
case statement.)
In F# , the vertical line character (
|) is used to denote a case selector for the function match specification. Here is an F# version of a pattern-matched Fibonacci number function:
let rec fib n = match n with | 0 -> 0 | 1 -> 1 | 2 -> 1 | n -> fib (n - 2) + fib (n - 1)
Like F#, Scala supports pattern matching on functions. Here is the example of a Fibonacci number calculation in Scala. Notice that Scala uses the keyword
case:
def fib( n: Int): Int = n match { case 0 => 0 case 1 => 1 case _ => fib( n -1) + fib( n-2) }
Page 1 of 2
|
http://www.developer.com/lang/other/article.php/3883051/Scala-vs-F-Comparing-Functional-Programming-Features.htm
|
CC-MAIN-2014-10
|
refinedweb
| 768
| 50.77
|
What is encapsulation and what's the point of it? We'll take a look at the meaning and benefits of encapsulation in this tutorial. We'll also see an example of encapsulation in the real world by looking at the API document for the String class. In this tutorial we'll build on the previous tutorial on the public, private and protected keywords to look at why and when you actually use these keywords for best programming practice.
When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.
Code for this tutorial:
App.java:
class Plant { // Usually only static final members are public public static final int ID = 7; // Instance variables should be declared private, // or at least protected. private String name; // Only methods intended for use outside the class // should be public. These methods should be documented // carefully if you distribute your code. public String getData() { String data = "some stuff" + calculateGrowthForecast(); return data; } // Methods only used the the class itself should // be private or protected. private int calculateGrowthForecast() { return 9; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class App { public static void main(String[] args) { } }
|
https://caveofprogramming.com/java-video/java-for-complete-beginners-video-part-27-encapsulation-api-docs.html
|
CC-MAIN-2018-09
|
refinedweb
| 204
| 55.03
|
Hi
Bellow is an example of my help system im working on:-
My question is the couts..Do they take up any cycles?
e.g
cout << "...........\n";
cout << "...........\n";
can also be written as:
cout << ".........\n" << ".........\n";
is the second one more efficent becuase it states less couts?
Thank You For Your Help
Alex
Code://C++ Help System Project #include <iostream> using namespace std; int main () { char choice; for(;;) { do { cout << "Help On: \n"; cout << " 1. if\n"; cout << " 2. switch\n"; cout << " 3. for\n"; cout << " 4. while\n"; cout << " 5. do=while\n"; cout << " 6. break\n"; cout << " 7. continue\n"; cout << " 8. goto\n"; cout << "===================\n"; cout << "Choose One (q to quit): "; cin >> choice; } while( choice < '1' || choice > '8' && choice != 'q'); if(choice == 'q') break;
|
http://cboard.cprogramming.com/cplusplus-programming/64046-cout-question.html
|
CC-MAIN-2014-10
|
refinedweb
| 128
| 96.99
|
Calling java method in BPEL assign stepKarthikeyan RS Feb 24, 2012 7:14 AM
I need your valuable support for the below issues. Kindly provide any possible solution
My queries :
We have used JCAPS and developed bpel2.0 processes.Now we need to convert those into JBoss bpel using this JBDStudio.
I am facing below issues while converting,
- ) We Used the xmlns:sxxf= reff imported in my bpel:process and we called the below functions in my copy assign
<bpel:copy>
<bpel:from> sxxf:current-dateTime()</bpel:from>
<bpel:to
<bpel:query<![CDATA[tns:result]]></bpel:query>
</bpel:to>
</bpel:copy>
But in JBDStudio I am getting the Unknown function "sxxf:current-dateTime" used in <bpel:from>
- ) I have a java class as a jar and placed in the D:\Jboss\jboss-soa-p-5\jboss-as\server\default\lib in my server location.
Now I am trying to call the one method which is there in the java class like below,
<bpel:copy xmlns:
<bpel:from>addQuery:display()</bpel:from>
<bpel:to
<bpel:query<![CDATA[tns:result]]></bpel:query>
</bpel:to>
</bpel:copy>
Same error I am getting in design time. While run time I am getting error below,
17:10:31,583 INFO [ASSIGN] Assignment Fault: {}selectionFailure,lineNo=78,faultExplanation=An exception occured while evaluating "{OXPath10Expression addQuery:display()}": No Such Function display
But the above two things are working well in the JCAPS and glassfish server.
Please provide the possible solutions , how can I achieve in the JBoss riftsaw. I am using JBoss SOA 5 platform as server.
1. Re: Calling java method in BPEL assign stepJeff Yu Feb 24, 2012 8:24 AM (in response to Karthikeyan RS)
Hi,
For the 1st question, this thread () might be of your interest.
In terms of invoking a java class from RiftSaw, I don't think it is doable right now. Why not expose that java class as JAX-WS web service, and then invoke it via web service way.
Hope It Helps.
Jeff
2. Re: Calling java method in BPEL assign stepJeff Yu Feb 24, 2012 8:26 AM (in response to Jeff Yu)
Just to let you know, the above two (your original version) are the SUNExtension, so it is not in the BPEL 2.0 spec. Therefore, they are vendor specific.
Regards
Jeff
3. Re: Calling java method in BPEL assign stepKarthikeyan RS Feb 26, 2012 10:55 PM (in response to Jeff Yu)
Thanks Jeff.
So suppose if i use my custion class and invoking any method inside the class how should i need to do? Where should place my classes in server path location?
Whethere should need make it as a java class jar or in any other way?
We can expose the java class as a webservice, but as per my requirent i can use only java code only.Once its working than i will update the same to my peers.
Kindly help me.
Regards,
karthick
4. Re: Calling java method in BPEL assign stepKarthikeyan RS Feb 26, 2012 10:58 PM (in response to Jeff Yu)
Again Thanks Jeff,
Your correct thats SUNExtension only.So where can i find the same functionality in Apache ODE or in RiftSaw.
Kindly provide the extension.
Regards,
Karthick
5. Re: Calling java method in BPEL assign stepJeff Yu Feb 26, 2012 11:53 PM (in response to Karthikeyan RS)
Hi Karthick,
This link might be of your interest..
You also can look up the thread on the ode user mailing list: such as:
Regards
Jeff
6. Re: Calling java method in BPEL assign stepKarthikeyan RS Feb 27, 2012 2:14 AM (in response to Jeff Yu)
Hi Jeff,
Thanks for your support.
I have used the same but when invoke the service using SOAP UI Tool i am getting the below error message,
12:07:53,185 INFO [STDOUT] Retrieving document at 'file:/D:/Jboss/jboss-soa-p-5/jboss-as/server/default/deploy/EMP_Java_Process-20120227120745.jar/empjavaprocessArtifacts.wsdl'.
12:07:53,340 INFO [WatchDog] [Endpoint files for {DeploymentUnit EMP_Java_Process-20120227120745}] updated
12:07:55,336 INFO [ASSIGN] Assignment Fault: {}selectionFailure,lineNo=78,faultExplanation=An exception occured while evaluating "{OXPath10Expression ext:display()}": Error while executing an XPath expression: net.sf.saxon.trans.XPathException: XPath syntax error at char 13 in {ext:display()}:
Cannot find a matching 0-argument function named {java:com.example.xpath.Random}display()
My Java Class is
public class TstEmpJavaClass {
public static void display(){
System.out.println("This is Process");
}
public static void main(String arg[]){
}
}
I have created jar and placed in the following location - D:\Jboss\jboss-soa-p-5\jboss-as\server\default\lib
My process step code is below,
<bpel:sequence
<!-- Receive input from requester.
Note: This maps to operation defined in empjavaprocess.wsdl
-->
<bpel:receive
<!-- Generate reply to synchronous request -->
<bpel:assign
<bpel:copy xmlns:
<bpel:fromext:display()</bpel:from>
<bpel:to
<bpel:query<![CDATA[tns:input]]></bpel:query>
</bpel:to>
</bpel:copy>
</bpel:assign>
<bpel:reply
</bpel:sequence>
Regards,
Karthick.
|
https://developer.jboss.org/message/719765
|
CC-MAIN-2019-26
|
refinedweb
| 832
| 54.42
|
Why would anyone want to do this with a language like Python?
Fortunately this is not a question I’ve had to ask myself since the answer seems pretty obvious to me. But basically that’s what this article is all about. Over the next few pages we’ll be looking at some of the different places you could use Python to automate and generally play with your images.
You will need to have at least basic knowledge of these subjects, so if you’re new to Python you should probably read Vikram Vaswani’s “Python 101″ first and come back later!
Essentially when you do anything to an image what you’re actually doing is writing/moving bytes around. You can do this manually, but when you have an excellent third party module like PIL (Python Imaging Library), why bother?
So let’s add a little extra image processing power to Python! You can get the latest version of PIL from
Windows users should download the windows installer (.exe). Those installing PIL from source should probably take a look through “Installing Python Modules” in the Python docs, if only out of interest.
On to the Fun Stuff
Ok, now that we have the “basics” out of the way, it’s time for the fun stuff! Something like converting a JPEG image to a GIF maybe. In most cases all you should have to do is open the image and save it with a different file extension and PIL will do the rest!
[code]
>>> import Image
>>> image = Image.open('sample.jpg')
>>> image.save('sample.gif')
>>>
[/code]
If this didn’t work for you, don’t worry; chances are all you have to do is add another line before saving.
[code]
>>> import Image
>>> image = Image.open('sample.jpg')
>>> image.convert('RGB')
>>> image.save('sample.gif')
>>>
[/code]
{mospagebreak title=Batch Processing}
Who ever said programming had to be hard work? With a little help from the OS module we can turn this into a nice piece of batch processing!
[code]
#!/usr/bin/env python
import os, Image
def convert(path, format):
for each in os.listdir(path):
if each.endswith(format[0]):
try:
name = os.path.join(path, each)
save = os.path.splitext(name)
Image.open(name).save(save[0] + format[1])
except IOError: None
if __name__ == '__main__':
convert('', ('.jpg', '.gif'))
[/code]
Ok, possibly a little scary at first glance but all this actually does is read a list of names from a given directory and loops over them performing some action. convert() just checks if ‘each’ ends with the extension we want before joining ‘path’ and ‘each’ together and splitting the extension from end. It then attempts to convert the image using PIL.
And no, you’re not limited to converting images between formats, or PIL would be pretty useless wouldn’t it! Actually one of the things I like most about PIL is that it hides a lot of the complexities that pop up when you’re working with images. That said let’s have a look at some of the other things we can do!
[code]
>>> import Image
>>> image = Image.open('sample.jpg')
>>> image.size
(200, 200)
>>> image.format
'JPEG'
>>> image.mode
'RGB'
>>> image.show()
>>> image.resize((100, 100))
>>> image.show()
>>> image.crop((0, 0, 50, 50))
>>> image.show()
>>> image.rotate(180)
>>> image.show()
>>>
[/code]
This shows off some nice features i.e. retrieving the image size, actual format, resizing, etc. The next part (after image.mode) does the actual work: resizing, cropping and rotating the image.
{mospagebreak title=Image.Show}
You’re probably wondering what all the image.show() calls are about; show() just creates a temporary image and opens it. This way we can see what’s happening to our image step by step!
Anyway let’s just slip off topic for a second here and imagine that you’re in charge of some online art gallery/community where members can upload images and have them displayed for the world to see. As part of the site’s design every image has a square thumbnail that links to the full-sized image.
We can think of this as a few steps:
- Cropping our image so we end up with a square.
- Resizing (100 x 100) and saving our thumbnail.
[code]
#!/usr/bin/env python
import Image
def thumb(image):
size = list(image.size)
size.sort()
image = image.crop((0, 0, size[0], size[0]))
image = image.resize((100, 100), Image.ANTIALIAS)
return image
if __name__ == '__main__':
image = Image.open('sample1.jpg')
image = thumb(image)
image.save('sample2.jpg')
[/code]
This really just defines a new user function named thumb() which we can then use to create our thumbnails! It starts by converting the images size to a list and sorting it in place so we have the smallest dimension at the beginning of the list (this value is then used while cropping our image). The next part then crops and resizes our image using the ANTIALIAS filter (better quality) before returning the new image.
Watermarking
Next up we’re going to do some watermarking and paste a smaller graphic onto our image. Which as far as I know makes this the only example of watermarking with PIL, even though once again this is incredibly easy!
[code]
#!/usr/bin/env python
def watermark(image, thumb):
imageX, imageY = image.size
thumbX, thumbY = thumb.size
if thumbX < imageX and thumbY < imageY:
point1 = imageX - (thumbX + 10)
point2 = imageY - (thumbY + 10)
point3 = imageX - 10
point4 = imageY - 10
image.paste(thumb, (point1, point2, point3, point4))
if __name__ == '__main__':
import Image
image = Image.open('sample.jpg')
thumb = Image.open('thumb.jpg')
watermark(image, thumb)
image.show()
[/code]
Quite proud of this for some reason; maybe because I’ve finally got my head around placing things where I want them on an image. Anyway what it is actually saying is that if ‘thumb’ is smaller than our image, then put it 10 pixels in from the bottom right hand corner of ‘image’ (since it would look pretty messed up in most cases otherwise).
{mospagebreak title=Lock It Down}
Last but not least: You may or may not have noticed those funky little images some websites use to stop automated signups and etc. No? Never mind if you haven’t because that’s what we’re about to do.
[code]
#!/usr/bin/env python
import Image, ImageDraw, ImageFont, random
def sample():
ascii = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
return ''.join(random.sample(ascii, 5))
def verify():
image = Image.new('RGB', (125, 40), (255, 255, 255))
font = ImageFont.truetype('Verdana.ttf', 25)
draw = ImageDraw.Draw(image)
draw.text((5, 5), sample(), font = font, fill = (0, 0, 0))
image.save('verify.gif')
if __name__ == '__main__': verify()
[/code]
There are a few differences between this example and the others we’ve talked about so far. Primarily the three modules ImageDraw, ImageFont and random and the two functions sample() and verify().
Why have two functions? We could have just as easily done this inside verify couldn’t we?
The thing is, sooner or later everyone ends up rewriting something they wrote for some other project. One of the nice things about using Python is it encourages you to write clean, reusable, modular code. Which is of course the main reason for the sample() function; since it just returns a string of random letters you could also use it to automate password generation!
Short and sweet, all sample() does is pick five letters at random from the string ‘ascii’ using random.sample() and returns them as a string.
verify() on the other hand has a little more going for it. This one unlike any of the other examples we’ve looked at starts off by creating a brand spanking new image instead of opening one! We’re going to write our random letters onto this in a second, but first we need to load the font we want to use, for this we’re using the ImageFont module. We then create a new instance of ImageDraw.Draw() which is used to draw the sample() string on the image!
Anyway it’s pretty safe to assume you have a good idea why this could be useful by now. You should also know enough to get started using PIL with your own images. Slap open up your Python shell and get playing!
Liked this article? Then you’ll probably find these links interesting too!
Python homepage
Python tutorial
Installing Python modules
PIL homepage
PIL tutorial
PIL documentation
Note: All the sample programs shown and discussed in this article where tested on Windows XP running Python 2.3 with PIL 1.4 and are meant only as examples.
|
http://www.devshed.com/c/a/Python/Imagine-Python/
|
CC-MAIN-2014-52
|
refinedweb
| 1,439
| 66.03
|
| Join
Last post 07-06-2008 1:56 AM by Paul Linton. 3 replies.
Sort Posts:
Oldest to newest
Newest to oldest?
Well See the example below. Key is that you have to have an IEqualityComparer implemented
1 static void Main(string[] args)
2 {
3
4 List A = new List { new Test { ID = 1, Name = "John" }, new Test { ID = 2, Name = "Mary" },
5 new Test { ID = 3, Name = "Andrew" },new Test {ID=4,Name="Peter"} };
6 List B = new List { new Test { ID = 1, Name = "John" }, new Test { ID = 21, Name = "Robert" },
7 new Test { ID = 9, Name = "Angela" },new Test {ID=3,Name="Andrew"} };
8
9 var ItemsinAThatDoNotExistinB = A.Except(B,new TestComparer()).ToList();
10 }
11
12 public class TestComparer : IEqualityComparer
13 {
14 #region IEqualityComparer Members
15
16 public bool Equals(Test x, Test y)
17 {
18 if (x.Equals(y))
19 {
20 return true;
21 }
22 else
23 {
24 return false;
25 }
26 }
27
28 public int GetHashCode(Test obj)
29 {
30 return obj.ToString().ToLower().GetHashCode();
31
32 }
33
34 #endregion
35 }
36 public class Test:IEquatable
37 {
38 public int? ID {get;set;}
39 public string Name { get; set; }
40
41 #region IEquatable Members
42
43
44
45 public bool Equals(Test other)
46 {
47 if (this.ID == other.ID && this.Name.Equals(other.Name))
48 {
49 return true;
50 }
51 else
52 {
53 return false;
54 }
55 }
56
57 #endregion
58
59
60 }
Assuming you have a suitable equality comparer, or have implemented IEquatable<T>, you can use the Except and Concat methods:
Try this
// You must have some class like this already
public class Info {
public int? ID {get; set;}
public string Name {get; set;}
}
// Load some data so I can test
List<Info> A = new List<Info> { new Info { Name = "John" }, new Info { Name = "Mary" }, new Info { Name = "Peter" } };
List<Info> B = new List<Info> { new Info { ID = 1, Name = "John" }, new Info { ID = 2, Name = "Robert" }, new Info { ID = 3, Name = "Angela" }, new Info { ID = 4, Name = "Andrew" } };
// Make List C
List<Info> C = A.Select(a => new { Name = a.Name }).Except(B.Select(b => new { Name = b.Name })).Select(c => new Info { ID = GetID(c.Name), Name = c.Name }).ToList();
// Append C to B
B = B.Union(C).ToList();
To create list C you need to make an IEnumerable with just the Name field, this is what the Select(a=> new {Name = a.Name}) does. The Except query operator is one way to do the 'not equals' join. Then create a new IEnumerable<Info> using GetID and the Names.
Appending C to B is just the Union query operator.
Hope this helps
Advertise |
Ads by BanManPro |
Running IIS7
Trademarks |
Privacy Statement
© 2009 Microsoft Corporation.
|
http://forums.asp.net/p/1285223/2467709.aspx
|
crawl-002
|
refinedweb
| 453
| 68.1
|
ECMASCRIPT 2015 or ES6 has introduced many changes to JavaScript. JavaScript ES6 has introduced new syntax and new awesome features to make your code more modern and more readable.
Originally published by Adesh at zeptobook.comWhat is ES6?
ECMASCRIPT 2015 or ES6 has introduced many changes to JavaScript. JavaScript ES6 has introduced new syntax and new awesome features to make your code more modern and more readable.
ES6 introduced many great features like arrow functions, template strings, class destructions, modules… and many more.
Let’s dive into more reasons of its popularities.Reason 1: You can write it now for all Browsers.
ES6 is now supported in all major browsers. Here is the list of Browsers support for ES6.
Photo Courtesy: W3Schools.comReason 2: Full Backward Browser Compatible
It has support for backward compatible version of JavaScript in current and older browsers or environments. JavaScript being a rich ecosystem, has hundreds of packages on the package manager (NPM), and it has been adopted worldwide. To make sure ES5 JavaScript packages should always work in the presence of ES6, they decided to make it 100% backward compatible.
This has one major benefit. You can start writing ES6 along with your existing JavaScript ES5. This also help you to start slowly embracing new features and adopting the aspects of ES6, which can make your life easier as a programmer.
To support full backward browser compatibility, here is a very cool project called Babel.
Babel is a JavaScript Transpiler that converts edge JavaScript into plain old ES5 JavaScript that can run in any browser. For more details about Babel, please click the below links.
Babel Usage Guide. How to setup Babel?Reason 3: ES6 is faster in some cases.
I am going to share one performance benchmark for ES6. ES6 performed more better or even hit the performance benchmark for the same function written in ES5. You can visit this link as well to check the ES6 performance benchmark.
Performance of ES6 features relative to the ES5 baseline operations per secondReason 4: Doing more with writing less code
As said above, now you can do lot more with writing less code in your ES6. You can write more cleaner and concise code in ES6. Here is few examples of code syntax of ES6.
No need to write function and return keywords anymore. This is one of the more awesome feature of ES6, makes your code looks more readable, more structured, and looks like modern code. You don’t need to write old syntax anymore.
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.
One of the benefit of arrow function is to have either concise body or the usual block body.
In a concise body, only an expression is mentioned in a single line with the implicit return value. In a block body, you must use explicit return keyword, normally with curly braces { return .. }.
var func = x => x * x; // concise body with implicit return keyword
var func = (x, y) => { return x + y; };
// block body with explicit return keyword
ES6 will throw an error if there is an improper line break in arrow function. Ideally, it should be single line statement. If you want to use it as multi line statement, use the proper curly braces or brackets.
var func = (a, b, c)
=> 1;
// Throw syntax error
//Use Proper syntax
var func = (
a,
b,
c
) => (
1
);
// no SyntaxError thrown
//ES6
odds = evens.map(v => v + 1)
//ES5
odds = evens.map(function (v) { return v + 1; });
Simple and smart way of passing default values of function parameters. Now, functions can be defined with default parameters values. If you miss to pass the function parameter, then missing or undefined values will be initialized with default parameters.
Default parameter will prevent you from getting the undefined error. If you forget to write the parameter, it won’t return the undefined error, because the parameter is already defined in the function parameter.
//ES6
function f (a, b = 10, c = 20) {
return x + y + z
}
f(5) === 35
//ES5
function f (a, b, c) {
if (b === undefined)
y = 10;
if (c === undefined)
c = 20;
return x + y + z;
};
f(1) === 35;
Easy way to pass rest parameters with three dots (…) with parameter name. With the help of rest parameter, you can pass an indefinite number of arguments as an array.
A function last parameter prefixed with ... which will cause all remaining arguments to be placed within a standard JavaScript array.
Only a last parameter can be a rest parameter.
One of the major difference between argument object and rest parameter is that, rest parameter are like real array instance, where argument object are not like a real array. This means that, you can apply array methods like sort, map, forEach or pop on it directly.
//ES6
function f (a, b, ...z) {
return (a + b) * z.length
}
f(10, 20, "ZeptoBook", true, 5) === 25
//ES5
function f (a, b) {
var z = Array.prototype.slice.call(arguments, 2);
return (a + b) * z.length;
};
f(10, 20, "ZeptoBook", true, 5) === 25
Concatenating the string in a more cleaner way. Template literals are string literals, which allow concatenated expression. String interpolation is one of the interesting feature of ES6. Prior to ES6, we use double or single quotes to concatenate string expression, which sometimes looks very weird and buggy.
Now, in ES6, template literals are enclosed by back-ticks () character instead of single or double quotes. You can find back-ticks at the top left of your keyboard under the esc key.
Template literals has placeholders with $ sign and curly braces like ${expression}. $ sign is mandatory for interpolation.
//ES6
var product = { quantity: 20, name: "Macbook", unitprice: 1000 }
var message =
I want to buy ${product.name}, for a total of ${product.unitprice * product.quantity} bucks?
//ES5
var product = { quantity: 20, name: "Macbook", unitprice: 1000 }
var message = "I want to buy " + product.name + ",\n" +
"for a total of " + (product.unitprice * product.quantity) + " bucks?";
Shorter syntax for defining object properties. Prior to ES6, every object property needs to be either getter-setter or key-value pair. This has been completely changed in ES6. In ES6, there is a concise way for defining the object properties. You can define complex object properties in a much cleaner way now.
//ES6
var x = 0, y = 0
obj = { x, y }
//ES5
var x = 0, y = 0;
obj = { x: x, y: y };
Support for method notation in object properties definitions. In the same way, which we discussed above, we can now define object methods concisely and in a much cleaner way.
//ES6Reason 5: New Built-In Methods In ES6
obj = {
add (a, b) {
…
},
multi (x, y) {
…
},
}
//ES5
obj = {
add: function (a, b) {
…
},
multi: function (x, y) {
…
},
};
There is a new function to assign enumerable properties of one or more source objects into a destination object.//ES6
var dest = { quux: 0 }
var src1 = { foo: 1, bar: 2 }
var src2 = { foo: 3, baz: 4 }
Object.assign(dest, src1, src2)
dest.quux === 0
dest.foo === 3
dest.bar === 2
dest.baz === 4
//ES5
var dest = { quux: 0 };
var src1 = { foo: 1, bar: 2 };
var src2 = { foo: 3, baz: 4 };
Object.keys(src1).forEach(function(k) {
dest[k] = src1[k];
});
Object.keys(src2).forEach(function(k) {
dest[k] = src2[k];
});
dest.quux === 0;
dest.foo === 3;
dest.bar === 2;
dest.baz === 4;
There is a new function to find an element in an array.
//ES6
[ 10, 30, 40, 20 ].find(x => x > 30) // 40
[ 10, 30, 40, 20 ].findIndex(x => x > 30) // 20
//ES5
[ 10, 30, 40, 20 ].filter(function (x) { return x > 30; })[0]; // 40
// no such function in ES5
There is a new string repeating functionality as well.
//ES6
" ".repeat(5 * depth)
"bar".repeat(3)
//ES5
Array((5 * depth) + 1).join(" ");
Array(3 + 1).join("bar");
New string functions to search for a sub-string
//ES6
"zepto".startsWith("epto", 1) // true
"zepto".endsWith("zept", 4) // true
"zepto".includes("zep") // true
"zepto".includes("zep", 1) // true
"zepto".includes("zep", 2) // false
//ES5
"zepto".indexOf("epto") === 1; // true
"zepto".indexOf("zept") === (4 - "zept".length); // true
"zepto".indexOf("ept") !== -1; // true
"zepto".indexOf("ept", 1) !== -1; // true
"zepto".indexOf("ept", 2) !== -1; // false
There are new functions for checking non-numbers and finite numbers.
//ES6
Number.isNaN(50) === false
Number.isNaN(NaN) === true
Number.isFinite(Infinity) === false
Number.isFinite(-Infinity) === false
Number.isFinite(NaN) === false
Number.isFinite(50) === true
//ES5
var isNaN = function (n) {
return n !== n;
};
var isFinite = function (v) {
return (typeof v === "number" && !isNaN(v) && v !== Infinity && v !== -Infinity);
};
isNaN(50) === false;
isNaN(NaN) === true;
isFinite(Infinity) === false;
isFinite(-Infinity) === false;
isFinite(NaN) === false;
isFinite(50) === true;
There is an in-built function to check whether an integer number is in the safe range.
//ES6
Number.isSafeInteger(50) === true
Number.isSafeInteger(1208976886688) === false
//ES5
function isSafeInteger (n) {
return (
typeof n === 'number'
&& Math.round(n) === n
&& -(Math.pow(2, 53) - 1) <= n
&& n <= (Math.pow(2, 53) - 1)
);
}
isSafeInteger(50) === true;
isSafeInteger(1208976886688) === false;
There is a mathematical function to truncate a floating number to its integral parts, completely dropping the fractional part.
//ES6Summary
console.log(Math.trunc(12.7)) // 12
console.log(Math.trunc(0.4)) // 0
console.log(Math.trunc(-0.4)) // -0
//ES5
function mathTrunc (x) {
return (x < 0 ? Math.ceil(x) : Math.floor(x));
}
console.log(mathTrunc(12.7)) // 12
console.log(mathTrunc(0.4)) // 0
console.log(mathTrunc(-0.4)) // -0
Javascript surely isn’t a perfect language. It has various imperfections. In the course of recent years, developers have gotten increasingly more involvement with the JavaScript ES5, which has lead to enhancements. ES6 brings many engrossing features that were not seen in previous version like ES5.
Originally published by Adesh at zeptobook.com
===========================================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | TwitterLearn More!
|
https://morioh.com/p/y7BwGAvnzblM
|
CC-MAIN-2020-05
|
refinedweb
| 1,652
| 68.57
|
Hi Team,
For this digit_sum task I have written below code and which giving me correct ouput but not sure why in codecademy console at bottom a message is coming and the course is not progressing.The NEXT button is in disabled state.
“Did you create a function called digit_sum? Your code threw a “global name ‘digit_sum’ is not defined” error.”
My code
def digit_sum(n): num_string = str(n) #list_a = [num_string] list_b = [] for i in range(0,len(num_string),1): x=[num_string[i:i+1]] list_b = list_b + x print list_b Total = 0 pos = 0 l = len(list_b) while (pos < l): Total = Total + int(list_b[pos]) pos += 1 print "Total addition: ",Total value= int(raw_input(">: ")) print value digit_sum(value)
|
https://discuss.codecademy.com/t/digit-sum/285170
|
CC-MAIN-2018-51
|
refinedweb
| 118
| 67.69
|
1. I have a schema that starts like:
2. I have an instance document that starts like:
Code: Select all
<xs:schema
3. I have a catalog that starts like:
Code: Select all
<something xmlns="">
4. oXygen sees the namespace declaration in the instance document, looks in the catalog and finds out the location of the local copy of the schema for that namespace, and uses it to validate the instance document.
Code: Select all
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system">
<uri name="" uri="schemas/something.xsd"/>
Note that I do not have the xsi:schemaLocation attributes in the instance document. I strongly prefer to omit those, and have validation triggered in the way I have described.
If this is not possible with oXygen out of the box, would it be possible for me to make oXygen use a different parser implementation that would be able to do this? Norm Walsh has a new version of the xml resolver code in the works, and I've been able to get it to work in this fashion. The only additional requirement is to "decorate" the catalog like this:
I like that a lot better than having to pollute my instance documents with all that xsi:schemaLocation stuff that is just intended to "fake out" the parser.
Code: Select all
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" xmlns:
<uri r:nature=""
r:
Would oXygen pay attention to the settings of these properties:
? If so, it might be possible to swap in the new xml resolver stuff and get this kind of validation to work. Or is there a simpler way to accomplish this without such tweaking?
Code: Select all
javax.xml.parsers.SAXParserFactory
javax.xml.stream.XMLInputFactory
javax.xml.parsers.DocumentBuilderFactory
Thanks!
|
https://www.oxygenxml.com/forum/post16562.html
|
CC-MAIN-2020-24
|
refinedweb
| 299
| 60.75
|
GIS Library - Date functions. More...
#include <time.h>
#include <grass/gis.h>
Go to the source code of this file.
GIS Library - Date functions.
(C) 2001-2008 by the GRASS Development Team
This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
Definition in file date.c.
Current date and time.
Returns a pointer to a string which is the current date and time. The format is the same as that produced by the UNIX date command.
Definition at line 30 of file date.c.
References localtime().
Referenced by E_edit_history(), G_short_history(), Vect__init_head(), and Vect_hist_command().
|
https://grass.osgeo.org/programming6/date_8c.html
|
CC-MAIN-2018-43
|
refinedweb
| 106
| 71.51
|
Introduction to Scala Interview Questions And Answers
Scala is a general-purpose programing language providing support for functional programming and a strong static type system. I was designed by Martin Ordersky and it has first appeared on 20 January 2004. The file extension is scala or .sc. Scala combines object-oriented and functional programming in one concise, high-level language. Scala’s static types help avoids bugs in complex applications, and its JVM and JavaScript runtimes let you build high-performance systems with easy access to huge ecosystems of libraries. It runs on Java platforms.
Example:
Hello, world program In Scala will be written like this:
Program:
object HelloWorld extends App {
println(“Hello, World!”)
}
For Compiling: scalac HelloWorld.scala
Running: scala HelloWorld
So if you are looking for a job that is related to Scala, you need to prepare for the Scala Interview Questions. Though every Scala interview is different and the scope of a job is also different, we can help you out with the top Scala Interview Questions and Answers, which will help you to take the leap and get you success in an interviews
Below is the Scala Interview Questions that are mostly asked in an interview these questions are divided into two parts:
Part 1 – Scala Interview Questions (Basic)
This first part covers basic Scala Interview Questions and Answers
1. What is Scala?
Answer:
Scala stands for Scalable Language. It is a multi-paradigm programming language. It supports both Object-oriented and functional programming language. Its runs for JVM(Java Virtual Machine).
4.5 (2,397 ratings)
View Course
2. What are the major advantages of Scala?
Answer:
The major advantages of Scala language are: Very precise code, flexible syntax, Supports all OOP features, More reusable code, highly productive.
3. Give some examples of JVM Language?
Answer:
Java, Scala, Groovy, and closure are very popular for JVM language.
4. What is the superclass of all classes in Scala?
Answer:
“Any” class is the superclass of all classes in Scala.
5. What is the Default access modifier in Scala?
Answer:
“Public” is the default access modifier in Scala.
6. What is similar between Scala Int and Java’s java.lang.integer?
Answer:
Both are used to define Integers, both are classes and both are 32-bit signed integer.
7. What is Null in Scala?
Answer:
Null is a Type in Scala. It is available in Scala package as “scala. Null”.
Let us move to the next Scala Interview Questions And Answer.
8. What is Unit in Scala?
Answer:
In Scala, a unit is used to represent “No value” or “No Useful value”. In the package, it is defined as “scala. Unit”.
9. What is the val and var in scala?
Answer:
Var is standing for variable and Val is standing for value. Var is used to define Mutable variable and value can be reassigned after the creation of it. Val is used to defining Immutable variables which means the value cannot be reassigned once it’s created.
10. What is REPL in Scala?
Answer:
REPL stands for reading Evaluate Print Loop. Generally, we called it “Ripple”. It is an interpreter to execute scala code from the command prompt.
11. What is Scala “If..else”?
Answer:
Scala “If. Else” is an expression. We can be assigned it to a variable. For EG:
val year = if( count == 0) 2014 else 2015
12. What do you mean by Scala Map?
Answer:
This is the basic Scala Interview Questions which is asked in an interview. Scala map is a collection of key-value pair wherein the value in a map retrieved using a key. Values in a map are not unique but keys are unique.
There are two types of maps: Mutable and Immutable.
13. What do you understand by a closure in Scala?
Answer:
The closure is the function in scale where the returned value of the function depends on the one or more than one variable which is defined outside the function.
Part 2 – scala Interview Questions (Advanced)
Let us now have a look at the advanced scala Interview Questions.
14. What do you mean by Option in Scala?
Answer:
It is used for wrapping the missing value.
15. What is Scala Trait?
Answer:
It’s a special kind of which enables the Multiple Inheritance. For Eg:
trait MyTrait {
deff()
}
16. Give some example of packages in Scala.
Answer:
lang, scala, scala.PreDef is the packages in Scala.
Let us move to the next Scala Interview Questions And Answer.
17. What is the use of tuples in Scala?
Answer:
Scala tuple is used to combine the fixed number of the item together. Nature vice the tuple are immutable and can hold objects with the different type. For Eg: Val myTuple = (1, “element”, 10.2)
18. What is the Monad in Scala?
Answer:
A Monad is an object in Scala which wraps another object.
19. In Scala how you will format a string?
Answer:
By the following way:
Val formatted= “%s %i”.format (mystring.myInt)
20. What are Scala Identifiers?
Answer:
There are four types of Scala Identifiers:
Alphanumeric identifiers
Operator identifiers
Mixed identifiers
Literal identifiers
21. What are different types of Literals in Scala?
Answer:
The literals in scale are given below:
Integer Literals
Floating point literals
Boolean Literals
Symbol Literals
Character Literals
String Literals
Multi-Line Stings
22. What is the latest version of Scala?
Answer:
Scala 2.12 which requires Java 8.
Let us move to the next Scala Interview Questions And Answer.
23. Which keyword is used to define a function in Scala?
Answer:
def keyword is used to define the function in Scala.
24. Differentiate object and Class in Scala?
Answer:
An object is a singleton instance of the class. It does not need to initiated by the developer.
25. What do you mean by Akka in Scala?
Answer:
Akka is a concurrency framework in Scala which uses Actor based model for building JVM application.
26. How to compile and run a scala program?
Answer:
Scala compiler scalac to complie Scala Program and scala command to run it.
Recommended Articles
This has been a guide to List Of Scala Interview Questions and Answers so that the candidate can crackdown these Scala Interview Questions easily. You may also look at the following articles to learn more –
|
https://www.educba.com/scala-interview-questions/
|
CC-MAIN-2020-10
|
refinedweb
| 1,050
| 68.36
|
Assert Yourself: A Detailed Minitest Tutorial
This post introduces automated testing with Ruby’s Minitest software, with an emphasis on using assertions. It discusses basic test scaffolding; assertions and refutations; skipping and flunking tests; setup and teardown.
Note: This article was originally published on the Launch School blog on 2016–08–28
One of the biggest keys to producing quality software is properly testing your program under a wide variety of conditions. Doing this manually is tedious and error-prone, and frequently doesn’t get done at all. This leads to buggy software, and sometimes software that doesn’t work at all.
Fortunately, modern programming environments support automated tests. Such tests can be run repeatedly with minimal effort: it’s even possible to run them automatically prior to every commit or release. While automated testing doesn’t guarantee that your code will be bug free — the tests are only as good you make them — it can certainly reduce the number of bugs your users will encounter. Automated testing can also help you find and fix bugs earlier in the development cycle, and prevent a lot of needless debugging trying to track down a particularly nasty bug.
In this post, we will talk about Minitest, the standard software testing framework provided with Ruby. It isn’t the only software testing framework available, but being supplied automatically with Ruby is a major advantage.
In particular, we will discuss how to use Minitest assertions to test your software. We aren’t interested so much in the theory of automated testing, but in how to use Minitest.
Definitions
A testing framework is software that provides a way to test each of the components of an application. These can be methods or entire programs; the framework should be able to provide appropriate inputs, check return values, examine outputs, and even determine if errors occur when they should.
Testing frameworks provide 3 basic features:
- a way to describe the tests you want to run,
- a way to execute those tests,
- a way to report the results of those tests.
There is a hierarchy to tests. Since there isn’t any formal agreement on exactly which terms are used to describe this hierarchy, we will use the following definitions:
- A test step, or simply a test, is the most basic level of testing. A test step simply verifies that a certain expectation has been satisfied. For example, in a to-do application, you may want to verify that a newly created to-do is not yet marked as completed. Test steps employ either an assertion or an expectation depending on your testing framework.
- A test case is a set of actions that need to be tested combined with any appropriate test steps. For example, a test case for the above test step may include creation of the to-do object, a call to the
#completed?method on that object, and, finally, an assertion that the return value of the
#completed?method is false. Typically, only one test step is used per test case; some developers insist on this, others are more flexible. For brevity, some of our test cases may show multple test steps.
- A test suite is a collection of one or more test cases that, taken together, demonstrate whether a particular application facet is operating correctly. We use this term quite loosely: a test suite can test an entire class, a subset of a class, or a combination of classes, all the way up to the complete application. The test suite may be entirely in one file, or it may be spread out over several files.
There are other terms you will encounter in the testing world, but for our purposes, these 3 terms will be sufficient.
What is Minitest?
Minitest is a testing framework that comes with every standard Ruby distribution. It’s not quite as powerful and flexible as its cousin RSpec, but for most cases, Minitest will do everything you need. It provides multiple interfaces — assertions and expectations — and a choice of several different output formats.
In addition to being a testing framework, Minitest provides the ability to create and use mock objects and stubs, and the ability to run benchmarks. These topics won’t be discussed in this post, but may appear in a future post.
Assertions or Expectations?
As mentioned above, Minitest provides assertion-based and expectation-based interfaces.
In the assertions-based interface, the test writer supplies one or more classes that represent test suites. Within each test suite are one or more methods that define test cases. Finally, each test case method has some code that exercises some aspect of the item under test and then runs one or more test steps to verify the results. Here’s a simple example of a test suite for testing a square_root method:
require 'minitest/autorun'class TestSquareRoot < Minitest::Test
def test_with_a_perfect_square
assert_equal 3, square_root(9)
end def test_with_zero
assert_equal 0, square_root(0)
end def test_with_non_perfect_square
assert_in_delta 1.4142, square_root(2)
end def test_with_negative_number
assert_raises(Math::DomainError) { square_root(-3) }
end
end
In the expectations-based interface, the test writer uses a domain-specific language, or DSL, to describe the tests:
require 'minitest/autorun'describe 'square_root test case' do
it 'works with perfect squares' do
square_root(9).must_equal 3
end it 'returns 0 as the square root of 0' do
square_root(0).must_equal 0
end it 'works with non-perfect squares' do
square_root(2).must_be_close_to 1.4142
end it 'raises an exception for negative numbers' do
proc { square_root(-3) }.must_raise Math::DomainError
end
end
As you can see, assertions are little more than basic Ruby code: all you need to know is what modules to require; how to name your classes (test suites) and methods (test cases); and the methods (assertions) you need to call to perform each test. On the other hand, expectations have a DSL that needs to be learned, with commands like
describe and
it, and those odd
must_* methods being applied to the return values of
square_root. The DSL is more English-like, but you still need to learn the DSL even if you know English.
For the remainder of this post, we will concentrate on using Minitest assertions.
Writing a Simple Test Suite
Setting up a Minitest test suite isn’t difficult, but it also isn’t obvious when first starting out with Minitest. Before you start writing your first test suite, you need to know how to prepare it.
Typically, test suites are stored in in a special
tests directory beneath your main application's development directory. For example, if you are working on a to-do application that is stored in
/Users/me/todo, then you will place your test suite files in
/Users/me/todo/tests. This isn't a requirement, but is good practice for source organization, particularly when working with large projects.
There are no universal conventions regarding how to name your test suites. In the absence of any rules imposed by projects guidelines, we recommend establishing your own naming conventions and sticking to them; for instance, a common convention is to name a test suite for a class named
ToDo as
t_to_do.rb or
to_do_test.rb.
Once you know where your tests suites will live and how they will be named, you need to set up some scaffolding code for the tests. Your scaffolding code will look something like this:
require 'minitest/autorun'
require_relative '../lib/xyzzy'class XyzzyTest < Minitest::Test
def test_the_answer_is_42
xyzzy = Xyzzy.new
assert(xyzzy.the_answer == 42, 'the_answer did not return 42')
end def test_whats_up_returns_doc
xyzzy = Xyzzy.new
assert(xyzzy.whats_up == "Doc", 'whats_up did not return "Doc"')
end
end
We start by requiring
minitest/autorun; this package includes everything you need to run most basic tests, and it ensures that all of the tests in your test suite will be run automatically when you run the test suite.
Next we require the file(s) that contains the code we want to test. You will usually need to use
require_relative, and will need to figure out the relative name of the module with respect to the test suite file. In this example, the source code is found in
../lib with respect to the location of the test file.
We then define a class that inherits from
Minitest::Test (or
MiniTest::Test; you may use
Minitest and
MiniTest interchangeably). This class defines the test suite -- a collection of one or more test cases. The name of this class is not important; however, it is common to append or prepend
Test to the name, and the rest of the name is often the name of the class or module being tested. What's important to Minitest is that the class inherits from
Minitest::Test; Minitest runs tests in every class that inherits from
Minitest::Test.
Finally, we have provided scaffolding for two example test cases: one that tests whether
Xyzzy#the_answer returns
42, and one that tests whether
Xyzzy#whats_up returns
"Doc". Both test cases have a bit of code to set up the test (we create an
Xyzzy object in both cases), and a test step that verifies each of the methods returns the expected answer. (We will return to the
assert calls in a bit -- for now, just understand that each of these tests succeeds if the specified condition is true. If the condition is false, the test fails, and the message string specified as the second argument is printed as part of the failure message.)
Note that each of the test cases is represented by a method whose name begins with
test_; this is required. Minitest looks for and runs all methods in the test suite whose name begins with
test_. The rest of the method name is usually a short description of what we are testing; as you'll see later, well-named test cases will help make it easier to understand failures caught by Minitest.
Every assertion-based Mintest test suite you set up will look something like this. Some test suites may have multiple test suite classes; Minitest will run all of the test suite classes defined in the file. Some test suite classes will have only one or two test cases; others may have many test cases.
NOTE: If the code you are testing includes code that starts your app, see the section on testing startup code near the end of this post.
Writing Tests
While we won’t be doing any actual development in this post, it’s important to understand how testing fits into the software development cycle. Ideally, your test cases should be run before writing any code. This is frequently called Test-Driven Development (TDD), and follows a simple pattern:
- Create a test that fails.
- Write just enough code to implement the change or new feature.
- Refactor and improve things, then repeat tests.
This is often called Red-Green-Refactor. Red describes the failure step; green describes the getting things working; and, of course, refactor covers refactoring and improving things.
Once you’ve been through these steps, you can move on the next feature and repeat all of the above steps.
This post is not about TDD. However, it is useful to use the TDD approach in developing tests at the lowest levels.
Example
Lets look at an example. Suppose we want to develop a method to calculate square roots rounded to the nearest integer. If we attempt to take the square root of a negative number, the method should return nil.
For brevity, we will write our
square_root method in the same file as our tests -- this is not usually good practice.
First Test Case: square_root(9) should return 3
For our first test, we will take a simple case — most people know that the square root of 9 is 3, so let’s test that.
require 'minitest/autorun'def square_root(value)
endclass SquareRootTest < Minitest::Test
def test_that_square_root_of_9_is_3
result = square_root(9)
assert_equal 3, result
end
end
This is our first test — it uses
#assert_equal to assert that the result of
square_root(9) is
3. (We will discuss
#assert_equal in more detail later.)
We have also supplied a dummy
square_root method just so the test case has something it can test. Note that we used the name
square_root because our test case uses that name -- the test case is already driving our development by describing the interface we want to use.
If we run this file, we get the following results:
Run options: --seed 51859# Running:FFinished in 0.000886s, 1128.2034 runs/s, 1128.2034 assertions/s. 1) Failure:
SquareRootTest#test_that_square_root_of_9_is_3 [x.rb:9]:
Expected: 3
Actual: nil1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
We can see that there is a failure, and it occurred on line 9 where
#assert_equal is called. Now that we have something that fails, let's fix it:
require 'minitest/autorun'def square_root(value)
Math.sqrt(value)
endclass SquareRootTest < Minitest::Test
def test_that_square_root_of_9_is_3
result = square_root(9)
assert_equal 3, result
end
end
This time, we get:
Run options: --seed 42248# Running:.Finished in 0.000804s, 1243.5305 runs/s, 1243.5305 assertions/s.1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
Notice the
. just below
# Running:; we should see one
. for every successful test case. If we see
F's, we know that one or more test cases failed. If we see
E's, we know that one or more test cases were completely broken. You may also see some
S's here: an
S indicates that a test case was skipped.
Second Test Case: square_root(17) should return 4
Our goal is to round the square root to the nearest integer, so the square_root of
17 should be rounded to
4. Lets write that test case and test it:
require 'minitest/autorun'def square_root(value)
Math.sqrt(value)
endclass SquareRootTest < Minitest::Test
def test_that_square_root_of_9_is_3
result = square_root(9)
assert_equal 3, result
end def test_that_square_root_of_17_is_4
result = square_root(17)
assert_equal 4, result
end
end1) Failure:
SquareRootTest#test_that_square_root_of_17_is_4 [x.rb:15]:
Expected: 4
Actual: 4.123105625617661
We get our expected failure — we seem to be on the right track. The problem here is that we aren’t rounding the result, but are returning a Float value that closely approximates the square root of
17. Let's fix that:
end
This time, both tests pass.
Third Test Case: square_root(24) should return 5
The square root of
24 is approximately
4.9 which, rounded to the nearest integer, is
5. Lets write another test case:
This fails with:
1) Failure:
SquareRootTest#test_that_square_root_of_24_is_5 [x.rb:20]:
Expected: 5
Actual: 4
We get our expected failure. The problem here is that we aren’t rounding the result, but are simply truncating it with
#to_i. To round it, we need to use the
#round method:
require 'minitest/autorun'def square_root(value)
Success once again.
Fouth Test Case: square_root(-1) should return nil
In the real domain, square roots aren’t defined for negative numbers, and our requirements require that
#square_root should return
nil if it is passed a negative number. Once again, let's write a test case, this time using
#assert_nil:
This fails with an error:
SquareRootTest#test_that_square_root_of_negative_number_is_nil:
Math::DomainError: Numerical argument is out of domain - "sqrt"
x.rb:4:in `sqrt'
x.rb:4:in `square_root'
x.rb:24:in `test_that_square_root_of_negative_number_is_nil'
Note in particular that this problem is occurring in the call to
square_root, not in the assertion. This means we have to do something in
square_root to deal with negative inputs:
require 'minitest/autorun'def square_root(value)
return -5
Note that we are now returning
-5 if the value is negative; this isn't the correct value for
square_root, but we need to have a failing assertion before we can do a proper test. Returning a value we know to be invalid is one way to handle this.
With this change, we now get the failure we want:
1) Failure:
SquareRootTest#test_that_square_root_of_negative_number_is_nil [x.rb:26]:
Expected -5 to be nil.
without introducing any new failures or errors. We can now modify
#square_root to return the correct value:
require 'minitest/autorun'def square_root(value)
return nil
Success once again.
At this point, we can now refactor things to improve the code if we need to do so. After each refactor, we should rerun the tests to ensure that our most recent changes have not broken anything.
Test Sequence
One thing to keep in mind with files that contain multiple test cases (or multiple test suites) is that Minitest varies the order in which it runs the tests. In the example in the previous section for example, there are 4 tests, but the order in which they are run is completely at random. On one run, the 3rd, 1st, 4th, and 2nd tests may be run in that sequence, but on another run, the 2nd, 4th, 3rd, and 1st tests may be run.
This random sequence is intentional, and should be left as-is. Your tests should not be order-dependent; they should be written so that any test can be performed in any order.
If you have a sporadic issue that only arises when tests are called in a specific order, you can use the
--seed option to run some tests in a known order. For instance, suppose you run some tests and get the following output:
Run options: --seed 51859...
1) Failure:
XxxxxTest#test_... [x.rb:9]:
Expected: 3
Actual: nil3 runs, 3 assertions, 1 failures, 0 errors, 0 skips
but a subsequent run produces:
Run options: --seed 23783...3 runs, 3 assertions, 0 failures, 0 errors, 0 skips
you can rerun the first set of tests by using
--seed 51859 on the command:
$ ruby test/tests.rb --seed 51859
If you absolutely, positively need to always execute things in order, you must name all your test methods in alphabetical order, and include the command:
i_suck_and_my_tests_are_order_dependent!
As you might surmise, the developers of Minitest feel very strongly about this. Don’t do it!
Simple Assertions
As we saw above, tests are written using a wide variety of different assertions. Each assertion is a call to a method whose name begins with
assert. Assertions test whether a given condition is true; refutations test whether a given condition is false. For now, we'll limit the discussion to assertions -- refutations, the negation of assertions, will be described later.
assert
The simplest possible assertion is the
#assert method. It merely tests whether the first argument is "truthy":
assert(reverse('abc') == 'cba')
If the condition is truthy, the test passes. However, if the condition is
false or
nil, the test fails, and Minitest issues a failure message that says:
Expected false to be truthy.
which isn’t particularly helpful. For this reason,
assert is usually called with an optional failure message:
assert(reverse('abc') == 'cba', "reverse('abc') did not return 'cba'")
which is slighty more informative. (As we’ll see in the next session, we can do even better than this.)
All refutations and almost all assertions allow an optional message as the final argument passed to the method. However, in most cases, the default message for methods other than
#assert and
#refute is good enough to not require a specific message.
The following assertions do not accept a message argument:
assert_mock
assert_raises
assert_silent
Typically,
#assert is used with methods that return true or false:
assert(list.empty?, 'The list is not empty as expected.')
More often,
#assert simply isn't used; instead, we use
#assert_equal with an explicit
true or
false value.
assert_equal
The most frequently used assertion is
#assert_equal -- it tests whether an actual value produced during a test is equal to an expected value. For instance:
assert_equal('cba', reverse('abc'))
In this call, the first argument represents an expected value, while the second argument is the actual value — in this case, the actual value is the return value of
reverse('abc').
#assert_equal uses the
== operator to perform its comparisons, so you can compare complex objects if an
#== method has been defined. If an explicit
#== method is not defined, the default
BasicObject#== is used, which only returns
true if the two objects are the same object.
If the expected and actual values are equal, the test passes. However, if they are not equal, the test fails, and Minitest issues a failure message that says:
Expected: "cba"
Actual: "some other value"
Since the
== operator is used, you must be careful when asserting that a value is explicitly
true or
false:
assert_equal(true, xyzzy.method1)
assert_equal(false, xyzzy.method2)
The first of these assertions passes only if the return value of
xyzzy.method1 is exactly equal to
true; it doesn't check for truthiness like
#assert. Similarly, the second assertion passes only if
xyzzy.method2 returns
false exactly; it fails if
xyzzy.method2 returns
nil.
assert_in_delta
If you’ve spent any time working with floating point numbers, you’ve no doubt encountered the strange fact that floating point numbers are not usually stored as exact representations; small precision inaccuracies occur in the least significant digits of some floating point numbers. Thus, something like:
value_a = 2
value_b = 1.9999999999999999
puts value_a == value_b
prints
true even though the two values look like they should differ. This inaccuracy means that it is inadvisable to make comparisions for exact values in your program. The same holds true for your test cases: you should not assert that a floating point number has a specific value.
Instead, you should assert that a floating point number is near some value: how near is up to you. This is accomplished with the
#assert_in_delta method:
assert_in_delta 3.1415, Math::PI, 0.0001
assert_in_delta 3.1415, Math::PI, 0.00001
In these two tests, the 3rd argument is the “delta” value: if the expected and actual answers differ by more than the delta value, the assertion fails. If the 3rd argument is not supplied to
#assert_in_delta, a delta value of
0.001 is assumed.
In this example, the first test succeeds because
3.1415 differs from the actual value returned by
Math::PI (3.141592653589793) by less than
0.0001 (the actual difference is approximately
0.0000027), while the second test fails because
3.1415 differs from
Math::PI by more than
0.00001.
assert_same
The
#assert_same method checks whether two object arguments represent the exact same object. This is most useful when you need to verify that a method returns the same object it was passed. For instance:
assert_same(ary, ary.sort!)
As with
#assert_equal, the first argument is the expected value; the second argument is the actual value.
Note that equality of objects is not the same thing as being the same object; two objects can be different objects, but can have equivalent state. Ruby uses the
#== method to determine equality, but
BasicObject#equal? to determine that two objects are the same.
#assert_same, thus, uses the
#equal? method; since
#equal? should never be overridden, you can usually be assured that
#assert_same uses
BasicObject#equal?.
Note, too, that
BasicObject#== does the same thing as
BasicObject#equal?, but most objects override
#==, while no class should override
#equal?. In most cases, you can assume that
#assert_equal tests for equivalent states, while
#assert_same tests for the same object.
assert_nil
#assert_nil checks whether an object is
nil. This is most useful in conjunction with methods that return
nil as a "no results" result.
assert_nil(find_todos_list('Groceries'))
assert_empty
#assert_empty checks whether an object returns
true when
#empty? is called on the object. If the object does not respond to
#empty? or it returns a value other than
true, the test fails.
#assert_empty is most useful with collections and Strings.
list = []
assert_empty(list)
Note in particular that the assertion is named
#assert_empty without a
?, but it checks the
#empty? method.
assert_includes
#assert_includes checks whether a collection includes a specific object. If the collection does not respond to
#include? or if the method returns a value other other than
true, the test fails.
list = %w(abc def xyz)
assert_includes(list, 'xyz')
Note that the assertion is named
#assert_includes with an
s but no
?, but it checks the
#include? method which has a
? but no
s. Note also that this method departs from the "expected, actual" or "value" format used by some other assertions.
assert_match
#assert_match is used when working with String objects: often, you don't need to test an exact value, but just need to determine whether a String matches a given pattern.
#assert_match uses regular expressions (regex) for those patterns.
Most often,
assert_match is used with text whose content only needs to contain a few specific words, such as an error message:
assert_match(/not found/, error_message)
Setup and Teardown
Many test suites have some code that needs to be run either before or after each test. For example, a test suite that validates a database query may need to establish the database connection prior to each test, and then shut down the connection after each test. This can be easily accomplished with helper methods inside your test suite classes; however, you would need to remember to call both methods in every test case. Minitest provides a better way: each class that defines a test suite can have a
#setup and/or a
#teardown method to automatically perform any preprocessing or postprocessing required.
The
#setup method is called prior to each test case in the class, and is used to perform any setup required for each test. Likewise,
#teardown is called after each test case to perform any cleanup required. It is common to set instance variables in
#setup that can be used in the actual test case methods. For example:
require 'minitest/autorun'
require 'pg'class MyApp
def initialize
@db = PG.connect 'mydb'
end def cleanup
@db.finish
end def count; ...; end
def create(value); ...; end
endclass DatabaseTest < Minitest::Test
def setup
@myapp = MyApp.new
end def test_that_query_on_empty_database_returns_nothing
assert_equal 0, @myapp.count
end def test_that_query_on_non_empty_database_returns_right_count
@myapp.create('Abc')
@myapp.create('Def')
@myapp.create('Ghi')
assert_equal 3, @myapp.count
end def teardown
@myapp.cleanup
end
end
This test suite runs two test cases. Prior to each test case,
#setup creates a
@myapp instance variable that references a
MyApp object. After each test case,
#teardown calls
@myapp.cleanup to perform any shutdown cleanup required by the
MyApp class. In this example, set up and tear down consist of code that establishes and then drops a database connection. Elsewhere in the test suite, we can reference
@myapp freely to access the object.
Note that both
#setup and
#teardown are independent and optional; you can have both, neither, or either one in any test suite.
Testing Error Handling (assert_raises)
Testing involves not only checking that methods produce the correct results when given correct inputs, but should also test that those methods handle error conditions correctly. This is easy when the success or failure of a method can be determined by just testing its return value. However, some methods raise exceptions. To test exceptions, you need the
#assert_raises method. We saw an example of this earlier:
def test_with_negative_number
assert_raises(Math::DomainError) { square_root(-3) }
end
Here,
#assert_raises asserts that the associated block (
{ square_root(-3) }) should raise a
Math::DomainError exception, or an exception that is a subclass of
Math::DomainError. If no exception is raised or a different exception is raised,
#assert_raises fails and issues an appropriate failure message.
Testing Output
Many tests require that you examine the terminal output of your application. In this section, we’ll examine Minitest’s techniques for testing output.
assert_silent
With many applications, methods, etc, the ideal situation is that no output at all is produced. To test for this situation, simply invoke the method under test in a block that gets passed to
#assert_silent:
def test_has_no_output
assert_silent { update_database }
end
If
#update_database prints anything to
stdout or
stderr, the assertion will fail. If nothing is printed to
stdout nor
stderr, the assertion passes.
assert_output
Sometimes you need to test what gets printed, and where it gets printed. For example, you may want to ensure that good output is sent to
stdout, while error messages are printed to
stderr. For this, we use
#assert_output:
def test_stdout_and_stderr
assert_output('', /No records found/) do
print_all_records
end
end
The first argument for
#assert_output specifies the expected output that will be sent to
stdout, while the second argument specifies the expected output for
stderr. Each of these arguments can take the following values:
nilmeans the assertion doesn't care what gets written to the stream.
- A string means the assertion expects that string to match the output stream exactly. (In particular, an empty string is used to assert that no output is sent to a stream.)
- A regular expression means the assertion should expect a string that matches the regex.
In our example above, the assertion expects that
#print_all_records won't print anything to
stdout, but will output an error message to
stderr that contains the regular expression pattern
No records found.
capture_io
An alternative to using
#assert_output is to use
#capture_io:
def test_stdout_and_stderr
out, err = capture_io do
print_all_records
end assert_equal('', out)
assert_match(/No records found/, err)
end
This is equivalent to the example shown in the previous section. The chief advantage of using
capture_io is it lets you handle the
stderr and
stdout separately. This is especially handy when you want to run multiple tests on one or both of
out and
err that can't readily be handled with
#assert_output.
Testing Classes and Objects
Ruby is pretty lax about types: methods can both accept and return values of different types at different times. Sometimes, it is handy to verify that a value has the expected type, or that it can respond to a particular method. For these cases, Minitest provides several useful methods.
assert_instance_of
#assert_instance_of asserts that an object is an object of a particular class; it is analogous to the standard Ruby method
Object#instance_of?.
assert_instance_of SomeClass, object
succeeds if
object is a
SomeClass object, fails otherwise.
assert_kind_of
#assert_kind_of asserts that an object is an object of a particular class or one of its subclasses; it is analogous to the standard Ruby method
Object#kind_of? or
Object#is_a?.
assert_kind_of SomeClass, object
succeeds if
object is a
SomeClass object or one of its subclasses, fails otherwise.
assert_respond_to
In Ruby, you often don’t need to know that an object has a particular type; instead, you’re more interested in what methods an object responds to. Ruby even provides a method,
Object#respond_to?, that can be applied to any object to determine if it responds to a given method. This carries over to testing as well: you're often more interested in knowing if an an object responds to a given method, and
#assert_respond_to provides this capability:
assert_respond_to object, :empty?
This test asserts that
object responds to the method
#empty?, e.g.,
object.empty? is a valid method call. The method name may be specified as a symbol, as shown above, or as a String that will be converted to a symbol internally.
Refutations
Most often, your test cases will be more interested in determining whether or not a specific condition is true. For example, you may want to know whether a method returns
true,
5, or
'xyz'. For such situations, assertions are ideal; you write your assertion in such a way that it asserts whether the actual value has the expected value.
Much less often, you will encounter situations in which you are interested in the negation of a condition; for example, if you want to ensure that a method that operates on an
Array returns a new
Array instead of modifying the original
Array, you need to assert that that result
Array is not the same object as the original
Array. You can write this as:
ary = [...]
assert ary.object_id != method(ary).object_id, 'method(ary) returns original Array'
However, this isn’t particularly clear because we are forced to use the bare
assert instead of one of the more specialized assertions like
assert_same, which would be easier to read.
For these cases, Minitest provides refutations. Refutations are assertions that assert that something isn’t true. For example, we can write:
ary = [...]
refute(ary.object_id == method(ary).object_id,
'method(ary) returns copy of original Array')
This simplifies further to:
ary = [...]
refute_equal ary.object_id, method(ary).object_id
Better yet, we can use the negation of
assert_same, namely
refute_same, to be even more clear:
ary = [...]
refute_same ary, method(ary)
Most of the Minitest assertions have equivalent refutations that test the negation of the condition. In all cases, the refutation uses the assertion name with
assert replaced by
refute, and arguments for refutations are identical to the arguments for assertions. So, for example, the refutation of:
assert_nil item
is:
refute_nil item
The following assertions do not have a corresponding refutation:
assert_output
assert_raises
assert_send
assert_silent
assert_throws
Uncovered Methods
This post isn’t meant to be a complete reference to Minitest; for that, you should refer to the Minitest documentation. However, here’s a short list of some other methods from the Minitest::Assertions module that you may find useful:
#assert_in_epsilonis similar to
#assert_in_delta, except the delta is based on the relative size of the actual or expected value.
#assert_operatoris used to test binary operation such as
#<=,
#+, etc.
#assert_predicateis used to test predicates -- usually used by expectations, not assertions.
#assert_sendcalls an arbitrary method on an object and asserts that the return value is true.
#assert_throwstests whether a block returns via a
throwto a specific symbol.
#capture_subprocess_iois similar to
#capture_ioexcept that is also captures output of subprocesses. If
#capture_iodoesn't do what you want, try
#capture_subprocess_ioinstead.
#flunkforces a test to fail
#skipforces a test to be skipped
#skipped?returns true if a test was skipped. Sometimes useful in
#teardown.
Testing Startup Code
If the module you are testing has some launch code that starts the program running, you may have to make a small modification to that code. For example, the launch code in an
Xyzzy module may look something like this:
Xyzzy.new.run
If you run this code during testing, the results may be confusing as your application will start in addition to being tested. To avoid this, you need to modify the launch code so it doesn’t run when the file is required. You can do this like so:
Xyzzy.new.run if __FILE__ == $PROGRAM_NAME
or
Xyzzy.new.run if __FILE__ == $0
If you run the program directly, both
__FILE__ and
$PROGRAM_NAME (or
$0) reference the program file. If, instead, you require the file into your test module,
$PROGRAM_NAME and
$0 will be the name of the test program, but
__FILE__ will continue to refer to the main program file; since the two names differ, the launch code will not run.
Some programs don’t have any obvious launch code like
Xyzzy.new.run; for example, Sinatra applications don't have any obvious launch code. In such cases, you may need to find a different way to prevent running the program when testing. With Sinatra (and Rack::Test), you must run the following before performing any route requests:
ENV['RACK_ENV'] = 'test'
This code is added to your test module.
Conclusion
This concludes our introduction to Minitest, and, in particular, its assertions interface. As we’ve seen, using Minitest is simple and straightforward, with a wide variety of assertions and refutations that can help you write the tests required to determine whether your application works.
This isn’t the complete story about Minitest. In particular, we only briefly mentioned topics such as expectations, mocking and stubs, benchmarking, custom assertions and expectations, and the different reporting and execution options. While we hope to cover some of these topics in future posts, for now you will need to refer to the Minitest documentation.
Wrap-up
We hope you’ve enjoyed this introduction to Minitest, and to its assertions interface in particular. This and many other topics are discussed extensively in the curriculum at Launch School. Logged in users (free registration) can also access many exercises on a wide variety of topics. Feel free to stop by and see what we’re all about.
|
https://launchschool.medium.com/assert-yourself-a-detailed-minitest-tutorial-f186acf50960
|
CC-MAIN-2022-05
|
refinedweb
| 5,991
| 62.78
|
Bugzilla – Bug 17234
Typos around Dialect in MEX
Last modified: 2012-05-31 00:14:03 UTC
(from poehlsen at itm.uni-luebeck.de )
Hello,
as far as I discovered, the dialect is a mex:QNameSerialization instead
of a xs:Qname as before.
Are there any information available, why this was changed?
Since "Normative text within this specification takes precedence over
the XML Schema and WSDL descriptions, which in turn take precedence
over outlines, which in turn take precedence over examples." it is
quite difficult to see what seems to be right.
Especially since the serialization algorithm is only provided as a
"note" (non-normative text?) within the spec. (In the description of
the dialect attribute /mex:Metadata/mex:MetadataSection/@Dialect a
_note_ says that "the QName is serialized as
{namespace-uri}localName."
In the XML Schema exists only a regex: <xs:pattern
In the outline in section 4 the dialect is a 'xs:Qname'
If the note is applicable Example 2-4 line 21, 27, and 34 have an
incorrect Qname serialization. It must be a QNameSerialization, same
with Example 2-6 line 19.
There is another bug:
Example 2-4 line 21 lacks an identifier. Now it is required in contrast
to the submission version of the spec.
Kind regards,
Stephan
Created attachment 1137 [details]
proposal 1
|
https://www.w3.org/Bugs/Public/show_bug.cgi?id=17234
|
CC-MAIN-2014-15
|
refinedweb
| 219
| 56.05
|
Utilizing Delphi Codes in VC Without Using a DLL
Environment: VC 4.1 or higher, Windows 9x/NT/2000/ME/XP
Abstract
Introduction
There are many free codes and components in the Delphi world. How can we utilize them in VC? A usual scenario will be: First, make a DLL in Delphi that exports some functions. Then, we call these exported functions in VC. But in this way you have to bundle the Delphi DLLs with your VC application whenever it is to be released. And the performance of your application will degrade if it uses a lot of tiny DLLs.
To avoid these inconveniences, you can use a tool, "DLL to Lib" (downloadable at), to convert the DLLs into equivalent static libraries, and use the static libraries in your VC application instead of the original DLLs.
Let's Start with a Demo
We know that Visual C++ doesn't support the JPEG format directly, whereas Delphi has a unit 'jpeg.pas' by which developers can read JPEG images easily. Therefore, we want to utilize the codes of 'jpeg.pas' in our VC application.
Write the DLL in Delphi
First, we write a DLL named JpegLib.dll with Borland Delphi (jpeglib_src.zip), which encapsulates the jpeg.pas unit and introduces a simple function, LoadJpeg, to read JPEG images:
function LoadJPEG(AFileName: PChar): HBITMAP; cdecl;
LoadJPEG returns the handle to a Windows bitmap holding the image data extracted from the JPEG file specified by AFileName.
Convert DLL into a Static Library
Second, let's convert JpegLib.dll into a static library. Start "DLL to Lib", then:
- Select JpegLib.dll in the "The DLL file to be converted" edit box.
- Since JpegLib.dll has no accompanying import libraries, we have to leave the "Import Lib Files for the DLL" list empty.
- Input JpegLibst.lib in the "Output Static Library File" edit box. We want "DLL to Lib" to produce a static library named JpegLibst.lib.
- Leave all other options intact and click "Start Convert" to convert the JpegLib.dll into JpegLibst.lib.
- After a while, you will see a dialog box saying "Converting JpegLib.dll into JpegLibst.lib successfully"; click "OK".
- You will see a dialog box titled "Header file for DllMain". Because your JpegLib.dll has used DllMain or other similar entry-functions, "DLL to Lib" will generate a corresponding JPEGLIB_DLLMain function declaration header file (JpegLib_supp.h) for you to do necessary initialization and finalization before using any other functions in the generated static library. Please see the "convert entry-point function in DLL" topic in "DLL to Lib"'s help document for more information. Here you can simply click the "Close" button.
- You will see a dialog box titled "Import Libraries Required" telling you that five import libraries, namely KERNEL32.LIB, GDI32.LIB, ADVAPI32.LIB, USER32.LIB, and OLEAUT32.LIB, are used by JpegLib.dll. You should add them to your project settings when using the corresponding static library JpegLibst.lib. Click the "Close" button to close the dialog. For detailed information, please refer to the "Add Import Libraries to Your project" topic in "DLL to Lib"'s help document.
- You will see a dialog box titled "Resource names or IDs used by dll" telling you about the resources used in JpegLib.dll. Save it to JpegLibres.txt for further reference and close the dialog.
- Analyzing the log list, we find a warning:
Warning 10: Cannot find corresponding export symbol for LoadJPEG in the import libraries; we have to assume the export symbol follows __cdecl call convention.
This warning means "DLL to Lib" cannot find the export symbol of the DLL in the import library (because you have not provided any import libraries), so "DLL to Lib" will use the default __cdecl call convention to process the export symbols. Remember we define LoadJPEG in the cdecl call convention, so there won't be any problems and we can just ignore this warning. If you want to know more information about call the convention, please refer to the "__cdecl call convention" topic in "DLL to Lib"'s help document.
We now have successfully converted JpegLib.dll into a static library JpegLibst.lib.
Rewrite DLL APIs in C
Now we will use JpegLibst.lib in our VC applications. Since JpegLib.dll does not provide a c header file, we have to write one for ourselves:
- From JpegLib.dll's source code, we know the pascal API for LoadJPEG is:
- According to the rules of type conversion between Delphi and C, we can write out the following equivalent C declaration:
#ifdef __cplusplus extern "C" { #endif #include <windows> HBITMAP __cdecl LoadJPEG(LPSTR AFileName); #ifdef __cplusplus } #endif
to a file named JpegLib.h. Note the original Pascal version API of LoadJPEG uses the cdecl call convention, so you must also use __cdecl in the C declaration. If you use other call conventions, an unexpected exception will be raised because of the incompatible parameter order and stack structure. Moreover, here we use
extern "C"
in the declaration to prevent the compiler from mangling the function name (which will lead to unresolved symbol errors when linked with the static library).
function LoadJPEG(AFileName: PChar): HBITMAP; cdecl;
Use the Static Library in a VC Application
Now we can open the demo project JpegTest (jpeglib_demo.zip) to test the static library:
- Copy the static library JpegLibst.lib to JpegTest's working directory.
- Copy the header file JpegLib_supp.h to JpegTest's working directory. Remember it contains the declaration for JPEGLIB_DllMain.
- Copy the DLL's declaration header file JpegLib.h to JpegTest's working directory.
- Since the code in JpegLibst.lib may use the resources in JpegLib.dll, we must add these resources into JpegTest project. To do this, we:
- Open JpegLib.dll in Visual C++ as resources and save them to a JpegLib.rc file. Visual C++ will generate a new resource.h when saving JpegLib.rc, but it is of no use, so please delete it right now.
- Copy JpegLib.rc and corresponding external resource files to JpegTest's working directory.
- Open the JpegTest project in VC.
- In VC IDE, from the View menu, choose Resource Includes and add the line
#include "JpegLib.rc"
to the "Compile-time directives" box. Note: a message box will pop up after you modify the resource includes; just click "OK" to close it.
- Modify the resources IDs or names in the JpegTest project if they conflict with those in JpegLib.dll. (You can refer to JpegLibres.txt.)
- Modify JpegTest.cpp by
- Add the line:
- Add an initialization statement to CJpegTestApp::InitInstance():
- Add a finalization statement to CJpegTestApp::ExitInstance() (you may need to create this function with ClassWizard first):
JPEGLIB_DllMain(AfxGetInstanceHandle(), DLL_PROCESS_DETACH, NULL);
the detail information about call entry-point function in DLL can be found in the topic 'Convert Entry-Point Function in DLL' in help document of "DLL to Lib".
- Open JpegTestDlg.cpp.
- Add the line:
- Add the following code to the click event handler for "Show" button:
- Add JpegLibst.lib, kernel32.lib, gdi32.lib, advapi32.lib, user32.lib, and oleaut32.lib to the object module list of the project.
#include "JpegLib.h"
void CJpegTestDlg::OnShowButton() { // TODO: Add your control notification // handler code here HBITMAP hBitmap; UpdateData(); hBitmap = LoadJPEG((LPSTR)(LPCSTR)m_strFile); if(hBitmap) ((CStatic *)GetDlgItem(IDC_JPEGIMAGE)) ->SetBitmap(hBitmap); }
- Now we can build the JpegTest project by click F7. Wait.... Okay. The project is built successfully.
- Run JpegTest, select a JPEG filename, and click "Show it". Okay; the JPEG image is shown in our dialog. We have ported the Delphi code to VC application JpegTest successfully. And it can run without JpegLib.dll. The screenshot is shown in the header of this article.
#include "JpegLib_supp.h"
JPEGLIB_DllMain(AfxGetInstanceHandle(), DLL_PROCESS_ATTACH, NULL);
DownloadsDownload demo project - 12.4 Kb
Download source - 100 Kb
Lightweight smart â Nike Unshackled TR Fit in shoot up 2013 3 seriesPosted by Tufffruntee on 04/20/2013 08:17am
Nike Manumitted TR Stalwart 3 prominent features is to use the additional plot: Nike Self-ruling 5 soles improved bending Groove; supplemental tractor imitate making training more focused when; lighter weight, the permeability is stronger, and more fashionable shoe designs not only order shoes [url=]nike free[/url] more pleasant wearing, barefoot training feel, but also more in vogue appearance. Nike Free TR Then 3 provides unequalled lateral reliability, you can be suffering with the legs in the untenable during training. Diligent vamp nobles breathable grating, demean suds's unique design can be [url=]nike huarache[/url] seen from stem to stern it. Lightweight, demanding, piddling soap up facts occupied at hand very some seams, more obedient, help is stronger. Demand more support, role of a training vex, lather come in more parts of the destitution in return flexibility, foam loose. Use twice patois moisture wicking mock materials, tiresome on your feet, mitigate maintain feet dry and comfortable. Phylite [url=]air max 90[/url] midsole offers lightweight surprise level, superior durability and even outsole can do to greatly lower the total load of the shoe. Qianzhang pods on the outsole and heel-shaped Grassland rubber enhances the shoe multi-directional purchase on extraordinary surfaces.Reply
Get LostPosted by Legacy on 01/05/2003 12:00am
Originally posted by: Jake
This is a place for programmer. Either you are really smart or completely the opposite. DO NOT TRY TO SELL YOUR PRODUCT HERE.Reply
This is an Ad!Posted by Legacy on 10/24/2002 12:00am
Originally posted by: A. Moeller
This article has been posted on the CodeProject a while ago. Here, the author received legitimate bashing for not mentioning that the used application is commercial and has to be paid for to be of any use at all.
This fact is still omitted even here (on CodeGuru), so I'll begin basing the author:
DO MENTION THAT "DLL to Lib" IS A COMMERCIAL APPLICATION AND THAT YOUR ARTICLE IS OF NO WORTH IF THAT APPLICATION ISN'T BOUGHT.
(Sorry for that all-uppercase sentence, but I deem it appropriate).Reply
|
http://www.codeguru.com/cpp/w-p/dll/importexportissues/article.php/c3647/Utilizing-Delphi-Codes-in-VC-Without-Using-a-DLL.htm
|
CC-MAIN-2014-42
|
refinedweb
| 1,662
| 65.42
|
Converts "<b>hi</b>" into "<b>hi</b>"Converts "<b>hi</b>" into "<b>hi</b>"Code:
String.prototype.stripHTML=function(){
return this.replace(/\&/g,"\&").replace(/\</g,"\<").replace(/\gt/g,"\>")
}
Printable View
Converts "<b>hi</b>" into "<b>hi</b>"Converts "<b>hi</b>" into "<b>hi</b>"Code:
String.prototype.stripHTML=function(){
return this.replace(/\&/g,"\&").replace(/\</g,"\<").replace(/\gt/g,"\>")
}
Its not quite efficient enough. But ill share how it scrolls the colors:Its not quite efficient enough. But ill share how it scrolls the colors:Quote:
Originally Posted by Ultimater
#FF0000
#FF00FF
#0000FF
#00FFFF
#00FF00
#FFFF00
But it also has a variable to control how light it gets.
Date.prototype.NumberOfDays(); Origional: A1ien51
I was modifying the old version to maintain the old date when I started from scratch. As much as I like the old one for its novel approach, I prefer this as it is 10 times faster.
Code:
Date.prototype.NumberOfDays=function(){
var a=this.getMonth();
if (a==1) {
var b=this.getFullYear();
return (b%4==0 && (b%100!=0 || b%400==0)) ? 29 : 28;
}
return (a==3 || a==5 || a==8 || a==10) ? 30 : 31;
}
Moosie, isn't the rule for leap years:
??Code:
if(year%4==0 &&(!year%100==0 || year%400==0)) //then leap year
Source:
Good point HaganeNoKokoro!
I knew that they occasionally make exceptions for leapyears but I didnt know there was a rule for it, I thought that chaos didnt allow for those kind of accurate predictions, it seems I was wrong. You can make that adjustment if you want. But for most cases it will not matter as it wont be effective in roughly a hundred years in both directions.
EDIT: made the correction anyway.
Boolean.isTrue();
This may come in handy ;)This may come in handy ;)Code:
Boolean.prototype.isTrue=function(){return this;}
Wow, I've needed a function like this for so long...
I sure hope you are kidding!I sure hope you are kidding!Quote:
Originally Posted by BigMoosie
I think he's being sarcastic :DI think he's being sarcastic :DQuote:
Originally Posted by HaganeNoKokoro
BigMoosie, as A1ien51 points-out, the function doesn't do anything and it's a wasted function call.
A boolean is either true or false, so your function call might look like this:A boolean is either true or false, so your function call might look like this:Code:
Boolean.prototype.isTrue=function(){return this;}
alert(true.isTrue())//true
alert(false.isTrue())//false
Maybe you meant something like this:
Code:
Boolean.prototype.ifElse=function(){if(this==true)return arguments[0];else return argument[1]}
Definitely kidding, and I'm pretty sure Moosie is too :rolleyes:Definitely kidding, and I'm pretty sure Moosie is too :rolleyes:Quote:
Originally Posted by A1ien51
Of course I'm being sarcastic fool! and I meant exactly what I wrote, even yours is a ridiculous waste of a function because it is equivalent to:Of course I'm being sarcastic fool! and I meant exactly what I wrote, even yours is a ridiculous waste of a function because it is equivalent to:Quote:
Originally Posted by Ultimater
Code:
(myBoolean) ? "arg0" : "arg1";
Any Boolean prototype-function is a joke! -- even mine :D
I'm stumped on why JavaScript even has Boolean prototypes in the first place.
cos that way no-one complains about them not being there.
and anyway booleans are great.
here is two more date prototypes UK to US format and DaysBetween, I do not think I posted these.
Code:
<script type="text/javascript">
Date.prototype.DaysBetween = function(){
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif/intMilDay);
return intDays;
}
String.prototype.UKtoUSDate = function(){
var arrDate = this.split("/");
return new Date(arrDate[1] + "/" + arrDate[0] + "/" + arrDate[2]);
}
var d1 = new Date("06/10/2005");
var d2 = new Date("06/13/2005");
alert(d1.DaysBetween(d2));
var dUK1 = ("10/06/2005").UKtoUSDate();
var dUK2 = ("13/06/2005").UKtoUSDate();
alert(dUK1.DaysBetween(dUK2));
</script>
Business Day Calcs, this method does not involve looping like I have seen people do.
EricEricCode:
Date.prototype.DaysBetweenBusiness = function(){
//Does not account for holidays! LOL
//return -1 if start or end date is not a business day
if(!this.IsWeekDay() || !arguments[0].IsWeekDay())return -1
var intMilDay = 24 * 60 * 60 * 1000;
var intMilWeek = intMilDay * 7;
var intSDay = this.getDay();
var intEDay = arguments[0].getDay();
this.setDate(this.getDate() + 7 - intSDay);
arguments[0].setDate(arguments[0].getDate() - intEDay);
var intMilDif = arguments[0] - this;
var intDaysTotal = Math.floor(intMilDif/intMilDay);
var intWeeks = Math.floor(intMilDif/intMilWeek);
return xD = 5 - intSDay + intEDay + intDaysTotal -(intWeeks*2)
}
Date.prototype.IsWeekDay = function(){
return this.getDay() > 0 && this.getDay() < 6
}
var d1 = new Date("06/6/2005");
var d2 = new Date("06/29/2005");
alert(d1.DaysBetweenBusiness(d2));
|
http://www.webdeveloper.com/forum/printthread.php?t=61883&pp=15&page=9
|
CC-MAIN-2016-26
|
refinedweb
| 799
| 60.01
|
Historically, moving from a Linux mail system- such as Postfix/Dovecot -to a Windows mail system- such as Smartermail -was not a seamless process. Mail formats are so largely different that it is next to impossible to copy mail over. Users were best suited to POP3 all mail off the Postfix server and then connect to the Smartermail server to achieve a complete migration. But how useful is this when you have possibly 1GB of mail? Or is this scalable if you have a company with many non-technical users?
A viable solution is to use a neat little Perl module named 'imapsync'. As the name suggests, IMAP must be enabled on both the source and destinations server. This module can be downloaded from one of the distributions here. A number of Perl modules are required as well:
All these modules can be obtained from CPAN's site. Once installed on the Postfix server, make sure you can telnet to the destination server on port 143. If any IPtables or firewall rules are blocking IMAP communications, obviously imapsync will error out.
For each user, you can then run a command like:
bash # imapsync --host1 localhost --user1 system_name
--password1 source_password --host2 destination_IP --user2 email_address
-password2 destination_password --authmech1 source_authmethod
--authmech2 LOGIN --prefix2 "" --sep2 "/"
Note that the users must be present on the source and destination server already. Imapsync will not create any users. The source and destination users also do not necessarily have to be identical. But it is important to use the system name if the Postfix user is not a virtual user. The source's authentication method can be looked up in /etc/dovecot.conf under 'auth default'. More than one may be present. Generally 'PLAIN' or 'LOGIN' is used. Dovecot is good at announcing its namespace when a connection occurs, but Smartermail is not. We can specify this with the prefix2 and sep2 parameters.
For increased security, password1/password2 can be replaced with passfile1/passfile2 and a path to file so passwords on not visible to other users using the ps command. Other advanced features can be used such as inclusions and exclusions using regular expressions. Age filters can be placed on messages if you are looking to possibly sync the last day's mail everyday on a cron job. Delete parameters can also be used to effectively 'move' the mail instead of copying it. Have fun!
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
|
http://www.codeproject.com/script/Articles/View.aspx?aid=35901
|
CC-MAIN-2014-35
|
refinedweb
| 417
| 64
|
Start of abstract interpretation in Lever
Today I provided introspection features to Lever:
import optable
optable.enc # encoding table.
optable.dec # decoding table.
function.spec.argc # required arguments
function.spec.optional # optionals, null allowed if missing.
function.spec.is_variadic # has variadic argument?
function.spec.varnames # all variable names.
code = function.code
code.closure # same as 'function.code'
code.module # module for this function
code.is_generator # is this a generator?
code.excs # exception blocks
code.regc # register count
code.localc # locals count
code.length # bytecode length
code[i] # i:th byte in code
code.get_sourceloc(pc)
code.getupv(frame, index)
code.constant(index)
Equipped with these, I can do abstract interpretation on Lever byte code.
Using these you can dump and read the source code after it has been loaded into memory. This is the feature that made it possible for RPython to translate Python programs into machine code.
As soon as I got the introspection to work, I dumped the bytecode of this simple function:
(a, b):
return a + b
Here's the bytecode printout:
0000: 0 = getloc 0(index)
0003: 1 = getloc 1(index)
0006: 2 = getglob "+"
0009: 3 = call 2 3 4
0014: return 1
0016: 5 = getglob "null"
0019: return 1
These instructions are internally represented in 16-bit unsigned integers. The first integer encodes the length in its lowest byte.
Please note that this might not be the most efficient format for interpretation, therefore the design focused on aspects such as on making it nice and enjoyable to use.
I can still remember how stubborn I was about the efficiency questions. The people working at PyPy insisted me that the bytecode was irrelevant for performance because the JIT performance really doesn't make any connection with specifics of the bytecode.
The rules on how the JIT transforms machine code can be thought as a partial evaluator that selects on what it partially evaluates. The bytecode is a constant, and therefore it is immediately elided away from every trace.
There is still a thing I am concerned about in the bytecode though. I believe it could further be simpler while fitting on what purpose it has. I believe the jumps and hoops and imitation of machine code with cond -instructions and exception handling lists might be entirely redundant and pointless.
I have already dug up my link lists and references for compiling and various instruction formats. In the few next months Lever runtime will get a translator and a compiler.
I will apply the translation framework to graphics programming and computer algebra systems.
|
http://boxbase.org/entries/2017/apr/10/lever-abstract-interpretation/
|
CC-MAIN-2018-34
|
refinedweb
| 426
| 58.58
|
Red Hat Bugzilla – Bug 475997
sytem-config-lvm crashed with 'IndexError: list index out of range'
Last modified: 2009-08-28 02:13:08 EDT
Description of problem:
- Remote login to server
- Execution of 'system-config-lvm'
- GUI pops up, additional pop-up 'Reloading LVM. Please wait.' appears
- GUI
Version-Release number of selected component (if applicable):
system-config-lvm-1.1.4-1.0.fc9.noarch
How reproducible:
always
Steps to Reproduce:
1. see above 'Description of Problem'
Actual results:
Crashed system-config-lvm
Expected results:
Running system-config-lvm
Additional info:
Worked in Fedora.
Fedora 10 has the same problem. This is my fix:
--- Multipath.py~ 2009-07-06 11:24:08.000000000 +0200
+++ Multipath.py 2009-07-06 11:24:23.000000000 +0200
@@ -1,3 +1,4 @@
+# -*- coding: iso-8859-15 -*-
import os
@@ -50,7 +51,10 @@
continue
if words[0][0] == 'b':
# [name, major, minor]
+ try:
block_devices.append(['/dev/' + words[9], words[4].rstrip(','), words[5]])
+ except:
+ pass
# process dmsetup table
for line in dmtable_lines:
With that fix block_devices won't be filled at all. Problem is in date format in ls. s-c-lvm is looking for:
brw-r--r-- 1 root root 250, 9 Mar 17 2008 zz
you have:
brw-r--r-- 1 root root 250, 9 2008-03-17 zz
'ls -l --time-style=long-iso' will create same environment everywhere
Thanks for reporting bug. Patch sent to upstream
Created attachment 356945 [details]
Proposed patch
system-config-lvm-1.1.8-1.fc10 has been submitted as an update for Fedora 10.
system-config-lvm-1.1.9-1.fc10 has been submitted as an update for Fedora 10.
system-config-lvm-1.1.9-1.fc10 has been pushed to the Fedora 10 testing repository. If problems still persist, please make note of it in this bug report.
If you want to test the update, you can install it with
su -c 'yum --enablerepo=updates-testing update system-config-lvm'. You can provide feedback for this update here:
system-config-lvm-1.1.9-1.fc10 has been pushed to the Fedora 10 stable repository. If problems still persist, please make note of it in this bug report.
Works for me. Thank you very much.
|
https://bugzilla.redhat.com/show_bug.cgi?id=475997
|
CC-MAIN-2017-34
|
refinedweb
| 374
| 60.11
|
I'm using
xamarin forms, but the widget was built in the
android project.
I have many instances of the same widget, each contains different accounts of the user . I'm saving widgetId and account as a
key, value in CrossSettings.
But right now all the widgets are updating whenever I call
OnUpdate(). I need to get the exact account from my
TextView , compare it to the widgetId and update only this widget..
It seems that
FindViewById is not supported in widgets. How can i get the text of my
textView?
var savedAccount = (TextView)FindViewById(R.Id.accountTextView) // NOT SUPPORTED! foreach (var widgetId in appWidgetIds) if (SavedAccount.Text == CrossSettings.Current.GetValueOrDefault<string>(widgetId.ToString())) //here comes the further update
Answers
try that
private ListView savedAccount;
savedAccount = FindViewById<TextView>(Resource.Id.accountTextView);
that's the thing - findViewById doesnt exist as a method here(
How does the part in your xml with the TextView look like?
I dont use listview, just a textview.
are u
using Android.Support.V7.App;?
i don't .
open your NuGet manager and search for Xamarin.Android.Support.v7.AppCompat and install that.
Need other variants here...
I did it by saving data in the cross settings
|
https://forums.xamarin.com/discussion/101001/xamarin-widget-get-the-data-from-textview
|
CC-MAIN-2019-39
|
refinedweb
| 200
| 61.63
|
A recipe to help setup a buildbot master and slaves
Introduction
This package provides 2 recipes for helping you manage your buildbot master and slave. We purposefully do not provide machinery for generating project configuration.
Creating and managing your master
To create a buildbot master, add something like this to your buildout.cfg:
[buildbot] recipe = isotoma.recipe.buildbot cfgfile = path/to/master.cfg config = "PORT_WEB": "8080",
cfgfile is a normal buildbot master config, but it has a config object in its global namespace that contains the buildout managed properties set under config.
This recipe will also create a wrapper for starting, stopping, reconfiguring and checking the configuration of the master. It will be in your buildout’s bin directory and have the same name as your part.
For buildbot 0.8.0+ installations, the recipe will create and perform migrations on your database.
Mandatory Parameters
- cfgfile
- Path to a buildbot configuration file. BuildMasterConfig will already be defined, so dont redeclare it.
- config
- A list of buildout managed settings that are passed to the buildbot master configuration
Optional Parameters
- eggs
- Any eggs that are needed for the buildbot to function. These are eggs to support your buildbot, as opposed to eggs to support the code buildbot is running for you.
- dburl
- A buildbot DBSpec for connecting to your buildbot database. Default is sqlite in var directory. See buildbot manual for help setting this.
Creating slaves
To create a buildbot master, add something like this to your buildout cfg:
[bb-slave-1] recipe = isotoma.recipe.buildbot:slave basedir = ${buildout:directory}/bb-slave-1 master-host = 10.0.2.2 master-port = 8082 username = blah password = blah
This will add a slave to the bb-slave-1 directory and add a bb-slave-1 start/stop script to the bin directory.
Mandatory Parameters
- basedir
- Where the slave will be created and where it stores its temporary data
- master-host
- The IP or hostname that a slave should connect to
- master-port
- The port the slave should connect to
- username
- A valid slave username on the master server to connect with
- A valid slave password on the master server to connect with
Changelog
0.0.33 (2012-06-11)
- And of course, brown paper bag
0.0.32 (2012-06-11)
- SIGUSR1 will become “graceful shutdown”, so use SIGUSR2 for log rotation
- Add logrotate and graceful-shutdown helpers to wrapper script
0.0.31 (2012-06-06)
- Nothing changed yet.
0.0.30 (2012-05-21)
- Nothing changed yet.
0.0.29 (2012-05-07)
- Support buildbot 0.8.7 (pre)
0.0.28 (2012-04-12)
- Support buildbot 0.8.6
0.0.27 (2011-10-04)
- Fix slave umask after twistd clobbers it
Release History
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/isotoma.recipe.buildbot/
|
CC-MAIN-2017-39
|
refinedweb
| 474
| 57.57
|
Ill try that, thanks
--- Update ---
Didn't seem to work, any other ideas?
Ill try that, thanks
--- Update ---
Didn't seem to work, any other ideas?
Hey, im currently making a 3D modeling program in java (its for a game). And, everything was working fine until yesterday. Eclipse shows no errors, and this shouldn't be happening, but I get the
...
It just gives me errors,
HashMap hm = new HashMap();
hm.put("a", new Double(K));
hm.put("b", new Double(eec));
hm.put("c", new Double(s));
hm.put("d", new Double(Ab));
Any idea of how to make it work with multiple letters together? The HashMap failed.
thanks
Oh, thanks. It's almost working perfectly, but I still need to make it register words. Should I do an array, or is there a different way? Thanks
jtfResult.getText() just locates the text, I have it set to 'setText' to set the 'encrypted' word in its place.
Ah, the semicolons were what caused the if else statements.
Now, it just clears the result.
import java.awt.BorderLayout;
import java.awt.Color;
Thats the thing, there is no error. Eclipse doesn't report anything. Heres my code -
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import...
Just tried it, that didn't work either. I may be doing it wrong, but im pretty sure its correct
Hey, I need some help with an encrypter.
I plan on actually making it use an encryption, but for now Im just having it set letters in the place of previous ones (and vice-versa).
My code that...
|
http://www.javaprogrammingforums.com/search.php?s=e98c737a34da41a6af42070259b3a06c&searchid=477533
|
CC-MAIN-2013-20
|
refinedweb
| 268
| 79.46
|
MATLAB Newsgroup
i typed ;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
keyboard=Robot;
ch=getKeyCode();
i also typed ch=keyboard.getKeyCode();
it didnt work again.. How can i run it properly ?
"andandgui isler" <bosisler_ist@hotmail.com> wrote in message <i8mt0s$4qn$1@fred.mathworks.com>...
> i typed ;
>
> import java.awt.AWTException;
> import java.awt.Robot;
> import java.awt.event.KeyEvent;
> keyboard=Robot;
>
> ch=getKeyCode();
>
>
> i also typed ch=keyboard.getKeyCode();
>
> it didnt work again.. How can i run it properly ?
>
>
Robot can't do this.
List of implemented methods:
You can press o relase a key, not get.
for example:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
robot=Robot;
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_I);
robot.keyRelease(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_B);
robot.keyRelease(KeyEvent.VK_B);
robot.keyPress(KeyEvent.VK_U);
robot.keyRelease(KeyEvent.VK_U);
robot.keyPress(KeyEvent.VK_D);
robot.keyRelease(KeyEvent.VK_D);
robot.keyPress(KeyEvent.VK_Y);
robot.keyRelease(KeyEvent.VK_Y);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
:)
Grzegorz
"andandgui isler" <bosisler_ist@hotmail.com> wrote in message
news:i8mt0s$4qn$1@fred.mathworks.com...
> i typed ;
>
> import java.awt.AWTException; import java.awt.Robot; import
> java.awt.event.KeyEvent; keyboard=Robot;
Keep in mind by doing this that you can no longer call the KEYBOARD function
until you clear this variable (or until you exit this function, if it's in a
function.)
--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ:
To contact Technical Support use the Contact Us link on
> Robot can't do this.
> List of implemented methods:
>
An article describing Java's Robot class and its use in Matlab:.
|
http://www.mathworks.com/matlabcentral/newsreader/view_thread/293408
|
CC-MAIN-2015-18
|
refinedweb
| 292
| 56.62
|
Top Features
People
Giving
Check-In
Worship
Accounting
Events
Church Connect
Resources
Support
Videos
Our Story
Start For Free
Blog Home
/ Migrating To ChurchTrac Online Giving
Migrating To ChurchTrac Online Giving
Around this time every year, we begin to see flocks of birds migrate south to warmer weather. In the same way, we see hundreds of ministries move over to our church management software to
simplify
their ministry and
save
money. Churches embrace features like Child Check-In, Contribution Statements, Mass Messaging, Worship Planning, and Volunteer Scheduling.
When it comes to switching Online Giving providers, churches often feel stuck. 😐
Why?
They depend on their old giving platform right now for a large portion of donations.
Many of their donors have just now gotten used to it. Switching could result in losing them temporarily (or permanently).
All web links, social media, worship guides, and bulletins point to their old giving platform.
And a few other minor reasons...
Thankfully, switching to ChurchTrac Online Giving is not as hard as you think. Switching giving platforms is not an "all-or-nothing" approach; it's a migration. Here's how you do it...
Step 1: Setup ChurchTrac Online Giving [Only takes 8-15 minutes]
Setting up Online Giving requires that you have your EIN number handy. You'll also need your bank account info, billing address, church website, and other basic info. When you have these things ready, begin the setup process
HERE
.
If your ministry has nonprofit status, you are eligible for reduced pricing as well. Email nonprofit@stripe.com with the following:
Your EIN, or a letter from the IRS designating your 501(c)(3) status
Confirmation of the primary email address associated with your Stripe Account
Confirmation that greater than 80% of your payment volume will be tax-deductible donations.
You will receive an email confirmation back with your reduced pricing within 1-2 business days from Stripe.
Step 2: Get all staff and leadership on board
In your next staff meeting, make an announcement that your ministry is making the switch to ChurchTrac Online Giving. Show them that the switch to ChurchTrac in an effort to reduce costs and better streamline the church's admin efforts. Show them the benefits donors receive as well (like text giving, recurring donations, ACH support, and more).
Step 3: Change your links and physical media
Once your staff and leadership are on board, update your website links for Online Giving to the new ChurchTrac Online Giving link. Any donate buttons on social media like Facebook, Instagram, and Twitter will need to be updated as well. If you include a link or QR code on a bulletin or worship guide, go ahead and change them to your new link or provided QR code. You can obtain your new link and QR code by navigating to
SETTINGS > ONLINE GIVING
.
Step 4: Message your people
We recommend emailing and texting all of your people. Provide them with the link to your ChurchTrac Online Giving. Like in your staff meeting, show them the benefits they receive as donors (like text giving, recurring donations, ACH support, and more).
Step 5: Follow-up messages & announcements
Follow-up Message:
About a month after you've emailed and sent a mass SMS message to your donors about the switch, proceed in sending a follow-up message to those who have
not
switched. Remind them of the benefits that they will receive by switching.
Announcements:
Make an announcement in your worship services and small groups about the switch. If you show informational slides on the projector before and after service, add this as one of those slides as well.
That's it!
After completing these 5 easy steps, you will have successfully migrated to ChurchTrac Online Giving. You and your people can begin to enjoy the many benefits of our built-in giving platform that integrates perfectly with everything else in your ChurchTrac database and Church Connect.
FAQS about migrating to ChurchTrac Online Giving
Can I use multiple online giving providers at the same time?
A. Absolutely! Migrating is a process, not an all-or-nothing approach. With our Giving Imports Tool, you can
easily import your CSV files
from other providers like Givelify, PayPal, Pushpay, and more!
How long does it take to migrate my people over to ChurchTrac Online Giving?
A. Most ministries are able to get all their people to migrate over in about 1-3 months.
What if I can't get all my people to migrate away from our old church donation platform?
A. You can still easily
import third party CSV files
into ChurchTrac Giving. Either way, you can keep all your data in one place.
What benefits do I get from switching to ChurchTrac as my church donation software?
A. Quite a few. For starters, our free church donation software has no monthly fees. On top of that, our rates are some of the lowest available with up to 2.2% for credit card transactions and a flat rate of $.25 per ACH transaction. We could go on about text giving and recurring donations...but you get the point.
Start Your Free Trial
Explore ChurchTrac for yourself by starting a free 30 day trial.
|
https://www.churchtrac.com/articles/migrating-to-churchtrac-online-giving
|
CC-MAIN-2021-49
|
refinedweb
| 868
| 63.19
|
We have seen how Collections class methods made Java Programmer job easy to operate on data structure elements and we have discussed nearly 25 operations like comparing, sorting and searching etc. with good example codes. Now it is the turn with Arrays class. Almost the same methods exist with Arrays class but useful to perform on array elements. Array class was introduced with JDK 1.2 and placed in java.util package and forms a part of collections framework. Before JDK 1.2, all the array elements manipulations (like shuffling, sorting and searching) were done by the developers from scratch level with enormous looping and if codes.
The general exception thrown by all the methods is NullPointerException if the array reference is null.
Following is the class signature
Following are the important methods of Arrays class and all are static methods so that they can be called with Arrays class directly (without the need of creating object).
class Arrays API Methods
-.
- static void sort(Object array1[], Comparator comp1): Sorts all the array1 elements in the order as per the Comparator comp1. Here, the elements must be compatible to get sorted (should be of same data type) else ClassCastException is raised.
- static void sort(Object array1[], int startIndex, int endIndex, Comparator comp1): It is a modified form of the previous method useful to sort a few elements of the array. If the comparator is given as null, the elements are sorted in natural order, by default.
-. It is just similar to Collections.binarySearch().
-.
-. It looks like disjoint() method of().
- static List asList(T array): It is useful to convert an array into a List. The method returns a List object with the elements of the array and further elements cannot be added to the list. Useful to have fixed size list on which add() and remove() method do not work. It is nearer to addAll() of Collections. Overloaded to take any data type array as parameter.
-.
Generally, these methods throw NullPointerException if the array refers null (unless not specified). Similar methods exist with Collections class also for operations on Collections elements.
Words:
The Arrays class from java.util package does not have copy() method to copy the elements of one array to another as arraycopy() method already exists with general arrays.
5 thoughts on “class Arrays API Methods”
Hi Srinivas p,
Please find below an array example without duplicate elements..and without using collections API methods. –
import java.util.ArrayList;
import java.util.List;
public class ArraySort {
public static void main(String argv[]){
List list = new ArrayList();
list.add(2);
list.add(5);
list.add(1);
list.add(7);
list.add(19);
list.add(4);
list.add(1);
list.add(5);
list.add(1);
list.add(7);
list.add(19);
Object[] obj=list.toArray();
for(Object o: obj){
if(list.indexOf(o)!=list.lastIndexOf(o)){
list.remove(list.lastIndexOf(o));
}
}
System.out.println(list);
}
}
Hi sir Good Morning..
How to get an array without duplicate elements..and without using collections API methods..can you please provide me an simple program for this ..?
Thank you..
It is simple C-lang question. Take each element and iterate the other to check whether element is same or not. Take idea from other but do not ask for the code; else you do not develop.
I have to write a program for printing the prime numbers from 1 to the limit input by the user.Can you help me for the same?
Do not ask this type programs anyone. You should develop yourself. You may take sometime. Try. Take idea (not code) from your lecturer. Do not take code itself from anybody.
|
https://way2java.com/collections/class-arrays-api-methods/
|
CC-MAIN-2020-50
|
refinedweb
| 607
| 59.6
|
This Tutorial Provides Detailed Explanation of Deque or “Double-ended Queue” in Java. You will learn about Deque Interface, API Methods, Implementation, etc:
The Deque or “double-ended queue” in Java is a data structure in which we can insert or delete elements from both the ends. The deque is an interface in Java belonging to java.util package and it implements java.queue interface.
We can implement deque as a stack (Last In, First Out) structure or as a queue (first-in-first-out). Deque is faster than Stack and/or LinkedList. Deque is pronounced as “deck” as in the “deck of cards”.
=> Check Here To See A-Z Of Java Training Tutorials Here.
What You Will Learn:
Deque In Java
A typical deque collection will look as shown below:
Deque is mostly used to implement stack, queue, or list data structures. It can also be used to implement priority queues. The features of undo or history mostly present in the web browsers can be implemented using deques.
Java Deque Interface
The diagram below shows the hierarchy for the double-ended queue or deque. As shown in the below diagram, the Deque interface extends to the Queue interface that in turn extends the Collection interface.
To use a deque interface in our program, we have to import the package that holds deque functionality using an import statement as shown below.
import java.util.deque;
or
import java.util.*;
As the deque is an interface, we need concrete classes to implement the functionality of the deque interface.
The two classes below, implement the deque interface.
- ArrayDeque
- LinkedList
Hence we can create deque objects using these two classes as shown below:
Deque<String> numdeque = new ArrayDeque<> (); Deque<String> strDeque = new LinkedList<> ();
Thus once the above deque objects are successfully created, they can use the functionality of the deque interface.
Given below are a few important points to be noted about deque:
- Deque interface supports resizable arrays that can grow as required.
- Array deques do not allow the use of Null values.
- Deque does not support concurrent access by more than one thread.
- Deque is not thread-safe unless an external synchronization is provided.
ArrayDeque In Java
ArrayDeque belongs to java.util package. It implements the deque interface. Internally, the ArrayDeque class makes use of a dynamically resizable array that grows as the number of elements is increased.
The below diagram shows the hierarchy for the ArrayDeque class:
As shown in the diagram, the ArrayDeque class inherits the AbstractCollection class and implements the Deque interface.
We can create a deque object using the ArrayDeque class as shown below:
Deque deque_obj = new ArrayDeque ();
Deque Example
The following Java program demonstrates a simple example to better understand the deque. Here, we have used the ArrayDeque class to instantiate the deque interface. We have just added some elements to the deque object and then printed them using a forEach loop.
import java.util.*; public class Main { public static void main(String[] args) { //Creat a Deque and add elements Deque<String> cities_deque = new ArrayDeque<String>(); cities_deque.add("Delhi"); cities_deque.add("Mumbai"); cities_deque.add("Bangaluru"); System.out.println("Deque Contents:"); //Traverse the Deque for (String str : cities_deque) { System.out.print(str + " "); } } }
Output:
Deque API Methods In Java
As the deque interface implements a queue interface, it supports all the methods of the queue interface. Besides, the deque interface provides the following methods that can be used to perform various operations with the deque object.
Let’s summarize these methods in the below table.
Deque Implementation In Java
Let’s now implement a Java program to demonstrate some of the major deque methods discussed above.
In this program, we use a String type deque and then add elements to this deque using various methods like add, addFirst, addLast, push, offer, offerFirst, etc. Then we display the deque. Next, we define the standard and reverse iterators for the deque and traverse through the deque to print the elements.
We also use the other methods like contains, pop, push, peek, poll, remove, etc.:
Frequently Asked Questions
Q #1) Is Deque thread-safe Java?
Answer: ArrayDeque is not thread-safe. But the BlockingDeque interface in the java.util.concurrent class represents the deque. This deque is thread-safe.
Q #2) Why is Deque faster than stack?
Answer: The ArrayDeque interface that implements the deque interface is memory efficient as it need not keep a track of the previous or next nodes. Also, it is a resizable implementation. Thus deque is faster than the stack.
Q #3) Is Deque a stack?
Answer: A deque is a double-ended queue. It permits LIFO behavior and thus it can be implemented as a stack though it is not a stack.
Q #4) Where is Deque used?
Answer: A deque is mostly used to implement features like undo and history.
Q #5) Is Deque circular?
Answer: Yes, Deque is circular.
Conclusion
This completes our tutorial on the Deque interface in Java. The deque interface is implemented by a deque data structure which is a collection that can insert and delete elements from both the ends.
The two classes i.e. ArrayDeque and LinkedList implement the deque interface. We can use these classes to implement the functionality of the deque interface.
=> Visit Here For The Exclusive Java Training Tutorial Series.
|
https://www.softwaretestinghelp.com/deque-in-java/
|
CC-MAIN-2021-17
|
refinedweb
| 884
| 57.47
|
IR Remote Controlled Led With Arduino
Introduction: IR Remote Controlled Led With Arduino
Hey guys!
This is my first instructable. It was after spending some time on the net and with a IR remote I figured out how to use it. So I thought I would make it easy for the newbies.I have simply clubbed two programs both not my own. I must admit that I do not take any credits of writing the code myself. So lets start
Step 1: Before We Begin
The components required would be
- Arduino
- 1 kilo ohms resistor
- led
- breadboard
- wires
- IR remote
- IR sensor
I have used KEYES remote and sensor available online. Can chose your own.
Now a special library is required . Including the library will provide us with some special functions and save our time from writing our own.
Thanks to GITHUB they have made it available for all
Download the zip folder. After downloading unzip and give it a name of your choice. Paste the folder in the 'libraries' folder of your 'Arduino'
To ensure that the library is put properly in its place you can always check as shown in the image.
This will conclude all the requirements to begin
Step 2: The Connections
The connections are done according to the code which I've used.
If you look closely at the IR receiver you'll find a letter written at each pin. There are three pins . Like any other receiver there is one GND and Vs. Another pin is pinout. In my KEYES receiver 'G' is for GND , 'R' for Vs and 'Y' for pinout.
Pinout is connected to pin 11 of arduino.
Now to connect an led shall not be a trouble. I've used 1 Kilo ohms resistor to protect the led. Led is connected to pin 13( which also has an on board led).....Every thing here is just like the blink program
Step 3: CODE
#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
pinMode(13, OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results))
{
Serial.println(results.value); //value displayed in the serial window are in decimal
unsigned long data= results.value;
if(data==16736925) //select the value of the button of your choice
{
digitalWrite(13, HIGH); //this is the famous blink program
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
irrecv.resume(); // Receive the next value
}
delay(100);
}
As I had initially, I take no credits of the above code,except for putting them together.
Now if you look at the code you'll find that only one header file is included. Usually we tend to include the required header files by selecting 'Include Library' from the menu bar. What happens in such a case is there will be also included which will give 'TKD2 error' while verifying. So do not include it as it is not required.
Step 4: Explanations
The code is self explanatory,but to those who find it hard to understand let me give a brief overview.
In the setup I've enabled the receiver. In the loop , I'm printing the values received by the receiver in the serial window. Each key holds a value which is decoded and displayed in decimal on the screen. First try out the values of different keys(button). After knowing the value of the button of your choice enter that value in the 'if' statement for comparison. I've given a simple task of blinking the led. Do any action of your choice.
After performing the operation the sensor prepares to accept another value.
Step 5: Your Done
So now you have learnt how to assign task for each button. Try out with different remotes and assign various tasks.
All the best!!
Keep thinking ,Keep doing
This is a really cool projects because you can use it to control just about anything from a TV remote.
|
http://www.instructables.com/id/IR-Remote-Controlled-Led-With-Arduino/
|
CC-MAIN-2017-43
|
refinedweb
| 655
| 74.69
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.