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 |
|---|---|---|---|---|---|
The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.
Following is the declaration for gets() function.
char *gets(char *str)
str − This is the pointer to an array of chars where the C string is stored.
This function returns str on success, and NULL on error or when end of file occurs, while no characters have been read.
The following example shows the usage of gets() function.
#include <stdio.h> int main () { char str[50]; printf("Enter a string : "); gets(str); printf("You entered: %s", str); return(0); }
Let us compile and run the above program that will produce the following result −
Enter a string : tutorialspoint.com You entered: tutorialspoint.com | https://www.tutorialspoint.com/c_standard_library/c_function_gets.htm | CC-MAIN-2020-40 | refinedweb | 145 | 71.55 |
Comparison of Chat Message Platforms
If you’re writing a chat app, the first big question to consider is whether you are going to write the actual chat backend. Why would you want to? You would get complete control over the functionality, reliability and interface. Why would you not want to? Well, persistent socket systems that scale to thousands or hundreds of thousands of users are no small undertaking. Plus, a bunch of good platforms already exist. It probably comes down do whether chat is part if your core business. If you’re Snapchat, you probably want to write your own chat platform. If chat is just a feature you use to deliver your actual value, it probably does not make sense to spend the engineering time on it.
What platforms exist that could be used to write a chat app, and how do they stack up? Here is a rundown as of late 2015. My criteria is specific to what I’m trying to build:
- Excellent documentation is a must.
- iOS, Node and Python SDKs preferred.
- iOS notifications.
- Web hooks (so we can use stateless web servers).
- Chats with more than two participants.
- Need to be able to extend the messages with custom metadata.
- End-to-end message encryption would be ideal.
- Proven ability to handle a large number of sessions.
I evaluated eight platforms, and seriously considered three options before making a final decision.
Also Rans
These platforms could be used to create a chat app, but all had various glaring issues.
- Telegram - No SDKs, just a REST APIs and a bunch of iOS code you can refactor to meet your needs. Hey guys, I don’t want to write HTTP request code manually for three platforms!
- Intercom.io - Their primary focus is providing a call center chat app themselves, not enabling you to build your own app. As far as I could tell, chats were always one to one.
- Pusher - They do much more than chat, not focused on that. No iOS notification support.
- Firebase - They do much more than chat, you can build your whole app and deploy it inside their platform. No native chat semantics, you would need to implement everything yourself.
- Iron.io - It’s a message queue. No iOS SDK. API is REST, not socket based.
#3: Quickblox
Quickblox focuse on chat, and on the developer experience (they don’t have a chat app themselves). They have been around for a while (2013), and they’re based on XMPP, which is an open standard. They have an excellent reference iOS application.
No Python SDK, and no web hooks. But the killer was the difficulty of our prototype work. Calling their REST API from Python was super painful. The auth request has a timestamp, nonce and HMAC signature, which is super brittle. If the order of the parameters is not alphabetical, or there is any problem with how you setup the HMAC, you just get a generic signature error with no trouble-shooting information. Then you have a series of required custom HTTP headers.
All of these problems are solvable by writing your own Python SDK. But the iOS and Node.js SDKs were also hard to get working. Their Node library, admittedly in beta, was broken. Overall, their documentation was poor - it was hard to get stuff working. Take a look at how verbose the following code is:
import random import time import hashlib import hmac import requests APP_ID = 'XXX' AUTH_KEY = 'XXX' AUTH_SECRET = 'XXX' USER_ID = 'XXX' PASSWORD = 'XXX' DIALOG_ID = 'XXX' def create_session(): nonce = str(random.randint(1, 10000)) timestamp = str(int(time.time())) signature_raw_body = ( 'application_id=' + APP_ID + '&auth_key=' + AUTH_KEY + '&nonce=' + nonce + '×tamp=' + timestamp + '&user[login]=admin' + '&user[password]=password') signature = hmac.new(AUTH_SECRET, signature_raw_body, hashlib.sha1).hexdigest() response = requests.post( '', headers={ 'Content-Type': 'application/json', 'QuickBlox-REST-API-Version': '0.1.0', }, json={ 'application_id': APP_ID, 'auth_key': AUTH_KEY, 'timestamp': timestamp, 'nonce': nonce, 'signature': signature, 'user': { 'login': 'admin', 'password': 'password', } }) json_data = response.json() return json_data['session']['token'] def get_messages(qb_token): return requests.get( '' + DIALOG_ID, headers={ 'QB-Token': qb_token, } ) if __name__ == '__main__': qb_token = create_session() messages = get_messages(qb_token) print messages, messages.content
#2: PubNub
PubNub is not focused exclusively on chat, but chat is a first class topic in their documentation. Truly excellent SDKs for virtually every language you could care about. Sometimes there are multiple SDKs for the same language that are specialized for particular frameworks - think Django, Twisted and Tornado. They have a lot of mindshare in the developer community; I constantly hear about other engineers using PubNub for hackathon projects. They pop up organically in my Twitter feed a lot.
Prototyping could not have been simpler. See the bellow code. The only downside is that they do not have true web hook support. Their web hooks are limited to when conversations start and stop, versus firing on every chat message.
Why are web hooks a big deal? They probably are not for many use cases. But one thing we want to be able to do is have a Python bot that listens to all conversations and performs various actions in real-time. As far as I can tell, the PubNub model for this is to use something like Twisted, which is an asynchronous event-based networking engine in Python. You leave a socket open to PubNub all the time and get notified of new messages over that active connection.
That performs really well, which is why they do it. But it drastically increases the complexity with regards to production high availability, versus a vanilla web server. With a web server, if you loose a node (and you will, think EC2 instance going down), it’s no problem. You simply have multiple nodes behind a load balancer. Because they are all stateless, recovery is automatic as new requests keep flowing to the remaining nodes.
With an active socket daemon, you have to solve the high availability problem yourself. If you create a master/hot backup architecture, you need to realize that the primary node is down and have the secondary server establish a connection and resume any in progress conversations. That’s a separate critical code path that will execute only very rarely - a recipe for bugs. If you go active/active, then you have all the same problems of resuming a portion of the connections when a node fails, plus you have to figure out connection sharding.
None of these are insurmountable problems. But they are significant added complexity, which is what I’m trying to avoid by using an existing platform. PubNub has a super simple SDK, but then they force you to solve a bunch of architectural complexity yourself.
Here is our prototype code. Notice the paradigm; event loops. This code blocks until you kill the process.
from pubnub import Pubnub def callback(message, channel): print(message) def error(message): print("ERROR : " + str(message)) def connect(message): print("CONNECTED") print pubnub.publish(channel='test', message='Hello from the PubNub Python SDK') def reconnect(message): print("RECONNECTED") def disconnect(message): print("DISCONNECTED") pubnub = Pubnub(publish_key='XXX', subscribe_key='XXX', secret_key='XXX') pubnub.subscribe( channels='dit', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect, )
#1: Layer
Layer is a new player. They focus solely on chat. They have good iOS and Node SDKs (but not Python). Their REST API semantics are dedicated to chat. Conversations and messages are first class concepts. Their documentation is good, if not as exhaustive as PubNub. Importantly, they have web hooks for each message (currently in private beta).
One downside is that they do not support end-to-end encryption per-se. Of course, you can manually encrypt your message bodies yourself. Being newer, they also do not have the track record that PubNub has.
Even though they do not have a Python SDK, our prototype code could not have been more Pythonic. This makes me confident we will be able to write clean code, and use a simple web server architecture.
Finally, there is significant upside to being a chat specific platform. The SDKs support concepts like read/unread, typing indicators, etc. You can do that yourself via PubNub, but you have to write more code. PubNub is schemaless - you are writing all the schema plus serialization yourself, separately for each language. Code is the enemy!
import requests APP_ID = 'XXX' PLATFORM_API_TOKEN = 'XXX' HOST = '' BASE_URL = HOST + '/apps/%s' % APP_ID HEADERS = { 'Accept': 'application/vnd.layer+json; version=1.0', 'Authorization': 'Bearer %s' % PLATFORM_API_TOKEN, 'Content-Type': 'application/json', } def _request(method, relative_url, data=None): data = data or {} callable_ = getattr(requests, method) return callable_( BASE_URL + relative_url, headers=HEADERS, json=data, ) def get_conversation(): return _request('post', '/conversations', data={ 'participants': ['John', 'Jane'], 'distinct': True, }) def get_messages(conversation_id): return _request('get', '/conversations/%s/messages' % conversation_id) def post_message(conversation_id, text): return _request('post', '/conversations/%s/messages' % conversation_id, data={ 'sender': { 'name': 'Chase', }, 'parts': [ { 'body': text, 'mime_type': 'text/plain', } ] }) conversation = get_conversation() conversation_id = conversation.json().get('id') conversation_id = conversation_id.replace('layer:///conversations/', '') print conversation_id messages = get_messages(conversation_id) print messages, messages.content post_response = post_message(conversation_id, 'this is a test') print post_response, post_response.content
Conclusion
I hope this helps you if you need to make a similar decision. Hit me up on Twitter and let me know how it goes! | https://chase-seibert.github.io/blog/2015/12/04/chat-message-platforms.html | CC-MAIN-2018-05 | refinedweb | 1,529 | 58.28 |
On Tue, Jul 24, 2012 at 01:46:24AM +0800, Thomas Goirand wrote: > On 07/23/2012 07:31 PM, Mike Gabriel wrote: > > * Package name : melange > This name clashes with Openstack Melange. > > > > > > Please don't use it. This name is *already taken* and used in Ubuntu > (though I don't think this is packaged in Debian ... yet). > > It would be really unfortunate that Debian can't use the same package > name as Ubuntu, let's avoid it! This seems an aweful lot like the nodejs / node situation. Let's not let anyone take "melange" and use cream-melange and openstack-melange :) No one has any more "right" to the name :) Ubuntu has gdm3 --> gdm, I mean, it's not unheard of. Although, after it's upstream, I'm guessing it'll get removed and sunk. Let's kill off a namespace thing before we get there. > > Cheers, > > Thomas Goirand (zigo) > > > -- > To UNSUBSCRIBE, email to debian-devel-REQUEST@lists.debian.org > with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org > Archive: [🔎] 500D8DF0.50900@debian.org">[🔎] 500D8DF0.50900@debian.org > -- .''`. | https://lists.debian.org/debian-devel/2012/07/msg00674.html | CC-MAIN-2017-43 | refinedweb | 180 | 74.69 |
The Dojo Toolkit has been around for over four years, and has undergone significant changes, both big and small, in becoming a great JavaScript toolkit. This article debunks myth and outdated assumptions (both fair and false) applied to Dojo over its four plus years of development.
Dojo is Undocumented
Far from it! Early on, Dojo’s only documentation was the source code. Today, we have a tremendous amount of information available, and we’re working to better organize and refine it.
To start, take a look at the Dojo QuickStart Guide, Dojo API Viewer, and Dojo Campus Documentation Project (the forthcoming replacement for the venerable Dojo Book).
Want offline docs? Check out the Dojo Toolbox for now, and soon the Dojo Campus Documentation Project.
Need a book? There are now four great dead tree Dojo books to choose from.
Need a great how-to or walthrough? Try one of these in depth Dojo tutorials.
Want to see demos? Look at the Dojo Campus Feature Explorer or the Dojo Spotlight.
Need hands-on Training? Contact SitePen for assistance.
Will Dojo continue to simplify and improve its documentation? Absolutely, and we welcome your help and feedback.
Dojo is Slow
Any JavaScript library can be slow if used incorrectly. In the days of Dojo 0.4, it was too easy to create apps that were slow by having the parser on by default, and include extraneous files and source code.
Today, the parser is a problem unique to Dijit. Dojo != Dijit, and today you only accept the performance hit of a parser (one that is much less than the days of 0.4) when you need a full-featured widget system.
For the past 18 months, Dojo has made it easy to create things with Dojo that are lean and fast, and any functionality that was in Dojo 0.4 is at least 100% faster in Dojo today, and some things are 1000% faster or more. In measuring performance with querying, dojo.query is as fast if not faster than other major leading toolkits with the SlickSpeed test suite.
And Dojo offers a plethora of performance optimization techniques and suggestions to squeeze every last KB and millisecond out of your source code. Reliable, cross-browser performance is a data-driven art that requires leaving many assumptions at the door, listening to data, and making compromises as necessary.
Dojo is Bloated, Larger and More Complex than Prototype, jQuery, MooTools, YUI, etc.
Dojo is designed to give you the necessary tools to solve complex engineering problems, while keeping the simple things simple. This myth exists simply because we use a package system, and we expect developers to leverage a build tool in production code to optimize performance. If you download the full Dojo source, you will see many files. Out of all of those files, you only need to include a single one with a script tag in your markup.
We make it easy to get started by just including dojo.js from AOL or Google’s CDN services. We call dojo.js “Dojo Base”. It is 26KB (gzipped) in size, and comparable in size, features, performance, and functionality to other major toolkits.
Dojo Base provides an extremely rich and lean set of functionality useful to any web developer. I think you’ll be hard-pressed to find more functionality and performance in less KB..
In the browser, every feature adds a slight performance hit, so Dojo values the flexibility necessary to include just what you need, and no more, while offering a wide amount of features in a coherent, organized manner. If you want to use more of Dojo’s functionality, it’s completely optional, and you just dojo.require the extra features you need. The class structure in most cases just follows the logical path structure of your project. For example, dijit.foo.Bar would be expected in /dijit/foo/Bar.js.
The simple provide and require namespace system system makes it easy to use Dojo code and your code alike. This makes it possible to easily create advanced, powerful applications as well as simple features such as the Dojo Flickr Badge.
The Dojo Package system, while adding a bit of complexity that takes two minutes for new developers to learn, makes it much more readable and organized, and provides you with the ability manage your code when script includes and dependencies otherwise become unwieldy. Dojo is a library, and behaves as such. Like Java and many other languages, we automatically include only the bare minimum amount of code, with plenty of other packages that you have to include manually.
There are frameworks within the various libraries inside Dojo, the most widely-known one being Dijit. The Dijit widgets have dependencies on the framework code. These sort of long dependency chains are rare within Dojo, but exist when needed to provide more involved functionality.
Dojo Requires Java
No, not at all—even though the full Dojo SDK does include a few jar files.
In addition to browser-based capabilities, Dojo provides completely optional Rhino-based tools to optimize your code in a build step to improve performance. Rhino is the Mozilla Foundation’s JavaScript engine implemented in the Java programming language.
Why would you ever want to “build” JavaScript? To reduce the size of your source code, to optimize caching, and reduce the calls to the server. For example, you can merge CSS rules together, and take HTML resources used by widgets and turn them into JavaScript strings to reduce the number of HTTP requests, overall file size, and more.
Dojo is Verbose and is “Java for JavaScript”
The only thing in Dojo that resembles Java is our desire to include things in namespaces. Our library structure still encourages brevity, with Dojo Base features living in the dojo.* namespace. Dojo prefers dojo.byId and dojo.query over $, though it is easy to roll your own Dojo bling function if you prefer!
Dojo prefers putting everything in namespaces to reduce our footprint in the global namespace, to allow Dojo code to coexist with other libraries and user code without naming conflicts. Also, Dojo minimizes function overloading, so using full APIs helps with code maintenance.
For brevity, anything that is widely used typically makes its way into the top level namespace in a short and easy to remember manner, e.g. dojo.connect and dojo.attr. The terseness of our API and namespace structure tends to surprise people who haven’t used Dojo since 0.4 or earlier.
Each component is a distinct “thing” and our only options are to address this in the global namespace which would create conflicts, or to hang it off of Dojo. Admittedly, some projects and toolkits don’t have namespaces simply because they don’t provide enough code to need namespaces.
Java developers do like Dojo (or DWR or even GWT or Ext), most likely because of the breadth, depth, and organization of the Dojo Toolkit APIs.
Much of the inspiration for Dojo is derived from Python, AOP, PHP, Java, and a variety of functional programming language constructs like hitch, mixins, delegation, and more. However, we explicitly avoid using any patterns from other languages, and we make great efforts to make our JavaScript leverage the patterns unique to JavaScript.
Toolkit constructs such as dojo.declare() may be considered Java-like, though most libraries have some sort of constructor and inheritance model. Dojo takes advantage of the flexibility of JavaScript rather than trying to provide a domain specific language on top of JavaScript.
Dojo is only Useful for Enterprise Apps and not for Small Sites or Blogs
This myth exists because Dojo was not as small and simple in the Dojo 0.4 days as it is now.
Dojo Base at 26KB gzipped or Dojo Mini down to 5.5KB, both with the same easy to use API, make it possible to do simple progressive enhancement or unobtrusive JavaScript, handle events, Ajax, animations, DOM, querying, and more.
Dojo is Not for Single-Page Apps
The developers from Cappuccino, Objective-J, and Sprout Core argue that they created their efforts because other toolkits are not optimal for true applications in the browser. In our opinion this is rubbish.
Dojo is used widely in feature-rich applications by a variety of companies, such as Sun Convergence, Cisco’s WebEx Connect and IBM’s Project Zero. Dojo is also very widely used for creating applications that live inside the firewall in what I call Ajax Dark Matter.
Dojo is not for Multi-Page Apps and Web Sites
While it’s unlikely that anyone believes both this myth and the previous one, this viewpoint is based on perspective. Given the perceived bloat and toolkit size, some people have suggested that Dojo not be used for multi-page sites, but Dojo’s extensive optimization options make this usage scenario a snap. The Eye-Fi Manager and even the Dojo Foundation web site itself show how snappy these apps and sites are.
Dojo is Just About Widgets
Dojo has a highly flexible, and extremely fast widget system called Dijit. This is a completely optional package for people needing to use and create their own widgets. It is designed to handle a variety of use cases in a modular manner, including accessibility, internationalization, layout, containment, templating, and much more. The underlying concept is that each widget is simply an HTML template, a CSS template, and a JavaScript file for logic.
Many of our users never even touch Dijit.
There are other ways to get lightweight reusable behavior on the fly, including Dojo’s implementation of the Django Templating Language (DTL).
Interest in Dojo is Waning
Why do people think this? Perhaps it is from badly argued stats. People do things like compare Google stats for searches like “jQuery JavaScript” “Prototype JavaScript” “Dojo JavaScript”, etc. because the words on their own conflict with general search terms. Lies, damn lies, and statistics, right?
While interest in other great toolkits has also grown significantly, the usage of Dojo continues to grow aggressively, based on the number of deployed applications, downloads, site traffic, books sold, and a variety of other usage statistics. By all appreciable measures, interest in Dojo is growing faster than ever.
Ajax has become increasingly more popular, and JavaScript is now considered a real language. Dojo has always treated JavaScript as a first-class language, and has a stricter focus on utility than on one particular aspect of the workflow, such as the DOM.
Dojo Doesn’t Validate
A long standing complaint is that Dojo doesn’t validate. DTD != valid HTML. Custom attributes have always been valid HTML, they just don’t validate when tested against a DTD.
If DTD validation is truly important to your project, it is simple to use Dojo with graceful degradation as well; the use of custom attributes is an implementation pattern only, not a hard requirement for using Dojo. Or you can always create a DTD.
In addition to performance benefits and efficiencies of custom attributes, they are a lot friendlier and human-friendly than other options. For example, some toolkits use the rel attribute, and stuff it with data. jQuery’s popular meta plugin looks like this: “<div class=”hilight { background: ‘red’, foreground: ‘white’ }”>”. Why is this better than this non-real, but Dojo style markup: “<div jQueryType=”hilight” background=”red” foreground=”white”>”?
The HTML specification states that any attribute not recognized is to be ignored by the HTML rendering engine in user agents, and Dojo optionally takes advantage of this to improve ease of development.
Dojo is Ugly
Creating beautiful web applications is about having a great sense of style, and interaction/user experience design capabilities. Dojo provides 3 professionally designed themes: Tundra, Soria and Nihilo. If you would like to make them look better, or create a new theme, then get involved!
Dojo’s themes are deliberately understated to make it easier to drop components in alongside existing designs and brands. But at SitePen, in our work with clients we’ve applied our CSS and design skills to Dojo-based applications to create excellent designs and amazing experiences.
Many other companies are also succeeding with theming their Dojo-based applications.
Dojo Doesn’t Offer Certain Features Provided by a Particular Library.
Dojo Doesn’t Work with a Particular Toolkit, Environment or Server
We go out of our way to make sure Dojo works with everything, even when a toolkit or server doesn’t behave the way we’d like. If something is not working for you, just ask on the Dojo Forums or through SitePen Support, and if there’s a bug, file a ticket and it will get fixed ASAP. We’ve gone to great lengths to make sure Dojo works well with popular toolkits, as well as in a variety of environments including: XUL, command-line, Jaxer, AIR, etc., support for initiatives by the OpenAjax Alliance, as well as integration with DWR, Persevere, Zend Framework, IBM Websphere, Django, Ruby On Rails, and much, much more.
Dojo was initially started to stop reinventing the DHTML toolkit wheel, with the original Dojo source code based significantly on the work of earlier toolkits such as netWindows, BurstLib, and f(m).
The People at Dojo Don’t Like a Particular Project
In general, on an interpersonal level, we’re friends with the people creating jQuery, Prototype, YUI, MooTools and more. While Dojo developers of course have differences of opinion in the best approach to development (great developers should disagree, as long as they keep the debate focused on merit rather than the form of the message), we find that fans of Dojo and other toolkits attempt to make things a bigger rivalry than toolkit authors do. After all, we are talking about open-source toolkits that are liberally licensed (BSD, AFL, MIT, Apache, etc.), so it’s hard for us to not get along. Alex Russell, Peter Higgins and I are also on record as inviting other toolkits to collaborate and cooperate to again stop reinventing the wheel.
In many cases, this is a matter of perspective. I know that many of us get bugged because so much of the mud flinging happens not because someone’s done something wrong, but because features of a particular toolkit are criticized because the person doing the criticizing doesn’t understand why those features even exist in a particular toolkit.
It is difficult to contribute to Dojo or Get Involved
Unlike most other toolkits, Dojo requires a CLA which protects your IP rights, and also requires that when you contribute code, you have the right to contribute it. The Dojo Foundation does this to ensure that we are able to redistribute every piece of code in the Toolkit completely free and with liberal licensing. It’s a simple process that should take at most fifteen minutes, and it is well worth the effort. For more information about getting involved, contributing, donating, visit the Dojo Foundation and Dojo Toolkit web sites, or visit the Dojo IRC channel on irc.freenode.net in #dojo.
Dojo lacks Commercial Support
A number of companies including SitePen offer Dojo development, support and training services. The Dojo community offers great free support, but when an issue goes beyond what is reasonable to ask of a volunteer, or needs to occur immediately and/or under an NDA, companies like SitePen are available to help you get productive, from fixing a bug in Dojo to building and designing your entire application.
Summary
As you can see, Dojo has come a long way since its initial creation 4+ years ago. Over the next several months, Dojo developers will continue to improve the toolkit source code, documentation and marketing to make Dojo easy to use regardless of the type of application or web site you are developing.
I hope you will make the decision to use, or not use, Dojo based on merit, rather than on myths or information that is no longer or was never accurate.
Pingback: Ajaxian » Debunking Dojo Myths
Pingback: Uxebu.com - JavaScript addicts » What dojo really is
Pingback: Dojo Javascript Opinions? - Irish SEO, Marketing & Webmaster Discussion
Pingback: DojoCampus » Blog Archive » Tooltips from Anchors
Pingback: Framework-uri JavaScript: Introducere | Interfete Web
Pingback: MooTools vs JQuery vs Prototype vs YUI vs Dojo Comparison Revised | Peter Velichkov's Blog
Pingback: Learning Dojo | SitePen Blog | http://www.sitepen.com/blog/2008/10/27/debunking-dojo-toolkit-myths/comment-page-1/ | CC-MAIN-2014-15 | refinedweb | 2,721 | 53.41 |
IronRuby is a Ruby implementation that is written on top of the .NET framework. It runs on top of the DLR (Dynamic Language Runtime), the bridge between the .NET framework and the dynamic languages that are written on top of it.
The main goal of IronRuby is to provide seamless integration with .NET objects that is achieved in a very elegant way; to work with a .NET assembly, just load it using Ruby’s require method (similar to adding a reference in C#/VB.NET).
For example, assuming you have the next C# class that features two methods which indicate whether a given time is daytime or nighttime and it is saved in an assembly named CustomTools.dll:
using System; namespace CustomTools { public class DayNightHelper { public bool IsDay(DateTime value) { if (value.Hour > 7 && value.Hour < 19) return true; else return false; } public bool IsNight(DateTime value) { bool isDay = IsDay(value); return !isDay; } } }
Using this class from IronRuby is easy as pie:
require "DayNightHelper.dll" # Call C# class constructor helper = CustomTools::DayNightHelper.new # Call C# method day = helper.is_day(Time.now) if day then puts "The sun is in the sky, go out!" else puts "Good night!" end
Because calling .NET assemblies is so easy from IronRuby code, it enables developers to take advantage of Ruby’s libraries and frameworks together with .NET assemblies, and make the most out of this combination.
One of the areas that pops to my mind instantly, which makes the Ruby/.NET combination shine the most, is using Ruby’s incredible testing frameworks to test .NET code.
In this article, I will introduce three of Ruby’s testing frameworksRSpec, Cucumber, and riotand show you how to use them to test .NET code.
RSpec
RSpec is one of the most popular testing frameworks in Ruby, if not the top one. It follows BDD (Behavior Driven Development) principles, a fact that reflects on its terms. Basically, in RSpec you separate your tests into behaviors which are the test containers. Every behavior contains multiple examples, which are the test methods. The logic behind the terms is to give you the illusion that you do not test codeyou validate behavior.
RSpec provides a DSL (Domain Specific Language) for tests that result in clean and elegant test code. A behavior is contained within a method named describe. This method receives a textual description of the behavior or a class type, if a single class is being tested. Inside the describe call body, you can add multiple examples via a method named it. This method receives a textual description as well, and contains the actual test code. In addition, every example must have some kind of comparison between the expected result and the actual one. This is done with the should method, which is added to all Ruby objects.
For example, a simple RSpec code to validate the behavior of the DayNightHelper class is as follows. Notice the clean code:
require "DayNightHelper.dll" # The following require statements are needed for RSpec to run require "rubygems" require "spec" require "spec/autorun" # Define a behavior with describe describe "Test DayNightHelper class for perfection" do # Define examples with it it "should be day on 15:00" do instance = CustomTools::DayNightHelper.new result = instance.is_day(Time.local(2012,12,21,15,0)) # Compare actual and expected result with should result.should == true end it "should not be night on 15:00" do instance = CustomTools::DayNightHelper.new result = instance.is_night(Time.local(2012,12,21,15,0)) # There are also some cool methods to do common comparisons. # For example, the next line is identical to "result.should == false": result.should be_false end end
Executing behaviors is done from the command line using the IronRuby interpreter: ir.exe. Assuming the RSpec code is located in a file named rspec_test.rb, executing it will be done as follows:
>ir rspec_test.rb .. Finished in 0.168009 seconds 2 examples, 0 failures
It is also possible to show the textual descriptions of the behavior and examples in the report by using --format s:
>ir rspec_test.rb --format s Test DayNightHelper class for perfection - should be day on 15:00 - should not be night on 15:00 Finished in 0.158009 seconds 2 examples, 0 failures
What I brought you here is only a taste of RSpec capabilities. To learn more about it, visit the RSpec official site. | http://www.informit.com/articles/article.aspx?p=1583174&seqNum=3 | CC-MAIN-2016-40 | refinedweb | 727 | 66.54 |
Context Menu Data Binding Basics
This article explains the different ways to provide data to a Context Menu component, the properties related to data binding and their results.
For details on Value Binding and Data Binding, and the differences between them, see the Value Binding vs Data Binding article.
First, review:
- The available (bindable) features of a context menu item.
- How to match fields in the model with the menu item data bindings.
There are two modes of providing data to a menu, and they all use the items' features. Once you are familiar with the current article, choose the data binding more you wish to use:
- Hierarchical data - separate collections of items and their child items.
- Flat data - a single collection of items with defined parent-child relationships.
Context Menu Item Features
The menu items provide the following features that you control through the corresponding fields in their data binding:
Id- a unique identifier for the item. Required for binding to flat data.
ParentId- identifies the parent to whom the item belongs. Required only when binding to flat data. All items with the same
ParentIdwill be rendered at the same level. For a root level item, this must be
null. There should be at least one root-level item.
HasChildren- can hide child items. The menu will fetch its children from the data source based on the
Id-
ParentIdrelationships (for flat data) or on the presence of the
Itemscollection (for hierarchical data). If you set
HasChildrento
false, child items will not be rendered even if they are present in the data. If there are no child items in the data, an expand icon will not be rendered regardless of its value.
Items- the collection of child items that will be rendered under the current item. Required only when binding to hierarchical data.
Text- the text that will be shown on the item.
ImageUrl/
Icon/
ImageClass- the URL to a raster image, the Telerik icon, or a class for a custom font icon that will be rendered in the item. They have the listed order of precedence in case more than one is present in the data (that is, an
ImageUrlwill have the highest importance).
Url- the view the item will navigate to by generating a link.
Separator- when set to
true, the item will be just a line that makes a distinction between its neighbors clearly visible. Thus, you can place logically grouped items between two separators to distinguish them. A separator item does not render text, icons, children or a navigable link.
Disabled- You can disable items by setting this field to
true. Such items will keep rendering but will not be clickable.
Data Bindings
The properties of a menu item match directly to a field of the model the menu is bound to. You provide that relationship by providing the name of the field from which the corresponding information is present. To do this, use the properties in the main
TelerikMenu tag:
- IdField => Id
- ParentIdField => ParentId
- TextField => Text
- IconClassField => IconClass
- IconField => Icon
- ImageUrlField => ImageUrl
- UrlField => Url
- HasChildrenField => HasChildren
- ItemsField => Items
- DisabledField => DisabledField
- SeparatorField => Separator
There are default values for the field names. If your model names match the defaults, you don't have to define them in the bindings settings.
If your model field names match any of the default names, the component will try to use them. For example, a field called
Icon will try to produce a Telerik icon out of those values and that may not be what you want. If you want to override such behaviors, you can set
IconField="someNonExistingField". You can read more about this here. This also applies to other fields too. Another example would be a field called
Url - in case you want to perform navigation yourself through templates, you may want to set
UrlField="someFakeField" so that the component does not navigate on its own.
Default field names for menu item bindings. If you use these, you don't have to specify them in the
TelerikMenu tag explicitly.
public class ContextMenuItem { public int Id { get; set; } public string Text { get; set; } public int? ParentId { get; set; } public bool HasChildren { get; set; } public string Icon { get; set; } public string Url { get; set; } public bool Disabled { get; set; } public bool Separator { get; set; } }
Data bind the context menu to a model with custom field names
@* This example shows flat data binding with custom fields, and two separator items around a disabled item at the root level and in the nested menu *@ <div class="menuTarget"> right click this context menu target </div> <TelerikContextMenu Data="@ContextMenuItems" Selector=".menuTarget" ParentIdField="@nameof(ContextMenuItem.SectionId)" IdField="@nameof(ContextMenuItem.Id)" TextField="@nameof(ContextMenuItem.Section)" UrlField="@nameof(ContextMenuItem.Page)" DisabledField="@nameof(ContextMenuItem.IsDisabled)" SeparatorField="@nameof(ContextMenuItem.IsItemSeparator)"> </TelerikContextMenu> @code { public List<ContextMenuItem> ContextMenuItems { get; set; } public class ContextMenuItem { public int Id { get; set; } public int? SectionId { get; set; } public string Section { get; set; } public string Page { get; set; } public bool IsDisabled { get; set; } public bool IsItemSeparator { get; set; } } protected override void OnInitialized() { ContextMenuItems = new List<ContextMenuItem>() { // sample URLs for SPA navigation new ContextMenuItem() { Id = 1, Section = "Overview", Page = "contextmenu/overview" }, new ContextMenuItem() { Id = 2, Section = "Demos", Page = "contextmenu/demos" }, new ContextMenuItem() // separator item { Id = 3, IsItemSeparator = true }, new ContextMenuItem() // disabled item { Id = 4, Section = "Disbled Item", IsDisabled = true }, new ContextMenuItem() { Id = 5, IsItemSeparator = true }, new ContextMenuItem() { Id = 6, Section = "Roadmap" }, // sample URLs for external navigation new ContextMenuItem() { Id = 7, SectionId = 6, Section = "What's new", Page = "" }, new ContextMenuItem() { Id = 9, SectionId = 6, Section = "Release History", Page = "" }, new ContextMenuItem() { Id = 10, IsItemSeparator = true, SectionId = 6 }, new ContextMenuItem() { Id = 11, SectionId = 6, Section = "Roadmap", Page = "" } }; base.OnInitialized(); } } <style> .menuTarget { width: 100px; background: yellow; margin: 50px; } </style>
The result from the snippet above
| https://docs.telerik.com/blazor-ui/components/contextmenu/data-binding/overview | CC-MAIN-2022-05 | refinedweb | 953 | 51.18 |
AxKit::App::TABOO::Data - Base class of abstracted Data objects for TABOO
You would rarely if ever use this class directly. Instead, you would call a subclass of this class, depending on what kind of data you are operating on. This class does, however, define some very useful methods that its subclasses can use unaltered.
It is to be noted that I have not,
neither in this class nor in the subclasses,
created methods to access or set every field.
Instead,
I rely mainly on methods that will manipulate internal data based on the for example objects that are passed as arguments.
For example,
the
write_xml-method (below),
will create XML based on all the available data in the object.
This is usually all you want anyway.
In some subclasses, you will have some degree of control of what is loaded into the object data structure in the first place, by sending the names of the fields of the storage medium (e.g. database in the present implementation).
Similarly, if data is sent from a web application, the present implementation makes it possible to pass an Apache::Request object to a Data object, and it is up to a method of the Data object to take what it wants from the Apache::Request object, and intelligently store it.
Some methods to access data will be implemented on an ad hoc basis,
notably
timestamp()-methods,
that will be important in determining the validity of cached data.
Sometimes you might want to retrieve more than one object from the data store, and do stuff on these objects as a whole. Furthermore, the load methods used to retrieve multiple objects may be optimized. For this, TABOO also has Plural classes.
new()
The constructor of this class. Rarely used.
load(what => fields, limit => {key => value, [...]})
Will load and populate the data structure of an object with the data from a data store.,
and must be used to identify a record uniquely.
It is itself a reference to a hash,
containing data store field values as keys and values are corresponding values to retrieve.
These will be combined by logical AND.
If there is no data that corresponds to the given arguments,
this method will return
undef.
_load(what => fields, limit => {key => value, [...]})
As the underscore implies this is for internal use only! It is intended to do the hard work for this class and its subclasses. It returns a hashref of the data from the datastore.
See the documentation for the
load method for the details on the parameters.
write_xml($doc, $parent)
Takes arguments
$doc,
which must be an XML::LibXML::Document object,
and
$parent,
a reference to the parent node.
The method will append the object it is handed it with the data contained in the data structure of the class in XML.
This method is the jewel of this class,
it should be sufficiently generic to rarely require subclassing.
References to subclasses will be followed,
and
write_xml will call the
write_xml of that object.
Arrays will be represented with multiple instances of the same element.
Fields that have undefined values will not be included.
It will also parse fields indicated by
elementneedsparse(),
see below.
Currently,
we get HTML from TinyMCE,
which we let XML::LibXML parse.
populate(\%args)
This method takes as argument a reference to a hash and will populate the data object by adding any data from a key having the same name as is used in the data storage. Fields that are not specified by the data object or that has uppercase letters are ignored.
It may be used to insert data from a request by first noting that in a HTTP request,
the Request object is available as
$r,
so you may create the hash to hand to this method by
my %args = $r->args;
Note that this only the case for HTTP GET, in the case of POST, you may have to construct the hash by e.g.
my %args = map { $_ => join('', $cgi->param($_)) } $cgi->param;
apache_request_changed(\%args)
Like the above method, this method takes as argument a reference to the args hash of a Apache::Request object. Instead of populating the Data object, it will compare the
\%args with the contents of the object and return an array of fields that differs between the two. Fields that are not specified by the data object, that has uppercase letters or has no value, are ignored.
save([$olddbkey])
This is a generic save method, that will write a new record to the data store, or update an old one. It may have to be subclassed for certain classes. It takes an optional argument
$olddbkey, which is the primary key of an existing record in the data store. You may supply this in the case if you want to update the record with a new key. In that case, you'd better be sure it actually exists, because the method will trust you do.
It is not yet a very rigorous implementation: It may well fail badly if it is given something with a reference to other Data objects, which is the case if you have a full story with all comments. Or it may cope. Only time will tell! Expect to see funny warnings in your logs if you try.
exist(%limitargs)
This method can be used to check if a record allready exists. The argument is the hash you would give to
limit in the load method.
stored()
Checks if a record with the present object's identifier is allready present in the datastore. Returns 1 if this is so.
onfile
Method to set a flag to indicate that the record is in the data store.
dbconnectargs(@args)
This method will set or retrieve the arguments that are passed to DBI's
connect method. Since this needs to be done for every object, you may also pass these arguments to the
new constructor of each subclass. However, it is recommended that you use environment variables instead.
elementneedsparse($string)
User-supplied formatting may not be valid XHTML, and so needs to be validated and parsed. This method takes a string consisting of a comma-separated list of fields that needs parsing as argument, or will return such a list if it is not given.
xmlelement($string)
This method is intended for internal use, but if you can use it without shooting somebody in the foot (including yourself), fine by me... It sets the root element that will enclose an object's data to
$string, or return it if not given.
xmlns($string)
Like
xmlelement(), this method is intended for internal use. It sets the namespace URI of the XML representation of an object to
$string, or return it if not given.
xmlprefix($string)
Alse like
xmlelement(), this method is intended for internal use. It sets the namespace prefix of the XML representation of an object to
$string, to allow using QNames, or return it if not given.
The data is stored in named fields, currently in a database, but there is nothing stopping you from subclassing the Data classes and storing it somewhere else. TABOO should work well, but if you want to make it less painful for yourself, you should use the same names or provide some kind of mapping between your names and the names in these Data classes. Note that any similarity between these names and the internal names of this class is purely coincidential (eh, not really).
Consult the documentation for each individual Data class for the names of the stored data.
There is the issue with the handling of references to other objects in the
save() method. I think it may actually cope in most cases, but it definately could use some more attention.
See AxKit::App::TABOO. | http://search.cpan.org/~kjetilk/AxKit-App-TABOO-0.52/lib/AxKit/App/TABOO/Data.pm | CC-MAIN-2017-09 | refinedweb | 1,297 | 70.43 |
With the author of Programming Praxis currently hospitalized, I’ll be posting some programming exercises in his stead until he’s recovered.
Conway’s game of life is the most well-known example of cellular automata. It consists of a 2D grid where each cell is either alive or dead. Alive cells stay alive if they have 2 or 3 alive neighbors, otherwise they die. Dead cells become alive when they have 3 alive neighbors. Other rule variations exist, but Conway’s version is the most commonly used one. These simple rules result in a lot of complexity. In fact, the game of life is equivalent to a universal Turing machine.
Theoretically, Conway’s game of life takes place on an infinite grid, but for practical reasons the size of the grid is often limited, with cells beyond the edges being assumed dead.
In today’s exercise, your task is to write an algorithm that takes a starting situation and can produce an arbitrary number of subsequent generations. When you are finished, you are welcome to read a suggested solution below, or to post your own solution or discuss the exercise in the comments below (to post code, put it between [code][/code] tags).
First, some imports.
import Data.List.Split import qualified Data.Map as M
Cells stay/become alive if they have 3 neighbors, or 2 if they’re already alive. Anything else dies.
rule :: (Num a) => Char -> a -> Bool rule c n = c == 'x' && n == 2 || n == 3
Since the algorithm needs to check a cell’s neighbors, we need to know what they are.
neighbours :: (Int, Int) -> [(Int, Int)] neighbours (y,x) = [(y', x') | y' <- [y-1..y+1], x' <- [x-1..x+1], (y', x') /= (y, x)]
We will need a way to load the starting situation.
load :: String -> M.Map (Int, Int) Char load = M.fromList . concat . zipWith (\y -> zipWith (\x c -> ((y, x), c)) [1..]) [1..] . lines
To obtain the next generation, we just apply the rule to every cell.
next :: M.Map (Int, Int) Char -> M.Map (Int, Int) Char next b = M.mapWithKey (\k a -> if rule a . length . filter (\p -> M.findWithDefault '.' p b == 'x') $ neighbours k then 'x' else '.') b
Next, we need a function to show a generation in a more readable format.
display :: M.Map (Int, Int) Char -> String display b = unlines . chunk (snd . fst $ M.findMax b) $ M.elems b
And, finally, something to show multiple subsequent generations.
run :: Int -> M.Map (Int, Int) Char -> IO () run n = mapM_ (putStrLn . display) . take n . iterate next
Let’s test to see if everything’s working correctly.
main :: IO () main = run 10 $ load ".........\n\ \.xx......\n\ \.xx..xxx.\n\ \.....x...\n\ \......x..\n\ \..x......\n\ \..x......\n\ \..x......"
If you implemented everything correctly, the last generation should look like this:
.....xx.. ....x..x. .....xx.. ......... ..xx..... .x..x.... .x.x..... ..x......
Tags: automata, bonsai, cellular, code, conway, game, Haskell, kata, life, praxis, programming | https://bonsaicode.wordpress.com/2010/05/11/programming-praxis-conways-game-of-life/ | CC-MAIN-2017-30 | refinedweb | 494 | 76.32 |
Wewelsburg Archives
publication
- 2018 -
Adolf Hitler, unser Führer
Contents
FOREWORD ............................................................................................. 1
VOLUME ONE
AN ACCOUNTING .................................................................. 3
CHILDHOOD HOME ............................................................................. 4
YEARS OF LEARNING AND SUFFERING IN VIENNA............................ 17
GENERAL POLITICAL CONSIDERATIONS OF MY VIENNA PERIOD .... 56
MUNICH .......................................................................................... 107
THE FIRST WORLD WAR .................................................................. 133
WAR PROPAGANDA ........................................................................ 150
THE REVOLUTION ............................................................................ 160
BEGINNING OF MY POLITICAL ACTIVITY ......................................... 178
THE “GERMAN WORKERS’ PARTY” ................................................. 186
CAUSES OF THE COLLAPSE .............................................................. 194
PEOPLE AND RACE .......................................................................... 250
EARLY DEVELOPMENT OF THE NATIONAL SOCIALIST GERMAN
WORKERS’ PARTY ............................................................................ 295
VOLUME TWO
THE NATIONAL SOCIALIST MOVEMENT ........................... 333
WORLD-CONCEPT AND PARTY ........................................................ 335
THE STATE ....................................................................................... 348
STATE MEMBER VS. STATE CITIZEN ................................................ 399
PERSONALITY AND THE IDEA OF THE PEOPLE’S STATE .................. 403
WORLD-CONCEPT AND ORGANIZATION ........................................ 413
THE STRUGGLE OF THE EARLY DAYS.
THE IMPORTANCE OF SPEECHES .................................................... 423
THE STRUGGLE WITH THE RED FRONT ........................................... 439
THE STRONG MAN IS MIGHTIEST WHEN ALONE ............................ 464
BASIC THOUGHTS ON THE MEANING AND ORGANIZATION
OF THE STORM TROOPS.................................................................. 473
THE MASK OF FEDERALISM............................................................. 508
PROPAGANDA AND ORGANIZATION .............................................. 532
THE UNION QUESTION .................................................................... 549
GERMAN ALLIANCE POLICIES AFTER THE WAR .............................. 560
EASTWARD ORIENTATION VS. EASTERN POLITICS ......................... 593
SELF-DEFENSE AS A RIGHT .............................................................. 620
AFTERWORD ....................................................................................... 641
Foreword
Adolf Hitler
The author
Landsberg on the Lech Prison Fortress
1
On November 9, 1923 at 12:30 P.M., the following men who believed in the
resurrection of their people, fell in front of the Field Marshall’s Hall in Munich:1
1Hitler dedicated the first volume to these men. They were the Nazi Party members who were
shot and killed during the failed putsch [putsch means coup d’état or government overthrow]
of 1923 which resulted in Hitler’s prison sentence.
2
VOLUME ONE
AN ACCOUNTING
CHAPTER ONE
Childhood Home
Today, I am pleased that Fate chose the city of Braunau on the Inn of Northern
Austria as my birthplace. This little town is on the frontier of the two German
states whose reunion, at least for those of us from the younger generation,
will be the accomplishment of a lifetime. We must do everything we can to
reunite these states.
Austria must return to the great German mother country. Not for
economic reasons. No, the economics are unimportant. Even if it did not make
economic sense, it must still take place because common blood belongs in one
common realm.
The German people have no moral right to set up remote colonies when
they cannot even unite their own children in a common state. The people will
only earn the right to acquire foreign soil when the Reich has expanded to
include every German. The plow will become the sword, and the wheat which
becomes the bread of posterity will be watered by the tears of war.
This little frontier city has now become the symbol of a great undertaking,
but it also has a past that we should take as a warning today. More than a
hundred years ago, this humble place had the privilege of being immortalized
in German history as the scene of a tragedy which shook the whole German
nation. It was the day of our Fatherland’s deepest humiliation when the
bookseller Johannes Palm, a citizen of Nuremberg, an unapologetic
“Nationalist” and hater of France, died for the Germany which he loved
passionately even in her time of misfortune.1 Palm stubbornly refused to
1Johannes Philipp Palm was a book dealer in Nuremberg and in 1806 sold a pamphlet
denouncing France titled Germany’s Deepest Humiliation, but France previously invaded and
was in control of Bavaria at that time. The Bavarian police chief turned him in. He refused to
4
Childhood Home
reveal the names of his fellows who believed as he did. He was very much like
our Leo Schlageter.2 And, like Schlageter, Palm was betrayed to France by a
government representative. An Augsburg police director was responsible, and
this act laid down the framework that formed the modern disreputable official
German government under the Reich of Mr. Severing.3 This little city on the
Inn, which was made golden as a result of the German martyrdom I
mentioned, was German-Bavarian by blood and Austrian only by borders. It is
here my parents lived in the late Eighteen-eighties. My father, a conscientious
employee of the state as a custom’s official, and my mother, occupied with
the household, were both, above all, devoted to us children with unwavering
love and care. I do not remember much from that period. After only a few
years, my father left the little frontier town he was so fond of so he could take
a new post at Passau in Germany itself. In those days, Austrian Customs
Officials traveled frequently. Soon afterward, my father went to Linz where he
retired from work. This does not mean the old gentleman had a chance to rest.
His family could be called very poor farmers and, even in his earliest days,
he had not lived in a happy home. Before he turned thirteen, the small boy
packed his knapsack and ran away from his home in the mountainous section
of lower Austria. Against the advice of villagers, he chose to go to Vienna and
learn a trade. This was back in the Eighteen-fifties, so it was not a simple
decision to travel into the unknown with only three crown coins. But by the
time the thirteen-year-old turned seventeen, he had passed his journeyman’s
examination to be a cobbler, yet he had still not found contentment. To the
contrary, the long period of economic problems back then, the unending
misery and wretchedness he encountered only strengthened his
determination to give up his trade and become something better. When he
was a poor boy in the village, he thought that the church pastor embodied the
name the author and Napoleon ordered Palm to be shot at Braunau on the Inn, where Hitler
was later born and where there is a monument to Palm.
2 Leo Schlageter fought in the First World War, joined the Nazi party in 1922, and committed
acts of sabotage against the French occupation of the Ruhr, and was betrayed, tried and
executed by the French. He was viewed as a hero in the Nazi party.
3 Carl Wilhelm Severing was a Social Democrat Official in the Weimar government controlling
Germany at that time who refused to make an effort to stop the execution of Schlageter.
5
Mein Kampf
6
Childhood Home
My desire for that calling soon disappeared and was replaced by hopes
that were better suited to my temperament. In rummaging through my
father’s library, I found various military books. There was a popular edition of
the Franco-Prussian War of 1870-71; two volumes of an illustrated magazine
from those years now became my favorite reading. It was not long before the
great heroic battle had become my greatest spiritual experience. From then
on, I became more and more enthusiastic over anything connected with war
or at least with being a soldier.
This was important to me for another reason. For the first time, I was
forced to ask myself if there was a difference between the Germans who
fought these battles and the Germans around me, and if they were different,
how were they different? Why did Austria not fight in the war? Why did my
father and all the others in our city not fight? Were we not like all the other
Germans? Did we not all belong together? This problem stirred in my young
brain for the first time. I learned that not every German was fortunate enough
to belong to the Empire of Bismarck. I could not understand this at the time,
so I began my studies.
Based on my character and especially my temperament, my father
decided that attending a classical secondary-school,4 would conflict with my
personality. He thought a vocational school would be more suitable. His
opinion was confirmed by my obvious ability to draw. That was a subject which
he believed was neglected in the Austrian humanistic schools. Perhaps his own
hard-working life made him think less of classical studies, which he considered
impractical. Being a man of principle, he had already decided that his son
should, no, must, become a state employee. His own difficult youth naturally
made his later accomplishments seem even greater because they were the
product of his own iron strength and ability. The pride of being a self-made
man led him to want the same or better for his son. He believed his own hard
work would make it easier for his child to succeed in the same field.
My outright refusal to follow a career that had been his whole life was,
to him, quite inconceivable. So, my father’s decision was simple, definite, and
4 Gymnasium or high school attended from age 10 to 18 which teaches in Greek or Latin
classics, but not vocational subjects.
7
Mein Kampf
clear, and, in his eyes, he had an obvious course of action. His lifetime struggle
for existence had made him domineering, and he would have never left an
important decision to a boy he saw as inexperienced. This would have seemed
an unforgivable weakness in the exercise of his parental authority over his
child’s future. It was impossible for him to reconcile it with his concept of duty.
And yet, it was all destined to end differently.
At the time, I was barely eleven, and for the first time in my life, I was
forced to oppose my father. Steadfast and determined as my father might be
in carrying out the plans that were fixed in his mind, his son was no less
stubborn and resistant in refusing this unappealing idea. I would not enter the
civil service.
Neither pleading nor reasoning with me had an effect on my resistance. I
would not be an official, “no” and again, “no.” Every attempt to arouse my
interest in that calling through descriptions of my father’s experience had the
opposite effect. I yawned myself sick at the thought of sitting in a government
office, not being the master of my own life, but a slave devoting my entire
existence to filling out various forms.
What affect could this possibly have on a young boy who was anything
but “good” in the ordinary sense? I did my school work with ridiculous ease
and had so much free time left that I was outdoors more than in.
Today, when my political opponents scrutinize my life with such loving
care—searching back even into my childhood for the satisfaction of
uncovering some piece of deviltry this fellow Hitler was up to in his youth—I
thank heaven for them giving me a few more memories of that happy time.
Field and forest were the battleground where my constantly recurring
differences in opinion were settled. Even the attendance at the secondary-
school which followed did little to restrain me. But now another dispute had
to be fought out.
So long as my father’s intention to make me into an official clashed only
with my general dislike of the career itself, the conflict was quite tolerable. I
could withhold my private views and I did not have to make a constant issue
of them. My own determination never to become an official was enough to
give me an inner calm. I clung to this determination firmly.
8
Childhood Home
9
Mein Kampf
10
Childhood Home
As in any battle, there are three groups in the struggle for our language
in old Austria: the fighters, the lukewarm, and the traitors. The sorting process
begins in school. The most remarkable thing about a language battle is that its
waves beat hardest upon the schools. The war is waged over the next
generation, and the first war-cry is to the children: “German boy, do not forget
that you are a German,” and “German girl, remember that you are to be a
German mother.”
Anyone who understands the soul of youth will realize that young people
will receive this battle-cry with joy. In a hundred ways they carry on the
struggle in their own fashion and with their own weapons. They refuse to sing
non-German songs; they are more enthusiastic over German heroes; the more
they are suppressed, the more they go hungry in order to save pennies for the
war-chest of their elders. They have an incredibly sensitive ear for a non-
German teacher. They wear the forbidden badges of their own nation and are
happy to be punished for it. In other words, they are a faithful image in
miniature of their elders, except that their devotion is often stronger and more
direct.
When I was small, I too shared in the struggle for German nationality in
old Austria. Money was collected for the South Mark German League by school
associations. We wore cornflowers and black-red-gold badges proclaiming our
beliefs.6 “Heil” was our greeting, and instead of the Imperial anthem, we
would sing the German anthem, “Germany Above All,”7 despite threats of
punishment. Young people were politically trained at a time when citizens of
a so-called national state still knew very little about their own national
character other than their language. I was not among the lukewarm even in
those days. I was soon a fanatical German Nationalist. Of course, I do not refer
to the present political party using that name.
My nationalistic development was very rapid. By the time I was fifteen, I
could easily see the difference between the patriotism shown by those who
6 Cornflowers were the symbol of Germans loyal to the Hohenzollern Monarchy and of
Austrians who supported the Pan-German movement.
7 The Song of Germany, Deutschland über alles.
11
Mein Kampf
followed rulers in the Imperial dynasty and the true “nationalism” for the
nation and for the people. For me, only nationalism existed.
Anyone who has not bothered to study the Hapsburg Monarchy8 may find
this strong nationalism puzzling. In Austrian schools, there is very little actual
Austrian history worth mentioning. The fate of Austria is so completely
intertwined in the Germanic life that it is unthinkable to separate history into
German and Austrian. When Germany finally split into two spheres of
authority, this very separation was German history.
The insignia of former German Imperial splendor, displayed for all to see
in Vienna, continued its spell as a reminder of our common and unending life
together.
The cry of the German people in Austria for a reunion with their German
mother country when the Hapsburg state collapsed resulted from a deep ache
that slept in the people’s hearts. They had never forgotten this longing to
return to the home of their fathers. This can only be explained through the
history taught to German-Austrians, which made those nationalistic feelings
grow. Their history is a fountain that never runs dry—a silent reminder in
times when it is easier to forget. Though we may be distracted by momentary
prosperity, we hear the whispers of a new future by remembering the past.
It is true that the quality of World-History education in intermediate
schools is in a sad state. Few teachers realize that to memorize and rattle off
historical dates and events is not true history. It is not important for a boy to
know exactly when some battle was fought, some general born, or when some
insignificant monarch was crowned. No, God knows, that is certainly not what
is important.
To truly “learn” history means to open your eyes and discover the forces
that cause historical events to happen. The art of reading and of learning
means remembering the important parts and forgetting the unimportant.
It is likely that my later life was influenced by the fact that I had a good
history teacher. He had a unique ability to teach and test us on principles, not
dates. My professor, Dr. Leopold Pötsch of the Linz school, was the very
12
Childhood Home
embodiment of this idea. He was an older gentleman. He was kind, but set in
his manner. His brilliant eloquence not only fascinated us, but absolutely
carried us away. I am still touched when I think of this gray-haired man, whose
fiery descriptions often made us forget the present as he conjured us back into
days long past, and how he could take dry, historical memories from the mists
of centuries and transform them into living experiences. In his class we were
often red-hot with enthusiasm, sometimes even moved to tears.
I was luckier than most because this teacher not only illuminated the past
by the light of the present, but he taught me to draw conclusions for the
present from the past. More than anyone else, he gave us an understanding
of the current problems.
He used our national fanaticism to educate us. He would appeal to our
sense of national honor, which brought us bad-mannered adolescents to
order more quickly than anything else ever could.
This teacher made history my favorite subject. Even then, though he did
not intend it, I became a young revolutionary. Indeed, who could possibly
study German history under such a teacher without becoming an enemy of a
State whose ruling house had such a catastrophic influence on the nation?
Who could preserve his allegiance to the emperors of a dynasty that had
betrayed the interests of the German people again and again for its own petty
advantage? Did we not know, even as boys, that this Austrian state had no
love for us as Germans, and indeed it could have none? My historical insight
into the work of the Austrian Hapsburg Monarchy was strengthened by my
daily experience. In the north and in the south, foreign people came in and
poisoned the body of our nation. Even Vienna became less and less a German
city. The House of the Archdukes showed favoritism to the Czechs at every
opportunity. It was the hand of the Goddess of Eternal Justice and Retribution
that overthrew the deadliest enemy of Austria’s German nature when She
struck Archduke Francis Ferdinand by the very bullets he had helped to cast.
After all, he was the patron who was charged to protect Austria from the
northern Slavs.
The burdens laid upon the German people were enormous. They suffered
unheard-of sacrifices in taxes and blood. Anyone who was not blind could see
13
Mein Kampf
their sacrifice would be in vain. What hurt us most was the fact that these
activities were shielded by the alliance with Germany. The gradual
extermination of German qualities in the old Monarchy was to a certain extent
sanctioned by Germany itself. The hypocrisy was evident when the Hapsburg
Monarchy worked hard to give the outside world the impression that Austria
was still a German state, and this only fanned hatred for that Monarchy into
blazing anger and contempt within Austria.
In Germany, the elected members of the government failed to see any of
this happening. It was like they were struck with blindness. They could have
walked beside a corpse showing signs of decay and proclaim they had
discovered signs of “new” life. In the alliance between the young German
Empire and the Austrian sham state grew the seeds of the First World War and
of the collapse.
Throughout this book, I will more thoroughly detail the problem of this
alliance. It will be sufficient now to say that as a boy I arrived at an insight,
which never left me, but only grew deeper. This insight was that the safety of
German culture in Austria first required the destruction of Austria, and that
feelings of nationalism have nothing to do with patriotism to an Imperial
dynasty. The house of Hapsburg was destined to bring misery on the German
nation.
Even then, this realization created a warm love for my German Austrian
homeland and a profound hatred for the Austrian state. I never abandoned
how I learned to think about history either. World history became my
inexhaustible source for understanding how the present events, that is to say
the political situation, came to be. I did not intend to “learn” from history;
instead, history was to teach me. If I became a political revolutionary so
quickly, then I also became a revolutionary in the arts equally fast.
The Upper Austrian capital had an excellent theater which put on nearly
everything. When I was twelve, I saw the heroic William Tell play for the first
time. A few months later, I saw my first opera, Lohengrin.9 I was totally
captivated. My youthful enthusiasm for the master of Bayreuth10 knew no
14
Childhood Home
bounds. Again and again I was drawn to his works and it seems fortunate to
me now that I could attend the smaller performances where I could get up
close, and it actually intensified the experience.
Once my painful adolescent years were over, my deep aversion to the
calling my father had chosen for me was even clearer. I knew that I could never
be happy as a civil servant. My talent for drawing had been recognized at
school, and my determination to be an artist was firmly fixed.
Neither prayers nor threats dissuaded me. I was going to be a painter and
I would not be an official for anything in the world. It was curious that, as I
grew older, I took an increasing interest in architecture too. At the time, I
thought it complemented my painting ability and was pleased that my artistic
interests had expanded. I never dreamed that it would all turn out quite
differently. My calling was to be decided sooner than I could have expected.
When I was thirteen, I lost my father suddenly. A stroke took the vigorous
old gentleman, painlessly terminating his earthly career, and plunging us all
into the deepest grief. His deep desire to give his child a livelihood and spare
his offspring from his own bitter struggle must have seemed unfulfilled. But
he had sown the seeds for a future which neither he nor I could have
understood then.
There was no outward change yet. My mother continued my education
according to my father’s wishes, intending that I prepare for a civil service
position eventually, while I myself was more determined than ever to avoid
becoming an official. I became less and less interested in school and grew
more indifferent. Suddenly, an illness came to my assistance. Within a few
weeks, my future and the subject which caused constant dispute at home was
decided for us. I had serious lung trouble, and the doctor urgently advised my
mother against putting me into a closed-office environment. My attendance
at the secondary-school was also interrupted for at least a year. What I had
secretly desired for so long, what I had always fought for had now, through
this illness, become reality almost of its own choosing.
Pressured by my illness, my mother finally agreed to let me go to the
Academy of Fine Arts in Vienna instead of the vocational secondary-school.
The happy days I expected to follow seemed to me almost like a beautiful
15
Mein Kampf
dream and a dream they were to remain. Two years later, my mother’s death
put a sudden end to all my fine plans.
She died at the end of a long, painful illness which had little room for
hope of recovery. Even so, the blow to me was terrible. I had honored my
father, but I had loved my mother..
16
CHAPTER TWO
17
Mein Kampf
had no aptitude for painting and that my true ability was in the field of
architecture. The School of Painting was out of the question, but the School of
Architecture was for me, even though at first they found it difficult to believe
that I had never attended an architectural school or had any instruction in
architecture.
As I left Hansen’s magnificent building on the square, I was at odds with
myself for the first time in my young life. What I had just been told about my
abilities was like a lightning flash illuminating an unexplainable confusion in
me that had been growing for a long time. Within a few days, I knew I would
be an architect someday.
I could see the path before me would be enormously difficult. Everything
I had been too stubborn to learn in secondary-school was now taking its bitter
revenge. Admission to the Vienna Academy School of Architecture required
attendance of the Building School of Technology, and admission here was
based on graduation and the final exams from an intermediate school. I did
not have either. It seemed my dream of art was now impossible.
After the death of my mother, I returned to Vienna, this time to stay for
some years. I once again regained my calm and determination. My earlier
spirit of defiance had also returned and I was determined to reach my goal. I
would be an architect. Obstacles exist to be overcome, and I would overcome
those obstacles with the image of my father before my eyes. He fought his
way from farm boy and shoemaker to state official, and my soil was richer than
his, so my battle should be that much easier. What had then seemed to me to
be the unkindness of Fate I accept as the wisdom of Providence. When the
Goddess of Trouble embraced me and often threatened to crush me, the will
to resist grew, and at last that will was victorious.
That period made me strong. I thank her for snatching me from the
emptiness of a comfortable life and for pulling this mama’s boy out of the
comfortable, cozy bed. I was reluctantly thrown into the world of misery and
poverty, which introduced me to those I would later fight for.
That is the point when I saw two dangers approaching. Previously, I did
not truly understand their names or their importance to the German people’s
existence. Their names were Marxism and Jewry.
18
Years of Learning and Suffering in Vienna
2Phaeacia is the final city visited by Homer in the Odyssey; however, it is also a common
knowledge reference in Germany and something any German would recognize. The belief is
that the people liked to enjoy life and the reference means a city of loafers or do-nothings, or
parasites.
19
Mein Kampf
that was not in contact with those who worked at pure physical labor. Strange
as it may seem at first glance, economic differences between this level and
that of ditch diggers is often deeper than one thinks. This antagonism comes
from a social group which has just recently lifted itself from the ranks of
physical labor and is afraid it could fall back, or at least be counted as one of
them.
There is often a repulsive memory of cultural poverty among this lower
middle class, so any social contact with physical laborers, which they feel they
have outgrown, becomes unbearable.
Aman from the higher social levels can mix with worker classes in a way
that would be thinkable to the relative newcomers of this lower middle class.
A newcomer to a social class is anyone who fights his way by his own
energy from one position in life to a higher one. But eventually, this bitter
battle kills off human sympathy for the class he escaped. One’s own painful
struggle for existence destroys his feeling for the misery of those left behind.
In this respect, Fate took pity on me. By forcing me back into the world
of poverty and insecurity, which my father had once abandoned, the blinders
of a limited lower middle class education were removed from my eyes. Only
then did I learn how to distinguish between a hollow or brutal man’s exterior
and his inner nature.
In the early years of this century, Vienna was among the most socially
unhealthy of cities. It was a combination of glittering wealth and revolting
poverty.
In the center of the inner districts, one felt the heartbeat of an empire of
fifty-two million people along with the dangerous magic of this State of mixed
nationalities. The blinding magnificence of this cultural and government
center was like a magnet to the wealth and intelligence of the State. On top of
that came the extreme centralization of the Hapsburg Monarchy. It offered
the only possibility of holding this stew of peoples together. The result was an
extraordinary concentration of high government offices in the capital and
around Imperial residence.
Vienna was not only the political and intellectual center, but also the
economic capital of the old Danube Monarchy. In contrast with the army of
20
Years of Learning and Suffering in Vienna
high officers, officials, artists, and scholars were a larger army of workers who
were against the wealth of the aristocracy and their practice of bleeding
poverty for all they could.
The palaces of the Ringstrasse, became a waiting room for thousands of
the unemployed, and below the arch of triumph of old Austria, the homeless
lived in the twilight and slime of the sewers.
There was not one German city where the social situation could have
been better studied than in Vienna. Do not be misled. This “studying” cannot
be done from above. Someone who has not been in the clutches of this viper
cannot truly know its venom. Studying from above results in superficial chatter
or the formation of false opinions based on emotion. Both are harmful: one
because it can never reach the heart of the problem; the other because it
passes by the problem entirely. I do not know which is more devastating—to
ignore those who lack the basic necessities such as we see in those who are
favored by fortune or live well as a result of their own effort, or is it those who
stand tall in their fashionable skirts or trousers and “feel for the people”
because it is the latest fad. In any case, these people commit a sin greater than
their limited intelligence will ever allow them to understand.
Then, they are astonished when their fashionable “social conscience,”
which they proudly display, never produces any results. When their fruitless
good intentions are resented, they blame the ingratitude of the people.
People with minds like this fail to understand that there is no place for merely
social activities. When the masses want results, social displays are not enough
and there can be no expectation of gratitude for such a show. It is not a matter
of distributing favors, but of retribution and justice.
I did not learn about the social problem by observing from the outside. It
drew me into its magic circle of suffering and instead of teaching me, it sought
to test its strength on me, and it receives no credit if I survived its tests safe
and sound. I could never completely relate my sensations from that time; I can
only describe the essential and most staggering impressions here along with
the lessons I learned.
I rarely had difficulty finding work. I was not a skilled worker but had to
earn my bread as best I could, so I did so as a helper or day laborer. I had the
21
Mein Kampf
attitude of the laborers of Europe who shake the dust from their feet with
their determination to build a new life and a new home in the New World.3
They are free from preconceived notions of occupation and social background,
of status and tradition, and they grasp any means of support that is offered to
them. They go to any job and gradually arrive at the realization that honest
labor is no disgrace, no matter what kind of labor it may be. I, too, was
determined to leap with both feet into a world that was new to me and to find
my way through it.
I soon learned that someone always needs some kind of work, but I
learned just as quickly how easy it is to lose that support again. The insecurity
of one’s daily bread soon became one of the darkest aspects of my new life.
The skilled worker is turned out on the street less often than the unskilled, but
even he can be pushed out the door. Instead of losing his job because he is
not needed, he is locked out or he strikes.
This dependence reveals a weakness in the whole economic system. The
peasant boy who is drawn to the big city by the promise of easier work and
shorter hours is accustomed to a certain amount of security. He has never left
one job without having another or at least the prospect of another lined up.
As more boys are drawn to the city, the shortage of farm labor takes its
toll and the chance of being unemployed increases. Now, it would be a
mistake to think that the young fellow who goes to the big city is made of
sterner stuff than the one who stays home and makes an honest living from
the soil. No, quite the contrary. Experience shows that emigrant groups are
more likely to be made up of the healthiest and most energetic individuals.
And these emigrants include not only the man who goes to America, but also
the young farm-hand who leaves his native village to move to the distant big
city. He is just as prepared for an uncertain fate as the farm boy going to
another country. Usually, he comes to town with a little change in his pocket
to last him at least a day if he does not immediately find work. However, his
situation will quickly worsen if he finds a job then loses that job at the wrong
time. Finding a new job as a worker can be almost impossible in winter
3The New World means the United States, which was receiving a large number of immigrants
at the time.
22
Years of Learning and Suffering in Vienna
months. For the first few weeks, he receives unemployment benefits from his
union and does his best to survive. But when his last penny is gone and the
union benefits expire, he then finds himself in a difficult position.. Eventually, he is able to
find some sort of work under a union, but then the game begins all over again.
He is hit a second time with unemployment in the form of a strike, then the
third time may be even worse. Gradually he learns to become indifferent to
the constant insecurity of his finances. The cycle changes into a habit that he
continues without further consideration.. He may not like the idea of going on
strike, but he is completely indifferent when he is handed strike papers.
I have watched this process a thousand times with my own eyes. The
longer I saw the game continue, the more I disliked this city of millions. It
greedily sucks men in, then cruelly wears them to pieces. When men came to
the city, they still belonged to their nation. When they stayed, they were lost
to it.
Life threw me around in the great city, too. I felt the full force of such a
fate, body and soul. I discovered something else as well—quickly switching
between periods of work and unemployment along with the seesaw
23
Mein Kampf
victim with a mirage which makes them see only well-fed prosperity,
regardless of their true circumstances. This mirage grows to such morbid
intensity that they give up all self-control the moment wages begin to flow
into their pocket. That is why a man who has difficulty finding any work
stupidly forgets to plan for bad times when he does find work. He, instead,
lives greedily and indulges in the moment. His tiny weekly income is instantly
spent because he does not even plan for the remainder of the week. At first,
his wages last five days instead of seven, then only three, then scarcely a day,
to be at last squandered the first evening.
These men are not all living life by themselves. They likely have a wife and
children at home. Their family is also poisoned by this way of life, especially if
the man is naturally kind to them and even loves them in his way. Before the
week’s pay has evaporated in two or three days, they eat and drink as long as
the money holds out. They then go through the remaining days together on
empty stomachs. Then, the wife slinks about the neighborhood, borrowing a
bit here and there, opening charge accounts with the shopkeepers, and trying
thus to survive the terrible later days of the week. At noon, they all sit at a
table which does not contain enough for everyone, if it contains anything at
all. They sit, waiting for the next payday, talking of it, making plans. While they
starve, they are already lost in the mirage of the good fortune which comes
on payday.
The children, even in their youngest days, will come to see this wretched
life of empty fantasy as normal. The situation can become worse if the man
lives like this and the wife objects for the sake of their children. Then, there
are quarrels and bad blood, and the more the husband drifts apart from his
wife, the nearer he drifts to alcohol. Every Saturday, he becomes drunk. Now,
his wife must fight for the few pennies she can snatch from him in an effort of
self-preservation for herself and the children. What she can get is only what is
left over from his journey between the factory and the bar. When he finally
comes home on Sunday or Monday night— drunk, brutal, and penniless—
there are likely to be scenes that would wring tears from a stone.
I saw all this going on in hundreds of cases. At first, I was disgusted or
outraged. I later came to realize the tragedy of this suffering and to
24
Years of Learning and Suffering in Vienna
understand its deeper causes. They were the unhappy victims of evil
circumstances. The housing conditions of those days were worse. The housing
situation of the Viennese laborer was absolutely frightful. I shudder now when
I think of those wretched caverns some lived in, of the houses where
journeymen of a common trade lived together, and mass dormitories which
were sinister pictures of refuse, filled with disgusting filth and worse.
It was bound to happen. The flood of slaves set loose from these squalid
caves pours down upon the rest of the world, upon its thoughtless fellow men!
It is bound to happen again. This other world lets things drift without thinking
about the consequences. It has lost its instinct to tell it that sooner or later,
Fate will move toward retribution unless mankind placates destiny before
time runs out.
I am indeed thankful to a Providence for sending me to that school of
hard knocks in the city. There, I could not sabotage what I did not like. I had to
quickly grow up. If I wanted to avoid falling into despair because of the people
who surrounded me, I had to learn the distinctions between their outer
character and inner life and the circumstances that created their lives.
Only through this understanding could I bear it all without giving up to
despair. It was no longer human beings who rose before me out of
unhappiness and misery, out of squalor and physical degradation, but the sad
products of sad laws. At the same time, my own fight for life, which was no
easier than theirs, preserved me from becoming emotionally involved with the
products of this ill society and allowed me to remain objective. No, emotional
sentimentality will not help understanding here. Even then I saw that only a
two-fold path could lead to the improvement of such conditions.
I experienced a deep feeling of social responsibility to establish a better
system for our development. I knew it would require brutal determination to
destroy this human outgrowth which had no chance of being preserved and
corrected. Nature does not focus on preserving what exists; nature
concentrates on breeding a new generation to perpetuate the species. It is
almost impossible for man to improve those bad things that exist in society,
but it is much easier to create healthier paths from the start.
25
Mein Kampf
26
Years of Learning and Suffering in Vienna
people? We cannot use the excuse that “it is the same in other countries”
because the worker in other countries has no difficulty holding onto his
nationality.
Even if this were so, it would be no excuse for one’s own shortcomings.
The French people teach France’s greatness in every department of culture,
or as the Frenchman says, of “civilization,” and we foolishly dismiss it as a
fanatical glorification in their upbringing.
The young Frenchman is simply not trained to be objective, but instead
he is given a subjective attitude of greatness anywhere the political or cultural
aspect of his fatherland is concerned. This type of education has to be
widespread and, if necessary, it must be pounded into the people’s memories
and feelings by perpetual repetition.
With us there is both the sin of omission and a destruction of what little
we were lucky enough to learn in school. The rats infecting our political system
gnaw even the tiny bit we have learned out of the hearts and memories of our
people. Poverty and wretchedness have also done their share to crush these
memories.
Here is an example: in a basement consisting of two stuffy rooms lives a
laborer’s family of seven. Among the five children is a boy of three years. This
is the age when a child first becomes conscious of things around him. Gifted
people carry memories of that period far into old age.
The small, overcrowded space produces an unfortunate situation. The
conditions often generate quarrels and bickering. The people are not living
with one another; they are merely living in the same place, squeezed together.
Every small argument leads to a sickening quarrel. In a larger dwelling, the
argument would be easily smoothed out simply by separation. The children
may tolerate these conditions because children can quarrel constantly and
forget the argument quickly. However, a daily battle between parents slowly
teaches the children a lesson. The dispute may take the form of a father’s
brutality to a mother, of drunken maltreatment. Any person who does not
know of this life can hardly imagine it. By the time the boy goes from three to
six, he has developed a working idea of the world which must horrify even an
adult. Now, he is morally infected and physically undernourished, and the
27
Mein Kampf
young “citizen” is sent to primary school with vermin living in his poor little
scalp.
Now, with great difficulty, he must learn reading and writing, and that is
about all he can manage.
Studying at home is out of the question. Father and mother argue and
use language that would not be socially appropriate right in front of their own
children, making studying impossible. But when the parents talk to teachers
and school officials, they are more inclined to talk roughly to them than to turn
their young child over their knee and introduce him to reason. Nothing the
little fellow hears at home strengthens his respect for his fellow human beings.
They never utter a good word about humanity. No institution is safe from
their profane attacks, from the school teacher to the head of the state. No
matter whether it is religion or morals, state or society, everything is defamed
and dragged in the muck. When the boy leaves school at the age of fourteen,
it is hard to tell which is greater—his incredible stupidity where common
knowledge and basic skills are concerned, or his biting disrespect and bad
manners.
The immoral displays, even at that age, make one’s hair stand on end.
He holds almost nothing sacred. He has never met true greatness, but he
has experienced the abyss of everyday life. What position can he possibly
occupy in the world which he is about to enter? The three-year-old child has
become a fifteen-year-old who despises all authority. Aside from filth and
uncleanliness, he has yet to find anything which might stir him to any high
enthusiasm.
As he begins the more demanding parts of his life, he falls into the ruts
he has learned from his father. He wanders about, comes home Heaven knows
when, beats the tattered creature who was once his mother, curses God and
the world, and finally he is sentenced to a prison for juvenile delinquents.
Here, he gets his final polish.
His fellow-citizens are astonished at his lack of national enthusiasm. They
see theater and movies, trashy literature, and yellow press day-by-day pouring
out poison. Then, they are surprised at the low morality and the national
indifference of the people. They do not realize movie trash, cheap journalism
28
Years of Learning and Suffering in Vienna
and the like would never produce the skills needed to recognize the greatness
of the Fatherland! I finally realized something I had never even dreamed of
before. The ability to “nationalize” a people is primarily a question of creating
healthy social conditions that can be used to educate the individual. Only
when upbringing and school training have taught a man the political greatness
of his own Fatherland will he achieve an inner pride that comes from
belonging to such a great people. You can fight only for something you love.
You can love only what you respect. You can respect only what you know.
When my interest in social problems was aroused, I began to study it
thoroughly. A world that had been so strange to me before suddenly began to
open up.
In 1909 and 1910, I no longer needed to earn my daily bread as a laborer.
I started working independently as a draftsman and watercolor artist. This line
of work was difficult financially; there was barely enough earnings to keep
body and soul together. However, it was great in that it was closer to my
chosen profession. I was no longer dead tired when I came home from work
in the evening, unable to even look at a book without dozing off. My new work
paralleled my future profession. As master of my own time, I could now plan
it better than before. I painted to earn a living and learned for pleasure.
I was also able to round out my understanding of the social problem by
building a necessary understanding of the theoretical background. I studied
pretty much every book on the subject I could get my hands on and plunged
myself in my own thoughts. My acquaintances must have thought I was more
than a little eccentric.
I passionately pursued my love of architecture. Along with music, I
thought architecture was the queen of the arts. It was not “work” to spend
time on it, but the height of happiness. I could read or draw late into the night
and it never made me tired. My faith was strengthened by the dream of a
future that would become a reality after all. Even though it took years, I was
firmly convinced that I would make my name as an architect.
The fact that I also took great interest in anything having to do with
politics did not seem especially significant. On the contrary, I felt that was the
duty of all thinking people. Anyone who did not actively learn about politics
29
Mein Kampf
lost all rights to criticize or complain. In this area, I continued to read and
learned a lot.
My definition of “reading” may be different from the average person’s
definition. I know people who “read” all the time— book after book, word for
word—but I would not call them well-read. They do have a mass of knowledge,
but their brain does not know how to divide it up and catalog the material they
have read. They cannot separate a book and identify what is valuable and what
is worthless for them. They retain some in their mind forever, but cannot see
or understand the other parts at all.
Reading is not an end in itself, but a means to an end. In the first place, it
should help to fulfill an individual’s personal framework and give each person
the tools and materials a man needs in his job or profession, whether it is for
daily necessity, simple physical fulfillment, or higher destiny. In the second
place, reading should give a man a general picture of the world.
In either case, what is read shouldn’t simply be stored in the memory like
a list of facts and figures. The facts, like bits of a mosaic tile, should come
together as a general image of the world, helping to shape this world image in
the reader’s head. Otherwise, there will be a confusion of information learned,
and the worthless mix of facts gives the unhappy possessor an undeserved
high opinion of himself. He seriously believes he is “cultured and learned”
while thinking he has some understanding of life and is knowledgeable simply
because he has a stack of books by his bed. Actually, every piece of new
information takes him further away from the real world, until often he ends
up either in a psychiatric hospital or as a “politician” in government.
No man with this kind of mind can ever retrieve from his jumbled
“knowledge” what is appropriate when he needs it. His intellect is not filled
with his own life experiences, but is filled with what he has read in books and
in whatever order the content happened to land in his head. If Fate reminded
him to correctly use what he has learned in his daily life, it would also have to
cite volume and page or the poor guy could never find what he needed. But
since Fate does not do this, these “knowledgeable” men are embarrassed
when it really counts. They search their minds frantically for appropriate
comparisons and usually end up with the wrong idea. If this were not the case,
30
Years of Learning and Suffering in Vienna
31
Mein Kampf
Who knows if I would have ever become absorbed in the doctrines and
character of Marxism if my life had not simply rubbed my nose in it! In my
youth, I knew almost nothing about Social Democracy and what I did know
was wrong. I thought it was a good thing that the Social Democrats were
fighting for the right of all men to vote by secret ballot. Even then my mind
told me this had to weaken the hated Hapsburg regime. I was also convinced
the Austrian state could never be maintained unless it sacrificed the German
element living in Austria. Even at the cost of slowly converting the German
element to Slavs, there was no guarantee the empire would survive since their
ability to preserve a Slavic society is highly doubtful.
Therefore, I was excited about any development which I thought would
lead to the collapse of this unstable state that has condemned to death the
Germanism of ten million people. The more the language uproar gnawed at
the parliament, the closer the hour of collapse approached for this Babylonian
Empire, and the closer the freedom of my German-Austrian people came
near.4 This was the only way that a return to the old mother country could
someday happen.
The activities of the Social Democrats Germanism and their
pitiful wooing of the Slavic “comrades” who were willing to accept this
courtship and make concessions. Otherwise, they maintained an arrogance
and conceit, which gave these insistent beggars their just reward.
At the age of seventeen, I had become somewhat acquainted with the
word Marxism and I thought Socialism and Social Democracy were identical
ideas. Again, the hand of Fate opened my eyes to this unprecedented fraud
on the people.
So far, I had encountered the Social Democratic Party only as a spectator
at a few mass demonstrations without gaining any insight into the mind-set of
4Babylonian Empire is a reference to the Tower of Babel story where the people were cursed
to speak different languages and scattered around the world.
32
Years of Learning and Suffering in Vienna
its supporters or the nature of its doctrine. Now, at one moment, I met face-
to-face with the results of its training and who supported its “World-Concept.”
In the course of a few months, I learned something that otherwise may have
taken years—an understanding of a disease masquerading as social virtue and
the love of one’s neighbor—a disease which humanity must free the earth
from or the earth would soon be freed of humanity. My first encounter with
Social Democrats was on a construction job.
It was not a good situation from the very beginning. My clothes were still
in good shape, my language was cultivated, and my manner reserved. I had so
much to do in dealing with my own Fate that I couldn’t trouble myself with
the world around me. I was looking for work only to avoid starving and so that
I could educate myself no matter how long it took. I might not have paid any
attention to my new surroundings if an event on the third or fourth day had
not compelled me to immediately adopt a new attitude. I was asked to join
the organized union.
My knowledge of the trade-union organization at that time was zero. I
could not have proved whether or not it was in any way useful. When I was
told I must join, I refused. My grounds for refusal were that I did not
understand the situation, and I would not be forced to do anything. Maybe
this was the reason they did not throw me out immediately. They may have
hoped they could convert me or wear me down within a few days. In either
case, they were very mistaken. Within a couple of weeks, I had reached the
end of my rope. During that time, I gained a better understanding of my
surroundings and no power in the world could have forced me to join an
organization whose members acted the way they did.
The first few days I was further annoyed. At noon, some of the men went
to nearby bars, while others stayed on the lot and ate their pitiful lunch. These
were the married men whose wives brought them their soup in heavily-worn
bowls. As the week progressed, their numbers grew. I figured out the reason
later. When they finished their soup, they would talk politics.
I drank my bottle of milk and ate my piece of bread somewhere out of
the way as I cautiously studied my new surroundings or considered my
misfortune. Still, I heard more than enough and it seemed that people crept
33
Mein Kampf
34
Years of Learning and Suffering in Vienna
35
Mein Kampf
be studied, etc. With sparkling clarity, I saw right in front of me the inevitable
result of this doctrine of intolerance.
The soul of the great masses of people is receptive to nothing weak or
half-way. Like a woman—whose spiritual perceptions are attracted more by
the strength of a leader than the reason of a follower—the masses love the
ruler more than the follower and they find more inner satisfaction in a
doctrine that tolerates nothing that it, itself, has not granted approval and
freedom. The masses are seldom able to make much use of such freedom and
are likely to feel neglected if given too much. They are as unconscious of the
shamelessness that intellectually terrorizes them as they are of the
outrageous mistreatment of their human liberty. After all, they have no clue
about the doctrine’s internal error. They only see the ruthless strength and
brutality of its expression, which they always yield to.
If Social Democracy opposes a more truthful, but equally brutal theory,
the new theory will win, even if it requires a battle first. In less than two years,
I had developed a clear understanding of both the doctrine and the technical
methods the Social Democrats used to propagate it.
I realized the infamous intellectual terrorism of this movement targets
the privileged-class, which is neither morally nor spiritually a match for such
attacks. They tell a barrage of lies and slander against the individual adversary
it considers most dangerous and keep it up until the nerves of the group being
attacked give in and they sacrifice the hated figure just to have peace and
quiet again. But the fools still do not get peace and quiet. The game begins
again and is repeated until fear of the villain becomes a hypnotic paralysis.
Since the Social Democrats know very well the value of power from their
own experience, their storming is directed mainly at those whose character
has this same quality. Conversely, they praise every weakling on the other
side, cautiously, then loudly, according to the intellectual qualities they see or
suspect. They fear an impotent, weak-willed genius less than they fear a
forceful nature with only modest intellect. Their highest recommendation
goes to weaklings in both mind and nature.
They are successful in creating the impression that giving-in is the only
way to win peace and quiet from them while they quietly, cautiously, but
36
Years of Learning and Suffering in Vienna
37
Mein Kampf
38
Years of Learning and Suffering in Vienna
39
Mein Kampf
40
Years of Learning and Suffering in Vienna
Even by the turn of the century, the labor union movement no longer
served its original purpose. From year to year it was drawn more and more
into the sphere of Social Democratic politics, until finally it served only as a
battering-ram in the class struggle. The Social Democrats assumed that
continual blows would make the whole economic structure tumble, then the
state—deprived of its economic foundations—would suffer the same fate. The
representation of the working people’s real interests played less and less a
part in the Social Democratic agenda. Eventually, political concerns made
relieving the social and cultural problems of the workers undesirable. If the
workers were not distressed and were fully satisfied, and their will was no
longer fueled by resentment, there would have been a danger that they could
no longer be used as an army.
Intuitively sensing this development, the leaders of the class struggle fell
into such a panic that eventually they simply refused to bring about any
beneficial social improvement and actually took a decided stand against any
improvements for the workers. There was no need to be embarrassed by such
seemingly incomprehensible behavior. They could avoid it by constantly
increasing their demands on businesses, which made the rejection of any
proposed improvement appear as if the business was engaged in a diabolical
attempt to cripple the workers’ most sacred rights. Considering the minimum
thinking power of the masses, the Social Democratic success is not surprising.
The privileged-class camp was outraged at these obviously deceptive
Social Democratic tactics, but they still based their actions on the statements
made by the Social Democrats. The Social Democrats’ fear of raising the
working class from its abyss of cultural and social misery should have led their
opponents to make supreme efforts to improve the workers’ lives. This would
have gradually twisted the weapons from the hands of the socialist leaders of
the class struggle. But this did not happen.
Instead of attacking and capturing the enemy position of the high moral
ground themselves, they preferred to be squeezed and shoved. Finally in their
negotiation battles with the unions, they relented and gave in to changes that,
no matter how far reaching, were insufficient for the socialists. The Social
Democrats easily rejected the changes because it was too little too late.
41
Mein Kampf
Everything remained the same except now there was more dissatisfaction
than ever among both the workers and the business owners.
Even then, the “free trade-union” already hung like a menacing storm
cloud on the political horizon and loomed over the existence of everyone. It
was one of the worst terrorist instruments against the security and
independence of the national economy, against the unity of the state, and
against the freedom of individuals. This turned the idea of democracy into a
ridiculous and disgusting cliché. It was an outrage against freedom and forever
mocked the idea of brotherhood as demonstrated in the saying, “If you will
not be a comrade too, it means a broken skull for you.”
This is how I came to understand mankind. Through the years, my views
broadened and deepened but there was no need to change my way of
thinking. The more I understood the outer nature of Social Democracy, the
more I longed to understand the inner core of the doctrine. The official party
literature was not very useful here. It is incorrect in both details and in the
proof it offers for economic questions. It is also untruthful in its discussion of
political aims. Besides, I was especially repelled by the dishonest and unethical
manner in which it was presented. Sentences are written using a lot of vague
words with unintelligible meanings that are as clever as they are senseless.
Only those unconventional types rotting among us could possibly feel at home
in this intellectual maze. They scrape some “spiritual experience” from this
artsy literary manure, and the message is assisted by the humility of our
people who think something is deep and wise just because they don’t
understand it.
I gradually built a clear picture of its inner intent by balancing the
theoretical untruth and nonsense of this doctrine with its actual outward
appearance.
When I began to understand, fear and horror crept over me. I saw a
teaching compounded by ego and hatred, which according to mathematical
law could very well lead to victory, but would then lead to the end of humanity
as well. During this time, I learned about the connection between this doctrine
of destruction and the nature of a people. Up until now, this was unknown to
me.
42
Years of Learning and Suffering in Vienna
43
Mein Kampf
weeks. Only when I began to settle in did I begin to look more closely at my
new world and see the busy scene more clearly. That’s when I encountered
the Jewish question.
I cannot say that the way I encountered it was particularly agreeable. At
first, I only saw the religious aspect of the Jew and for reasons of human
tolerance, I maintained my opposition to religious attacks. The tone of the
anti-Semitic press in Vienna seemed unworthy of the cultural tradition of a
great people. I was bothered by the memory of certain happenings in the
Middle Ages which I did not want to see repeated.5 Since the newspapers in
question were not generally considered among the most outstanding quality,
I thought they were the product of angry envy rather than the result of a
principle, even if it was wrong.
My belief was strengthened by what I considered the infinitely more
dignified and commendable way in which the truly great newspapers
answered those attacks. They did not even mention them, but responded with
silence. Eagerly I read the world press, the “New Free Press”;6 the Vienna Daily
Newspaper,7 etc., and I was astonished at how much they offered the reader
and at their objectivity. I also admired their dignified tone. Occasionally, I did
not like their pretentious style, but I thought it might be more acceptable in
the bustle of the cosmopolitan city.
Since I considered Vienna such a city, I thought this amateur explanation
might be a sufficient excuse. But the way these newspapers played up stories
in the Royal Court’s favor did repel me more than once. There was rarely an
event at the Hofburg Imperial Palace,8 which was not told to the reader in
tones of enraptured ecstasy or grief-stricken sorrow. When an event dealt
with the “wisest Monarch” of all times, it read almost like a mating dance
between lovers.
5 All through the Middle Ages, Jews were blamed for any bad occurrence and killed by the
thousands at a time. Some cities blamed them for the Black Death plague. Some areas exiled
them or forced them into ghettos, others required them to wear yellow cloth armbands or
buttons, and they were restricted from certain fields of work, all throughout the Middle Ages.
6 A Vienna newspaper.
7 Wiener Tagblatt.
8 The palace of the Hapsburg Dynasty in Vienna, Austria.
44
Years of Learning and Suffering in Vienna
The whole thing seemed so fake. I thought that such a policy was a stain
on the ideal of liberal democracy. The way they would crawl for the Court’s
approval and betray the dignity of the nation. This was the first bad feeling I
developed about the press.
As always, I followed every event in Germany with burning concentration,
whether political or cultural. With proud admiration I compared the rise of the
Reich with the sickness and decline of the Austrian state. Happenings outside
Austria were mostly a source of pure pleasure; the less agreeable events at
home often brought worry and gloom. I did not approve of the fight then being
carried on against William II.9 I saw him not only as the German Emperor, but
primarily as the creator of a German Navy. I was extraordinarily annoyed when
the German parliament forbade the Emperor to speak in Parliament. The
prohibition came from a people who had no reason to object considering the
fact that these parliamentary geese chattered more nonsense in a single
session than a whole dynasty of emperors could produce in centuries.
I was outraged that the heir of the Imperial crown could receive
“reprimands” from the shallowest chattering-institution in a state where
every half-wit claimed the right to criticize and might even be turned loose on
the nation as a “lawgiver.” But, I was even more angered when the Vienna
press, which bowed to the lowest member of the Royal Court hoping for some
attention, now expressed doubts about the German Emperor. Their apparent
concern seemed more like malice in my opinion. They quickly claimed they
had no intention of meddling in the affairs of the German Emperor, heaven
forbid, but they pretended that by touching a delicate spot in such a friendly
way they were fulfilling a duty resulting from the mutual alliance between the
two countries, and at the same time, discharging their obligations of
journalistic truthfulness. Then the finger pushed into the sore spot and dug
ruthlessly into the wound.
Cases like this made the blood rush to my head. This was what gradually
made me regard the great press with more caution. I did have to admit that
45
Mein Kampf
one of the anti-Semitic papers, The German People’s Paper,10 was honorable
on occasion.
Another thing that bothered my nerves was the revolting cult of France
which the big papers were then propagating. It was enough to make a person
ashamed of being a German. We were constantly bombarded with praises to
the “great civilized nation.” More than once, this wretched spell of French
captivation made me lay down one of the “world papers.” In fact, I began to
turn to The German People’s Paper more often, which was much smaller, but
cleaner in such matters. I disliked the sharp anti-Semitic tone, but I did
occasionally read arguments which gave me something to think about.
Such stories eventually educated me about the man and the movement
which then governed Vienna’s destiny—Dr. Karl Lueger and the Christian
Socialist Party.11 When I came to Vienna, I was hostile to both. In my eyes, the
man and the movement were opposed to political and social change.
However, a sense of common justice forced me to change my opinion
gradually as I learned about the man and his work. Eventually, my opinion
grew into admiration.
Today, more than ever, I consider the man the greatest German mayor
of all times. But, how many of my preconceived views were upset by this
change in attitude toward the Christian Socialist movement?! My opinions on
anti-Sem.
During my bitter struggle between emotional ties to what I learned as a
child and cold reason, the streets of Vienna offered me priceless first-hand
lessons. The time had come when I no longer walked blindly through the vast
46
Years of Learning and Suffering in Vienna
city as I did at first. I kept my eyes open and looked at people as well as
buildings.
Once, as I was strolling through the inner city, I suddenly met a figure in
a long caftan with black curls. “Is that a Jew?” was my first thought. Jews did
not look like that in Linz. I covertly observed the man, but the longer I stared
at that alien face, scrutinizing feature after feature, my question changed
from, “Is that a Jew?” to “Is that a German?” As always, I tried to resolve my
doubts through books. For a few coins, I bought the first anti-Semitic
pamphlets I had ever purchased in my life.
Unfortunately, they were all based on the theory that the reader grasped
or at least was familiar in principle with the Jewish question. Their tone made
me feel new doubts because of the often shallow and unscientific proofs they
offered.
I would relapse to my former way of thinking for weeks, sometimes
months. The matter seemed so monstrous and the accusations so
unrestrained that I feared it might be unjust for me to decide one way rather
than another, and again I became timid and uncertain.
Even I could no longer doubt that this was a question about a people in
itself and not about Germans of a particular religious persuasion. Since I had
begun to occupy myself with the question and to pay attention to the Jew,
Vienna had appeared to me in a new light. Wherever I went now, I saw Jews
and the more I saw, the more clearly my eye distinguished them from other
people. The inner City and the Districts north of the Danube Canal were
especially filled with people who didn’t look anything like Germans. If I
continued to have doubts, my indecision was ended by the attitude of the
Jews themselves. A great movement among many of them, especially in
Vienna, sharply emphasized the special character of Jewry as a separate
people: Zionism.
Only some of the Jews approved of this movement, and while the great
majority condemned and even rejected the very idea, the appearance of the
movement melted away in an evil fog of excuses, I could even say lies. So-
called liberal Jewry rejected the Zionists as Jews who were impractical and,
perhaps dangerous in their public adherence to Judaism. It made no
47
Mein Kampf
difference; they were all still Jews. There was no real separation and they
maintained their internal solidarity.
This fictitious conflict between the Zionists and the Liberal Jews soon
disgusted me. It was false through and through and contradicted to the moral
dignity and pure character their race had always prided itself upon.
Morality and purity of character were terms that had their own meaning
among these people anyway. It was obvious from their unclean appearance
that they were not water-lovers. I am sorry to say that this was very clear, even
with my eyes closed. I was frequently nauseated by the smell of these caftan-
wearers. In addition, their clothes were dirty and they generally looked poor.
All this was unattractive enough by itself, but one was positively repelled
when they realized uncleanliness went beyond personal filth and into the
moral mud-stains of these people. My greatest concern was the activities of
the Jews in certain fields of life. I slowly penetrated this mystery. Was there
any shady undertaking, any form of foulness, especially in cultural life, in
which at least one Jew did not participate? If you carefully punctured this
abscess with a knife, like a maggot in a rotten body who was blinded by the
sudden influx of light, you would discover a Kike.12
I saw a great burden of guilt fall upon Jewry when I came to understand
how it controlled the press, the influence in art, in literature, and in the
theater.
All their slimy declarations now meant little or nothing. It was enough to
look at one of the billboard pillars and study the names credited for the awful
movie or theatrical presentations in order to be firmly convinced of the Jewish
problem.
Here they were, infecting the people with a pestilence—an intellectual
pestilence worse than the Black Death of ancient days. This poison was
produced and distributed in massive quantities too! Naturally, the more
immoral these artists and producers are, the more they grow. Such a fellow
flings his garbage in the face of humanity like a windmill. Do not forget their
unlimited number. For every one German writer like Goethe, nature plants at
12 Ein Jüdlein.
48
Years of Learning and Suffering in Vienna
least ten thousand of these slimy creatures in the pelt of humanity where they
poison the people with their disease. It was a dreadful but inescapable fact
that the Jew seemed specially chosen by nature in tremendous numbers for
this horrible destiny. Are we supposed to assume that this is the way he is
“chosen?” At that time, I began to carefully examine the names of all the
producers of these unclean products in the world of art, and this scrutiny only
damaged my attitude toward the Jews more. Though my feelings were
outrage times a thousand, I must surrender to my reason and let it draw the
conclusions. It was true that nine-tenths of all the literary filth, artistic trash,
and theatrical nonsense must be attributed to a people constituting scarcely
one one hundredth of the country’s population. It was a plain fact.
I now began to scrutinize even my beloved newspapers from the world
press. The deeper I probed, the more my previous admiration shrank. The
style grew more intolerable. I objected to the content as flat and shallow. The
objectivity was transformed into more of a lie than honest truth—of course
the authors were Jews. Jewish author, while their disapproval never fell on anyone
except a German. The constant and quiet sneering at William II revealed they
had a deliberate plan. Their advocacy of French culture and civilization also
played into their schemes. The trashy content of the short stories now became
an indecency and I heard sounds of an alien people in the language. The
general sense was so clearly harmful to everything German that it could only
be intentional. But who had an interest in this? Was it all mere chance?
Gradually I became unsure.
My development was accelerated by the insights I gained into a series of
other matters. This was the general display of manners and morals openly
shown by most of Jewry.
49
Mein Kampf. If a person
walked the streets and alleys of Leopoldstadt13 in the evening, all along the
way you could see things which remained hidden from the great majority of
the German people.14 These things remained secret until the First World War
gave the soldiers on the Eastern front an opportunity, or rather forced them
to see similar happenings.
It sent a chill down my spine when I first realized the Jew was the
manager of this immoral trade among the scum of the city. He was icy calm
and shamelessly businesslike which made me fuming angry. Now, I no longer
evaded discussing the Jewish question. Now I wanted to discuss it. I had seen
the Jew in every area of cultural and artistic life, then I suddenly encountered
him in another spot where I would have least expected to see him, and I
recognized the Jew as the leader of Social Democracy, the Marxists, and that
is when the blinders fell from my eyes. Suddenly, a long, spiritual struggle
came to an end.
I was astonished how easily my fellow workmen changed their minds
over a question. Often their opinion changed within a few days, sometimes
even within a few hours they turned around. I could hardly understand how
people who individually held reasonable views could suddenly lose them the
moment they came under the spell of the masses. It was enough to drive a
person crazy. I would argue for hours and finally believe I had broken the ice
or cleared up some piece of nonsense they had in their heads. I would feel
pride in my success and then the next day, I would be stressed to find out I
had to begin all over again. It had all been for nothing. Their crazy opinions
seemed to always swing like a pendulum.
I could understand how they felt. They were dissatisfied with their place
in life. They cursed Fate, which often dealt them such hard knocks; they hated
13Leopold Town.
14Leopoldstadt is a district in Vienna separated from the main city by the Danube waterways.
The area was heavily Jewish and considered a ghetto.
50
Years of Learning and Suffering in Vienna
the businessmen, who seemed to be the heartless tools of Fate, and criticized
government offices, which in their eyes had no sympathy for the workers’
situation. They demonstrated against food prices and marched through the
streets in support of their demands. All this I could understand, but what I
could not understand was the boundless hatred they felt for their own
nation—the way they despised its grandeur, the way they defiled its history,
and the way they dragged great men in the gutter.
This struggle against their own kind, their own nest, their own homeland,
was as senseless as it was incomprehensible. It was unnatural. They could
temporarily be cured of this vice, but only for days or for weeks at the most.
Later, if one met a supposed convert, he may have fallen back into his old self
against his fellow men. His unnatural tendencies would again have him in their
grip.
I gradually came to realize that the Social Democratic press consisted
mostly of Jews, but I attached no particular importance to this situation.
Circumstances were the same at the other newspapers. One thing was
remarkable to me; there was not one paper where Jews worked that I would
have considered a proud national voice that was in line with my concept of
national pride.
I forced myself to at least make an attempt at reading this Marxist
journalism, but the more I did, the more I disliked it. I now tried to get closer
to the manufacturers of these mischievous words. From the editor on down,
they were all Jews. I picked up every Social Democratic pamphlet I could and
looked up the author’s name. Jews. I noticed the names of almost all the
leaders. Most of them were also members of the “chosen people,” the Jews,
whether they were representatives in the government or secretaries of the
unions, chairmen of organizations, or street agitators. The same uncanny
picture was continually repeated. I will never forget the names of Austerlitz,
David, Adler, Ellenbogen, and others.
One thing was plain to me now. The leadership of the party whose petty
representatives I had to fight my most violent battles with for months
consisted almost exclusively of an alien people. I then had the happy
51
Mein Kampf
satisfaction of knowing for certain that the Jew was no German. Now, for the
first time, I became thoroughly familiar with the corrupter of our people.
Living one year in Vienna had been enough to convince me that no
worker is too inflexible to yield to greater knowledge and superior
enlightenment. I had gradually become an authority on their own doctrine,
which I used as a weapon in the battle for my convictions. Success was almost
always on my side.
The great mass of people could be saved, even if it was only by the
greatest sacrifice of time and patience. But no Jew could ever be freed from
his opinion.
In those days, I was still childish enough that I would try to explain the
madness of their doctrines to them. In my own little circle, I talked until my
tongue was sore and my throat was hoarse and thought I must succeed in
convincing them how destructive their Marxist madness was, but the very
opposite was the result. Growing insight into the destructive effect of Social
Democratic theories only increased these people’s determination.
The more disputes I had with them, the better acquainted I became with
their arguing techniques. First, they would count on the stupidity of their
adversaries, and then, if there was no way out, they pretended to be stupid
themselves. If all else failed, they claimed they did not understand, or, being
challenged, they would instantly jump to another subject and talk about
obvious truths. If these were agreed on, they immediately applied them to
entirely different matters. When they were caught off guard, they would avoid
the conversation and claim they had no knowledge or understanding of the
issue. No matter where you seized one of these apostles, your hand grasped
slimy ooze, which spurted through your fingers, only to unite again the next
moment. If your argument really gave a man a shattering defeat in front of
others, he could do nothing but agree. You might suppose that this was one
step forward, but how surprised you would be the following day! The next
morning you will find that Jew has not even the slightest memory of yesterday
and continues to repeat his old mischievous nonsense as if nothing at all had
happened. When pressed about the previous conversation, he would pretend
52
Years of Learning and Suffering in Vienna
astonishment and could remember nothing at all except the truth of his
statements, which he felt had been proven the day before.
Frequently I was simply paralyzed. It was hard to know what to admire
the most: their fluency or their artistry in lying. Gradually, I began to hate
them.
There was one good result in all of this. My love for my own people was
bound to grow just as fast as the expansion of Social Democracy. After all,
considering the diabolical skillfulness of these seducers, who could possibly
condemn their poor victims? It was unbelievably difficult for me to master and
overcome the contradictory lies of this race! Any success with people who
twisted the truth was immediately turned around. They would make a
statement one moment to counter your argument, then the next moment use
the same reasons they just tried to discredit in order to prove their own point!
No. The better I became acquainted with the Jew, the more I could forgive the
worker.
In my opinion, those to blame were not the workers. The blame fell
squarely on those who did not think it worthwhile to sympathize with their
own kinsfolk. With those who would not give to the hard-working son of the
national family what was his by the iron logic of justice. The blame fell on the
same seducer and corrupter who should be placed against the wall.
Stimulated by the experience of daily life, I now began to search for the
sources of the Marxist doctrine itself now that I had come to understand its
effect in detail. Every day, its success caught someone’s attention, and with a
little imagination I could see where the results were leading us. The only
question remaining was whether the founders had foreseen the results of
their creation in its final form or whether they were victims of error. I felt that
both answers were possible.
On one hand, it was the duty of every thinking person to force his way
into the front ranks of the cursed movement and try to prevent it from going
to extremes. On the other hand, the actual creators of this national disease
must have been true devils. Only in the brain of a monster—not a human
being— could an organization’s plan take shape that would eventually result
in the collapse of human civilization and the desolation of the world.
53
Mein Kampf
If this were the case, the last hope was battle. A battle by every weapon
which the human mind, understanding, and will could grasp, no matter who
Fate blessed.
I began to familiarize myself with the founders of this doctrine in order
to study the foundations of the movement. I was able to obtain results sooner
than I had even dared to hope because of my new, if not yet profound,
knowledge of the Jewish question. That alone allowed me to compare its
realities with the theoretical shuffling by the founding apostles of this Social
Democracy movement. It had taught me to understand the language of the
Jewish people, who speak to conceal, or at least veil, their thoughts. Their real
purpose is often not in the writing itself, but sleeping snugly between the lines.
This was a time when my spirit experienced the greatest upheaval it has
ever endured. I turned away from a weak set of political notions and into a
fanatical anti-Semite.
Once more and for the last time, restless, uneasy, and oppressive
thoughts came to me in my extreme anxiety.
I had researched the work of the Jewish people during long periods of
human history, and suddenly I was struck by the alarming question of whether
the mysteries of Fate had irrevocably determined that the final victory was not
the destiny of our little people for reasons unknown to us puny humans. The
Jews are a people which live for this earth alone. Could they have been
promised the earth as their reward? Do we have an objective right to fight for
self-preservation or is this just an illusion? I buried myself in the teachings of
Marxism and gave calm, clear consideration to the work of the Jewish people.
Fate itself gave me my answer.
54
Years of Learning and Suffering in Vienna
crown will be the death and destruction of all mankind. Earth would again
move uninhabited through space as it did millions of years ago.15 Eternal
Nature takes revenge for violation of her commandments. I believe I am acting
today in the spirit of the Almighty Creator. By standing guard against the Jew,
I am defending the work of the Lord.
15Hitler originally said thousands of years ago in the very first edition, but it was changed in
the second printing. Although, it could be considered correct either way because he was
talking about humanity.
55
CHAPTER THREE
Generally, a man should not be active in public politics under the age of thirty
unless he is of extraordinary talent. The reason is obviously that before that
age, he has been building a general platform from which he can examine the
various political problems and build his own beliefs. Only after he has
established a fundamental World-Concept and has stabilized his own way of
looking at the individual questions of the day, should the man who is at least
achieved an inner maturity be allowed to guide the community politically.
Otherwise, he is in danger of either changing his previous positions on
fundamental questions once he realizes he was wrong or clinging to a view
which he no longer supports or may even be against. This will make it
politically difficult for his followers to maintain their faith in him. Their old
unshakable solid belief will be upset because he now appears to be undecided
himself. To followers, such an about-face of their leader, means complete
confusion in addition to their feeling of shame in front of those they have
previously attacked over the issue. The second alternative brings about a
result which is particularly common today. The leader continues to publicly
claim he believes in what he had previously said. He then becomes more
hollow and superficial and eventually becomes more corrupt. He no longer
dreams of working seriously for his political ideals; no one dies for something
he does not himself believe in, and his demands upon his followers grow
greater and more shameless to compensate for his own insincerity until at last
he sacrifices his remaining fragment of leadership and begins to play the
political game for the sake of politics alone.
56
General Political Considerations of my Vienna Period
He has joined that class of people whose only real conviction is absence
of conviction coupled with a bold and shamelessly well-developed skill at lying.
Unfortunately for decent people, if such a fellow moves into big government,
the essence of his politics is limited to a heroic battle for permanent
possession of his position to maintain his political life for himself and his
family. The more his wife and children cling to him, the more stubbornly he
will fight for his seat. If only for this reason, he is the personal enemy of every
other man with political instincts. In every new political movement he senses
the possible beginning of his end. In every greater man he senses a danger
which may threaten him. I will have more to say about this sort of Parliament
(bed)bug later.
Even a man who is thirty years old will have much to learn in his life, but
what he learns will merely fill out and complete the picture which his
fundamental World-Concept presents to him. His learning will be more than a
mere re-learning of principles. It will mean learning more, understanding
better. His followers will not have to choke down the uneasy feeling that up
to this time he has misled them on some matter. On the contrary, the visible
organic growth of the leader will give them satisfaction since his learning
seems to be the deepening of their own doctrine. In their eyes, this is an
argument that proves the truth of their views.
A leader who has to abandon the platform of his World-Concept because
he realizes it is mistaken is honorable if he admits his view was faulty and is
ready to correct his conclusions. He must then give up any further public
political activity as well. Since he has already fallen victim to error once in
building his fundamentals, the possibility of a second lapse is always present.
He has no right to ask for, let alone demand, the confidence of his fellow
citizens.
We can judge from the general moral corruption of the group who feel
called upon to be politicians that such ideas of honor are not practiced today.
Many feel called, but rarely is one truly chosen.
I believe I was more concerned about politics than many others, but I
avoided making any public appearances. Only in very small groups did I talk
about what inwardly moved or attracted me. This kind of intimate talking
57
Mein Kampf
helped me a lot. I did not learn much about “speaking,” but I came to know
people through their primitive views and objections. In doing so, I trained
myself and wasted no opportunity to further my education. There was
nowhere in Germany that could have provided such a favorable opportunity
as I found in Vienna, Austria at that time.
Judging by its extent, general political thinking in the old Danube
Monarchy1 was larger and more inclusive than in the old Germany of that
period, except in parts of Prussia, Hamburg, and the coast of the North Sea.
The Austrian part of the great Hapsburg Empire was settled by Germans and
was in every respect the cause of that state’s creation. The population alone
had the strength to support cultural life for centuries, yet was still politically
artificial. The more time passed, the more the existence and future of that
state came to depend on the preservation of this German seed of the Empire.
If the old Monarchs were the heart of the Empire—forever sending fresh
blood into the circulation of state and cultural life—then Vienna was the brain
and strength of the nation. On the outside, this city looked like it had the
strength to rule as the queen over a huge group of people. Her splendid beauty
caused the deadly signs of mental deterioration to be forgotten.
No matter how the interior of the Empire was shaken by the bloody
turmoil between individual nationalities, the world outside, and Germany in
particular, saw only the charming image of this city. The illusion was easier to
accept because the Vienna of this time seemed to be taking its last and
greatest visible rise. Under the rule of a mayor who was a true genius, the
inspiring Residence of the Kaisers of the old Empire rose up to a wonderful
new life. The last great German born to the colonist people of the Ostmark
was not officially included as a “statesmen,” but as Mayor of the “Capital City
and Imperial Residence” of Vienna; Dr. Lueger, made magic with his
achievements in every field, whether it was community, economic, or cultural
policy.
58
General Political Considerations of my Vienna Period
59
Mein Kampf
which supplied the whole Dual Monarchy and never seemed to run out.2
Germans were the pillar of all foreign policy with the exception of a small body
of Hungarians. Nevertheless, every attempt to preserve the Empire was
useless since the most essential requirement for its preservation was missing.
For Austria there was only one possible way of overcoming the scattering of
the individual states. The states had to be centrally governed—an organized
internal government—or it would fail.
When the Highest officials were temporarily thinking clearly, they
realized this truth, but it was quickly forgotten or set aside because they
believed it would be too difficult to accomplish. Thoughts of a more united
version of the Empire were bound to go wrong because there was no strong
state instigator, no one with dominant authority. The internal status of the
Austrian state was very different from that of the German Empire as Bismarck
shaped it. In Germany, it was only a question of overcoming political traditions
since a common cultural basis was always there. Germany was primarily made
up of only one group of people aside from small alien fragments. In Austria,
the situation was reversed.
Except for Hungary, the individual countries had no political memory of
their own grandeur, and among the people, that memory had been
eliminated.
Now, nationality and racial forces began to develop again, which was
increasingly difficult to overcome as national states began to form along the
edge of the Monarchy. The people of these states, racially related or similar
to the individual fragments within Austria, now began to exert a stronger
attraction than the German-Austrian could. Even Vienna could not hold out
for long in this conflict.
When Budapest had grown large enough to rival Vienna, their mission
was not to hold together the distant parts of the Empire, but rather to
strengthen one part. Within a short time Prague followed the example of
Budapest, and later on came Lemberg, Laibach and others. These places were
raised from small provincial towns to national cities which created rallying
2The Dual Monarchy was the Austrio-Hungarian Monarchy which was the union forming the
Hapsburg Monarchy.
60
General Political Considerations of my Vienna Period
centers for an independent culture. Through this, the local national instincts
acquired a spiritual foundation and gained a more profound hold on the
people. The time was sure to come when the interests of each country would
become stronger than their common imperial interests. Once that stage had
been reached, Austria’s doom was sealed and the Empire would fall apart.
These developments after the death of Joseph II were plain to see.3 The
rapid growth of these areas depended on a series of factors that included the
Monarchy itself and the Empire’s position in foreign politics. If the battle to
preserve the state was to be fought to the finish, only a central government
as ruthless as it was persistent could possibly succeed. In that case, it was
necessary to establish a uniform state language that would emphasize the
unity of the people and furnish the government with a technical tool necessary
to maintain a unified state. Only then could a consistent state awareness be
created through the schools. This could not happen in ten or twenty years, it
was something that would take centuries; however, in all questions of
developing a country, a large goal is more important than momentary efforts.
Both administration and political leadership must be conducted with rigid
unity. I learned a lot when I discovered why this was not done and why this
did not happen. The person guilty of this omission was the one who was
completely responsible for the collapse of the Empire.
More than any other state, Old Austria depended on the greatness of its
leadership. The cornerstone of a national state was missing. The basis of a
national state is the people and they still have the power to sustain it no
matter how bad the leadership is. Thanks to the natural activity of its
inhabitants and the power of resistance that results from that independence,
a unified national state can often survive the worst administration or
leadership without being destroyed. A body like this often seems to have no
life at all, as if it were dead and gone, then suddenly what appeared to be a
3 Joseph II was co-regent or co-ruler with his mother, Maria Theresa, for much of his reign. He
is known for his efforts to unify the Kingdom, but his diplomatic skills were poor. When his
brother, Leopold II, succeeded him, he tried to restore relations by giving concessions to those
Joseph II had alienated.
61
Mein Kampf
corpse rises up and gives mankind astonishing signs of its indestructible life
force.
However, this is not true of an empire composed of different people who
are living under a common strong arm of leadership and not connected by
common blood. In this situation, governing weakness does not lead to the
hibernation of the state, but to an awakening of all the individual instincts
which are present in the blood of the various groups. Even if they are unable
to grow under the influence of a single dominant will, the individual elements
will still rise. Only centuries of common education, common tradition, and
common interest can reduce that danger. This is why the younger a state
structure is, the more they depend on the greatness of their leadership. In
fact, the work of strong, outstanding figures and intellectual heroes often
collapses immediately after the death of the great, lonely founder.
Even after centuries, however, these dangers cannot be considered
defeated. They are sleeping and often will suddenly awake the moment
weakness in a common leadership is felt. The force of education and the
grandeur of tradition are no longer strong enough to overcome the native life
force in the various races.
It is the House of Hapsburg’s fault that this was not understood. Fate gave
one of them the opportunity to change the future of his country, but that
flame of hope was extinguished forever. In a state of panic, Joseph II, Roman
Emperor of the German Nation, saw how his leadership was being driven to
the outside edge of the Empire. It was eventually going to disappear in the
whirlwind of a corrupt people unless everything that his fathers had failed to
do was fixed at the last minute. The “Friend of Mankind,” Joseph II, decided
he would use superhuman strength and try to correct in a decade the
centuries of neglect by his forefathers. If he had been given just forty years for
his task, and if only two generations had continued the work he had begun,
the miracle would probably have succeeded. But, he died after ruling barely
ten years. He was worn out in body and soul and his work followed him to the
grave, to sleep forever, without reawakening. His successors had neither the
intelligence nor the will to get the job done.
62
General Political Considerations of my Vienna Period
When the first sparks of a new age began to flash through Europe, the
revolution set Austria on fire. When things started really rolling, those flames
were fanned more by the people than economic, social, or even general
political causes.
The Revolution of 18484 was a class struggle everywhere else, but in
Austria, it was the beginning of a new war between nationalities. At that time,
the German man forgot or didn’t realize his origin and sealed his own fate by
entering the service of the revolutionary uprising. He helped to stir up the
spirit of Western Democracy that soon deprived him of the foundation for his
own existence. Without first deciding on a common state language, the
formation of a parliamentary representative body had laid the foundation for
the end of German supremacy in the Monarchy. From that day on the state
was lost. Everything that happened after that was the historical liquidation of
an Empire.
Watching the Empire dissolve was as moving as it was instructive. The
execution of a historical sentence took place in a thousand different ways. The
fact that most people walked blindly through the resulting decay only proved
that it was God’s will to destroy Austria. I do not want to get lost in details;
that is not my purpose. I only want to provide information about those
processes which still have importance for us today and which helped to
establish my political way of thinking, like the unchanging causes of the decay
in the people and the state.
The institutions that most clearly demonstrated the decay inside the
Austrian Monarchy was the Parliament or Reichsrat as it was called in Austria,
which should have been the strongest institution. This was obvious even to
the half-blind, privileged-class Philistine.
The model for this group was obviously in England, the land of classical
“Democracy.” That excellent parliamentary structure was transferred almost
directly to Austria with as little alteration as possible. In the House of Deputies
and the House of Lords, the English two-chambers of government were
4The European Revolutions of 1848 were known in some countries as the Spring of Nations,
Springtime of the Peoples or the Year of Revolution. This wave of revolution caused
political upheaval throughout the European continent.
63
Mein Kampf
5 Barry was Sir Charles Barry, an English architect who, after a fire, rebuilt the Palace of
Westminster which is the English Parliament building in London.
6 Theophilus Hansen was a master of the Historicism of the period, which interpreted in
Classicist, Byzantine and Renaissance style in Vienna, where his buildings include the
Musikverein concert hall, 1869, the Stock Exchange, 1877, and the Parliament building, 1884.
7 Paul Wallot was the architect of the German Reichstag Parliament Building completed in
1894.
64
General Political Considerations of my Vienna Period
admiration I could not get rid of very quickly. According to the great reports in
our newspapers, the dignity with which even the lower House fulfilled its
duties impressed me greatly. How could there possibly be any nobler form of
self-government for a people? For that very reason, I was an enemy of the
Austrian Parliament. The way that the whole thing was carried on seemed to
me unworthy of its great model. The following considerations also influenced
my attitude: the fate of the German race in the Austrian state depended upon
its position in the Austrian Parliament. Until the introduction of secret ballot
voting for all men, there was still at least a small German majority in
Parliament, even if it was an insignificant one. Even this was dangerous. The
national attitude of the Social Democrats was unreliable, and in crucial
questions concerning German character, they always fought against German
interests to avoid losing their followers among the various alien peoples. Even
in those days, Social Democracy could not be considered a German party. The
introduction of universal voting, however, destroyed the German numerical
superiority. There was no longer any obstacle to the further de-Germanization
of the state.
The instinct of national self-preservation made it impossible for me to
welcome a representative system where the German element was not
represented properly, but was instead betrayed by the Social Democratic
fraction. These defects could not be attributed to the parliamentary system as
such, but rather to the Austrian State. I still believed that if the German
majority could be restored in this representative body, there would be no
need to oppose such a system as long as the old Austrian State continued to
exist.
This was the opinion I held when I entered those sacred and coveted
halls. For me, they were sacred only because of the radiant beauty of that
majestic building. A Greek wonder on German soil. Soon, though, I was
outraged at the wretched spectacle that happened right before my eyes!
There were several hundred representatives present who were expressing
their opinions on a question of economic importance.
The events of the first day alone gave me enough to keep me thinking for
weeks. The intellectual content of what they said was at an extremely
65
Mein Kampf
depressing level, that is, if you could understand their chatter at all. Some of
the gentlemen didn’t speak German. They only sputtered in their Slavic
mother tongues or dialects. Now I had a chance to hear with my own ears
what I had previously known only from reading the papers. It was a wild
commotion with gesturing, yelling, and interruptions in every tone of voice. In
the middle of it all was a harmless old man who was trying his best to restore
the dignity of the House by violently ringing a bell and shouting in a soothing
way, then in warning tones. I could not help laughing.
A few weeks later, I visited the chamber again. The scene was
transformed beyond recognition. The hall was almost empty. Down below,
people were asleep. A few deputies were in their seats, yawning at one
another while one of them “spoke.” A Vice President of the House was present
and he looked over the chamber with visible boredom.
I had my first misgivings, but I kept looking in on meetings whenever I
could possibly find time. I watched what was going on quietly and attentively,
listened to as much of the speeches as was understandable, studied the more
or less intelligent faces of the chosen representatives of the nations in this sad
state, and then gradually formed my own ideas.
A year of calm observation was enough to absolutely change or rather
destroy my former opinions on the nature of the institution. I no longer
objected to the distorted form Parliament had assumed in Austria. No, now I
could no longer acknowledge Parliament as a government body at all. Up until
now, I had only seen the ruin of the Austrian Parliament in the lack of a
German majority, but now I saw destruction in the whole nature and character
of the institution. I saw a whole new series of questions that needed to be
answered.
I began to familiarize myself with the democratic principles of majority
rule as the foundation of the whole institution, but I was equally attentive to
the intellectual and moral values of the gentlemen who were the chosen
members of the nations and who were supposed to pursue this goal. I became
familiar with both the institution and the men who made it up.
Within a few years, my perception and understanding allowed me to
form a clear and well-rounded image of the most dignified figure of modern
66
General Political Considerations of my Vienna Period
8Hitler’s humorous use of this quote is from J. W. von Goethe’s Faust where Faust calls
Mephistopheles, “You are the birth/monstrosity of filth/crap, and fire.”
67
Mein Kampf
68
General Political Considerations of my Vienna Period
9Pericles was a great speaker and statesmen in ancient Greece known for a period called the
“Age of Pericles.”
69
Mein Kampf
which recently has grown to a real scandal. The cowardice of our so-called
“leadership” is obvious. How lucky for them that when it comes to any
decisions of importance, they can hide behind the skirts of the majority! Just
take a close look at one of these political doormats. He begs for the approval
of the majority for every action in order to guarantee he has an adequate
number of accomplices so he can unload all responsibility! That is the main
reason why this sort of political activity is disgusting and hateful to any decent
and courageous man. It attracts the most contemptible characters. Anyone
who will not take the personal responsibility for his actions and runs for cover
to avoid responsibility is a cowardly villain.
Once a nation has put despicable leaders like these in place, the people’s
punishment will be swift. Representatives will no longer have the courage to
make any decisions and would rather accept abuse, defamation, even
dishonor as long as they do not have to pull themselves together and make a
real decision. After all, there is no one left who is ready to take responsibility
for himself and carry a difficult decision through.
Never forget that a majority cannot replace a man. A majority always
represents stupidity and cowardice. A hundred cowards do not make a hero
any more than a hundred fools make a wise man. The less responsibility the
individual leader has, the more would-be politicians will feel they are called
upon to devote their pitiful “gifts” to the nation. They are not even able to
wait for their turn. They stand in a long line, sadly counting the people ahead
of them and marking off the minutes until it will be their turn to board this
political train. They wait a long time for any change in the office they have
fixed their eye on, and are grateful for any scandal which thins the ranks ahead
of them. Occasionally, someone refuses to move from his office, which makes
the ones in line feel like there has almost been a violation of a sacred promise.
Then, they grow spiteful and do not rest until the bold politician holding onto
their office is ousted. After that, he won’t hold office again anytime soon. If
one of these creatures is forced to give up his post, he will immediately try to
crowd into the waiting lines again, that is, unless he is prevented by the yelling
and abuse from the others.
70
General Political Considerations of my Vienna Period
71
Mein Kampf
used in the service of their country. In other words, to analyze thoroughly their
step-by-step procedure.
We must be objective in considering an institution whose members think
it is necessary to refer to “objectivity” in every other sentence as the only just
basis for any judgment or belief. Anyone who examines these gentlemen for
themselves can only be astonished at the result. The parliamentary life looked
more and more desolate as one penetrated its structure and studied the
people and principles of the system in a spirit of ruthless objectivity.
If you do consider the matter with absolute objectivity, the parliamentary
principle is wrong. There is no other principle as wrong as the parliamentary
principle. We can say this without even referring to the way the election of
the honorable deputies takes place, the way they get into office, and the way
titles are given to them. Only in a tiny fraction of cases are the offices filled
based on widespread desire and certainly it does not stem from any need. It
is obvious to anyone that the political understanding of the masses has not
reached the point where they can arrive at political views on their own. They
are incapable of picking out the most qualified person. What we always call
“public opinion” is based only on individual experience or knowledge. Most
public opinion results from the way public matters are presented to the
people through an overwhelmingly impressive system of controlled
information. Just as religious beliefs are the result of education, the political
opinion of the masses is the result of an often incredibly thorough and
determined assault on the mind and soul.
By far the greater part of political “education” or propaganda is the work
of the press. It is the press which primarily takes care of the “work of
enlightenment” and acts as a sort of school for adults. This means the teaching
materials are not in the hands of the state, but in the clutches of characters
who are motivated by their own interests. As a young man, Vienna gave me
the best opportunities to become intimately acquainted with the owners and
manufacturers of this mass-education machine. At first, I was astonished to
see how quickly this evil power succeeded in producing a particular opinion
among the public, even though the meaning may be twisted or a flat-out false
representation of public desire. A few days were enough to turn some
72
General Political Considerations of my Vienna Period
ridiculous affair into a momentous act of state, while vital problems were
generally forgotten or simply erased from the memory of the masses.
In the course of a few weeks, the press could conjure up names out of
nothing and attach the incredible hopes of the public to them. Suddenly they
would become more popular than a really important man may ever enjoy in a
lifetime. These were names which no one had even heard of only a month
before. At the same time, old and stable figures of government or public life
simply ceased to exist as far as the world was concerned, or they were buried
under such rudeness that their names soon risked becoming symbols of
wickedness or dishonesty. If we are to understand this process, we have to
study this infamous Jewish way of magically drenching the clean garments of
honorable men with the slop buckets of filthy libel and slander from hundreds
of directions at once. We must study it if we are to understand the real danger
from these journalistic villains.
There is nothing these powerful intellectual newspaper rogues would not
do if it allowed him to accomplish his disrespectful ends. He sniffs his way into
the most secret family affairs and he does not rest until his nosiness has rooted
up some awful situation which will serve to cook the unlucky victim’s goose. If
he does not uncover anything in public or private life, he resorts to slander.
He has a deeply-rooted belief that some of it will stick. Even if there are a
thousand contradictions in his claims, after it is repeated a hundred times by
all his accomplices, the victim usually can’t put up a fight at all. This pack of
scoundrels will never admit their actions affect mankind, and they certainly
would never admit that they even understand what they are doing.
Heaven forbid! These idle and dishonest people are like squids that hide
in a cloud of truth, proclaiming “journalistic duty” and other lies while
attacking the rest of the world in the sneakiest way possible. They congregate
at congressional meetings and conventions to confirm the tedious talk about
their journalistic duty and the honor they do to society. Then this species bows
to pay their respects to one another and with it they end their meeting. This
insidious group manufactures more than two-thirds of all so-called “public
opinion,” and this is where parliament obtains their strength.
73
Mein Kampf
To describe all of this in detail and prove its lies and falsehoods would
take volumes. But putting all this aside, if we just look at the product and its
effect, I think this will be enough to show how this crazy business works in
such a way that even the most innocent and skeptical person will understand.
The quickest and easiest way to understand this senseless and dangerous
deviance is by comparing democratic parliament systems with a genuine
Germanic democracy.
A body of five hundred men, or even recently, women, is chosen, whose
duty is to make a final decision on all kinds of issues. They alone are effectively
the government. Even though they may choose a cabinet, which on the
outside is supposed to manage the affairs of state, this is only for show.
In reality, the government cannot take any step without first getting
permission from the general assembly. Consequently, it is not responsible for
anything since the final decision does not rest with anyone in the government,
but with the majority of Parliament. In any case, the government simply
carries out the will of the majority. Its political capacity can really only be
judged by its skill in either conforming to the will of the majority or convincing
the majority to switch to its side. This reduces it from being a real government
to being a beggar at the feet of the majority. Its most urgent job is to gain the
favor of the existing majority or to try to set up a more agreeable new
majority. If it succeeds, it can continue the political game for a little while
longer. If it does not succeed, it must quit. Whether its intentions are right or
wrong are not even considered. This eliminates all responsibility for anyone’s
actions or decisions.
It does not take a lot of thinking to figure out what the results will be. The
five hundred representatives of the people present a disjointed and usually a
pitiful picture if you look at their dissimilar occupations or their varied political
abilities. Surely no one would assume that those elected by the nation are
chosen because of their ability to reason or their intellect. I hope no one is
foolish enough to think that hundreds of statesmen can emerge from ballot
boxes which have been stuffed by those who themselves only possess an
average intelligence. We can never denounce sharply enough the silly idea
that geniuses are discovered through general elections. The average nation
74
General Political Considerations of my Vienna Period
only finds a real statesman once in a blue moon, not a hundred at a time. The
masses will oppose any outstanding genius because it is their instinct. A camel
can pass through the eye of a needle sooner than a great man can be
“discovered” by an election.10 History has always shown that those who rose
above the average level did so through the driving force of an individual
personality. Now we have five hundred people of mere modest ability voting
on the most important issues of the nation and installing a government which
requires the approval of the exalted five hundred. This government in turn
learns that to secure its position it must carry out the policy of the five
hundred. Unfortunately, the policy is actually created by five hundred people
and it carries the same shabby appearance.
Even if there were no question about the ability of these representatives,
we must remember how varied the problems are that are waiting to be solved
and in how many totally separate fields answers and decisions have to be
given. We can easily understand how worthless a government institution is
that entrusts the right to make a final decision to a mass meeting of people
among whom only a few have any knowledge and experience in the matter
being discussed. The most important economic measures are presented to a
forum where only a tenth of the members have any economic training. This is
simply putting the final decision on an important matter in the hands of men
who lack the skills to deal with it intelligently.
That is how it ends with every question. Things are always settled by a
majority of ignoramuses and incompetents, since the membership of this
institution never truly changes. The problems presented extend to almost
every field of public life and would require a constant change of parliamentary
leaders to judge and vote on them. After all, it is impossible to let the same
people deal with matters of transportation and with a question of important
foreign policy. Otherwise, they would all have to be geniuses in every area and
this does not happen once in centuries. Even worse, they are not “brains” at
all, but only narrow, conceited, and arrogant amateurs and intellectual
pretenders of the worst sort. In fact, that is the reason for the
10 Matthew 19:24 is the Bible verse about a camel passing through the eye of a needle which
is referenced by Hitler; similar passages also appear in the books of Mark and Luke.
75
Mein Kampf
76
General Political Considerations of my Vienna Period
are dependent on the intellect of everyone around them. They become easier
to lead in a certain direction as their abilities decrease. This is the only way
party politics can be carried on. This is the only way it is possible for the
puppeteer to remain hidden in the background without ever being personally
held accountable for what he does. Then, every decision, no matter how
harmful to the nation, is blamed on a whole party and not just one
mischievous culprit pulling the strings. All responsibility disappears because
responsibility can only exist if an individual makes a decision and not an
association of parliamentary windbags.
Only an evil creature of the night, fearful of daylight, could approve of
this institution, while every honest man who accepts personal responsibility
for his own actions must find it disgusting. Consequently, this kind of
democracy has become the tool of that race whose real purpose forces it to
hide its actions from sunlight where others might see now and forever. Only
the Jew can praise an institution as dirty and deceptive as himself.
On the other side, we have the true Germanic democracy consisting of a
free election. This leader is bound to assume full responsibility for everything
he does. In this format, there is no roll call of a majority on individual
questions, but only the rule of an individual who has to support his decisions
with his property and his life. To anyone who objects by saying no one would
be willing to devote himself to such a risky responsibility under those
conditions, there is but one answer: thank God. It is the very purpose of a
Germanic democracy to keep every unworthy political climber who might by
chance fall into the office from gaining any power in the government of his
fellow man through the back door. The very magnitude of this responsibility
is meant to scare off weaklings and incompetents.
If such a fellow should try to sneak in any way, it is easier to find and
harshly punish him: “Get away, you coward! Step away, you are stinking up
the stairway. The front steps to the Pantheon of history are not for cowards,
but for heroes!” I arrived at this opinion after watching the Vienna Parliament
for two years. Then, I stopped going. Parliamentary government was largely
responsible for the ever-increasing weakness of the old Hapsburg state during
the previous few years.
77
Mein Kampf
The more its work shattered German supremacy, the more a system of
playing one nationality against another gained ground. In the Parliament
Building itself, this was always at the expense of the Germans and eventually
at the expense of the Empire. By the turn of the century, it had to have been
obvious to any fool that the central force of the Monarchy could no longer
overcome the individual countries’ attempts to break loose. On the contrary,
the more terrible the methods became that were used by the state for self-
preservation, the more universally the state was hated. In Hungary and in the
individual Slavic provinces, the people did not identify themselves with the
Monarchy so they did not feel its weakness was shameful to them. Instead,
they were rather pleased at the signs of senility because they preferred the
Monarchy’s death to its recovery.
The complete collapse of Parliament was only prevented by giving in to
humiliating concessions that consisted of inappropriate demands. Of course,
the Germans had to foot the bill. In Austria, defense of the State depended on
playing off the various nationalities against one another. But the general line
of development still bore down on the Germans. When the Imperial
succession gave Archduke Francis Ferdinand more influence, the increase of
Czech authority really began to accelerate with his support from above. This
future ruler of the Dual Monarchy used every means possible to promote and
encourage the removal of the German element, or at least to cover it up.
Through the civil servants, purely German towns were slowly but surely
pushed into the danger-zone of mixed language. In Lower Austria, this policy
progressed even quicker and many Czechs already considered Vienna “their”
greatest city.
The family of the new Hapsburg Monarchy spoke only Czech. The
Archduke’s lower class wife, a former Czech countess, belonged to a group
who held their fear of Germans as a tradition. His primary purpose was
gradually to set up a Slavic state in Central Europe built on a strong Catholic
foundation as a defense against Orthodox Russia. The Hapsburgs commonly
made religion the servant of their political idea and this had a disastrous effect
on Germans.
78
General Political Considerations of my Vienna Period
The results were more than sad in several respects. Neither the House of
Hapsburg nor the Catholic Church received the expected reward. The
Hapsburgs lost their throne and Rome lost a great state. By putting religious
elements to work for political purposes, the Crown awakened a spirit that it
had not dreamed was possible. When they attempted to completely
exterminate German culture in the old Monarchy, the response was the Pan-
German movement in Austria. This movement wanted to unify all German
language speakers and German ethnic people into a single German state.
By the Eighteen-eighties, the Manchester Liberalism,12 which was
fundamentally Jewish, had reached the peak of influence in the Dual
Monarchy. Like everything in old Austria, the reaction against it was primarily
founded on nationalistic and not social considerations. Self-preservation
forced German elements to defend themselves with the greatest force.
Economic considerations slowly gained an important influence, but only as an
afterthought. Two parties emerged from the general political turmoil—one
had a nationalistic tendency and the other more social—and both were
extremely interesting and instructive for the future.
After the crushing conclusion of the War of 1866,13 the House of
Hapsburg considered retaliation on the battlefield. The death of Emperor
Maximilian of Mexico prevented a closer alliance with a France.14 His
unfortunate expedition was blamed on Napoleon III, and his desertion by the
French soldiers aroused universal anger. But even then the Hapsburgs were
lying in wait.
If the War of 1870-7115 had not turned out to be such a triumphant
march, the Vienna Court would probably still have ventured the bloody game
of revenge for Sadowa.16 When the first remarkable and unbelievable but true
House. He was installed with the help of the French in 1864 as a monarch of Mexico but was
overthrown and executed in 1867.
15 The Franco-Prussian war, the Prussian victory restored the German Empire.
16 The German name for Sadová, a village in the Czech Republic.
79
Mein Kampf
tales of heroism came from the battlefield, the so called “wisest” of all
Monarchs realized the timing for revenge was inappropriate and tried to make
the best of a bad situation by accepting it with grace.
The heroic struggle of those years produced an even greater miracle. The
Hapsburgs showed new attitudes but it never meant there was a change of
heart, just pressure from the current situation. The German people in the old
Eastern Territories were carried away by Germany’s joyful intoxication in
victory and were deeply touched by the resurrection of their fathers’ dream
which became a reality. Make no mistake, even in the Czech city of Koniggratz,
the German-spirited Austrian saw the tragic but inevitable need for the
resurrection of the Empire, an empire which could not be contaminated with
the stench of the old German Confederation.17 Above all, he learned by bitter
personal experience that the House of Hapsburg had at last completed its
historical mission, and that the new Empire must only choose the Kaiser as a
man whose heroic spirit made him worthy of the title “Crown of the Rhine.”
The spirit of Fate, which bestowed this honor upon the descendant of a
House that in the distant past had given the nation a shining symbol of
national praise in Frederick the Great—a symbol to last forever—that Fate
deserves great praise.
After this great war, the House of Hapsburg began to slowly and with
desperate determination exterminate the dangerous German element in the
Dual Monarchy. Without any doubt, this was the purpose of the policy which
eliminated the German element in favor of Slavs. At that moment, the
resistance of these people who were marked for total destruction flamed up
in a way new to German history.
For the first time, patriotic and nationally-minded men became rebels.
They were rebels against a way of government that would lead to the
destruction of their own nationality and not rebel against state or nation. For
the first time in recent German history, the customary patriotism for a dynasty
was distinguished from the patriotism of national love for the Fatherland and
its people by open conflict.
17Koniggratz is a reference to the Battle of Koniggratz where Prussia defeated Austria and this
became the first step in the formation of the German Empire.
80
General Political Considerations of my Vienna Period
81
Mein Kampf
82
General Political Considerations of my Vienna Period
When I came to Vienna, my support was totally on the side of the Pan-
German movement. The fact that people had the courage to stand up in
Parliament and shout “Heil Hohenzollern!”18 impressed and delighted me. I
felt a happy confidence because they continued to regard themselves as only
temporarily separated from the German Empire and not a moment passed
without announcing the fact. It seemed to me that the only remaining road to
salvation for our people was to speak out without hesitation on every question
concerning the German element and never to compromise. But I could not
understand why, after its first magnificent rise, the Pan-German movement
could collapse. I understood even less how in the same period, the Christian
Socialist Party19 had built an enormous power base. It was just then reaching
the peak of its fame.
While I was attempting to compare the two movements, Fate gave me
the best instruction I could have hoped for and helped me to understand the
reason behind this puzzle.
I began my deliberation with the men who must be considered the
leaders and founders of the two parties: Georg von Schonerer and Dr. Karl
Lueger.20
In purely human terms, they both tower above any so-called
parliamentary figures. In the swamp of general political corruption, they
remained pure and above reproach.
My personal compassion was on the side of the Pan-German, Schonerer
at first and gradually extended to the Christian Socialist leader, Dr. Karl Lueger.
Schonerer’s ability seemed to be much better and he was a more solid thinker
on problems of principle. He realized the inevitable end of the Austrian State
more clearly and more correctly than anyone else. If the German Empire had
listened to his warnings about the Hapsburg Monarchy, the catastrophe of
Germany’s First World War against all of Europe would never have happened.
Semitic, Anti-Slav, Anti-Catholic and Pro Pan-German. He formed the Pan-German Party.
83
Mein Kampf
Schonerer could grasp the inner nature of a problem but was completely
unsuccessful as a judge of men. This was Dr. Lueger’s strong point. He was a
rare judge of human nature and was careful to never view men as better than
they are. Consequently, he primarily dealt with the practical possibilities of life
of which Schonerer had little understanding. Everything the Pan-German
Schonerer thought was theoretically true, but he did not have the strength or
ability to explain this theory to the masses. He could not express it in a way
that the common people, with limited understanding of the issue, could
comprehend. Therefore, all his insight was just the wisdom of a seer and could
never become a reality.
This lack of understanding when it came to human nature eventually led
to errors in judging the strength of the movements as a whole and the old
traditions. Lastly, Schonerer recognized that these were questions worthy of
a World-Concept, but he did not realize that only the broad masses of people
can be the foundation of such, almost religious, convictions. He did not see
how the fighting spirit in the privileged-class circles was so badly limited. They
had no fighting will because of their economic position. The individual who is
afraid may lose too much will and hold himself back and avoid risk. In general,
a World-Concept can only hope for victory if the broad masses—the
foundation of the new doctrine—are prepared to fight the necessary battle.
His inability to understand the importance of the lower classes gave him
an inadequate understanding of the social problem. In this way, Dr. Lueger
was Schonerer’s opposite. Lueger’s thorough knowledge of human nature
allowed him to judge the possible forces of men, and, at the same time,
prevented him from judging the power of existing institutions. This may have
been what led him to use the masses as a means to accomplish his goals.
He very well understood that the political fighting strength of the upper
level of the privileged-class in modern times was small and not sufficient to
assure victory for a great new movement. In his political activity, he put the
most emphasis on winning over the population whose daily life was
threatened. This stimulated rather than paralyzed their fighting spirit. He was
also willing to use every instrument of power available to win the favor of
powerful existing institutions and derive the greatest possible advantage for
84
General Political Considerations of my Vienna Period
his own movement from the old sources of power. He aimed his new party
chiefly at the middle-class, which was threatened with destruction, and thus
assured himself of an almost unshakable following—a following that was
ready for great self-sacrifice and full of stubborn, dogged-fighting
determination. His relation to the Catholic Church was built up with infinite
shrewdness, and soon attracted so many of the younger clergy that the old
clerical side of the party was forced to either abandon the field of battle or, a
wiser choice, to unite with the new party.
We would be doing the man a serious injustice if this was the only
characteristic we saw in him. Besides being a shrewd tactician, he had the
qualities and the genius of a truly great reformer, but all these were limited
by the resources he believed were available and also by his own capabilities.
This truly outstanding man set himself a completely practical goal. He
wanted to capture Vienna. Vienna was the heart of the Monarchy. The last
remnants of life went out from this city into the sickly and aging body of the
rotten Empire. The healthier the heart became, the more quickly the body
could heal. The idea was right in principle but could only be put in practice for
a limited time. That was the weakness of the man. What he achieved as Mayor
of the city of Vienna is immortal in the best sense of the word, but that did not
enable him to save the Monarchy. It was too late.
His opponent, Schonerer, had seen this more clearly. Dr. Lueger was
extremely successful in putting his plans into practice, but this did not give him
the result he hoped for. Schonerer did not have the ability to accomplish what
he wanted. What he dreaded most finally happened and to a frightening
degree.21 So neither man reached his ultimate goal. Lueger was too late to
save Austria, and Schonerer was too late to preserve the German people from
destruction. It is extremely enlightening for us today to study the causes of
both parties’ failure. It is particularly useful for my friends, because today
conditions are not very different from conditions then. By looking back, we
21The Prime Minister proclaimed civil servants were to be required to speak Czech as the
official language in Bohemia which excluded German speakers from applying for government
jobs. Soon thereafter Schonerer lost support due to his strong views and active opposition.
85
Mein Kampf
can avoid the same mistakes that brought about the end of one movement
and made the other sterile.
In my opinion, there were three reasons for the collapse of the Pan-
German movement in Austria. First, there was only a vague idea of the
importance of the social problem, which is particularly bad for a new and
revolutionary party. Schonerer and his followers primarily focused on the
privileged-classes so the result was bound to be tame and weak. Although its
individual members would never suspect it, the German privileged-class,
especially the upper privileged-class, is opposed to war to the point of self-
surrender in matters of nation or state. In times when the government is
functioning well, this inclination is the reason why this class of people is
extraordinarily valuable to the state. However, in times when the government
is functioning badly, they become absolutely catastrophic. In order to fight a
serious battle, the Pan-German movement would have to devote itself to
winning over the masses. It did not do this. From the beginning, it was
deprived of the basic drive needed to support a wave of momentum and allow
it to build. Without this support, it subsided quickly. If you do not realize this
principle and carry it out from the beginning, the new party can never recover
from this omission later. When a large, moderate, privileged-class element is
captured, the movement’s beliefs will always be directed along their pre-
existing ideas, and then any chance of winning strength from the common
people is lost. After that, the movement can never progress beyond weak
arguing, pale wrangling, and criticism. We can no longer find a religious-like
faith and a willingness for self-sacrifice. They are replaced by a process that
gradually wears away the rough edges of the questions in dispute resulting in
“constructive” collaboration, which in this case means acknowledging the
existing state of affairs. Ultimately they wind up in a satisfyingly-corrupt
peace.
That was what happened to the Pan-German movement. It did not start
by recruiting its followers from the great mass of common people. It became
“privileged-class, respectable, and restrained.” This mistake gave birth to the
second cause of swift decline. By the time the Pan-German movement arose,
the German element’s situation in Austria was already desperate. From year
86
General Political Considerations of my Vienna Period
to year, the Parliament had strengthened its intent to slowly destroy the
German people. Any hope of rescue lay in the removal of this institution.
This raised a question of fundamental importance for the movement. In
order to destroy the Parliament, should it be done from the inside or the
outside? They went in and came out beaten. They had no choice but to go in
because fighting such a power from the outside means being armed with
unshakable courage and ready for infinite sacrifice. In this situation the bull
must be seized by the horns. We will take a lot of sharp blows and are often
knocked down in this kind of fight. We may even have shattered limbs, but we
must stand up again. Victory rests with the bold attacker only after an extreme
struggle. The magnitude of the sacrifice is the only way to attract new fighters
for the cause. This must continue until determination is rewarded with
success. For that purpose, the children of the great masses of the people are
needed. Only they would be determined and persistent enough to fight the
battle to the bloody end. The Pan-German movement did not control these
great crowds. There was no choice but to go into Parliament.
It would be a mistake to think that their decision was the result of a long
spiritual consideration. No, they never considered any other option. Being a
part of this nonsense was just the concrete result of vague ideas concerning
the importance and meaning of taking part in an institution which they
recognized as wrong in principle. In general, they probably hoped it would be
easier to enlighten the broad masses of the people by grabbing the
opportunity to speak in front of a “forum of the whole nation.” Also, it seemed
obvious that an attack from inside the root-of-the-evil would be more
successful than an outside. They believed the screen of parliamentary
immunity would add to the safety of the individual fighter and the force of the
attack would only be increased.
What actually happened was quite different. The forum the Pan-German
deputies spoke to had become smaller, not larger. No one can speak and reach
a larger audience by using reports and summaries. The only audience they will
reach is the circle which can either hear or already accepts them.
The greatest direct forum of listeners is not found in the chamber of a
Parliament, but in great, public mass meetings.
87
Mein Kampf
22Matthew 7:6, meaning, it is a wasted effort to reveal pearls of wisdom to people who plan
to reject us or do not appreciate the value.
88
General Political Considerations of my Vienna Period
five hundred parliamentarians and that explains why they never reached the
public. The worst part was that the Pan-German movement could only count
on success if it understood from the beginning that the problem was about a
new World-Concept and not about a new party. Nothing less could stir up the
necessary inner strength to fight this gigantic battle to the end. Only the best
and bravest minds were of any use as leaders. Unless they are heroes, ready
to sacrifice themselves and lead the fight for a new concept, there will be no
soldiers ready to follow them and die for the cause either. A man who is
fighting for his own existence has nothing left over for a common cause.
While the new movement may offer fame and honor among generations
to come, today it can offer nothing because it is nothing. The more a
movement has open posts and positions which are easy to obtain, the more
people who are zeros will step forward to fill them. Finally, these political
daylaborers overrun a successful party so much that the honest fighter of the
early days no longer recognizes the old movement, and the new arrivals
strongly object to him as an intruder. And thus ends any such movement’s
“mission.”
The moment the Pan-German movement sold its soul to Parliament, it
naturally gained “parliamentarians” instead of leaders and fighters. It sank to
the level of one of the ordinary political parties of the day and lost the strength
to courageously fight to the death. Instead of fighting, it learned to “speak”
and “negotiate.” The new parliamentarian soon preferred and believed it was
less risky to fight for the new World-Concept with the “intellectual” weapons
of parliamentary eloquence rather than to throw himself into a battle whose
result was uncertain, possibly risking his own life. With this mindset, nothing
could be gained.
Now that the party had people in Parliament, the followers outside began
to hope for and expect miracles, but that of course, never happened and never
could happen. They quickly became impatient. Even what they heard from
their own deputies didn’t satisfy the voters. This was easy to explain since the
hostile press was careful not to give the people a truthful picture of the Pan-
German deputies’ work.
89
Mein Kampf
The more the new representatives acquired a taste for the gentler style
of “revolution” in Parliament, the less they were willing to return to the more
dangerous work of enlightening the large masses of the common people. For
this reason, the mass meetings that were truly effective, directly personal, and
a way of exerting influence and possibly winning over a large number of the
people, were abandoned.
When the beer table of the meeting hall was finally exchanged for the
auditorium of Parliament, and the speeches were poured into the heads of
the so-called “chosen” and not to the people, the Pan-German movement
ceased to be a people’s movement and quickly sank into a club for academic
discussions. The bad impression given in the newspapers was no longer
corrected by personal testimonies at meetings and finally the word “Pan-
German” left a very bad taste in the mouths of the common people.
One thing all the champions with ink-stained fingers and fools of today
should take to heart is that the great upheavals in this world have never been
guided by a pen. The only job of the pen has been to explain them in theory.
Since the beginning of time, the force that started the great religious and
political landslides of history has been the magic power of the spoken word
alone.
The great masses of a people yield only to the force of speech. All great
movements are people’s movements..
A man who has no passion and whose mouth is closed has not been
chosen by Heaven as a Messenger of its Will. Let writers stick to their ink-pens
and do “theoretical” work if their intelligence and ability will let them. He has
not been born or chosen to be a Leader.
A movement that hopes to achieve great things must be alert and keep
its connection with the common people. Every question must be considered
90
General Political Considerations of my Vienna Period
from that standpoint and decided with that view. A movement must avoid
anything that might reduce or even slightly weaken its ability to influence the
masses. Without the mighty force of a great people, no great ideas, however
noble and exalted, can possibly be achieved. Harsh reality alone must
determine the path to the goal. An unwillingness to take difficult roads in this
world too often means abandoning the goal. When the Pan-German
movement emphasized its activity in Parliament and not among the people, it
lost the battle for the future and received a cheap, momentary success in its
place. It chose the easier battle which made it no longer worthy of the final
victory.
I thought through these particular questions very thoroughly in Vienna.
In my effort to understand them, I saw one of the chief causes of the
movement’s collapse, which I previously believed was destined to assume the
leadership of German elements in Austria at that time.
The first two mistakes which wrecked the Pan-German movement were
closely related. The Pan-Germans did not understand the inner, driving forces
of great upheavals and they failed to understand the importance of the great
masses of people. Their interest in defining the social problem was small, their
attempts to capture the soul of the lower levels of the nation inadequate, and
their positive attitude towards Parliament only increased their inadequacy.
If they had realized the enormous power inherent in the masses as their
greatest supporter, they would have approached propaganda issues
differently. Their emphasis for the movement would have been put on the
factory floor and the street and not in Parliament.
Even their third mistake had its origin in the fact that they did not
recognize the value of the masses. The masses are set in motion like a toy car
that is pointed along a path by superior intellects, and, as it travels, it then
maintains its momentum after it is in motion. From that point on, the founders
provide encouragement and determination right up to the attack. The hard
struggle the Pan-German movement fought against the Catholic Church can
be explained by its insufficient understanding of the people’s spiritual nature.
The new party’s violent attack upon the center of Catholicism, Rome, also
had a number of causes. When the House of Hapsburg finally decided to
91
Mein Kampf
92
General Political Considerations of my Vienna Period
93
Mein Kampf
24This is a reference to the Treaty of Versailles’ reparations and the Ruhr-Area occupation by
France.
94
General Political Considerations of my Vienna Period
95
Mein Kampf
While I was in Vienna, I had the opportunity to look into this question
without having a previously formed opinion on the matter. My daily contacts
with people confirmed my view a thousand times over. In this mixture of
nationalities, it was quickly proven that only a German pacifist will always try
to look objectively at the interests of his own nation, while the Jew never does
this with the interests of the Jewish people. Only the German Socialist is
“international” in a sense where he considers outside interests to be equal
with his own nation’s interests, and this prevents him from winning justice for
his own people except by whimpering and bawling to his international
comrades. It is never true of the Czech or the Pole. I saw even then that the
spreading harm was only partly in the doctrines themselves, and our weak
devotion to the nation was the result of our inadequate training in our own
nationality.
This disproves the first purely theoretical argument for the Pan-German
movement’s struggle against Catholicism. We should train the German people
from childhood to exclusively recognize the rights of their own nationality and
not infect the children’s hearts with our curse of “objectivity,” especially in
matters of self-preservation. The result of this would be that the Catholic
element in Germany, just as in Ireland, Poland, or France, will be a German
first and foremost. Of course, all this assumes a radical change in the national
government. Our strongest proof of this argument is in the period when our
people last appeared before the judgment-seat of history for a battle of life
and death. As long as leadership representing the Heavens was present, the
people did their duty overwhelmingly. Protestant pastor and Catholic priest
both contributed enormously to continuing our resistance, not only at the
front, but at home. During those first years there was really only one Holy
German Empire for both camps and everyone turned to his own Heaven to
sustain that future.
There was one question that the Pan-German movement in Austria
should have asked itself: Is the preservation of German-Austrian culture
possible with a Catholic faith or not? If so, the political party had no business
bothering with religious and confessional matters. If not, then a religious
reformation was necessary and not a political party. Anyone who thinks he
96
General Political Considerations of my Vienna Period
97
Mein Kampf
ambitions. Amid the political battle, they forget that they are the guardians
and not defenders of a higher truth. But for every unworthy figure, there are
a thousand honorable shepherds of souls faithfully devoted to their mission
who stand out like little islands from the swamp of the present corrupt and
deceitful age.
I do not and must not condemn the Church if some corrupt creature
wearing a priest’s collar happens to commit a moral offense. I also must not
condemn the whole group if one among the many soils and betrays his
nationality, especially in an age when this is a daily occurrence. We should not
forget that for every public traitor like the famous Greek betrayer Ephialtes,
there are thousands who feel the misfortunes and have deep sympathy for
their people. These great men long for the moment when Heaven will once
more smile on us.25
If anyone feels these are not petty, everyday problems but questions of
fundamental truth and beliefs in general, we can only answer him with
another question. Do you think you are chosen by Fate to proclaim this truth?
Then do it. But have the courage not to do it through a political party. This is
a deception and a betrayal of your vocation. Instead, replace the bad parts
with something better, something that will last and improve the conditions for
future generations.
If you do not have the courage or if you are not sure about the alternative
you are supporting, then let things alone. In any case, do not try to sneak into
a political movement that you would not dare to reach for openly. As long as
religious problems do not undermine the morals and ethics of one’s own race
like an enemy of the people does, political parties have no business meddling
with them. Just as religion should not identify itself with political party
mischief, political parties should not meddle in religion.
If dignitaries of the church use religious institutions or even doctrines to
injure their own nationality, we must never follow them or try to fight them
with their own weapons. To the political leader, the religious beliefs and
25Ephialtes was a soldier who betrayed the Spartan army. He is said to have told the Persians
about the pass of Thermopylae around the mountains which they used to attack in the Battle
of Thermopylae in 480 B.C., so this reference means a traitor.
98
General Political Considerations of my Vienna Period
26 Kulturkampf.
99
Mein Kampf
adversary. Nothing is more dangerous for a political party than to let itself be
led back and forth hither and yon between decisions because this means it can
never accomplish anything visible.
No matter how many things may actually be wrong with a particular
religious persuasion, a political party must never, not even for an instant, lose
sight of the fact that no purely political party in a similar situation has ever
succeeded in a religious reformation. This is well established in history. We do
not study history to forget its teachings; we study it to put those teachings to
practical use. We should not think that things are different now and that its
eternal truths no longer apply. On the contrary, from history, we learn what
we should do today. No one who cannot learn from history should imagine
himself as a political leader. He is actually a shallow and usually very conceited
simpleton, and all the goodwill in the world does not excuse his deficiencies.
In any age of history, the qualities of a truly great and popular leader
consisted of focusing on a single adversary and not distracting the people’s
attention. The more unified the people’s will to fight a single object, the
greater the magnetic attraction a political movement will have and the more
tremendous its impact. It is part of the genius of a great leader to make even
widely separated adversaries appear as if they belonged to just one category.
Weak characters who have difficulty making decisions will begin to doubt
whether their own side is right when they see a variety of enemies.
When the wavering masses see themselves fighting against too many
enemies, objectivity immediately appears with the question of whether all the
others are really wrong and just one side is right. That is the first sign of one’s
own strength weakening. Therefore, a number of opponents must always be
lumped together so that in the eyes of one’s own followers, the battle is
fought against one single enemy.
This strengthens their faith in their own cause, and increases their
bitterness against anyone who attacks it. This cost the Pan-German movement
their success when they failed to realize the importance of a single front. The
Pan-German goal was correct and its will was pure, but the road it took was
wrong. It was like a mountain climber who keeps his eye fixed on the peak to
be scaled and takes the obvious trail while he is filled with great determination
100
General Political Considerations of my Vienna Period
and energy. As he walks, he pays no attention to the path and he doesn’t see
where it truly leads because his eye is always on the goal. He finally wanders
astray.
The position of its great competitor, the Christian Socialist Party, seemed
to be reversed. The road it took was clever and correctly chosen, but a clear
understanding of the goal was missing. In almost every matter where the Pan-
German movement was lacking, the attitude of the Christian Socialist Party
was right and was deliberately planned to achieve results.
It realized the importance of the masses and secured at least part of them
by clearly emphasizing its social aspect from the very start. By adjusting itself
to win the middle and lower-middle classes, it obtained a following as faithful
as it was stubborn and self-sacrificing. It avoided fighting any religious
institution and secured the support of a mighty organization in the Church.
Consequently, it only had one truly great adversary. It recognized the value of
large-scale propaganda and was skilled in working on the human instincts of
the broad mass of its followers. However, it also failed to reach its dream of
saving Austria.
There were two shortcomings in its method: the means they employed,
and the lack of a clear goal. The anti-Semitism of the new movement was
founded on a religious concept instead of a racial insight. The reason this
mistake occurred was the same reason that caused the second error. If the
Christian Socialist Party was to save Austria, the founders felt it must not take
its stand on the race principle because they feared the State would collapse
from the pressure. In the party leaders’ view, the multi-ethnic situation in
Vienna made it necessary to put aside anything that divided people, and in
their place, emphasize anything that united the public.
By that time, Vienna was already so thoroughly impregnated with
foreigners, especially Czech elements, that they had to be extremely tolerant
when it came to race questions otherwise they could not keep these elements
in a party that was not anti-German from the beginning. If Austria was to be
saved, the people in Austria could not be tossed aside. An attempt was made
to win the great number of Czech lower classes in Vienna by a drive against
Manchester Liberalism. It was presumed that this attack would be seen as
101
Mein Kampf
struggle against Jewry on a religious basis, which would bridge all the national
differences of old Austria. Such an attack would only create a small amount of
worry among to the Jews. At worst, a dash of baptismal water would always
save his business and Judaism both.
With a superficial argument like this, they never achieved serious
scientific treatment of the whole problem and so they repelled anyone who
did not understand this sort of anti-Semitism already. The attractive power of
the idea was limited almost exclusively to intellectual circles. The leaders
failed to go from that point to developing a real insight by using a pure
emotional experience. The political elite remained hostile. The whole affair
looked more and more like a mere attempt at a new conversion of the Jews
or even envy of competitors. The struggle lost the appearance of a movement
born from devout conviction and seemed to many average people immoral
and reprehensible. There was no reason to believe that this was a vital
question for all of humanity or that the Fate of all non-Jewish people
depended on it.
This half-hearted attempt destroyed the value of the Christian Socialist
Party’s anti-Semitic attitude. It was a movement that made no pretenses to
anti-Semitism, and that was worse than having no leaning towards anti-
Semitism at all. The people were being lulled into a sense of security and
thought they had the enemy by the ears, while in reality, they were being led
around by the nose.
The Jew, however, soon became so accustomed to this sort of anti-
Semitism that he probably would have missed it more if it wasn’t there than
he was bothered by its presence. Submitting to a State of mixed nationalities
demanded one great sacrifice, and the upholding of German culture
demanded a greater sacrifice. The party could not be “nationalistic,” and if
they were, they would lose the ground under their feet in Vienna. By gently
evading any question of nationalism, they hoped to save the Hapsburg State
and that is what ruined the movement. At the same time, the movement lost
a great source of inner strength—a strength that can fill a political party with
an inner driving force for the long run. The Christian Socialist movement
became a party no different from any other.
102
General Political Considerations of my Vienna Period
I followed both movements closely. One was from the urging of my own
heart and the other was because I had so much admiration for the rare man
who even then seemed to be a bitter symbol of all Austrian-German culture.
When the tremendous funeral procession carried the dead mayor27 from
the City Hall out toward the Ring Street of Austria,28 I was among the many
hundreds of thousands who watched the tragic scene. Feelings were stirred,
and I knew this man’s work was in vain because Fate was inevitably leading
the State towards its doom. If Dr. Karl Lueger had lived in Germany, he would
have been ranked among the great minds of our people.
Having lived in this impossible State was unfortunate for him and for his
work.
When he died, the flames in the Balkans were already greedily flickering
higher every month, and Fate had mercifully spared him from seeing what he
still believed he could prevent. I tried to understand the reasons for the failure
of one movement and the misdirection of the other. Aside from the
impossibility of fortifying the State in old Austria, I came to the definite
conclusion that the mistakes of the two parties were the following: The Pan-
German movement was on the right track in principle as it desired the goal of
a German revival, but its choice of weapons was unfortunate. It was
nationalistic but did not have the social appeal needed to conquer the masses.
Its anti-Semitism; however, rested on a correct realization of the importance
of the race problem and not on religious concepts. On the other hand, the
attack on a particular religious persuasion was wrong.
The Christian Socialist movement had vague ideas about the goal of a
German renaissance, but it made an intelligent choice in its weapons to carry
out the party policy. It realized the importance of the social aspect but was
mistaken in the principles it used to fight Jewry, and did not understand the
strength of the nationalistic idea.
If the Christian Socialist Party had taken their shrewd knowledge of the
broad masses and adequately understood the importance of the race problem
as the Pan-German movement did and been nationalistic, or if the Pan-
27 Lueger.
28 Ringstrasse.
103
Mein Kampf
German movement had adopted the practical insight and attitude toward
Socialism of the Christian Socialist Party along with its true insight into the goal
of the Jewish question and the meaning of the nationalist idea, the result
would have been that one of these movements might have successfully
changed the fate of Germans. The nature of the Austrian State was the reason
this did not happen.
Since my convictions were not represented clearly in any political party
around me, I could not make up my mind to join or fight for one of the existing
organizations. Even then, I thought all the political movements were failures
and incapable of carrying out a national renaissance for the German people
on any large scale.
My distaste for the Hapsburg State continued to grow. The more
attention I began to pay to questions of foreign politics, the more my
conviction strengthened that this State structure could only lead to serious
misfortune for German culture. More and more clearly, I saw that the fate of
the German nation was being decided here in Austria as well as within the
German Empire itself. This was true in cultural life and in questions of politics.
Even in the field of purely cultural or artistic affairs, the Austrian State
showed every sign of weakening and it was losing its importance to the
German nation as a cultural resource. This was especially true in the field of
architecture. Modern architecture in Austria could not be successful because
after the Ring Street was built in Vienna, the rest of the jobs were insignificant
when compared to the plans being developed in Germany. I began to lead a
double life more and more. Reason and reality made me go through a bitter
though useful apprenticeship in Austria, but my heart was elsewhere.
An uneasiness came over me as I realized the emptiness of this State and
that it was impossible to save it. At the same time I felt perfectly certain that
it would bring misfortune to the German people if Austria collapsed. I was
convinced that the Hapsburg State would balk and hinder every German who
might show signs of real greatness, while at the same time it would aid and
assist every non-German activity.
104
General Political Considerations of my Vienna Period
This conspicuous mix of races in the capital of the Dual Monarchy, this
motley collection of Czechs, Poles, Hungarians, Ruthenians,29 Serbs and
Croats, and always that infection which dissolves human society, the Jew,
were all here and there and everywhere. The whole scene was repugnant to
me. The gigantic city seemed to be the embodiment of mongrel depravity.
The German I learned to speak in my youth was a dialect which is also
spoken in Lower Bavaria. I never forgot that particular style of speech, and I
could never learn the Viennese dialect. The longer I stayed in the city, the
hotter my hatred burned for the promiscuous alien people who began to gnaw
away at this ancient seat of German culture. The idea that this State could be
preserved much longer seemed absolutely ridiculous.
Austria was like an old mosaic where the cement holding the separate
bits of stone together had become old and started to crumble. As long as it is
not touched, the work of art still appears solid, but the moment it is shaken,
it falls into a thousand fragments. The only question was when the jolt would
come.
Since I had never loved an Austrian Monarchy, only a German Reich, the
moment of the State’s collapse seemed to be the beginning of the salvation of
the German nation. For all these reasons, my desire grew stronger to go where
my secret wishes and secret love had been pulling me since early youth. I
hoped someday to make a name as an architect and to work hard for the
German nation on either the large or small scale as chosen by Fate.
Lastly, I wanted to enjoy the happiness of living and working in the place
where the greatest desire of my heart must someday be fulfilled: the union of
my beloved homeland with its common Fatherland, the German Empire.
Even today, many people will not be able to understand my deep desire,
but I appeal especially to two groups of people. The first are all those who
have been denied the happiness I have spoken of, and the second are those
who once enjoyed that happiness but had it torn from them by a harsh Fate. I
speak to all those who are separated from the mother country and must fight
for even the sacred possession of their native language, those who are
29 Ukranians.
105
Mein Kampf
pursued and tormented for their faithfulness to the Fatherland and who long
in anguish for the moment that will bring them back to the heart of the
beloved mother. I speak to all of these and I know they will understand me!
Only those who know by bitter experience what it means to be a German
without the privilege of belonging to the dear Fatherland can measure the
deep longing, which always burns in the heart of the children who are away
from the mother country. It torments its victims and denies them happiness
and contentment until the doors of the paternal house open and common
blood will find rest and peace in a common realm.
Vienna was and has remained the hardest and most thorough school of
my life. I had entered the city as a young boy and I left it as a quiet and serious
man. There I laid the foundation for a general World-Concept and a particular
way of political thinking which I later completed in detail. Only now can I fully
appreciate the real value of those years of apprenticeship.
I have addressed this period of my life at some length because it gave me
my first object lessons in issues that form the basis of the Party, which had tiny
beginnings and in just five years has started to develop into a great mass-
movement. I do not know what my attitude would be today toward Jewry,
toward Social Democracy, or toward Marxism as a whole, and toward the
social question if a cornerstone of personal views had not been laid early by
the pressure of Fate and by my own self-education.
Even though the misfortunes of the Fatherland may stimulate thousands
upon thousands to think about the inner causes of the collapse, such could
not lead to a thorough knowledge and deep insight that a man develops on
his own, who has fought a difficult battle for many years so that he might be
master of his own Fate.
106
CHAPTER FOUR
Munich
In the spring of 1912, I moved to Munich for good.1 The city was as familiar to
me as if I had lived within its walls for years. My studies were the reason for
this because they repeatedly turned my attention towards German art. If you
haven’t seen Munich, you haven’t seen Germany or German art. This time
before the war was the happiest and by far the most contented of my life. My
living was still meager because I only painted enough to meet my living
expenses and so I could continue my studies. I believed that someday I would
still reach the goal I had set for myself. This in itself made it easy for me to
tolerate the small worries of daily life. I had a deep love that possessed me for
this city ever since I first arrived, more than any other town I knew. It was a
true German city! What a difference after Vienna! Thinking back to that
corrupt Babylon-like city of races turned my stomach. The dialect in Munich
was also much more natural to me. When I talked to the Lower Bavarians, it
reminded me of the days from my youth. There must have been a thousand
things which were or became dear and precious to me in this city. I was most
attracted by the wonderful mix of natural vigor and a fine artistic temper, the
unique line from the architecture of the Hofbräuhaus,2 to the music house,3
and the September-October Festival4 to the beautiful Art Museum.5 Today, I
am more attached to that city than to any other spot in the world, no doubt
partly because it is so firmly intertwined with the development of my own life.
The happiness of true inner contentment that I enjoyed then could only be
107
Mein Kampf
attributed to the magic spell that the wonderful capitol of the Wittelsbachs
casts on every person.6 Visitors who are drawn here are clearly blessed with a
sharp intelligence and with a sensitive spirit.
Aside from my professional work, what attracted me the most was the
study of the day’s political events, especially matters of foreign policy. I was
attracted to matters of foreign policy through the German Alliance Policy,
which even in my Austrian days I had considered absolutely wrong. But in
Vienna, I had not fully realized the extent of the German Empire’s self-
deception. I had been inclined to assume that people in Berlin knew how weak
and unreliable their ally would actually be, but were withholding this
knowledge for more or less mysterious reasons. At least, this is what I told
myself. They might be trying to support an alliance policy, which Bismarck
himself had originally introduced and thought it was not a good idea to break
it off suddenly.
They may want to avoid arousing other foreign countries, which were
lying in wait for their chance to strike or perhaps it might alarm the citizenry
at home.
I was soon horrified to discover from my contacts that my belief was
wrong. To my surprise, everywhere I looked, even the most well-informed
circles were clueless about the nature of the Hapsburg Monarchy. The
common people were especially victims of the idea that their ally could be
considered a serious power that would support them in their hour of need.
The masses still considered the Monarchy a “German” state and thought they
could depend on it. They believed that strength could be measured by the
millions of people in Germany itself. They completely forgot that Austria had
long since ceased to be a German state and the inner structure of this Empire
was moving closer to dissolving by the hour.
I understood this state structure better than the so-called “official
diplomacy” did. As usual, they were spinning blindly toward disaster. The
opinions of the people resulted from what had been poured into their heads
by the leaders. But the leadership was nurturing a cult like following of our
108
Munich
“ally” similar to the historical golden calf. They probably hoped to make up for
the lack of honesty on the other side by being exceptionally friendly, so
everything the other side told them was always taken at face value.
In Vienna, I was furious when I saw the occasional difference between
the speeches of the official statesmen and what was printed in the Vienna
newspapers. Even then Vienna at least appeared to still be a German city.
The situation was totally different if one traveled from Vienna, or
German-Austria, into the Empire’s Slavic provinces! A person only needed to
look at the newspapers to see how the deception of the Triple Alliance was
judged there. They had nothing but bloody sarcasm and contempt for this
“masterpiece of statesmanship.” During this period of peace, while the two
Emperors kissed each other on the brow as a token of friendship, the people
made no bones about the fact that they knew the Alliance would collapse as
soon as this glimmering glory of a Nibelungen ideal was tested in reality.7
The people were very unhappy a few years later when the moment came
for the Alliance to prove itself, and Italy broke away from the Triple Alliance
leaving her two allies on their own. Italy then became an enemy herself! How
the people ever believed for a moment such a miracle was possible—that Italy
would fight on the same side with Austria—was absolutely incomprehensible
to anyone not blinded by diplomacy. But the situation in Austria was identical.
The sole support for the alliance in Austria came from the Hapsburgs and
the German-Austrians. The Hapsburgs supported it because it was in their own
interests and they had no choice. The Germans supported in good faith and
out of political stupidity. The good faith of the Triple Alliance came from the
fact that they thought they were doing the German Empire a great service by
helping to strengthen and defend it. The political stupidity was because their
belief was mistaken and they were actually helping to chain the Reich to a
dead state. This was bound to drag both into a bottomless pit and most of all,
this very Alliance sacrificed them to the very efforts aimed at destroying
German culture. The alliance gave the Hapsburgs reason to believe that the
7The reference to Nibelungen is from Wagner’s opera and Germanic mythology. Here it is a
reference to a mythical royal family which was the supposed origin of the some royal
bloodlines or to the royals of that area.
109
Mein Kampf
German Empire would not interfere in their domestic affairs, which left them
free to carry out their domestic policy of gradually eliminating the German
element without risk.
Not only were they shielded from any protest of the German government
by the well-known “objectivity,” but by referring to the Alliance, they could
always silence the dirty mouth of Germans in Austria if it became too
objectionable in its threats to stop some method being used to convert the
area to a Slav region. After all, what could a German in Austria do when the
German Reich itself expressed admiration and confidence for the Hapsburg
regime? Was he to resist and be branded as a traitor to his own nationality
throughout the German-speaking world? He, who for decades had made the
greatest sacrifices for his nationality? What value did the Alliance have once
the German elements in the Hapsburg Monarchy were exterminated? Was the
value of the Triple Alliance for Germany not absolutely dependent upon the
preservation of German elements in Austria? Or did they really think they
could live in alliance with a Hapsburg Empire of Slavs? The official attitude of
German diplomacy, as well as that of the general public towards internal
problems affecting the Austrian nationalities, was not merely stupid, it was
insane. The Alliance destroyed any level of security and erased the possibility
that a nation of seventy million could continue to exist, while at the same time,
they allowed their partner to continue his policy of undermining the sole
foundation of that Alliance.
Eventually, all that will remain is a formal contract with Vienna diplomats.
The Alliance itself would be useless and Germany could never depend on the
Allies for any form of support.
Italy knew this from the beginning. If the people in Germany understood
history and national psychology a bit more clearly, they never would have
believed that the Princes of Rome and the Vienna Hofburgs8 would ever fight
together. Italy herself would explode before the government would have
dared send a single Italian to the battlefield for the hated Hapsburg State, not
unless the soldier was sent to fight against the Hapsburgs. More than once in
8 The Hofburg is the Imperial Palace of the Austrian Hapsburg Royal Family.
110
Munich
Vienna, I saw absolute contempt and unending hatred flare up between the
Italians and the Austrian State. The sins of the House of Hapsburg against
Italian freedom and independence stretching over centuries was too great to
be forgotten. This kind of hatred ran too deep, neither the people nor the
Italian government wanted to forget.
For Austria, there were only two options available when it came to facing
Italy, either alliance or war. By choosing alliance, she was able to take her time
in preparing for the second. The German alliance was both senseless and
dangerous, especially since Austria’s relations with Russia came closer and
closer to armed conflict. Here was a classic example of the total lack of deep
or profound thinking in foreign policy. Why did they decide on an alliance at
all? Was it only to assure a better future for Germany than she could manage
with her own resources? But the future of Germany depended on the
preservation of the German people’s existence. So, the question becomes,
what position should the German nation take in the face of this predictable
future, and how can we guarantee security for this development while living
in the European balance of power? After carefully looking at the requirements
for German statesmanship to be successful in foreign politics, we must come
to the following conclusion: The yearly increase in Germany’s population is
almost 100,000 people. The difficulty of feeding this army of new citizens is
bound to grow from year to year and will eventually end in catastrophe unless
we find a means in time to avoid starvation.
There were four ways to avoid this frightening development.
Using the French model—pregnancies could be aborted and therefore
overpopulation avoided.
It is totally true that in times of great trouble, bad climate conditions, or
a poor crop yield, Nature herself takes steps to limit a population’s increase in
certain countries or races. She does it both wisely and with no mercy. She does
nothing to destroy actual reproduction, but prevents the survival of what is
reproduced by exposing the new generation to such difficulties and
deprivations that all the weaker and those that are less healthy are forced to
die.
111
Mein Kampf
112
Munich
113
Mein Kampf
balancing the crop production with the population growth will be impossible
and will force all mankind to stop expanding the human race.
Either they will have to leave the decision to Nature or strike the
necessary balance by solving the problem themselves, but by a method better
than those available today. This will be true for all people, while now, only
those races that no longer have the strength and energy to assure themselves
of the land they need in this world are in trouble. At present, large areas of
land still exist in the world that are being unused and just waiting to be broken
by the cultivator. It is also true, however, that Nature is not holding this land
in reserve for the future of a particular nation or race. The land is for the
people who have the strength to take it and the diligence to till it.
Nature knows no political boundaries. She simply deposits life on this
globe and watches what happens. The boldest and most industrious of her
children becomes her favorite and is made the Lord over Creation.
If a group of people confines itself to internal colonization while other
races are grabbing greater areas, their options will be limited when the other
races can constantly increase in number. Someday this will happen and the
smaller the people’s living space, the sooner it will be. The best nations, which
are the only truly civilized races, decide in their pacifist blindness to make no
effort to expand their land and are content with internal colonization while
inferior nations succeed in taking large livable areas of the world. A smaller
and densely populated territory may be better from the cultural standpoint of
these less ruthless races, which are limited by land and restricted in their
population’s growth, but people of lower civilizations, which are simple-
minded and cruel, would still be able to increase without limit because of all
their territory. In other words, the world will someday be dominated by the
culturally inferior but more energetic part of humanity.
Some day in the future, there will be two possible outcomes. Either the
world will be governed according to the ideas of our modern democracy and
the equality of every decision will lie with the more numerous races, or the
world will be ruled by the natural laws of relative strength, and the people
possessing brutal will power will triumph over the nations that have denied
themselves what they need to survive.
114
Munich
There is no doubt that the world will someday be the scene of huge
battles for the existence of mankind. In the end, the craving for self-
preservation alone will triumph. That stupid and cowardly group of humanity
that thinks they know more than everyone else will find their humanitarianism
melts like snow in the March sun when they face destruction. In eternal battle,
mankind can find greatness; in eternal peace, it will find destruction.
For Germans, the slogan of “internal colonization” is damnation, if for no
other reason, it immediately confirms the belief that we have found a peaceful
existence that allows us to lead a gentle dreamlike life, by working for our
living. If we ever took this idea seriously, it would mean the end of any effort
to maintain our rightful place in the world. Let the average German become
convinced that his life and future can be guaranteed and it will extinguish any
effort to protect German vital necessities. If the whole nation took this
attitude, we could regard any useful foreign policy as dead and buried along
with the German people.
It is not an accident that the Jew is the one who first plants such deadly
ideas among our people. He knows his wimps too well not to realize that they
will be willing victims of any swindler who tells them he can snap his fingers
causing Nature to jump to attention, and that he can alleviate the hard
struggle for existence while still allowing them to ascend to lordship over the
planet by working only when a pleasing chance presents itself, but mostly by
it just happening.
I cannot emphasize enough that all German internal colonization must
serve primarily to correct social abuses by those who do not make good use
of land, especially by withdrawing the land from public control which prevents
its use, or to release it from the grasp of speculators who only buy it without
using it; but, internal colonization can never adequately assure the future of
the nation without acquiring new land. If we follow any other path, we will
soon be at the end of our territory, as well as at the end of our strength.
If we pursue internal colonization alone, we will soon reach a point
beyond which the resources of our soil can no longer sustain us, and at the
same time, we will reach a point beyond which our manpower cannot expand.
115
Mein Kampf
116
Munich
117
Mein Kampf
strength has gained us a large state and territory for our race, which alone has
allowed us to survive to the present day.
There is another reason this is the correct solution. Many European states
today are like inverted pyramids. The territory of some European countries is
ridiculously small compared to their load of colonies and their level of foreign
trade, etc. We can correctly say that the apex is in Europe and the base is all
over the world. In contrast, the American Union’s base is still on its own
continent and only the apex touches the rest of the earth. The enormous
strength of the American State comes from their size and the reverse is true
for most European colonial powers which contributes to their weakness.
England does not disprove this because in front of the British Empire, we
have a vast community linked by a common language and culture throughout
the world. Because of its linguistic and cultural ties with the American Union,
England’s position cannot be compared with that of any other state in Europe.
For Germany, the only territorial policy was acquiring new land in Europe
itself. Colonies are useless for this purpose unless they are suitable for large-
scale settlement by Europeans. In the nineteenth century, that sort of colonial
territory could no longer be obtained by peaceful means. Any attempt at a
colonial expansion outside of Europe would have required a large military
effort. It would have been more practical to undertake that military struggle
in Europe and gather land there instead of spreading abroad.
A decision of this magnitude requires absolute, single-minded devotion
once it is made. There must be no half-hearted efforts or hesitation in
attacking a task which can only be achieved by using every last ounce of
strength. The political leadership of the Empire must be devoted exclusively
to this purpose. Everything done must be done to accomplish this task without
distractions. The goal could only be achieved by force, and that knowledge
should be taken to the battle with determination, peace, and calm.
Any alliance with another country should have been considered and
assessed based on its usefulness from this standpoint alone. If European soil
was the objective, it could be acquired primarily at the expense of Russia. The
new Empire must once again march the road of the ancient Knights of the
118
Munich
German Order and use the sword to provide land for the German plow which
can then provide our daily bread.
For this kind of policy, there was only one ally in Europe—England. Only
with England covering our rear could we have begun a new Germanic
migration. Our justification would have been as strong as our forefathers.
None of our pacifists refuse to eat food from the East, and they ignore the fact
that the first plowshare there was actually a sword! No sacrifice should have
been too great to win England’s friendship. We should have given up all
thought of colonies and sea power and avoided competition with British
industry if that is what was needed. Only absolute clear-sightedness could
bring success along with abandoning world trade, colonies, and a German
navy.
The State’s power must be totally concentrated on the army. The result
would have been a temporary setback, but a great and mighty future.
There was a time when we could have discussed this plan with England.
England understood very well that Germany had a growing population with
growing needs. Those needs would be filled either with England as an ally in
Europe or by another ally in the world. At the turn of the century, London itself
tried to establish a relationship with Germany. For the first time, people were
upset thinking we might have to pull England’s chestnuts out of the fire. This
attitude was unfortunate and caused them to act as if an alliance did not
require mutual give-and-take! Such a deal could easily have been made with
England. British diplomacy was at least smart enough to know that nothing
can be expected without something in return.
If a wise German foreign policy had taken over Japan’s role in 1904,10 we
can hardly grasp the impact it would have had for Germany.
Things would never have reached the point of “The First World War.” The
bloodshed in 1904 would have saved bloodshed in 1914 to 1918 by ten times.
And what a position Germany would hold in the world today! The alliance with
Austria would then have been nonsense. This dead state was only allied with
10In the Russo-Japan War, also called the Manchurian Campaign, where Japan was victorious
over Russia and gained large territories.
119
Mein Kampf
Germany to preserve a continued peace, which could be cleverly used for the
slow but sure extermination of German culture in the Monarchy.
The alliance could never have been used to fight a war. If for no other
reason, this alliance was impossible because there were no German national
interests to be upheld. How could we expect a state that did not have the
strength and determination to put an end to the destruction of German
culture on its own frontier to be a true ally in time of war? If Germany didn’t
have enough national common sense or ruthlessness to maintain control over
the fate of ten million of its own race and protect them from the Hapsburg
State, it could not be expected to take on such a daring and future-focused
plan. The attitude of the old German Empire toward the Austrian problem
might have been seen as a test of its stamina where the destinies of the whole
nation were at stake.
In any case, they had no business watching idly while German culture was
whittled away year after year. The value of Austria’s alliance depended totally
on the preservation of the German element in Austria, but they made no effort
to preserve or protect our people. They feared falling into a struggle more
than anything and were finally forced into the battle at the worst time. They
hoped to flee Fate and were overtaken by it. They dreamed of preserving
world peace and ended up in a World War.
Here is the main reason the expansion necessary for a German future was
not even considered. They knew that the acquisition of new territory could
only be accomplished by going East through Russia. They understood the
battle that would be necessary and they wanted peace at any price. The song
of German foreign policy had long since changed from “Preservation of the
German nation by every means” to “Preservation of world peace by any
means.” How “well” they succeeded, everyone knows. I will have more to say
on that subject later.
Then there was the fourth possibility: industry and world trade, sea
power and colonies. At the beginning, this development was easier and
quicker to achieve. True colonization of territory, however, is a slow process
and often takes centuries. Indeed the strength of colonies results from the fact
that they take a long time to build and are not the result of a sudden burst of
120
Munich
energy like industrial growth. Industrial growth bursts can be built within a
few years.
Unfortunately, the industrial result is not of great quality but is frail, more
like a soap-bubble. It is much easier to build quickly than to follow through
with the difficult task of settling a territory with farmers and establishing
farms. It is also true that the easy path is more quickly destroyed than the slow
one.
When Germany chose to maintain peace at any cost, she had to realize
that this choice would lead to battle someday. Only children could expect
pleasant and mannerly behavior, and a constant emphasis on peaceful
intentions would give them their “bananas” in the “peaceful competition of
nations.”
These people talked as if they were groveling diplomats hoping war
would never come.
No. If we took this road, someday England was bound to be our enemy.
Our innocent assumptions fit nicely with pacifism, but it was silly to resent the
day England would violently oppose what they saw as an attempted
expansion. Obviously they would enforce their self-interests. Of course, we
would never have done such a thing; how could we protect our self-interests
with pacifists at the helm? A European territorial expansion policy could be
carried on strictly against Russia and in-league with England as our ally. On the
other hand, if we allied with Russia against England, then a colonial and world-
trade policy would be possible against England and her colonies only with the
support of Russia. In that case, the most important conclusion must be drawn
here: that Austria must be sent packing at once.
Considered from any angle, the alliance with Austria was sheer madness,
even by the turn of the century.
Germany never dreamed of allying with Russia against England any more
than siding with England against Russia, because in either case, the result
would have been war. It was only to avoid war that the commercial and
industrial policy was chosen in the first place. By using the “peaceful economic
conquest of the world” policy, they thought they would break the neck of the
old policy of force once and for all. There may have been some doubts about
121
Mein Kampf
122
Munich
Everyone was gradually affected by this nonsense and the result was to
underestimate our enemy; for that we paid dearly. The misrepresentation was
so overwhelming that people firmly believed the Englishman was a business
man whose sharp negotiation skill was equaled only by his incredible personal
weakness. Unfortunately, it did not occur to our dignified teachers and
dispensers of wisdom that a world empire the size of England’s could not be
built by stealing and swindling. The few men who sounded a warning were
ignored or met with a conspiracy of silence. I can still remember the
astonishment on my comrades’ faces when we clashed in person with the
Tommies11 in Flanders. After the first few days of battle, it began to dawn on
everyone that these Scotsmen were not the men they had been led to believe
and were not like the ones depicted in comic books and newspaper articles.
That was when I first began to understand some of the most useful forms of
propaganda.
These false representations had one advantage for its perpetrators. The
example could be used to show that the economic conquest of the world was
a sound idea. If the Englishman could do it, so could we. Our greater honesty
and the lack treachery, which was so English in itself, was considered a great
advantage for us. People hoped to win sympathy from the smaller nations as
well as the confidence of the great ones.
Because we took it all seriously, we never dreamed that our honesty was
an outrage to the rest of the world. They considered our behavior an
extremely cunning form of dishonesty. It was not until our Revolution that
they realized our “honest” intentions were sincere to a point beyond stupidity
which they no doubt found astonishing.
Only this rubbish of “peaceful economic conquest” of the world could
make the foolishness of the Triple Alliance clear and understandable. What
other state could Germany possibly become allies with? They could not obtain
territory from any state in Europe when allied with Austria. This was the inside
weakness of the Alliance from the beginning. Bismarck could allow this as a
temporary solution, but that did not mean every inexperienced successor
11 English soldiers.
123
Mein Kampf
should do the same, especially in an age when the basis of Bismarck’s alliance
had long ago ceased to exist. Bismarck still believed in his time that Austria
was a German state. But, with the gradual introduction of the general right to
vote, the country had sunk to a parliament controlled, un-German state of
confusion.
As a matter of race policy, the alliance with Austria was also disastrous.
The growth of a new strong Slavic power was tolerated right on the borders
of the Empire. They should have seen that the attitude of this power toward
Germany would sooner or later be very different from that of Russia. At the
same time, the Alliance itself was bound to grow empty and weak from year
to year because the sole supporters of the idea lost influence in the Monarchy
and were crowded out of the most influential positions.
By the turn of the century, 1900, Germany’s alliance with Austria had
reached the same stage as Austria’s alliance with Italy. We had to make a
choice: Either side with the Austrian Hapsburg Monarchy or openly protest
the oppression of German culture in Austria. Once a decision of this sort is
made, it usually ends in open battle.
Even psychologically, the Triple Alliance had only a modest value since
the strength of an alliance declines as soon as it begins to limit itself to
preserving an existing situation. On the contrary, an alliance increases in
strength when it offers both parties the hope of territorial expansion. It is true
everywhere that strength is not in the defense, but in the attack.
This was recognized in many places, but, unfortunately, not in the so-
called “competent” circles of the elected officials. Colonel Ludendorff, Officer
on the Great General Staff at that time, pointed to these weaknesses in a
paper written in 1912. Of course the other “statesmen” attached no value or
importance to the situation. Clear common sense is apparently only needed
for ordinary mortals and it can always be dispensed with in the case of
“diplomats.”
Germany was lucky that Austria was the cause of the war in 1914. This
required the Hapsburgs to participate. If war had come from the other
direction, Germany would have been alone. The Hapsburg State could never
have taken part, or even wanted to take part, in a struggle started by
124
Munich
Germany. If Germany was the cause of war, Austria would have done what
Italy was later so loudly condemned for doing. It would have remained
“neutral” in order to at least protect the State from a revolution at the very
start. The Austrian Slavs would rather have broken up the Monarchy in 1914
than offer to help Germany.
Very few people at that time realized how great the dangers were or the
added problems that the alliance with the Monarchy brought with it. In the
first place, Austria had too many enemies who hoped to inherit the decaying
State. During that time, Germany was bound to be exposed to some hatred
because Germany was the obstruction to the dismemberment of the
Monarchy which was almost universally desired. In the end, nations came to
the conclusion that Vienna could only be reached by way of Berlin.
In the second place, Germany lost its best and most promising chance of
forming an alliance with another country. Instead, tensions increased with
Russia and with Italy. The general feelings in Rome toward Germany were
favorable and equally hostile toward Austria, but tensions still built against
Germany politically.
Since the commercial and industrial expansion policy had been
established, there was no longer any reason for Germany to struggle with
Russia. Only the enemies of both Germany and Russia could have any real
interest in a conflict between them. In fact, it was chiefly Jews and Marxists
who used every way they could think of to stir up war between the two states.
Third and lastly, the Alliance concealed one huge threat to Germany. Any
great power that was hostile to Bismarck’s Empire could easily mobilize a
whole string of states against Germany by promising spoils at the expense of
the Austrian ally.
All of Eastern Europe, especially Russia and Italy, could have been raised
up against Austria and the Monarchy. The world coalition started by King
Edward would never have happened if Germany’s ally, Austria, had not been
an irresistibly tempting prize. This promise was the only way to unite these
states that otherwise had such varied desires and goals. In a general advance
against Germany, everyone could hope to benefit at the expense of Austria.
125
Mein Kampf
The danger was actually even greater because Turkey also seemed to belong
to this unlucky alliance as a silent partner.
The forces behind International Jewish World Finance needed this bait in
order to carry out its long-cherished plan of destroying Germany. At this time
Germany had not yet given in to general international control because of its
finance and economic structure. It was the only way to forge a coalition which
would be strong and bold enough and would have the numbers of marching
millions, which could battle with the armored skin of Siegfried at last.12 Even
in Austria, I was completely unhappy with the Hapsburg Monarchy alliance,
and it was now the subject of a long, inward analysis which ended by
confirming my earlier opinion even more strongly.
In the humble circles in which I moved, I didn’t hide my conviction that
this unhappy treaty was with a state marked for destruction, and it must lead
to a catastrophic collapse of Germany too if we did not get out in time. My
solid conviction never wavered, even when the storm of the First World War
seemed to have cut off all sensible thinking and the flood of enthusiasm had
swept away those who could coldly look at reality with total objectivity.
Whenever I heard these problems discussed, even while I was at the
front, I maintained my opinion that the alliance must be broken off, and the
sooner the better for the German nation. It would be no sacrifice at all to
deliver up the Hapsburg Monarchy if Germany could limit the number of her
adversaries.
Millions strapped on the steel helmet to save the German nation, not to
preserve a wicked dynasty.
Once or twice before the war, at least one camp would have some doubts
about the soundness of the alliance policy. From time to time, German-
Conservative circles began to warn about being too trusting. Their warnings
were ignored along with all other common sense. People were convinced they
were on the high road to a world “conquest.” All they could see was the
enormous chance of success without any cost whatsoever. Once again, there
12A Wagner opera reference where Siegfried bathes in the blood of a dragon, which forms
scales on him as protection, similar to Achilles. Here Siegfried is another name for the
Germanic race.
126
Munich
was nothing for the average man to do but watch in silence while the “elected
officials” marched the country straight to damnation, with the good folk
following after them like rats, following the Pied Piper of Hamelin.13 The
general state of our entire political thinking was the main reason it was
possible to make a group of people accept the nonsense of “economic
conquest” as a political goal, and this same weak thinking caused them to
accept the preservation of “world peace” as a political goal.
With the victorious march of German industry and invention and the
growing successes of German trade, people could no longer see that the whole
thing was based on the assumption that the state was strong. In many circles,
people went so far as to argue that the state itself owed its existence solely to
the industry, and that the state was primarily an economic institution which
should be governed based on economic interests. They thought its existence
depended on the economic life—a condition which was praised as the
healthiest and most natural form of being.
This is wrong. The state has nothing whatsoever to do with any particular
economic concept or development. The state is not a union of economic
contracting parties within a definite limited area to perform economic tasks.
It is the organization of a community. A collection of physically and spiritually
similar people who, together, make the preservation of their species possible,
as well as the accomplishment of the goal which Providence has set for their
existence. That and that alone is the purpose and meaning of a state.
The economic system is one of the many methods needed to reach this
goal. It can never be the purpose of a state unless it is set up on an incorrect
and unnatural basis from the beginning. That explains why a state should not
assume any territorial limitations as a requirement of its founding. Expansion
is necessary for people who want to assure their species continues with their
own resources and who are ready to fight in order to live from their own
efforts. People who succeed in sneaking in among the rest of mankind like
loafers—letting the others work for them while making all kinds of excuses—
13The Pied Piper of Hamelin is the subject of a Middle Ages legend where he led a great many
children from the town of Hamelin, Germany to their death after he was not paid for his
services leading rats away from the town.
127
Mein Kampf
can form states without any definite living boundaries of their own. This is
especially true of those people that the rest of honest humanity is suffering
from today, the bloodsucking Jews.
The Jewish State has never been limited by space. Their one race has
universally unlimited territory. Therefore, these people have always formed a
state within the state. It is one of the most brilliant tricks ever invented to have
this State sail under the colors of a “religion.” The tolerance by the Aryan is
assured because he is always ready to make allowances for a religious group.
The Mosaic Law religion14 is nothing but a doctrine for the preservation of the
Jewish race. This is why it includes almost every field of sociological, political,
and economic knowledge that could possibly serve that purpose.
The instinct for preservation of the species is the original reason for the
formation of human communities. The state is a race oriented organization
and not an economic organization. As great as the difference is between them,
it is still totally incomprehensible to the “statesmen” of today. They think they
can build up the state by purely economic means, but in reality, the state
comes from the will of a species and race to survive. These qualities are always
heroic traits and never the ego of a businessman. After all, the survival of a
species depends on its willingness to sacrifice the individual. The words of the
poet, “And if you do not stake your lives, life shall never be your prize,”15
signify that giving up personal existence is necessary to assure the survival of
the species. The most essential requirement for the formation and
maintenance of a state is a community of similar character and a species who
believe in that community, and are willing to back it up by whatever means
are necessary.
People protecting their own soil become heroes. With parasites, it is
different. It leads to lying hypocrisy and malicious cruelty.
The initial formation of a state can only take place by applying these
heroic qualities. In the resulting struggle for self-preservation, some people
who lack these qualities will fall victim to the parasites and become economic
slaves who will be defeated and eventually die.
128
Munich
These are not heroes; they can’t resist the methods of the hostile
parasites. But even here, it is almost never a lack of wisdom, but more a lack
of courage and determination which tries to hide under the cloak of humane
principles.
There is only the slightest connection between economics and state-
building and state-preserving. This is best demonstrated by the inner strength
of a state which only rarely coincides with its economic success. We can also
find countless examples that show prosperity is a sign of approaching decline.
If the formation of human communities were primarily for economic forces,
strong economic development would mean the greatest strength of the state
and not the other way around.
Faith in the state-building or state-preserving power of economics is
particularly hard to understand when it holds influence in a country that
clearly demonstrates the opposite from its history. Prussia wonderfully proved
that ideals and virtues alone make the creation of a state possible and not
material qualities. Only under their protection can economic life flourish.
When the elements that were responsible for state-building collapse, the
economic structure also topples. This is a process we are now seeing in a sad
way. The material interests of mankind always flourish best when they are
shadowed by heroic virtues, but when economics attempts to take center
stage, they destroy the essential part of their own existence.
Whenever a strong political power has existed in Germany, economic life
has always progressed. Whenever the economic system has become the only
substance of our people’s life, it smothered the virtues of idealism, and the
state collapsed and carried the economic benefits with it into the ground.
If we ask ourselves what forces preserve a state, we can lump them all in
one category: the ability and willingness of an individual to sacrifice himself
for the whole. These virtues have nothing at all to do with economics. We can
see this from the simple fact that man never sacrifices himself for economics.
People don’t die for business, but for ideals. Nothing showed more clearly the
Englishman’s superior ability to look into the psychology and into the soul of
his people than the motivation he demonstrated in his struggle. While we
were battling for bread, England was fighting for “freedom” and it was
129
Mein Kampf
freedom for the little nations, not even for herself. We laughed and were
annoyed by this audacity. We showed the same thoughtless stupidity the
German statesman demonstrated so well before the war. Men lost the
slightest desire to die of their own free will. As long as the German people in
1914 still believed they were fighting for ideals, the battle continued; when
they were told to fight for economic survival, they gave up. When something
finds itself fighting simply for the production of daily bread, it prefers to give
up.
Our intelligent “statesmen” were astonished at this change in public
sentiment. They never understood that from the moment a man begins to
fight for an economic interest, he avoids the death that would prevent him
from ever enjoying the rewards of his struggle. The most delicate mother
becomes a heroine to save her own child.
The battle for the preservation of the species and of the home or state
that shelters it is what always made men willing to go to war.
We offer the following as an eternal truth: No state has ever been created
by establishing a peaceful economy. Only through the instincts that preserve
the species, whether they are heroic virtue or shrewdness, have states been
created. Heroic virtue produces true Aryan, working, civilized states while
shrewdness produces Jewish parasite colonies. When instincts in a race or a
state are overrun by economics, the economic structure itself releases the
causes that lead to defeat and oppression.
The belief before the First World War that Germany could open up or
even conquer the world through peaceful colonial means and commercial
policy was a sign that the state-building and state-preserving virtues had been
lost. Also lost was the insight, strength of will, and determination needed to
take decisive action. The law of Nature brought the First World War and its
results as revenge upon our heads. Anyone who failed to look below the
surface would only see an unsolvable puzzle when considering this universal
attitude of the German nation. After all, Germany herself was the most
wonderful example of an empire created by power and military valor. Prussia,
the nucleus of the Empire, was created by brilliant courage, not by financial
operations or business deals. The Empire was missing the magnificent reward
130
Munich
16 Bismarck passed laws in 1878 to curb Social Democrat and Marxist activities.
131
Mein Kampf
how they could stagger so blindly towards a horrible danger whose aims were
clearly and openly discussed by the leaders of Marxism. Among my
acquaintances, then and now, I warned against the smooth talking, soothing
slogan of all cowardly wretches who said, “Nothing can happen to us!” A
similar troublesome attitude had destroyed one giant empire already. Did
everyone believe Germany alone was going to be exempt from the laws that
governed all other societies? In 1913 and 1914, I announced my conviction
that the future of all Germans depended on destroying Marxism. Some of the
circles where I spoke are now faithfully part of the National Socialist
movement today. In the destructive German Triple Alliance policy, I saw the
result of the Marx.
The inner decline of the German people started long before they
recognized the destroyer of their existence was growing among them. Now
and then, there was some treatment of the disease, but the symptoms were
too often confused with the cause. As people did not or would not look at the
cause, the struggle against Marxism was as effective as a long-winded quack’s
miracle cure.
132
CHAPTER FIVE
What depressed me more than anything when I was a wild youth was that I
had been born into an age that honored only tradesmen or civil servants.
The surge of large waves seen in history seemed to have calmed down so
much that the future belonged only to the “peaceful competition of people”
or to quiet, mutual swindling where any aggressive method of self-defense
had been abandoned. More and more, the individual nations began to
resemble businesses that mutually undercut one another, stole customers
and orders, and tried to outwit each other in every way, while making protests
as loud as they were harmless. This development not only seemed to progress,
but it was generally hoped it would someday transform the world into one
huge department store where the reception area would for all time display
statues of the most skillful manipulators and most harmless executives. The
English could then furnish the businessmen, the Germans would furnish the
administrative officials, and the Jews would have to sacrifice themselves as
managers since they speak the most languages, and, by their own admission,
they never make a profit, but “keep paying” forever.
Why couldn’t I have been born a hundred years sooner? Say at the time
of the Wars of Liberation1 when a man had some value apart from the
“business” which he operated.
It often annoyed me when I thought that my life started too late. I
believed the age of “peace and good order” in front of me was an undeserved
cruel strike of Fate. Even as a boy, I was no “pacifist” and every attempt to
push me in that direction was a failure.
133
Mein Kampf
Then, the Boer War2 appeared like a bright light on my horizon. Every day,
I anxiously waited the newspapers. I devoured news reports and letters. I was
happy to witness this heroic struggle, even if it was from a distance. During
the Russo-Japanese War,3 I was more mature and more observant. Here I took
sides for more rational reasons and supported the Japanese in every
discussion we had.
I saw the defeat of the Russians as a defeat of the Austrian Slavs.
Years had passed since then, and what I had thought was slow-moving
weakness as a boy, I now believed to be the calm before the storm. Even in
my Vienna days, the Balkans4 were burning under the feeble heat that usually
predicts the approach of a hurricane.
Flashes of light were already beginning to flicker, only to be lost again in
the strange darkness. Then came the Balkan War5 and with it, the first puff of
wind whipped across a nervous Europe. The approaching events weighed on
men like a nightmare—like feverish, brooding tropical heat—and it continued
until the constant worry finally turned the feeling of approaching catastrophe
into desire. Let Heaven give in to the destiny that could not be avoided. Then,
the first mighty flash of lightning struck the earth. The storm broke and the
thunder of the sky was mixed with the roar of the artillery in the First World
War.
When news of the murder of Archduke Francis Ferdinand arrived in
Munich, I was sitting at home and caught only bits and pieces of what
happened.6
At first I was afraid and worried that the bullets had come from the pistol
of a German student. They were angry at the Crown Prince over his constant
work to convert the nation to a Slav region, and they wanted to free the
German people from this enemy within. It was easy to imagine what the result
134
The First World War
7Maria Theresa was an Archduchess of Austria and the only ruler until 1765 when she
recognized her son, Joseph II, as co-regent. She unified the Hapsburg Monarchy, but after the
135
Mein Kampf
government circles to blame them for starting a war that otherwise might
have been avoided. It could no longer have been avoided— possibly
postponed for one or two years— but not avoided. The curse of German and
Austrian diplomacy was that it had always tried to postpone the inevitable
reckoning until it was finally forced to strike at the most inopportune moment.
We can be sure that another attempt at peace would only have brought on
the war at an even more unfavorable time.
Anyone who did not want this war must have the courage to accept the
consequences of their past refusal. This consequence could have only been
the sacrifice of Austria. The war would still have come, but probably not with
everyone against us. Instead, it would have meant the separation of the
Hapsburg Monarchy. It was necessary to decide whether to take part or simply
to gawk empty-handed while Destiny took its course. The very people who
today curse the loudest and pass judgment about the starting of the war were
the ones who took the most fatal part in leading us into it.
For decades, the Social Democrats had been sneaky in their efforts to
spark war against Russia. The German Centrist Party,8 on the other hand, had
made the Austrian State the pivotal point of German policy for religious
reasons. Now, the results of this craziness were upon us. What came next was
inevitable and could no longer be avoided under any circumstances. The
German government’s share of the guilt was that in its effort to preserve
peace, it missed all the best moments to fight. It became wrapped up in the
alliance to preserve world peace and finally became the victim of a world
coalition, which was absolutely determined to oppose a World War and to
preserve world peace at any cost. Even if the Vienna government had given an
ultimatum in more palatable terms, it would not have changed the situation
but, instead, it might have generated public outrage if the masses saw the
ultimatum as too moderate and certainly not extreme or excessive. Anyone
who denies this today is either a forgetful blockhead or an intentional liar.
death of her husband withdrew and was no longer active as a Monarch even though she had
made many civil reforms earlier.
8 A Catholic political party.
136
The First World War
The First World War of 1914 was not forced on the masses, but was
demanded by the people. They wanted to finally put an end to the lingering
uncertainty. Only on that ground can we understand how more than two
million German men followed the flag into this supreme struggle, ready to
protect it with their last drop of blood.
To me, those days seemed like deliverance from the anger of my youth.
Even now, I am not ashamed to say that I fell on my knees overcome by a wave
of enthusiasm, and thanked Heaven from an overflowing heart that it had
granted me the good fortune to live in this time.
A battle for freedom had begun whose unparalleled greatness the earth
had never seen. Destiny had barely begun to take its course before the great
masses started to realize that this time it was not just Serbia’s or Austria’s fate
at stake, but the existence of the German people itself.
After many years, the people could finally see the future. At the very
outset of the monstrous struggle, the intoxicating, extravagant enthusiasm
was quickly replaced by the necessary serious undertones. Only this
realization made the nation’s exaltation more than just a passing fad. This was
necessary because the majority of the people did not have the slightest idea
how long the battle would be. They dreamed of soldiers being home again by
winter so they could return to their peaceful jobs.
What man wants, he also hopes for and believes in. The overwhelming
majority of the nation was sick of the eternal uncertainty, so it was
understandable that no one believed in a peaceful solution of the Austrian-
Serbian conflict and instead hoped for a final settlement. I was one of these
millions.
The news of the assassination had barely reached Munich when two
ideas flashed through my mind. First, war was now unavoidable, but beyond
this, the Hapsburg State would now be compelled to stick to its alliance. What
I had always feared most was the possibility that some day Germany itself
might be involved in a conflict that was not caused by Austria. Then, for
domestic, political reasons, the Austrian State would not have the resolution
to back up its ally. Even though the alliance had already been made, the Slavic
majority of the Empire would have sabotaged it at once and would have
137
Mein Kampf
preferred to shatter the whole State rather than given help to their ally. This
danger was now removed. The old Austrian State had to fight whether it
wanted to or not.
My own attitude toward the conflict was perfectly clear and simple. What
I saw was not Austria fighting for some satisfaction against Serbia, but
Germany fighting for her all. The real battle was the German nation fighting
for its existence or nonexistence, for its freedom and future. Bismarck’s
creation must now go out and fight. What its fathers had once conquered in
battle with their heroic blood—from Weissenburg to Sedan and Paris—young
Germany had to now earn back. If the battle was victorious, then our people
would rejoin the circle of great nations once more. The German Empire could
prove itself again as a mighty stronghold of peace without having to put its
children on short rations for the sake of maintaining peace.
As a boy and young man, I had often wished I could demonstrate that my
nationalistic enthusiasm was no empty obsession. It often seemed to me
almost a sin to cry out in joy with the crowd without having any real right to
do so. Who could rightfully shout hurray without having tried it, when all
pettiness is over and the Goddess of Fate’s cruel hand begins to test the
strength of everyone’s convictions? Like millions of others, my heart
overflowed with happiness now that I could be free of this paralyzing feeling.
I had sung “Deutschland über alles”9 and shouted, “Heil” so often at the top of
my lungs. Now it seemed to me almost like Heavenly grace granted retroactive
justice by allowing me to testify to the truth of my convictions and prove they
were real. I knew from the first moment that in the face of an inevitable war,
I would abandon my books immediately. I also knew that my place must be
where the inner voice of conscience sent me.
I left Austria primarily for political reasons. Now that the struggle was
beginning, it seemed natural that I should review my convictions. I would not
fight for the Austrian Hapsburg State, but I was ready at any time to die for my
people and for the German Empire they belonged to.
9 “Germany ahead of all”, the actual song title is “The Song of Germany.”
138
The First World War
10 A statue that commemorates the founding of the German Empire after the Franco-Prussian
War.
11 “Guard on the Rhine.”
139
Mein Kampf
through the mist, we were suddenly met with an iron greeting as it hissed over
our heads. With a sharp crack, it hurled the little pellets of shrapnel through
our ranks, splashing up the wet soil. Before the little cloud was gone, the first
“hurray” came from two hundred voices in response to this greeting by the
Angel of Death. Then the crackling and thunder began; singing and howling,
and with feverish eyes, everyone marched forward, faster and faster. At last,
across beet-fields and hedges, the battle began—the battle of man against
man. From a distance, the sound of song reached our ears, coming closer and
closer, and jumping from company to company. Just as Death began to busy
himself in our ranks, the song reached us too, and we in turn passed it on:
“Deutschland, Deutschland über alles, über alles in der Welt!”12 Four days
later, we went back to camp. We even walked differently. Seventeenyear-old
boys now looked like men. Maybe the volunteers of the List Regiment13 had
not really learned to fight, but they did know how to die like old soldiers.
That was the beginning. That’s how it went on year after year, but horror
had replaced the romance of battle. Enthusiasm gradually cooled down and
the wild excitement was smothered in deadly fear. For each man, the time
came when he had to struggle between the instinct of self-preservation and
the obligations of duty. I was not exempt from this struggle. Whenever Death
was close, a vague something in me tried to revolt and tried to disguise itself
as reason to the weak body, but it was still just that sly cowardice laying sneaky
traps. A great tugging and warning would begin, and only the last remnant of
conscience would get me through the day.
But the harder this voice worked to caution me and the louder and more
piercingly it spoke to me, the stiffer my resistance became, until finally, after
a long inner struggle, duty won. This struggle was decided for me by the winter
of 1915-1916. My will had finally become the absolute master. The first few
days I ran to the fight laughing and gloating, but now, I was calm and
determined. That was the frame of mind that would endure. Now, I could
proceed to the final trial of Fate without nerves cracking or the mind failing.
The young volunteer had become an old soldier.
140
The First World War
This transformation had taken place throughout the army. They had
come out of the perpetual battle older and stronger, and whatever could not
stand up to the storm was simply broken.
Only now was it fair to judge this army. After two or three years of fighting
one battle after another—always fighting a force greater in numbers and
weaponry, starving and suffering hardships—then was the time to judge the
value of that unique army.
Thousands of years from now, no one will speak of heroism without
mentioning the German Army in the First World War. Through the veil of
history, the iron front of gray steel helmets will appear, unswerving and
unyielding, a monument of immortality. As long as there are Germans, they
will remember that these were sons of their forefathers.
When I was a soldier I did not want to talk politics. That was not the time
for it. To this day, I am convinced that the last stable-boy was more valuable
to the Fatherland than the first “parliamentarian.” I had never hated these
windbags more than now as every quiet, truthful lad said what he had to say
point blank in the face of the enemy, or else left the small talk at home and
focused on doing his duty in silence. Yes, at that time I hated all these
“politicians,” and if I had my say about it, a parliamentary pick-and-shovel
brigade would have been formed at once. There, they could have chattered
between themselves to their hearts’ content without annoying or harming
decent, honest humanity.
I wanted nothing to do with politics, but could not help adopting attitudes
toward things that affected the whole nation, and especially to things that
affected us soldiers.
There were two things which annoyed me at that time that I thought
were harmful to our interests. After the very first report of victory, a certain
section of the press began slowly, and possibly unnoticed to some, to sprinkle
a few drops of bitterness into the general enthusiasm. This was done behind
a false front of benevolence, good intentions, and concern. They did not
believe in celebrating victories “too much.” They claimed they were afraid that
such celebrations were unworthy of a great nation and out of place. The
bravery and heroism of the German soldier were to be taken for granted
141
Mein Kampf
because they were accepted facts which did not justify such jubilation. They
said outbursts of joy should not be encouraged because foreign countries may
view quiet and dignified rejoicing as more attractive than unrestrained
excitement. Finally, we Germans, should not forget that the war was not our
creation and that we shouldn’t be ashamed to admit openly as men that we
were ready at any time to do our share in the reconciliation of mankind. It was,
therefore, not wise to tarnish the purity of the army’s deeds by too much
shouting. The rest of the world might not understand such behavior. They said
nothing was more admired than the modesty and restraint with which a true
hero calmly and silently forgot his deeds. That was basically their warning to
the people.
Instead of bringing these fellows to the forefront and pulling them high
on a pole with a rope, so that the victorious enthusiasm of the nation should
no longer offend the sensibilities of these knights of the pen, people actually
began to follow their lead and issue warnings against the “unsuitable”
character of the victory celebrations.
The politicians never realized that once the enthusiasm was stopped, it
could not be revived when it was needed. It is a state of intoxication and must
be maintained as such. Without this sort of enthusiasm, how could the nation
endure a struggle which would make enormous demands on their spiritual
stamina? I knew the nature of the broad masses well enough to realize that a
“showy” display of moral superiority was no way to fan the flames needed to
keep the iron hot. I thought officials were crazy when they did not act to raise
the boiling point, increase the heat of passion, but I surely didn’t understand
why the government would push policy to restrain the little excitement that
existed.
The second thing that annoyed me was the attitude that Marxism was
acceptable. In my eyes, this just proved that people had no idea how
dangerous this disease truly was. They seemed to sincerely believe that by no
longer recognizing any political party distinctions during the war, they had
brought Marxism to reason and restrained it.
Marxism is not a matter of a political party, but of a doctrine which is
bound to lead to the utter destruction of humanity. This was not widely
142
The First World War
understood because that side of Marxist theory was not taught at our Jew-
ridden universities. Too many people have been trained to think that if
something is not taught in their university then it is not important enough to
pick up a book and learn about it, which is silly, especially among the higher
level government officials and civil servants. This revolutionary trend passed
over these “intellectual-official-heads” without them paying any attention to
it, which is the reason why state institutions usually drag behind private ones.
Heaven knows the German proverb is truer of those intellectual-officials
than of anyone else: “What the peasant doesn’t know, will not bother him.”14
The few exceptions just prove the rule.
It was an unparalleled mistake to identify the German workman with
Marxism in August of 1914. When the time came, the German workman chose
to free himself from the grasp of this poisonous epidemic or he could never
have taken part in the struggle of the war. But people were stupid enough to
think that, now, perhaps, Marxism had become “nationalistic.” This was a
stroke of “genius,” which proves that for many long years, none of these
official heads of the State had ever bothered to study the nature of the Marxist
doctrine. If they had done their homework, such a crazy idea would have never
survived.
Marxism’s ultimate goal is and always will be the destruction of all non-
Jewish national states. It was horrified to see that in July of 1914, the German
working class, which it had previously trapped, was waking up and quickly
entering the service of the Fatherland. Within a few days, the whole smoke
screen of this deceit, of this infamous fraud on the people, was blown away
and suddenly the Jewish leaders were alone and deserted. It was as if there
wasn’t a trace left of the nonsense and insanity which they had been pouring
into the masses for sixty years. It was a bad moment for the deceivers of the
German working class people. But, the instant the leaders recognized the
danger that threatened them, they dawned their tarn-caps and boldly
14 The English idiom is “What you don’t know can’t hurt you”, a variation of “Ignorance is
bliss”, “If you do not know about a problem then you cannot make yourself unhappy by
worrying about it.”
143
Mein Kampf
pretended to take part in the national revival.15 This would have been the time
to take a stand against the whole fraudulent brotherhood of Jewish pests
hiding among the people. Now was the time to give them a severe penance
without the slightest consideration for any protest or consequence that might
have arisen as a result. In August of 1914, the Jewish chant of international
solidarity was gone with a single blow to the heads of the German working
class. A few weeks later, this nonsense was replaced by American shrapnel as
it poured the blessings of worker-solidarity over the helmets of the marching
soldier’s columns.
Now that the German workman had returned to his own nationality, it
should have been the duty of any responsible national government to
unmercifully annihilate the agitators who stood against it. If the best men
were falling at the front, the pests assaulting national spirit could at least have
been exterminated at home.
But instead, His Majesty the Kaiser himself held out his hand to these old
criminals offering these disloyal assassins of the nation mercy, protection, and
an opportunity to collect themselves for their next strike.16 The serpent could
then go on working, more cautiously than before, but this made him more
dangerous. While honest people dreamed of peace and security, the lying
criminals were organizing a revolution. I was more than dissatisfied with the
fact that officials had settled on a set of terrible half-measures to deal with the
problem, but I didn’t even realize how horrible the result would eventually be.
Then what should have been done next? The leaders of the whole
movement should have been put under lock and key immediately. They should
have been put on trial and the nation freed from them. Every resource of
military power should have been used to brutally exterminate this epidemic.
The Marxist parties should have been dissolved and the Reichstag brought to
15 A tarn cap, or Tarnkappe, means a magical cap that allows the wearer to take any form they
wish. Siegfried uses one in Wagner’s operas and the reference is common in Germanic stories.
Other stories give it the power of invisibility and strength;, however, it is likely Hitler was
referring to Wagner’s version meaning the people put on the trappings and took the form of a
nationalist as if by magic.
16 The old criminals refers to Dr. Edouard Bernstein, a Socialist Democrat, and Albert Ballin,
managing director of the Hamburg-America cruise ships and friends with Wilhelm II.
144
The First World War
145
Mein Kampf
This process will always be useless from the beginning if the doctrines to be
fought have gone beyond a certain small circle.
As with all growing movements, destruction is only possible when the
movement is young. While resistance increases with the passing years, the
movement will grow and then yield to fresh and younger members who will
sprout new groups in a different form and with slightly different motives.
Almost all attempts to uproot a doctrine and its related organizations by
violence with no intellectual or spiritual basis are failures. Frequently in fact,
such efforts produce the opposite result from the one intended.
When sheer force is used to combat the spread of a doctrine, then that
force must be used systematically and persistently. Only regular and steady
suppression of a doctrine can possibly be successful. The moment there is any
hesitation and violence alternates with mercy, the doctrine being overcome
will not only recover, but it will gain new value from each following
persecution. This happens because when pressure is eased, resentment at
what has been suffered brings new followers to the old doctrine, and existing
supporters cling to it with greater defiance and deeper hatred than ever. In
fact, after the danger is gone, even those who renounced and betray their
movement will try to return to their old beliefs. The only way to achieve
success is through a constant and regular use of violence. This persistence can
only happen with a definite intellectual and spiritual conviction backing it up.
All violence not founded on a solid spiritual or intellectual basis is indecisive
and uncertain. It lacks the stability that can only live in a fanatically intense
world concept. It flows from the energy and brutal determination of an
individual. This dependence on the individual also makes it subject to changes
of its nature, personality, and strength as it changes hands.
There is still another consideration. Any World-Concept, whether
religious or political in nature—though it can be difficult to tell when one ends
and the other begins—strives less for the negative destruction of hostile ideas
than to positively affirm its own ideas. Its battle must be more offense than
defense.
This is an advantage because the movement knows its own goal. The aim
is victory for its own idea. On the other hand, it is hard to decide when the
146
The First World War
17 Marxists.
147
Mein Kampf
no workable substitute for this doctrine. What could they have offered the
masses if Social Democracy had failed? Not one movement existed that could
successfully draw the great crowds of workers under its influence once their
leaders were gone. It is silly and more than stupid to presume that the
international fanatic, having left his working-class political party, will suddenly
join a privileged-class party or any new class organization at all. As
disagreeable as it may be to various organizations, there is no denying the fact
that privileged-class politicians believe separation of classes is important as
long as it does not result in a political disadvantage. Denying this fact proves
the audacity and stupidity of these liars.
In general, we must avoid thinking that the masses are more stupid than
they actually are. In political matters, decisions are based more on feeling than
understanding. The belief that this feeling on the part of the masses somehow
proves stupidity towards international matters can be immediately disproved
by simply pointing out that a pacifist democracy is equally insane because its
supporters are almost exclusively from the intellectual privileged classes.
When millions of citizens continue to reverently worship their Jewish
democratic press every morning, it looks bad for the upper class to make fun
of the stupidity of the common “comrade” who, in the end, is swallowing the
same dirt, just presented differently. The manufacturer is one and the same
in both cases, the Jew.
We must be careful not to deny things whose existence is obviously a
fact. It is an undeniable fact that class questions have nothing to do with
ideals, though that tripe is commonly served up at election time. The class
arrogance of many upper class people and the low regard of the manual
laborer is not in the imagination of a lunatic, but a well-known fact. Apart from
this, it shows the small thinking-power of our so-called intellectual elite when
they assume that circumstances that failed to prevent the rise of Marxism can
now somehow find a way to recover what has been lost to it.
The privileged-class parties can never bring the lower class masses into
their camp. These are two worlds that are divided in nature and artificially.
When they stand together, there will be battle, but no matter what, the
younger one, Marxism, will be victorious.
148
The First World War
149
CHAPTER SIX
War Propaganda
Pursuing all political events with interest like I did made me very interested in
propaganda. In it, I saw a tool that the Socialist-Marxist organization
understood well and used with masterful skill. I realized early that the proper
use of propaganda is a true art and one that remained practically unknown to
the privileged-class parties.
Only the Christian-Socialist movement achieved a certain skill with this
tool and its success was owed to Lueger’s contributions in his day. Not until
the war was there a chance to see the enormous results that focused
propaganda can produce. Here again, unfortunately, the other side was the
sole subject of study because our side’s understanding and use of propaganda
was insignificant. This negligence was obvious to every German soldier. It was
an absolute failure of the entire German information system. This now led me
to investigate more thoroughly the use of propaganda.
Often there was more than enough time for consideration and reflection,
but, unfortunately, it was the enemy who gave us this great practical lessons.
What we failed to do, our adversaries did with extraordinary skill and
calculation amounting to genius. Even I learned an infinite amount from the
enemy’s war propaganda. But of course, time passed without a trace of
understanding raining on the politicians’ heads. Some of them thought they
were too clever to take lessons from the enemy, and the rest were unwilling
to learn. Did we have any propaganda at all? Unfortunately, no. Everything
that was tried in this area was so inadequate or wrong from the start that, at
best, it did no good and was often actually harmful. After a careful review of
German war propaganda, it was inadequate in form, and it was psychologically
wrong in fundamentals. Anyone could see this was true, even with a cursory
150
War Propaganda
inspection. Officials were not even clear in their own minds about whether
propaganda is a means or an end.
It is without question a means and has to be judged based on how it
accomplishes the ends. Its form has to be adapted to accomplish the desired
result. It is also obvious that the importance of the end may vary. The ends
may even stray from the general needs of the public. The propaganda must
also adjust to match the value of the ends desired. The end that we struggled
for during the war was the most glorious and tremendous that a man could
imagine: the freedom and independence of our people, security of income for
the future, and the nation’s honor which is something that does exist despite
those with contrary opinions. It must exist because people without honor lose
their freedom and independence sooner or later. This, in turn, agrees with a
higher justice because generations of scoundrels without honor deserve no
freedom. No one who is willing to be a cowardly slave can or should possess
any honor because that kind of honor would quickly become an object of
universal hatred.
The German people were fighting for their very existence, and the
purpose of propaganda in the war should have been its goal to back up the
fight and victory.
When people are fighting for their existence on this planet and are faced
with the fatal question, “to be or not to be,” all considerations of humaneness
or appearances crumble into nothing. These concepts are not floating in the
air, but are born in man’s imagination where they will cease to exist when he
ceases to exist. Man’s departure from this world dissolves those concepts into
nothing because Nature does not know them. They are limited to the men in
a handful of countries or rather a few races, and their value is only to the
degree they unfold from these men’s feelings. Humaneness and showy
idealism for the sake of appearances would disappear from the inhabited
world if the races that created and upheld these concepts were lost.
In a peoples’ struggle for its existence in the world, these concepts are of
only minor importance. They are not important in determining the form of the
struggle. If the time comes when they might cripple the drive for self-
preservation in a struggling people, they must be discarded.
151
Mein Kampf
1Known as Moltke the Elder, Helmuth Karl Bernhard von Moltke was a Prussian soldier, Chief
of General Staff in 1858 and responsible for the French defeat in 1870.
152
War Propaganda
educated masses? It must be aimed continuously at the masses alone! For the
intellects, or those today who think they are intellectuals, we do not offer
propaganda, but scientific teaching. Judging by its substance, propaganda is
no more science than an advertising poster drawing is art. The art of the poster
is in the designer’s ability to attract the attention of the crowd with form and
color. A poster advertising an art exhibition only has to draw attention to the
art in the exhibition. The better it succeeds, the greater is the art of the poster
itself. In addition, the poster should show the masses the importance of the
exhibition, but it should never be a substitute for the art there on display.
Anyone who wants to involve himself with actual art must study more than
just the poster. In fact, for him, a simple walk through the exhibition is not
enough. Only after a detailed study of the exhibits can he be expected to give
a thoughtful examination to the individual works, and then slowly form a
sound opinion.
The situation is the same today with what we call propaganda.
Propaganda’s purpose is not scientific training of the individual, not to give
details or to act as a course of instruction, but directing the masses’ attention
to particular facts, occurrences, and necessities. The importance of these facts
can only be brought in their view by the means of propaganda.
The art of propaganda consists in putting a matter so clearly and forcibly
before the minds of the people that it creates a strong conviction in everyone.
It is essential to success that propaganda reinforces the reality of the facts
that are promoted, the necessity of what is being promoted, and the just or
rightness of its character.
This art is not an end in itself. Its purpose must be identical to the
advertisement poster—to attract the attention of the masses and not to
distribute instructions to those who already have an educated opinion on
things or who prefer to form their opinions based on objective study. That is
not the purpose of propaganda. It must appeal to the feelings of the public
rather than to their reasoning ability.
All propaganda must appeal to the common people in tone and in form
and must keep its intellectual level to the capacity of the least intelligent
person at whom it is directed. In other words, the intellectual level must be
153
Mein Kampf
154
War Propaganda
155
Mein Kampf
evaluate other causes. It must not objectively explore any truth that favors the
other side or fairly weigh the options, and then present the masses with a
strict doctrine. It must not argue matters based on theoretical rules of justice.
Propaganda must constantly endeavor to present only the aspect of the truth
that is favorable to its own side.
It was a fundamental error to discuss who was responsible for starting
the First World War and then declare that Germany was not totally
responsible.
The right way would have been to pile the guilt totally on the enemy,
even if this wasn’t true, but in this case, it was.
What was the result of this half-and-half propaganda? The great masses
of people are not made up of diplomats, professors of law, or even people
capable of making a judgment based on reason and logic. They are human
beings—indecisive and subject to doubt and uncertainty. The moment our
own propaganda admits even the faintest glimmer of justice is due to the
other side, the seeds of doubt have been planted and they will begin to
question whether our own side is just. The masses cannot tell where the
enemy’s wrongs end and their own begin. In these cases, they become
uncertain and suspicious. This is especially true when the enemy does not
commit the same foolishness, but puts the guilt, lock, stock and barrel, on his
adversary.
It was natural for our own people to believe the more intense and
focused hostile propaganda of our enemy instead of their own people’s words.
This is easily seen in those who have a mania that craves objectivity, like the
Germans! Everyone preferred to be fair to the enemy rather than to risk
injustice.
Even willing to destroy his own people and State in the process.
The masses never realized that this outcome was not the leaders’
intention but it was their failure to understand which was the cause. The
overwhelming majority of the people tend to be so feminine in their leanings
and beliefs that emotion and feelings rather than serious logical reasoning
determine thought and action. This feeling is not complicated. It is simple and
firm. There is no gray area. There are not many different shadings, but a
156
War Propaganda
positive or a negative, love or hate, right or wrong, truth or lie, but never half-
and-half, never part of one and part of the other.
These are all things English propaganda did in an excellent manner. They
never allowed two sided arguments which might have raised doubts. They
realized the broad masses’ emotional state was primitive. They proved this by
publishing horror story propaganda that met the masses on their level.
They ruthlessly and brilliantly reinforced their moral position, which
strengthened endurance at the front despite great defeats. They were equally
vivid in their “festival” nailing-down of the German foe, portraying him as the
sole guilty party for the outbreak of the War. This was a lie, which because of
the complete and one-sided colossal boldness of its presentation, appealed to
the emotional and extreme attitude of the common people, and therefore it
was totally believed.
The effectiveness of this sort of propaganda was most noticeably shown
by the fact that after four years, it was still holding the enemy to his guns and
had started to eat away at our own people.
It was really no surprise that our propaganda was unsuccessful. It carried
the seed of ineffectiveness in its deep ambiguity. Its content alone made it
highly unlikely that it would create the impression on the masses that was
necessary for success. Only our irresponsible “statesmen” could have hoped
to generate enthusiasm in men to the point of dying for their country with this
stale, watered down pacifist tea.
This sorry product was not just useless, but harmful. All the brilliant
presentations in the world will not lead to the success of propaganda unless
one fundamental principle is always kept clearly in view. Propaganda must
limit itself to saying a very little, but saying it a lot. First and foremost, that is
the absolute important prerequisite for success.
In the field of propaganda, we must never be guided by the beauty of
propaganda itself because the expression and form of what was said would
soon only attract literary tea-parties of intellectuals instead of being suited to
the masses. Neither must it be guided in a carefree manner because the lack
of emotional freshness makes it weak and people are constantly seeking new
stimulants. Intellectuals quickly become bored with everything. They cannot
157
Mein Kampf
imagine themselves in the same place as their fellow man or even understand
his needs. These intellectuals are always the first to criticize propaganda’s
content, which they think is too old-fashioned, too stale, and too worn out.
They are always looking for something new, seeking variety and are the death
of any effective political mass recruiting. As soon as party propaganda is
organized and its substance focuses on the intellectuals’ needs, they lose their
unity and become scattered.
The purpose of propaganda is not to be a constant source of interesting
diversion for unconcerned, smart gentlemen, but to convince the masses. The
masses are slow-moving, and it may take a long time before they are ready to
even notice something. Only constant repetitions of the simplest ideas will
finally stick in their minds.
Any variations in the propaganda message must never change the
purpose of the propaganda, but should always reinforce the same conclusion.
The main slogan must be highlighted from various angles, stated in different
ways, but every discussion must end with the conclusion itself. Only then can
and will propaganda produce a unified and concentrated effect.
Only this broad approach, through steady and consistent use, will ever
pave the way to final success, and this steadfast course must never be
abandoned. It is astonishing to discover the enormous results which such
perseverance can accomplish.
The success of any advertising, whether in business or politics, depends
on perseverance and consistency. The enemy war propaganda was a perfect
model because it was restricted to a few points, targeted exclusively at the
masses, and continued with tireless perseverance. When those basic ideas and
methods of presentation were seen to be solid, they were used throughout
the war without even the slightest change. At first, the propaganda seemed
idiotic in its use of disrespectful statements. Later, it became unpleasant, then
it was finally believed.
After four and a half years, a revolution whose slogan originated in enemy
war propaganda broke out in Germany. The English understood that the
success of this weapon lies in extensive usage, and once it is successful, it more
than pays for the cost.
158
War Propaganda
The English saw propaganda as a primary weapon, while with us, it was
the last resort of employment for jobless politicians and a comfy job for those
who avoided the role of hero-soldier. All in all, its success was zero.
159
CHAPTER SEVEN
The Revolution
Enemy propaganda first came to us in 1915. From 1916 on, it became more
and more intensive and swelled until the beginning of 1918 when it grew into
an absolute flood. The effects of “dangling the bait” were seen at every step.
The army gradually learned to think the way the enemy wanted it to.
The German counter-efforts were a complete failure. The so-called
“leader” who guided the army had those around him who possessed the drive
and desire to take up the struggle of counter-propaganda, but the necessary
tools were not there and they had no means to distribute anything even if they
had produced it. It would have been a mistake psychologically for the army to
give this enlightenment to the troops. If it was to be effective, it had to come
from home. Otherwise, it was impossible to count on it being successful
among men who had suffered starvation and whose immortal deeds of
heroism and endurance had been performed for that very homeland for
nearly four years.
But what did come from home? Was the failure a result of stupidity or
evil? In midsummer of 1918, after the retreat from the southern bank of the
Marne,1 the German press started to demonstrate not only incompetence, but
criminal stupidity. I asked myself with daily and increasing disappointment if
no one at home was going to put an end to this intellectual sabotage of the
army’s heroism.
What happened in France when we swept into the country in 1914 in an
unparalleled whirlwind of victory after victory? What did Italy do while her
Isonzo front2 was collapsing? What did France do in the spring of 1918 when
160
The Revolution
161
Mein Kampf
162
The Revolution
were all still internal matters. The same man who growled and cursed would
silently do his duty a few minutes later as if it were habit. The same company
that was feeling discontented would dig into the section of trenches it had to
defend, as if Germany’s Fate depended upon this hundred yards of mud and
shell-holes. This front line was still formed by the old, magnificent “Army of
Heroes!” I would soon experience the difference between it and home in
glaring contrast. At the end of September, 1916, my division entered the battle
of the Somme.3 For us, it was the first of the huge battles that now followed,
and the impression it created is hard to describe. It seemed more like Hell than
a war. The German front held out against the whirlwind drumming of the guns
for weeks at a time. Sometimes, they were pushed back; then they would
advance again, but they never gave up.
On October 7, 1916, I was wounded.
I arrived safely at the rear and was ordered to Germany by transport
vehicle. Two years had passed since I had seen home, which was an almost
endless stretch of time to be away. I couldn’t even imagine how Germans who
were not in uniform would look. When I was in the base hospital at Hermies,4
I was startled when the voice of a German woman, a nurse, addressed a man
lying next to me. It was wonderful hearing a sound like that for the first time
in two years! The nearer to the border the train approached—which was
bringing us home—the more restless each man became. All the towns moved
past that we had ridden through two years before as young soldiers: Brussels,
Louvain, Liege. Finally, we thought we recognized the first German house by
its high gables and its striking shutters. It was the Fatherland! In October,
1914, we had been on fire with wild enthusiasm when we crossed the border.
Now, stillness and reverence ruled. We were all happy that Fate allowed us to
once again see what we were defending so fiercely with our lives.
Almost on the anniversary of my departure, I arrived in the hospital in the
Brandenberg town of Beelitz near Berlin. What a change! From the mud of the
Battle of the Somme into the white beds of this amazing structure! At first,
3 One of the largest battles in the First World War with over 1.5 million casualties at the river
Somme in northern France.
4 A farming village in France at the time.
163
Mein Kampf
one hardly dared lie on them. Unfortunately, this world was new in other ways
too.
The spirit of the front-line army wasn’t here. For the first time, I heard
something we didn’t know about at the front: someone boasting of his own
cowardice. One did indeed hear cursing and grumbling at the front, but never
to encourage the neglect of or the dereliction of duty, let alone to glorify the
coward. No, the coward was still a coward and nothing more.
On the front, he was treated with a contempt as strong as the admiration
that was felt for a true hero. But here in the hospital, conditions were almost
the reverse. The most dishonest trouble-makers and unprincipled trouble-
seekers took the floor and tried in every way with every resource of their sorry
eloquence to make the decent soldier appear ridiculous and the coward’s lack
of character a model to be emulated.
A few disgraceful fellows were the ringleaders. One said that he had stuck
his own hand into the barbed-wire entanglement so he would be sent to the
hospital. Despite the minor nature of his injury, he appeared to have been
here a very long time and was planning to stay. It appeared that an
arrangement was struck as the result of a swindle or bribe, which allowed him
to stay here, and another such act was the only reason he made it on a transit
train for Germany at all. This filthy pest of a fellow actually had the nerve to
display his own cowardice shamelessly and claim it was the result of a bravery
higher than the heroic death of the honest soldier. Many listened in silence;
others walked away; a few actually agreed.
I was disgusted within an inch of my life, but the troublemaker was calmly
tolerated in the hospital. What could anyone do? Surely the hospital office
knew who and what he was, yet nothing happened.
When I could walk again, I was allowed to go to Berlin. Hardship was
obviously very severe everywhere. Millions were suffering from hunger.
Discontent was all around. In different shelters where the soldiers visited
and in pubs the tone was the same as at the hospital. It seemed like these
fellows deliberately sought out such spots in order to spread their views.
But things were even worse, much worse, in Munich itself. When I was
discharged from the hospital after my recovery and was assigned to the
164
The Revolution
reserve battalion, I hardly recognized the city again. Anger, disgust, and
abusive talk were everywhere. In the reserve battalion itself, the spirit was
absolutely beneath contempt. One factor was the total incompetent
treatment of the active soldiers by non-commissioned training officers who
had never spent a single hour on the battlefield. For this reason, they were
only able to establish a working relationship with the battle-experienced
soldiers. The old front-line soldiers did have certain peculiarities, which were
the result of their own experience at the front lines, but these were
incomprehensible to the inexperienced officers of the reserve troops. An
officer who had himself come from the front was not puzzled by them. Such
an officer received a very different sort of respect from that given to the
officers who served at the rear away from the action or at headquarters.
Besides this, the general temper was awful. Avoidance of military service
began to be considered a sign of higher wisdom while the faithful endurance
of service became the earmark of inner weakness and partial blindness. The
government offices were full of Jews. Almost every clerk was a Jew and every
Jew a clerk. I was astonished at this multitude of “chosen people” and could
not help comparing it with their sparse presence at the front lines.
The situation in business was even worse. Here the Jewish people had
actually become “indispensable.” This spider was slowly beginning to suck the
blood from the people. In the business of “War Companies,” an instrument
had been found to gradually sweep away the national, free economy. The
necessity of creating centralized suppliers without restrictions was
emphasized. In fact, by 1916-1917, almost all production was under the
control of financial Jewry.
But at whom did the people now direct its hatred? I was horrified to see
a doom approaching which was bound to lead to a collapse if it wasn’t avoided
in time. While the Jew was plundering the whole nation and forcing it under
his domination, people were being turned against the “Prussians.” At the front
lines and at home, nothing was done by the leadership to curb this poisonous
propaganda. Nobody seemed to understand that the collapse of Prussia would
not mean the rise of Bavaria. On the contrary, the fall of one would inevitably
drag the other with it into the abyss.
165
Mein Kampf
166
The Revolution
If it was successful, the German front would break and the wish of the
Social Democratic newspaper, Vorwärts,5 that Germany would not be the
victor this time would be fulfilled. Without weapons, the front would collapse
in a few weeks. The offensive would be prevented, the political agreement
saved, and the international capital made ruler of Germany. Cheating the
people was the inner goal of the Marxist and they succeeded. It was the
destruction of the national economy in order to establish the rule of
international capital and it happened thanks to the stupidity and gullibility of
one side and the enormous cowardice of the other.
The munitions strike was not as successful as was hoped and did not
deprive the front line of weaponry and armaments. It collapsed too early for
the weapons shortage alone to condemn the army to destruction according to
plan. However, the moral damage that was done was so much worse! First,
what was the army fighting for if people at home did not even want victory?
Who were the enormous sacrifices and hardships for? The soldier is sent out
and told to fight for victory, and at home they strike against it! Second, what
was the effect upon the enemy? In the winter of 1917-18, dark clouds rose for
the first time on the Allied sky. For almost four years, the Allies leaned against
the German giant and had been unable to topple him. He had only one arm
holding a shield for defense in the West which left his sword arm free to swing
to the East and the South.
Now, the giant was finally free from his battles behind. Rivers of blood
had flowed before he succeeded in smashing one of his adversaries. Now, this
giant could turn and let the sword join the shield in the West. The enemy had
not succeeded so far in breaking down the defense; the attack would now fall
completely on him. The enemy dreaded him and feared the imminent victory.
In London and Paris, there was one meeting after another, but on the
front line, a drowsy silence reigned. The insolence of the allied leaders
suddenly sank. Even the enemy propaganda was struggling. It was not as easy
to prove the impossibility of a German victory. The same thing was also true
on the front lines. They too began to see a strange light. Their inner attitude
5 “Forward.”
167
Mein Kampf
toward the German soldier had changed. Up until now, they might have
thought he was a fool marked for defeat, but now, they were facing the
destroyer of their Russian ally. The necessary confinement of German
offensives to the East now seemed to be part of an inspired strategy.
For three years, the Germans had charged against Russia and appeared
to have no effect. People almost laughed at these pointless attempts. After
all, the Russian giant with his superior numbers must be the ultimate winner
while Germany would surely collapse from loss of blood. The evidence seemed
to justify this hope.
Starting in September, 1914, when the endless masses of Russian
prisoners from the battle of Tannenberg,6 began to march into Germany along
highways and railroads in long caravans; the stream appeared to continue
forever, but for every Russian army that was beaten and annihilated, a new
one arose to take its place. The vast Empire kept giving the Czar new soldiers
and fed the war its new victims. How long could Germany last in this race?
Wouldn’t the day come, after a great German victory, when the Russian army
reserves would prepare themselves for the final battle? And then what? In all
human probability, Russia’s victory might be postponed, but it would
eventually come.
Now, all these hopes pinned on Russia were lost. The ally who had laid
the greatest blood-sacrifices on the altar for the Allies was at the end of his
strength and lay at the feet of the merciless attacker. Fear and horror crept
into the hearts of the soldiers who, up until now, had filled their minds with
blind faith. They now feared the coming spring. If they had not succeeded in
breaking the German line when he could give only part of his energy to the
Western Front, how could they expect victory against the entire strength of
the mighty land of heroes which was gathering itself for an attack? The
shadows of defeat from the South Tyrolean Mountains7 sank uneasily on the
imagination. As far away as the fog of Flanders,8 the beaten armies of General
Cadorna created gloomy spirits and their belief in victory crumbled as they
6 A decisive battle between Russia and Germany in the early days of the First World War.
7 The Alto Adige mountain range in Italy.
8 In France.
168
The Revolution
saw a future filled with fear and defeat.9 Just as people thought they could
hear the steady rumble from advancing shock troops of the German army in
the cool of the night and when they were anxiously expecting the coming
judgment day, suddenly a glaring red light blazed from Germany, throwing its
flare into the last shell-hole of the enemy front. At the moment the German
divisions were making their final preparations for the great assault, the
general labor-strike broke out in Germany.
For a moment, the world was speechless. But then, with a sigh of relief,
the enemy propaganda grabbed this opportunity for a reprieve in the twelfth
hour. In one strike they found ways to restore the diminishing confidence of
the Allied soldiers, to call the chance of victory a certainty again, and to change
the uneasy dread of what was coming into confident determination. Now, the
regiments waiting for the inevitable German attack could go into the greatest
battle of all time with the conviction that the end of the War would be decided
not by the bravery of the German assault, but by the persistence of its own
defenses. Let the Germans win as many victories as they pleased. At home,
the Marxist Revolution was welcomed as it marched in, not the victorious
army.
The English, French, and American newspapers began to plant this belief
in the hearts of their readers, while a substantial and skillful propaganda
movement fed the morale of their troops at the front.
“Germany on the eve of Revolution! Victory of the Allies inevitable!” This
was the best medicine to set the wavering French and English on their feet.
Now, German rifles and machine-guns could be fired again, but instead
of fleeing in panic and terror, they met determined resistance and confidence.
This was the result of the strike at weapons factories. It strengthened the
enemy’s faith in victory and swept away the paralyzing hopelessness of the
Allied front. Afterward, thousands of German soldiers paid with their lives
while the originators of this dishonorable wickedness were slated to move into
the highest State offices of Germany as a result of the Revolution.
9General Luigi Cadorna led 250,000 Italian soldiers to their death in the early days of the First
World War along the Isonzo River and he achieved little or no military gains.
169
Mein Kampf
The visible effects of this act on the German troops could be overcome
for now, but on the enemy’s side, the results had a long lasting effect. The
resistance was no longer an aimless army that has given everything up for lost,
but instead the bitter intensity of a struggle for victory appeared. In all human
probability, victory would come if the Western Front could just hold out for a
few months against the German attack. The parliaments of the Allies
recognized this future chance for victory and approved the use of astonishing,
stupendous amounts of money to continue the propaganda which would
eventually undermine Germany.
It was my good fortune to have a part in the first two and the last
offensives. They are the most tremendous impressions of my life. They were
tremendous because this was the last time the struggle lost the character of
defense and took on that of attack, as it felt in 1914. The men in the trenches
and dugouts of the German army drew a deep sigh of relief now that the day
of revenge was here at last after more than three years of stubbornly resisting
the enemy inferno. Once more, the victorious battalions shouted, and they
hung the last immortal laurel wreaths on the battle flags amid the lightning
flashes of victory. Once more the songs of the Fatherland roared toward
heaven along the endless marching columns and for the last time, and, the
Lord’s mercy smiled.
In Mid-summer of 1918, stifling heat covered the front. At home people
were quarreling. Over what? Many stories circulated through the various
divisions of the army in the field. The War was now hopeless, they said, and
only fools could still believe in victory. The people had no more interest in
continuing in resistance; only the capitalists and the Monarchy wanted to
continue. That was the story from home and it was discussed on the front as
well.
At first, there was scarcely any reaction. What did we care about general
voting rights? Was that what we had fought four years to gain? It was a piece
of evil robbery to steal the war’s goal from the graves of dead heroes. The
young regiments that died in Flanders did not cry, “Long live general voting
rights,” but they shouted, “Germany ahead of all.” The difference was “small,”
but not insignificant. Those who were shouting for general voting rights were
170
The Revolution
never there when the fighting was going on. The whole political party rabble
were strangers to the front. One only saw a fraction of the “Honorable
Parliamentarians” in places where decent Germans were found.
The old soldiers who were the backbone of the front had no interest in
this new war aim of Ebert, Scheidemann, Barth, and Liebknecht.10 We could
not see why these slackers should suddenly have the right to inappropriately
claim State authority for themselves over the army’s leadership.
My personal attitude was settled from the start. I hated the whole pack
of wretched, nation-swindling party scoundrels intensely. I had realized for a
long time that with this gang it was a question of filling their empty pockets
and not of the nation’s welfare. For this purpose, they were now willing to
sacrifice all the people, and if necessary, let Germany go to her doom. In my
eyes, it was time to string them up. Giving in to their wishes meant sacrificing
the interests of the working people in favor of a set of pickpockets. Those
wishes could only be fulfilled if one were ready to give up Germany, and this
is what the great majority of the fighting army still thought. The
reinforcements from home quickly grew worse and worse. Their arrival
weakened instead of strengthened the fighting power. The young
reinforcements in particular were mostly worthless. Often, it was hard to
believe that these were sons of the same people who had once sent out their
youth to the battle of Ypres.11
In August and September, the symptoms of disintegration quickly
increased. The enemy attacked with terrible effect, but it was mild when
compared to the past defensive battles of Somme and Flanders,12 which were
blood curdling.
At the end of September, my division re-took for the third time places
which we had once stormed as young volunteer regiments. Those were some
great memories! For there, in October and November of 1914, we had
received our baptism of fire. With love of the Fatherland in its heart and a song
on its lips, our young regiment had gone to battle as if to a dance. The most
10 Social Democrats who were key figures in the German Revolution of 1918.
11 The First battle of Ypres, also called the Battle of Flanders in 1914.
12 Battlefields in France.
171
Mein Kampf
precious blood was joyfully given in the belief that this would preserve
independence and freedom for the Fatherland.
In July of 1917, we walked on this ground, sacred for us all, for the second
time. Here slept the best of our comrades, children almost, who had given
their lives for the Fatherland, their eyes glowing with enthusiastic love. We
veterans, who had marched out with the regiment long ago, stood with deep
reverence at this altar of “faithfulness and obedience unto death.” The
regiment had stormed this ground three years before. Now, it was to defend
it in a bitter battle of resistance.
With three weeks of continuous artillery, the English prepared for the
great Flanders offensive. Now, the spirits of the dead seemed to come alive.
The regiment braced itself in the filthy mud and dug into the shell-holes and
craters, unyielding, unwavering, and grew smaller and thinner, just as they
had once before at this spot. Finally, the English attack came on July 31, 1917.
Early in August we were relieved by fresh troops. What once had been
the regiment was now a few companies. They staggered back, covered with
mud, more like ghosts than men. Except for a few hundred yards of shell-
holes, the Englishman had only won death.
Now, in the fall of 1918, we stood for the third time on the ground we
had stormed in 1914. The small town of Comines,13 where we once had been
stationed on a base, was now our battlefield. The battleground was the same,
only the men had changed. The troops now talked politics, too.
The poison from home began to take effect here, as it was everywhere
else. The younger reinforcements were absolutely useless because they came
from home where they had succumbed to its effects.
On the night of October 13th to 14th the English attacked with gas on the
southern front south of Ypres.14 They used yellow-cross gas15 whose effect was
unknown to us as far as personal experience was concerned. I found out about
it firsthand that very night. The evening of October 13th, on a hill south of
13 In Belgium.
14 A Belgian municipality in West Flanders.
15 Yellow crosses were painted on gas shells to show they contained mustard gas producing
liquid.
172
The Revolution
173
Mein Kampf
174
The Revolution
to continue and began to tell us that we would now have to end the long War
and that the future of our Fatherland would face heavy burdens. The War was
lost and we were throwing ourselves upon the mercy of the victors. He also
said the Armistice was to be accepted and our trust was put in the generosity
of our enemy. By that time, I could stand it no longer. It was impossible for me
to stay in the room. Everything went black before my eyes again and I
staggered and stumbled my way back to the dormitory, flung myself upon my
cot, and buried my burning head in the blanket and pillow.
I had not cried since the day I stood beside my mother’s grave. In my
youth, whenever I was gripped by the hard and cruel hand of Fate, my
stubbornness increased. When Death took dear comrades and friends from
our ranks in the long years of the war, I would have thought it almost a sin to
complain. Were they dying for Germany or not? When I fell victim to the
creeping gas that began to eat into my eyes during the very last days of that
frightening struggle, and I suffered the horror of going blind forever, there was
a moment when I was ready to lose courage, but then the voice of conscience
thundered at me: “You miserable wretch! Who are you to whimper while
thousands of souls are a hundred times worse off than you?” So, I bore my
fate in silence. I had realized for the first time how personal suffering
disappears in the face of the misfortune of the Fatherland.
It had all been in vain. All the sacrifices and starvation were in vain; the
hunger and thirst that stretched for months without end were in vain; the
hours gripped by deathly terror in which we still did our duty were in vain; and
the death of the two million who gave their lives, it was all in vain. Surely the
graves would open up returning all the hundreds of thousands who had
marched out believing in the Fatherland? Surely they must open and send
forth the silent heroes, covered with mud and blood, as avenging spirits to the
homeland which had so outrageously cheated them of the highest sacrifice
that a man can offer to his people in this world? Was this what the soldiers of
August and September, 191421 had died for? Was this why the volunteer
regiments followed their old comrades in the fall of the same year? Was this
21 Referring to the Battle of Tannenberg where the Germans decimated the Russians.
175
Mein Kampf
why these boys of seventeen had died on the soil of Flanders? Was this the
meaning of the sacrifice that the German mother made for the Fatherland
when, with an aching heart, she sent her dearest boys out, never to see them
again? Was all of this so a mob of miserable criminals could dare to lay hands
on the Fatherland? Was this why the German soldier, exhausted by sleepless
nights and endless marches, hungry, thirsty, and frozen, had stood fast
through burning sun and driving snow? Was it for this he had gone through
the inferno of continuous artillery fire and the fever of gas attacks, never
yielding, always remembering the single duty to guard the Fatherland from
enemy invasion? Truly, these heroes deserved a monument that says:
“Stranger, when you travel to Germany, tell them that we lay here, faithful to
the Fatherland and obedient to duty.”22 But was the supreme sacrifice all we
must consider? Was the Germany of the past worthless? Do we have any
obligation to our own history? Were we still worthy enough to take on
ourselves the glory of the past? And how could this deed be justified to the
future? These are immoral and miserable criminals! The more I tried to
understand this outrageous event, the more my cheeks burned with
indignation and shame. The pain of my eyes was nothing compared to this
wretchedness. Awful days and worse nights followed. I knew that all was lost.
Only fools or these liars and criminals could hope for the enemy’s mercy.
During those nights, hatred grew—hatred for the perpetrators of this deed.
In the next few days, I became aware of my own Fate. I had to laugh when
I thought of my personal future, which had caused me so much worry only a
short a time ago. It was funny to think of building houses on this ground.
Finally, I realized that the thing I had dreaded so often, the thing which was
inevitable had happened, but I did not have the heart to believe it.
Emperor William II had been the first German Emperor to offer the hand
of reconciliation to the leaders of Marxism, not dreaming that those crooks
have no honor. While they grasped the Imperial hand with their left hand, the
other hand was reaching for the sword. With the Jew there can be no
22
These words are paraphrased from the monument erected at Thermopylae in Greece to the
memory of Leonidas and his Spartan soldiers.
176
The Revolution
177
CHAPTER EIGHT
Beginning of
My Political Activity
By the end of November, 1918, I was back in Munich. I went to the reserve
battalion office of my regiment, which was in the hands of the new “Soldiers’
Councils.” The whole administration was so disgusting to me that I decided to
leave as quickly as possible. With a faithful friend of the campaign at my side,
Ernst Schmidt, I traveled to Traunstein1 and remained there until the camp
was broken up.
In March of 1919, we went back to Munich. The situation there was shaky
which threatened to continue the Revolution. Eisner’s death only hastened
the development and it finally led to the dictatorship of the Councils.2 Or,
more accurately put, to a temporary Jewish domination which was the original
goal of those who created the Revolution.
At that time, plans bounced back and forth in my head. For days, I
considered options and thought about what could possibly be done, but the
result of every train of thought was the sober realization that no one knew me
and I did not have the means to actually do anything. Later I will explain the
reason why I could not even make up my mind which of the existing political
parties to join.
During the new Revolution of the Councils, for the first time, I behaved in
a way that the Central Council found annoying. The later result was that I was
to be arrested early in the morning of April 27, 1919, but the three fellows
178
Beginning of my Political Awakening
who came for me did not have enough courage when facing the muzzle of my
rifle to complete their task and ran off as quickly as they came.
A few days after the “liberation” of Munich, I was ordered to appear
before the Commission of Investigation to discuss the revolutionary events in
the Second Infantry Regiment. This was my first, somewhat, purely political
activity.
Within a few weeks, I received orders to attend a “course” or a series of
lectures which was being held for members of the military forces. Here, a
soldier was supposed to receive a definite foundation for his thinking as a
citizen. The only value in the performance to me was that it gave me a chance
to meet like-minded comrades with whom I could discuss the real situation at
hand. We were all firmly convinced that Germany could no longer be saved
from the coming catastrophe, certainly not by the parties who committed the
November crime,3 the Center Party and the Social Democratic Party. Even if
they had the best intentions in the world, the so-called “privileged class
Nationalist” organizations could never correct what had already been done.
They lacked the full set of necessary fundamentals and without them,
such a task could not succeed.
Time has shown that our view was correct.
In our little circle, we discussed the formation of a new Party. The basic
ideas we had in mind were the same that were later realized in the “German
Workers’ Party.”4 The name of the movement to be founded must help us
reach the broad masses from the very beginning. Without the ability to reach
the masses, the whole task would be senseless and unnecessary. We hit on
the name “Social Revolutionary Party” because the social views of the new
organization actually constituted a revolution.
But there was also a much deeper reason for the name. Attentive as I had
always been to economic problems, my focus had been confined to the social
problems. Only later were the bounds of my attention extended as I examined
the Triple Alliance.5 This alliance was mostly the result of a poor assessment
179
Mein Kampf
of the economic system, as well as a vagueness about the basis on which the
German people could be sustained in the future. All these ideas rested on the
opinion that money was only the product of labor, and finances could be
corrected by adjusting issues that helped or hurt human activity. In fact, this
unexpectedly revealed the true role of money because it depended
completely on the greatness, freedom, and power of the State and people.
This dependency requires financial sectors to actively support the State and
people. It is a matter of instinct and self-preservation for the improvement of
its own development. The necessary dependence of finances upon the
independent free State would compel financial sectors to work for this
freedom, power, and strength of the nation. This made the duty of the State
toward finances comparatively simple and clear. It only had to be certain that
capital remained a servant of the State and did not become the master of the
people. The expression of this attitude could then remain within two boundary
lines: preservation of a healthy, independent national economy on one side,
and the safeguarding of the wage-earner’s social rights on the other.
Previously, I did not realize there was a difference between capital as the
result of work and a capital derived from speculation investments—not until I
received a push in the right direction. This push was by one of the various
gentlemen who lectured in the previously mentioned course, Gottfried Feder.6
For the first time in my life, I heard a basic outline explaining the workings
of international finance and loan capital. When I heard Feder’s first lecture,
the idea instantly flashed through my mind that I had now found my way to
accomplish one of the key essentials needed in the foundation of a new party.
In my mind, Feder’s merit was demonstrated in his ruthless and vigorous
method of describing the double character of the finances used in stock
exchanges and loan transactions. He laid bare the fact that this capital is
always dependent on the payment of interest. His explanations of all the basic
questions were so sound that from the start, his critics did not dispute the
theoretical correctness of the idea but they doubted the possibility that it
6 An economic theoretician who was later a key member and guided the Nazi party.
180
Beginning of my Political Awakening
181
Mein Kampf
182
Beginning of my Political Awakening
something important for posterity. The greater the future will be for a man’s
work, the less the present can grasp it, the harder the battle will be, and the
rarer success will be found. If success does smile on one man in centuries, a
glimmer of the coming glory may possibly surround him in his old age.
Even so, these great men are just the marathon runners of history. The
glory of the present only rests upon the brow of the dying hero. We must
count these men as the great warriors of this World. Those are the men who
are not understood by the present, but who are nevertheless ready to fight to
the end for their ideas and ideals. They are the ones who will someday be
closest to the people’s hearts. Each of these individuals felt it was his duty to
repay the wrongs which great men have suffered at the hands of their
contemporaries. Their lives and their work are then studied with touching and
grateful admiration. In dark days of distress, such men have the power to heal
broken hearts and elevate the people from their despair.
To this group belong not only the genuinely great statesmen but all the
great reformers as well. Besides Frederick the Great7 we have such men as
Martin Luther and Richard Wagner.
When I heard Gottfried Feder’s first lecture on “Breaking the Slavery of
Interest,” I immediately knew that this was a theoretical truth which was of
huge importance for the future of the German people. The separation of
finance capital from the national economy made it possible to oppose the
internationalization of the German economy without threatening national
self-preservation. I saw Germany’s development much too clearly not to have
known that the hardest struggle would have to be fought against international
capital and not against hostile people. In Feder’s lecture, I heard a mighty
rallying cry for this coming struggle.
Subsequent developments showed how right our feeling was. Today, we
are no longer laughed at by our deceptive, privileged-class sly-boots
politicians. Today, if they are not deliberate liars, even they see that
international finance capital not only took the lead in nurturing the War, but
7 Friedrick II, from the Hohenzollern dynasty, who united much of the Prussian dynasty.
183
Mein Kampf
especially after the struggle has ended it is doing everything possible to make
the Peace into a Hell.
The struggle against international finance and loan capital interest has
become the most important point in the program of the German nation’s
economic independence and freedom. For those practical people who may
object, I offer these answers: All apprehensions about the economic
consequences that would follow the abolition of the slavery that results from
interest-based financing capital are not valid because in the first place, the
economic principles that we have previously followed already proved to be
quite disastrous to the interests of the German people.
The comments by the authors of those plans on questions of self-
preservation strongly remind us of the past verdicts passed out by similar
“experts” such as the Bavarian Medical Faculty regarding the question of
introducing the railroad. We now know that none of this exalted body’s fears
have happened since riders of the new “steam-horse” did not become dizzy,
spectators watching the train pass were not made ill, and the board fences
intended to hide the new invention are gone. All that is left are invisible
blinders on the so-called “experts” and those will always be there.
In the second place, we should remember that any idea becomes
dangerous if it presumes to be an end in itself, but in reality, it is just a means
to an end. For me and all true National-Socialists, there is only one doctrine:
Folk and Fatherland. We must fight to assure the existence and the growth of
our race and our nation. We must feed our children and keep our blood pure.
We must fight for the freedom and independence of the Fatherland so that
our nation may grow and fulfill the mission given to it by the Creator of the
Universe.
Every ideal and every idea, every teaching and all knowledge must serve
this purpose. It is from this perspective that we must judge everything and use
it or discard it according to its suitability for our purpose. In this way, a theory
can never harden into a deadly doctrine since it must all serve the common
good.
The insight of Gottfried Feder led me to deep study in a field where I
previously had little knowledge. I resumed the process of learning and came
184
Beginning of my Political Awakening
to realize for the first time the purpose behind the life work of the Jew, Karl
Marx. Now, I really began to understand his currency, the capital he used, as
well as the struggle of Social Democracy against the national economy—a
struggle that was meant only to lay the groundwork for the rule of true
international finance by interest-based money.
In another respect, these courses had a great effect upon my later life.
One day during the course, I asked for the floor in a discussion after one of the
men attending the course felt compelled to break a lance for the Jews and
defended them at great length. This aggravated me so much I had to reply.
The overwhelming majority of those present were on my side. The result was
that a few days later I was assigned to a Munich regiment as an “education
officer.”
The discipline of the troops at that time was still fairly weak. They
suffered from the after-effects of the Soldiers’ Council. The introduction of
military discipline and subordination in place of “voluntary obedience,” a term
for the filth under Kurt Eisner,8 had to be implemented very slowly and
cautiously. The troops themselves had to learn to feel and think as Nationalists
and be patriotic. My new focus was pointed in those two directions.
I happily began my task. Suddenly, I had an opportunity to speak before
large audiences. What I had always felt and assumed to be true was now being
proven—I could “speak.” My voice had improved enough so that people could
always understand me, at least in the small squad room.
No task could have made me any happier. Now, before being discharged,
I could do a useful service for the institution which had been so close to my
heart, the army. I can say my talks were a success. During the course of my
lectures, I led hundreds, probably thousands, of my comrades back to their
Folk and Fatherland. I “nationalized” the troops and was able to help
strengthen the general discipline.
In the process, I became acquainted with a number of comrades, who
believed as I did and later formed the center of the new Movement.
8 Who led the Marxist revolution in Bavaria and was Premier until 1919.
185
CHAPTER NINE
One day, I received orders to find out about a political organization going
under the name of “The German Workers’ Party,” which had scheduled a
meeting in a day or two where Gottfried Feder was to speak. I was to attend,
The army’s curiosity in regard to political parties was more than
understandable. The Revolution gave the soldiers the right to take part in
politics, and it was the most inexperienced men who were now making full
use of it. Until the Center Party1 and Social Democratic Parties2 realized to
their distress that these men were beginning to turn away from the
Revolutionary party aims and turn toward the national movement; did they
think it was appropriate to deprive the troops of their right to vote and forbid
their involvement in political activity? It was obvious that the Center Party and
Marxism would resort to this measure because if they had not cut off “civil
rights,” which is what they called the political equality of the soldier after the
Revolution, then within a few years, there would have been no November
State left and no more national shame and humiliation that came with it. The
troops at that time were well on the way to freeing the nation from its blood-
suckers as well as the politicians inside the government who were tools of that
political agreement. The fact that even the so-called “nationalist” parties
voted enthusiastically for this doctrine of the November criminals,3 without
regard to its true meaning, and thus helped to squelch the tools of a national
revival, which should have been the nationalists’ goal, showed once more that
1 A Catholic-based party.
2 The Marxists.
3 To reverse soldiers’ right to vote.
186
The “German Workers’ Party”
the inflexible attachment to an idea that is purely abstract can lead the gullible
away from their own goals. Suffering from total intellectual deterioration, this
privileged-class party seriously believed the army would again become a
stronghold of German bravery. The real goal of the Center Party and Marxism
was to cut out the dangerous nationalist fangs of the military. But without the
ability to bite, an army becomes the police, not a body of troops that can do
battle with the enemy. This is something which later events proved fully.
Did our “national politicians” think the army could have developed in any
way other than becoming nationalistic? That would be just the style of these
gentlemen. That is what happens when someone spends the war as a windbag
parliamentarian and not as a soldier. They lose any sense of what is going on
in the hearts of men. The hearts in the army are filled with a stupendous past
reminding them that they were once the best soldiers in the world.
So, I resolved to attend the previously mentioned party meeting since I
was not familiar with them and had not heard of them before. When I arrived
that evening and went to the back room of the former Sternecker Brewery
beer-hall, which is now a place of historical significance, there were about
twenty or twenty-five people, mostly from the lower class.
I was already familiar with Feder’s lecture through the courses I had
taken, so I focused primarily on observing the society itself. It did not make a
good or bad impression on me. It was just another new organization. Those
were the days when anyone who was dissatisfied with previous developments
and had lost confidence in the existing parties thought he should start a new
party. Such societies sprang up like mushrooms everywhere, but disappeared
without a squeak after a short time. Most of the founders did not have the
slightest idea what it meant to turn a social gathering into a political party, let
alone a movement. So, the groups they founded almost always drowned in
their own ridiculous pettiness.
After listening for about two hours, I decided that the “German Workers’
Party” could be lumped in with the rest. I was glad when Feder finally finished
speaking. I had seen enough and was getting ready to go when they
announced there would be an open discussion. With that, I was persuaded to
stay awhile longer. Nothing of any consequence happened here until suddenly
187
Mein Kampf
188
The “German Workers’ Party”
me to read. So, I began to read it. It was a small pamphlet in which the author
—this very workman who gave it to me—described how he had escaped the
Marxist and trade-union slogans and returned to thinking on nationalistic
lines. The title was “My Political Awakening.” Once I started reading, I
consumed the pamphlet with interest all the way through. It described a
process which reminded me of the one I had gone through twelve years
before. I recalled my own development again. I thought about the matter
several times throughout the day and was ready to put it aside again, when,
less than a week later, I received a post-card stating that I been made a
member of the German Workers’ Party. The card asked what I thought about
this and would I please come and share these thoughts at a committee
meeting of the party the following Wednesday.
I must say, I was more than astonished at this method of “recruiting”
members, and did not know whether to be annoyed or amused. I would not
have dreamed of joining an existing party; I intended to found my own. This
request was really out of the question for me. I was about to send my answer
to the gentlemen in writing when I was overcome with curiosity and I decided
to go on the scheduled day to explain my reasons in person.
Wednesday came. The pub where the meeting was to take place was the
Altes Rosenbad4 in the Herrnstrasse5 area, a very shabby place where
somebody might wander by mistake once in a blue moon. That was not
surprising in 1919, at a time when the menus of even the larger restaurants
had only the most humble and sparse offerings. But this particular pub, I had
never even heard of before.
I went through the dim front room, discovered the door to the back room,
and found myself in the presence of the “meeting.” In the faint glow of a half
functioning gas light, four young men were sitting around a table. Among
them was the author of the little pamphlet, who immediately and excitedly
greeted and welcomed me as a new member of the German Workers’ Party. I
was rather surprised at this. I was told that the real “national chairman” had
not yet arrived and I decided to save my explanation for everyone at once.
189
Mein Kampf
Finally, he showed up. He was the chairman from the meeting at the
Sternecker Brewery when Feder had lectured.
While waiting, I had become curious again and waited to see what would
happen. Now, at least, I found out the names of the various gentlemen. The
chairman of the “national organization” was Karl Harrer and, the Munich
chairman, Anton Drexler.6
The minutes of the last meeting were now read, and a role call of
confidence in the secretary was passed. Then it was the treasurer’s turn to
read his report. The finances of the organization totaled all of seven marks and
fifty pfennigs and for this, general confidence was expressed for the treasurer.
This was also recorded in the minutes. Then, the chairman read aloud letters
they had prepared in reply to past correspondence. One was a letter to Kiel,
one to Dusseldorf, and one to Berlin. These were unanimously approved. Then
the incoming mail was recorded and consisted of a letter from Berlin, one from
Dusseldorf, and one from Kiel, whose arrival seemed to be received with great
satisfaction. This increasing correspondence was declared to be an excellent
and visible sign of the spreading importance of the “German Workers’ Party.”
Then, there was a long discussion regarding the reply letters to be written in
answer to the newly received correspondence.
Awful, just awful! This was a small-town club of the worst kind and this
was what I was supposed to join? The new members were offered the floor
for consideration of their membership. In other words, my capture in their
trap was complete.
I began to ask questions, but I found that other than a few guiding
principles, there was nothing—no program, no printed material at all, no
membership card, not even a humble rubber stamp of the party seal. All I saw
was good faith and good intentions.
I had lost my desire to laugh at these happenings. This was all a sign of
total confusion and complete discouragement, which was common to these
parties with their programs, purposes, and their activities. The deep feeling
6A machine and railway worker and a member of the völkisch movement offshoot which was
anti-Semitic. He, together with journalist Karl Harrer, founded the German Workers’ Party
(DAP) in Munich with Gottfried Feder and Dietrich Eckart in 1919.
190
The “German Workers’ Party”
that drew these few young men together into this ridiculous meeting was a
result of their inner voice which, more instinctively than consciously, made all
past party activities seem useless for the nationalist revival of Germany or for
the cure to its inner ailments, which were caused by those controlling the
internal affairs of the State. I quickly read over the basic principles, which were
in typewritten form, and I thought they revealed that these souls were
searching and longing for answers rather than showing any knowledge of the
battle that needed to be fought. Much of it was vague or uncertain and a lot
was missing, but it was obvious they were looking for truth. What inspired
these men was something that had been deep inside me too. It was the
longing for a new movement which should be more than a party in the old
sense of the word.
When I went back to the barracks that evening, my opinion of the
organization was clear. I was faced with probably the most difficult question
of my life: Should I join or should I decline? My reason advised me to refuse,
but I had a restless feeling and the more I tried to convince myself the whole
club was nonsense, the more I felt inclined to favor it. I could not rest for the
next few days.
I began to argue back and forth with myself. I had decided to become
politically active a long time ago. I was also convinced that a new movement
was necessary, but my impulse to act had been lacking. I am not one of those
who start something today, then forgets about it the next day or switches over
to something new. My very conviction was the main reason it was so hard for
me to decide to join a new organization. This organization either had to grow
to be everything I saw it should be or else was better left alone. I knew I was
making a decision forever and there could be no turning back. For me, it was
no temporary plaything, but a deadly serious undertaking. I have always had
an instinctive dislike for people who start everything and finish nothing.
To me, such a jack-of-all-trades was to be loathed. I thought what they
did was worse than doing nothing.
This was one of the main reasons why I could not decide as easily as
others when it came to start something because it must either become
everything or otherwise be conveniently left undone. Fate itself now seemed
191
Mein Kampf
to give me a sign and point me down the right road. I would never have joined
one of the existing large parties, and will explain my reasons in a moment. I
felt this ridiculous little creation with its handful of members had one
advantage in that it had not yet hardened into an “organization.” Instead, it
still gave the individual a chance for real personal input and activity. Here, a
man could still accomplish some effective work, and the smaller the
movement was, the greater the chance of forming it into the right shape. Here,
in this group, its character could still be formed, which was out of the question
from the start with the existing big parties.
The longer I considered, the more convinced I became that a small
movement like this would serve as an instrument of national resurgence. This
could never happen with one of the parliamentary political parties which clung
far too tightly to old ideas, because they profited in the structure of the new
regime. What must be declared here was a new World-Concept, and not a
new election slogan.
Still, it was a frightening and difficult decision to try to turn a purpose into
reality. What tools could I bring to the task? Being poor and without resources
was the least of my troubles. A greater problem was that I was unknown. I was
one of the millions whom Chance could let live or die without even his nearest
neighbors noticing. In addition, there was the problem that I had never
completed my schooling.
The so-called “intelligent people” look down with unlimited
condescension on anyone who has not been dragged through the required
schools so that he has the necessary knowledge pumped into him. After all,
nobody ever asks, “What can the man do?” but, “What has he learned?” The
“educated” people will like the greatest idiot if he is covered in enough
diplomas while they will care nothing for the brightest boy who does not have
those precious wrappings. So I could easily imagine how the “educated” world
would receive me. My only mistake was in thinking men are a little better than
they actually are. True, the exceptions shine even brighter because of who
they are. For my part, I learned to distinguish between those who are endlessly
preparing for the real world through schooling and the men of real ability who
can take action.
192
The “German Workers’ Party”
193
CHAPTER TEN
The fall of any group is always measured by the distance between its present
position and its original position. The same thing holds true for the downfall
of races and states. This makes the original position highly important. Only
what rises above the ordinary limits can be noticed in its fall. The collapse of
the Second Reich was so hard and so horrible to every thinking and feeling
person because the fall came from a height which today, in the face of our
disastrous present humiliation, is hard to even imagine.
The very founding of the Reich seemed to be made golden by the magical
happenings that elevated the whole nation. After a victorious and unequaled
journey, an Empire grew for their sons and grandsons as the ultimate reward
for immortal heroism. Whether consciously or unconsciously, the Germans
felt that the noble way it was founded raised this Empire higher than any other
state. Its existence was not due to parliamentary maneuvers to jockey above
the standing of other states. It was not in the small talk of a parliamentary
argument, but in the thunder and roar of the battlefront around Paris that the
solemn act took place. This was a demonstration of the will of the Germans,
princes and common people, who sought to form one Empire for the future
that would once more exalt the Imperial Crown as a great symbol. It was not
done by a knife in the back. Deserters and traitors were not the founders of
Bismarck’s State; it was built by regiments at the front lines.
This unique birth and fiery baptism alone were enough to surround the
Empire with a glow of historic glory that few of the oldest states could claim.
What a rise began from that point! Freedom from the outside world gave
us independence and a means for creating our own daily bread on the inside.
The nation grew in number and in wealth. The honor of the State and the
people was guarded by an army, which was the most powerful demonstration
194
Causes of the Collapse
of the difference between the new unified Empire and the old German
Confederation.
The downfall which has overtaken the Empire and the German people is
so deep that everyone seems dizzy and dumbfounded. People can barely see
in their mind’s eye the old heights of the Empire because today’s disgrace is
such a contrast to the unreal dreams of yesterday’s greatness and
magnificence. It is natural enough for people now to be so blinded by the past
splendor that they forget to look for the reason behind the great collapse.
There must have been a symptom in some form that caused the collapse.
This is true only for those to whom Germany was more than just a place
to live and make and spend money. Those who truly valued the Empire can
feel the present state of collapse. To the others, it is the fulfillment of their
long-hoped-for silent wishes.
The warning signs predicting the collapse were present and clearly visible
in the early days. Few people tried to learn anything from them. Today, this is
more necessary than ever. A disease can only be cured if it is diagnosed. The
same is true when it comes to curing political ills. The visible symptoms of a
disease, which is easy to see, is more easily identified than the inner cause.
This is also the reason why so many people never move beyond the
recognition of symptoms. They confuse the symptoms of the political disease
with the cause. They may even try to deny the existence of the cause. Even
now, most of us see the German collapse as the cause of our general economic
distress, but that is actually the result which came with the German collapse.
To truly understand this catastrophe, almost everyone has to personally suffer
his share of the burden, and that is why every individual looks upon the
current economic troubles as the cause of the State’s problems. The great
masses are far less capable of recognizing the collapse in its political, cultural,
and moral aspects. This is why many people’s instinct and understanding are
both at a complete loss.
Some might say that this is only true of the great masses, but the fact that
even in intellectual circles, the German collapse is primarily seen as an
“economic catastrophe” and can be fixed by economic means is one of the
reasons why no recovery has yet been possible. Only when we realize the
195
Mein Kampf
196
Causes of the Collapse
its victory banner back this time! And now, the defeat is supposed to be the
cause of our collapse? Of course it would be quite pointless to argue with such
a group of forgetful liars. I would not waste words on it if this nonsense were
not unfortunately repeated by so many thoughtless people who have no real
hatred or intention to deceive. They merely parrot what they read. This
discussion is intended to furnish our followers— our warriors of
enlightenment— with the weapons which will be necessary when the spoken
word is twisted in its meaning, often even before one can get it out of his
mouth.
Here is the reply that should be given to anyone who says that the loss of
the war was responsible for the German collapse: True, the loss of the War
had dire consequences for the future of our Fatherland. Yet, the loss is not a
cause but only a result of other causes. It was always perfectly clear to every
intelligent and honest person that failure would be the outcome of this life-
and-death struggle. Unfortunately, there were also people who failed to see
this at the right time. There were also those who first questioned then denied
the truth. These were the ones who suddenly understood too late the
catastrophe their collaboration had helped to cause. And there were those
who denied the truth after their secret wish was fulfilled even though they
knew better. All of these people were guilty of causing the collapse, not the
lost war, as they suddenly chose to say or pretended to know. The loss of the
war was the result of their activity and not the result of “bad” leadership as
they now try to claim. The enemy was no coward; he, too, knew how to die.
He had more soldiers than the German army from the start, and the arsenals
and armory factories of the whole world were available to him.
Therefore, the German victories that were steadily gained through four
long years against the world were due solely to superior leadership as well as
the heroism of our soldiers. The organization and direction of the German
army were the most tremendous things the world had yet seen. Their faults
were no more than the limits of human fallibility. The army’s collapse was not
the cause of our present misfortune, but only the result of other crimes. This
result ushered in another and more visible collapse.
197
Mein Kampf
This collapse is shown from the following analysis: Does a military defeat
automatically mean a complete breakdown of a nation and a state will be the
result? Since when has this been the result of an unsuccessful war? Are
nations ever destroyed by lost wars and that alone? The answer in short is
“yes,” if their military defeat reflects these people’s inner rottenness,
cowardice, lack of character, and unworthiness. If this is not the case, the
military defeat would instead be the drive that leads to a new and greater
advancement rather than the gravestone of a people’s existence. History
offers endless examples to prove this statement.
Unfortunately, the military defeat of the German people is not an
undeserved catastrophe, but a deserved punishment of Eternal revenge. We
more than earned that defeat. It is simply the obvious outward symptom of
decay resulting from a series of inner problems. They may have been hidden
from the eyes of the average men or those ostrich-like people who refused to
see the obvious and stuck their heads in the sand.
Consider how the German people received this defeat. Didn’t many
groups welcome the misfortunes of the Fatherland joyfully and in the most
shameful ways? Who could act like this without bringing down vengeance on
his head for his attitude? Didn’t they go even further and boast that they
finally made the war-front collapse? It was not the enemy who disgraced us.
Oh no, the German’s own countrymen put this shame on our heads! Was it
unjust for disaster to follow them after their actions? When has it ever been
customary to take full blame for a war oneself? What people would accept
such guilt even though they have better sense and know the truth to be
different! No, and again no. How the German people received its defeat is the
best sign that the true cause of our collapse has to be found somewhere other
than in the military loss of a few positions on hilltops or the failure of an
offensive. If the front lines had really given way and if a military misfortune
had caused the Fatherland’s catastrophe, the German people would have
received the defeat in a completely different way. They would have borne the
disaster that followed with clenched teeth or have grieved about it,
overpowered by agony. Their hearts would have been full of rage and anger
against the enemy that was victorious merely through the double-cross of
198
Causes of the Collapse
Chance or the will of Fate. Like the Roman Senate, the nation would have gone
to meet the beaten divisions carrying the thanks of the Fatherland for their
sacrifice and begging them not to lose hope for the Empire. Even the surrender
would have been signed with the calm intellect of the brain, while the heart
would have pounded as it already looked toward the revival to come.
That was how a defeat would have been received that was due to Fate
alone. There would have been no laughing and dancing, no boasting of
cowardice and no glorifying defeat, no jeering at the fighting troops and
dragging their flag and medals in the mud. Above all, things would never have
come to pass which caused an English officer, Colonel Repington,2 to say
contemptuously, “Every third German is a traitor.” No, this disease would have
never risen to the choking flood that for the past five years has drowned the
last remnants of the world’s respect for us.
This is what best proves the statement that the lost war is the cause of
the German collapse and the enormous lies of Jewry and its army of Marxists to put
the blame for the collapse on the very man who was trying single-handed with
super-human energy and will-power to prevent the catastrophe he had
foreseen, and to spare the nation from its deepest degradation and shame.
Ludendorff3 was branded as guilty for the defeat and with this act, the
weapon of moral righteousness was snatched from the hand of the only
accuser who was dangerous enough to have risen up against the betrayers of
the Fatherland and brought them to justice. Here they were acting on the true
principle that within a big lie, a certain fraction of it is always accepted and
believed. At the bottom of their hearts, the great masses of a people are more
2 Retired Colonel Charles Repington, a British war correspondent for the Times, who first
coined the phrase World War.
3 A well-known German general who created the Dolchstoßlegende, the Stab-in-the-back
theory that Germany was betrayed and because of this lost WWI; he was also a proponent of
propaganda, an anti-Marxist and anti-Semitic who held Adolf Hitler in high regard.
199
Mein Kampf
200
Causes of the Collapse
201
Mein Kampf
202
Causes of the Collapse
It meant that the virtues of idealism had moved to second place behind
the value of money. It was clear that once we set out on this path, the warrior
nobility must soon take a secondary position to the financial nobility.
It is easier to find success in financial operations than military operations.
There was no longer any attraction for the real hero or statesman who did not
care to be thrown together with the first stray Jewish banker. The really
deserving man no longer had any interest in being presented with cheap
decorations.8 Instead he declined them with a simple thanks. The purity of
blood was an even more gloomy matter in this decline. More and more, the
nobility lost the essential racial element required for its existence. For many
of them, the name “ignobility” would have been far more suitable.9
A serious sign of economic decay began with the slow disappearance of
personal control over property and the gradual transfer of the entire
economic system into the hands of stock-controlled corporations. Labor had
become an object of exploitation and speculation for deceitful stockbrokers
with no conscience. The transfer of property from the wage-earner to the
financiers grew out of proportion. The stock exchange began to triumph, and
slowly but surely, started to take the life of the nation under its protection and
control.
The German economic system had already started down the road of
internationalization when it began issuing shares of stock. German
industrialists made a determined effort to save the system, but it eventually
fell before the united attack of money-grabbing financiers who fought this
battle with the help of their most faithful friend, the Marxist movement.
Marxism launched a constant and visible war on German heavy industry
to turn it into an international business. This could only be accomplished
through the victory of Marxism in the Revolution. As I write this, the attack
has succeeded against the German Government Railways, which are now
being handed over to International financiers. This “International Social
Democracy” has once more accomplished another of its great objectives.
203
Mein Kampf
We can see how far this attempt to make “economic animals” of the
German people succeeded from the fact that after the war, one of the leading
minds of German industry, and especially of commerce, said that only
economic improvement could possibly put Germany on her feet again. This
nonsense was spouted at the same time by France who was restoring the
German education system, a “humanitarian” gesture, in order to promote the
belief that the nation and the State owe their survival to economics and not
to eternal values. This remark of Stinnes10 regarding commerce as the only
savior for Germany caused incredible confusion. It was picked up at once by
all the babbling and idiotic bums Fate had unleashed on Germany as
“statesmen” after the Revolution.
One of the worst signs of decay in Germany before the war was the habit
of doing everything halfway. It comes from people being timid in their actions
as well as from a cowardice growing out of this and other causes.
The disease was made worse by the education system. German education
before the war had an extraordinary number of weaknesses. It was very one-
sided and aimed to produce pure “knowledge” to the exclusion of teaching
practical ability. Even less value was attached to the development of individual
character, at least as much as it is possible to teach character, and there was
little encouragement to learn responsibility and no cultivation at all of will and
determination. The result was not to produce strong men but passive
“Polymaths.”11 This is how the world saw and treated Germans before the war.
The German man was popular because he was very useful as a result of his
knowledge, but he was not respected because of his weak character. For this
reason, he was the quickest of almost all peoples to lose or forget his
nationality of the Fatherland when he traveled outside the country. The
common saying, “He who travels with hat in hand can go the whole width of
the land” tells the entire story.12
204
Causes of the Collapse
205
Mein Kampf
Monarchy. It is truly rare that monarchs are the flower of wisdom and reason
or even of character, even though people may choose to pretend they are.
Only the professional boot-lickers who win favor through flattery believe
this, or at least pretend it is true. Upright men are the ones most valuable to
the State and they cannot help but be repelled by the nonsense of such “wise-
monarchs.” For them, history is history and truth is truth, even where
monarchs are concerned. The people are rarely fortunate enough to have a
great man as a great monarch and if they do, they must realize they are lucky
that the cruelty of Fate has spared them from the absolute worst monarch.
The value and meaning of the Monarchy concept cannot lie in the
monarch himself unless Heaven decides to put the crown on the brow of such
an inspired hero as Frederick the Great or such a wise character as William I.
Such leaders may find their way to the top once in centuries, but rarely more
often. The idea of a Monarchy should be above the person, then the system
exists totally in the institution. This means the monarch himself is one of those
who must serve the Monarchy. He is but a wheel in the machine and must do
his duty to it. He must also adjust to the office so he can follow the higher
purpose. Therefore, the true “monarchist” is not the man who silently allows
the wearer of the crown to violate it, but prevents any violation. If the
significance of the Monarchy were not in the idea but in the “sacred” person
who wears a crown, the establishment of an obviously insane prince could
never be questioned and he could never be removed.
It is necessary to establish this as a fact because lately, those figures
whose sorry attitudes were in part to blame for the Monarchy’s collapse have
come out of hiding again. With a certain naive shamelessness, these people
start talking about “their King.” This is the same king they disgracefully
deserted at a critical moment only a few years ago. Now they call anyone who
refuses to join in their chorus of lies a bad German. Yet these are the very
same chicken-heart cowards who scattered and fled in 1918 to the red arm-
band of Marxism. They left their King to look out for himself as they hastily
exchanged their sharp weapon for a walking stick, put on neutral neckties, and
vanished without a trace or tried to mix in among peaceable civilians. In an
instant these royal champions were gone. It was only after the revolutionary
206
Causes of the Collapse
hurricane had begun to die down that they could shout “Hail to the King, all
Hail.” These “servants and counselors” of the Crown begin to make a cautious
appearance again but only after others had suppressed the Revolution and
taken a bloody nose for it. Now, they are all here again, gazing longingly at the
luxurious life. They are once more filled with excitement, energy, and devotion
for their King. At least until the day when the first red arm-band appears again
and the whole crew of profit seekers from the old Monarchy once more
scatters like mice from a cat! If the monarchs were not responsible themselves
for these things, we could only pity them heartily. But the monarchs
themselves must realize that thrones can be lost with knights such as these,
but never won.
Such slavish submission was a weakness of our whole system of
education and the results in this situation were especially disastrous. Thanks
to it, these sorry figures could maintain themselves at all the royal courts and
gradually undermine the foundation of the Monarchy. When the pillar started
to shake, the entire structure collapsed and was gone with the wind. Naturally,
belly crawlers and selfish flatterers are not going to wait to be killed for their
master. Monarchs never see this and almost never bother to learn it; this has
always resulted in their ruin..
207
Mein Kampf
208
Causes of the Collapse
209
Mein Kampf?13
13
The League of Nations resulted from the Treaty of Versailles after the First World War and
was meant to maintain peace.
210
Causes of the Collapse
because they hoped to win the favor of this pest by flattery, by recognizing the
“value” of the press, its “importance,” its “educational mission,” and other
such nonsense. All of this the Jews accepted with a sly smile, giving devious
thanks in return.
This shameful powerless display by the State was not so much due to its
failure to recognize the danger as it was to a cowardice that cried to Heaven
for relief and the resulting half-hearted effort behind every decision. No one
had the courage to use a radical remedy that would completely solve the
problem. Here, as everywhere, people fooled around with weak half-cures.
Instead of stabbing the heart of the problem, they merely provoked the viper.
This resulted in the countermeasures staying the same, but the power of
the groups that should be combated grew from year to year.
The resistance of the German government in those days against the
mostly Jewish press, which was slowly corrupting the nation, lacked any direct
determination, and above all, it had no visible goal. The officials completely
failed to understand the situation because they did not properly estimate the
importance of the struggle and failed to choose the means to combat the
problem. They did not create a definite plan. They tinkered aimlessly, and
sometimes, if they were bitten too hard, they would lock up one of these
journalistic vipers for a few weeks or months, but the snakes’ nest itself was
left undisturbed.
This was partly the result of the endless, crafty tactics of Jewry on one
side and a stupidity or naivety on the other. The Jew was far too shrewd to
allow a simultaneous attack to occur against the entire press. Then when one
part of the press was attacked, the other members would give cover to protect
their stronghold. The Marxists were taking the field in the lowest way possible
to attack and revile all that man holds sacred and wickedly attacking both
State and government, and setting social classes of the people against each
other. The Jewish propaganda newspapers, which were aimed at the
privileged-class, knew exactly how to make themselves appear to be the
heralds of objectivity and carefully avoided all strong language. They knew
that the empty-headed can only judge what is on the outside and are never
able to look deeper; avoiding strong language concealed their true message
211
Mein Kampf
by hiding it in a pretty box. So, for them, the value of something is measured
by the exterior instead of by the substance, a human weakness that the press
has carefully studied and understands well.
For such empty-headed people, the Frankfurter Zeitung14 was and is the
very essence of “decency.” It never uses rude language, opposes all physical
brutality, and urges war only with “intellectual” weapons, which oddly enough
is always the favorite idea of the most unintelligent people. This is a result of
our half-way education system, which teaches students to separate
themselves from natural instincts and pumps them full of certain information
without leading them to the ultimate knowledge or true understanding.
Diligence and good intentions alone are useless if they fail to provide the
necessary understanding of what is being taught. This final combination of
intelligence and natural instinct is indispensable. Ultimate knowledge consists
of intellectually understanding the causes which are already instinctively
perceived.
Man must never be so misguided that he believes he has ascended to the
position of lord and master over Nature. The conceit of half-education has
made men think this illusion is possible. He must understand the fundamental
law of necessity rules in Nature’s domain, and realize how completely his
existence is subject to these laws of eternal battle and the struggle for
dominance. Only with this understanding will he see that in a universe where
planets revolve around greater suns, moons revolve about their greater
planets, where the strong are masters over the weak; there can be no separate
law for mankind. Man must be subject to these laws or be crushed by them.
This supreme wisdom must dominate man. He can try to understand these
principles, but he can never free himself from them.
It is for those who choose to be kept, like a seedy harem among the
followers of this press, that the Jew writes his so-called newspapers he writes
for that “intelligent” reader. The Frankfurter Zeitung and the Berliner
Tageblatt15 are made for this intellectual crowd because their tone is chosen
14 The Frankfurt Newspaper, a German newspaper in Frankfurt which openly supported the
Treaty of Versailles.
15 The Berlin Daily, a major liberal newspaper in Berlin.
212
Causes of the Collapse
so that it speaks to them and influences these people the most. Carefully
avoiding any seeming harshness and never speaking in a crude manner, they
nevertheless pour their poison into the hearts of their readers by other means.
With a steady flow of pretty words and phrases, they lull their readers into
believing that these lovely words are a fountain of knowledge and moral
principles which are pouring from their pages. In truth, theirs is the brilliant
and crafty art of disarming any enemy who might oppose the Jews and their
press. As one group of newspapers drips with decency, the half-wit followers
are all the more ready to believe that the other newspapers speak the same
truth only in a slightly more crude fashion. It is a question of degree. The
offenses of one group does not seem as serious or extreme when compared
to this journal of “decency.” These abuses then appear to be small, and being
of such a perceived minor nature, would never lead to any restriction upon
“freedom of the press.” That is the loophole that allows such newspapers to
escape legal punishment for this harmful poisoning and lying to the people.
Therefore, the government hesitates to take action against these journalistic
bandits for fear they will immediately have the “decent” press line up against
them too. This fear is well founded. The moment anyone attempts to take
action against one of these scandal sheets, all the others immediately rush to
its defense. It is not because they approve of its method of fighting, Heaven
forbid. It is said to be a matter of freedom-of-the-press and a matter of free
expression of public opinion. That alone is what is being defended. Even the
strongest men will fall down, weakened under this uproar, because the outcry
comes entirely from the mouths of “decent” newspapers.
This poison was allowed to enter and do its work in the blood stream of
our people without interference and without the State exercising the strength
needed to control the disease. In the ridiculous half-measures it employed,
one could see the pending downfall of the Empire. An institution, which is no
longer determined to protect itself with every available weapon, has
effectively surrendered its existence. Every half-hearted act is a visible sign of
inner decay which will eventually be followed by outward collapse.
I believe that the present generation, with proper guidance, will more
easily conquer the danger. This generation has gone through various
213
Mein Kampf
experiences which have strengthened the nerves of everyone who did not lose
their nerve altogether. In the days to come, the Jew will raise a terrible protest
in his newspapers when a hand is laid on his favorite den to stop his journalistic
mischief, and the press is set to work as a means of forming public opinion
through education for the State. This valuable messenger can no longer be left
in the hands of aliens and enemies of the people. This necessary action will
not disturb us younger men as much as it would have our fathers. A ten-inch
shell hissing overhead is louder than a thousand Jewish newspaper snakes. Let
the vipers hiss! Another example of weakness and half-hearted actions on the
part of the government of pre-war Germany concerning the most important
questions to the nation is this: For many years a horrible physical poisoning of
the people has run its course alongside the political and moral infection of the
citizens.
Syphilis began to spread in the large cities, while tuberculosis gathered
its harvest of death almost uniformly throughout the country.
In both cases, the effects on the nation were horrible yet the government
could not make a decision to take action and stop them. Toward syphilis, the
attitude of the State and race-focused leaders can only be described as
absolute surrender. Any serious attempt at stamping it out needed to go
farther than anything that was actually done. The invention of a questionable
remedy and its commercial exploitation did little good against this disease.
Here, too, the only possibility was a fight—a fight against the cause, not the
removal of the symptoms. The primary cause is our prostitution of love. The
mixing of blood16 through prostitution is the corruption. Even if it did not result
in this disease of nature, it would still damage the people morally.
The devastation that follows this perversion is enough to lead our people
slowly but surely to ruin. This Judaism of our soul by commercializing our
natural instinct will sooner or later corrupt our future generations. Instead of
vigorous, emotionally healthy children, we will have only the sorry products
of a quick financial deal for selfish pleasure. Financial considerations have
16 Mixing of races.
214
Causes of the Collapse
become the foundation and sole requirement for marriage. The result is that
love looks elsewhere to find itself.
Man may defy Nature for a certain length of time, but eventually she will
call her due, and payback will come. When man recognizes this truth, it is often
too late.
We can see in our noble class the disastrous results of long and continued
neglect of the natural fundamentals for marriage. Nobility are paired
according to their status and how the marriage can improve their standing.
We observe the consequences of a reproduction which is focused partly on
social pressure and partly on financial considerations. One leads to general
weakening, the other to blood-poisoning because any Jewish daughter of a
department store owner is thought good enough because they can increase
the standing of His Grace’s descendants financially. Even the privileged classes
now follow this example. In both cases, complete degeneration is the result.
With no concern for the consequences, people ignore this unpleasant
truth as if ignoring it would make the problem go away. No, our metropolitan
population is prostituting its love life more and more, and growing numbers
are falling victim to the plague of syphilis. This fact will not disappear if we
close our eyes to it. It is there. The clearest results of this mass sickness can be
found in the insane asylums, and, unfortunately, in our children. Children in
particular are the sad products of the poisoning of our sexual life. In the
sickness of the children we see the immoral habits of the parents.
There are various ways people deal with this unpleasant, horrible fact.
Some people see nothing at all, or rather choose to see nothing. This is by far
the simplest and cheapest “attitude.” Others wrap themselves in the saintly
garments of a prude and pretend to have modesty, which is nothing but a
deception. They speak of the whole subject as if they were talking about a
great sin, and express profound righteous anger toward every sinner who is
caught. They close their eyes in self-righteous loathing to this godless plague,
and pray to the good Lord that He will pour fire and brimstone upon this
Sodom and Gomorrah to make an example, preferably not before their own
natural death of course. This would then provide an educational lesson to the
rest of shameless humanity. A third group sees the awful consequences which
215
Mein Kampf
this plague can and will someday bring with it, but they merely shrug their
shoulders, convinced that they can do nothing against the coming danger.
They stand aside and allow events to run their course.
All of these people choose the simple and easy path. The problem is that
such apathy will have fatal consequences for the nation. The excuse that other
nations are no better off will make little difference when our nation is the one
to fall. The only benefit to that claim is the sympathy toward others makes our
own misfortune slightly more bearable. The most important question is which
nation will step forward and defeat the epidemic, and which nations will
submit and be smothered by it. That is what it comes down to in the end. This
is just a measure of racial excellence, a test of racial values. The race that
cannot stand the test will simply die and make room for healthier, stronger
races which can endure hardships more easily. Since this question primarily
concerns future generations, it is about them that it is said with such
frightening truth: “The sins of the fathers will be visited on the tenth
generation.”17
This holds true only for crimes against blood and race. The sin against
blood and race is the original sin of this world and it will bring the end of any
humanity which surrenders to it.
The attitude of pre-war Germany concerning this one question was truly
sad! What did they do to stop the infection of our young people in the great
cities? What was done to attack the disease and selfish commercialization of
our love life? What was done to combat the spread of syphilis that resulted?
The easiest way to find the answer is to point out what should have happened.
The question should not have been taken so casually. Authorities should
have understood that a solution, or lack of a solution, would impact the
happiness or unhappiness of generations to come. The existence of a solution
might decide the future of our people. To admit this would have required
action. Action would have meant the enactment of ruthless measures and
intervention efforts. The conviction and attention of the whole nation should
216
Causes of the Collapse
217
Mein Kampf
falling into despair before giving up. They may see their long-term goal in the
far distance ahead, but they only recognize the immediate goal as they follow
the path one section at a time. It is like the traveler who knows his destination,
but can only make the long trip when he divides it up into sections and attacks
each one as if it were his only journey. This is the only way he can maintain his
determination to reach the ultimate objective without losing faith in his ability
to achieve the final goal.
Every type of propaganda should have been used to fight syphilis. It
should have been presented as the main and most important responsibility of
the nation, not just as a task. For this purpose, its ill effects should have been
hammered into people by every available method and shown as the most
awful of all disasters until the whole nation became convinced that future
depended a solution to this problem. They must be faced with the unavoidable
choice between a healthy future or absolute national decay. This kind of
education and preparation should have continued for years if necessary. Only
then will the attention and the determination of all of the people be aroused
to such a level that even severe measures involving great sacrifice can be used
without danger of being misunderstood or suddenly neglected by the masses.
Everyone must know that enormous sacrifices and equally enormous efforts
are necessary in attacking this plague.
A successful battle against syphilis requires a battle against prostitution,
against prejudices, against old customs, against pre-existing ideas, and against
public opinion, such as the false pretense of extreme modesty in certain
circles.
Before the State can claim any moral right to attack these things, it must
allow and encourage people to marry earlier.18 Allowing marriages to only take
place for older generations forces us to preserve a system that is dysfunctional
and causes shame to humanity. The custom of late marriage, which causes so
much trouble, is a creature that misrepresents itself as the “image” of God.
Prostitution is a disgrace to humanity, but it cannot be abolished by moral
lectures or pious intentions. Its restriction and eventual disappearance
18At this time in Germany, women could marry at age 18 but men could not marry until age
21. Many also waited until later in life to marry.
218
Causes of the Collapse
19Siegfried refers to the Wagner opera character and his invulnerable skin. The reference
means the husband has been compromised, his protection weakened, his strength gone, and
he is not a true man any longer.
219
Mein Kampf
220
Causes of the Collapse
221
Mein Kampf
weak and spiritually undone young man receive his introduction to the
mysteries of marriage through some big-city whore? No, he who seeks to
strike at the root of prostitution must first remove its spiritual cause. He must
sweep out the garbage of our moral infection of city “culture” and do so
mercilessly without wavering when the protests and screaming start from the
outcry that will surely follow. If we do not lift youth from the disgusting mess
of its present surroundings, it will sink deeper into that filth. The man who
refuses to see these things is supporting them, and through his inaction he
assumes a share of the guilt for the slow prostitution of our future which
grows in the coming generation. This purification of our culture must expand
into almost every area. Theater, art, literature, cinema, press, advertisements,
and store windows must have the pollution which is rotting our world
removed, and they must be forced into the service of a moral idea of State
and culture. Public life must be free from the overpowering perfume of
eroticism and also of all unmanly elements and false prudishness. In all these
things, the goal and road to that goal must be carefully considered then set in
stone for the preservation of our people’s health in body and soul. The right
of personal freedom is secondary to the duty of preserving the race.
Only when these educational measures are complete can the medical
assault on the disease itself begin and still have some chance of success.
There can be no halfway measures. We have to make the most serious
and most radical decisions. It would be a half-measure to allow those who
cannot be cured the chance to infect others who are in good health. This sort
of humaneness avoids causing suffering to one individual while it sends a
hundred to the damnation of death. It must be made impossible for diseased
persons to produce equally defective children. This requirement is simply
common sense. This would be humanity’s most humane deed if it were
consistently carried out. It will save millions of unfortunate souls from
undeserved suffering and in the end, lead to an overall improvement in
national health. The determination to proceed with this plan will also halt the
further spread of venereal diseases. We may have to resort to harsh
segregation of those who cannot be cured. This is a savage measure, especially
for the unhappy victim of the disease, but it is a blessing for the rest of the
222
Causes of the Collapse
country and for posterity. The temporary suffering of one century can and will
free thousands of future generations from suffering.
The battle against syphilis and its distributor, prostitution, is one of
humanity’s greatest tasks. It is enormous because it does not involve just one
single solution, but the removing a series of evils which lead this disease into
the veins of our society. The disease of the body is simply the result of diseased
moral, social, and racial instincts.
If this battle is not fought because of laziness or cowardice, imagine what
the nation will look like in five hundred years. There will only be a few men
left in God’s image, the rest will be a blasphemy against the Almighty.
How did people try, in the old Germany, to deal with this disease? Calm
consideration returns a truly sad answer. The havoc caused by the disease was
known to the government, though they may not have fully comprehended its
consequences. In fighting it, they were a complete failure, and instead of
making thorough reforms, they preferred to resort to miserable and
ineffective controls. They concentrated their efforts on fixing the results of the
disease and left the causes alone. They subjected the individual prostitute to
medical examinations and supervised her as well as they could. If disease was
discovered, they shoved her into some hospital and when she no longer
showed signs of disease, she was once more let loose on mankind.
The government did introduce “protective legislation.” According to this
law, anyone who had venereal disease or who was not entirely cured was
prohibited from engaging in sexual intercourse under penalty of law. This in
itself was a proper measure, but when it came to implementing the plan, it
was almost a complete failure. When the woman suffers such a misfortune, in
most cases she will probably refuse to be dragged into court as a witness
against the miserable poisoner who corrupted her health. This can be the
result of her limited education or understanding of the system and often can
result in the answering of hurtful or embarrassing questions. The woman is
the one who benefits the least. In most cases, she will suffer the worst anyway.
The hatred of her unkind neighbors will fall on her much more heavily
than it would with a man. Finally, imagine her position if the carrier of the
disease is her own husband. Is she to bring a complaint against him or what
223
Mein Kampf
else is she to do? In the case of the man, he may encounter this disease when
he is drunk. In that condition, he is the least able to judge the quality of his
“beautiful one.”
The diseased prostitute realizes this stupor only too well and they have
learned to fish for men in this ideal state. The result is that no matter how the
unpleasantly surprised man may later rack his brains, he cannot remember his
kind-hearted benefactor’s name or face. This is scarcely surprising in a big city
like Berlin or even Munich. The prostitute’s catch is often an unsophisticated
visitor from the provinces who is confused and bewildered by the magic
charms of a great city.
Ultimately, who can tell whether he is infected or healthy? There are
many cases where a person appears cured and then has a relapse and does
the most dreadful damage without even realizing it. The result of this legal
penalty for the act of infection is actually zero. The same is true of control over
prostitutes—even the value of the cure is still uncertain and it may not even
work. Only one thing is sure: all of these measures have failed to keep the
disease from spreading. This is the most conclusive proof of the
ineffectiveness of these measures. Everything that was done was inadequate
and ridiculous. The spiritual prostitution of the people continued and nothing
was done to stop it.
If anyone is inclined to take this matter casually, let him study the
statistics on the spread of this disease. Compare its growth in the last hundred
years and imagine where it will go from here. He must be as simple-minded as
a donkey if he does not have an unpleasant shiver running down his spine
when faced with these facts. The weakness and half-hearted attitude adopted,
even in old Germany, toward this terror is a visible sign of our people’s decay.
When the courage no longer exists to fight for one’s own health, the right
to struggle in this life is at an end. True strength belongs to the vigorous
“whole” man and not to the weak “half” man.
One of the clearest signs of decay in the old Empire was the slow decline
in culture and I do not mean civilization. Civilization seems to be more of an
enemy who raises the standard of living and woos the mind. Even before the
turn of the century, a previously unknown element began to intrude into our
224
Causes of the Collapse
art. Even in earlier days, there were sometimes offenses against good taste,
but these were rather artistic eccentricities to which future generations could
at least attach a certain historical value. Then came products of degeneration
to the point of senselessness, not in art, but in the spirit. These were cultural
signs of the political collapse which became clearly visible later.
The Bolshevism of art is the only possible cultural form of life and
intellectual expression that Bolshevism is capable of.
Anyone who thinks this is unclear or strange need only look around those
“fortunate” Bolshevized States. This official and State-recognized art is looked
at with horror. I speak of morbid disfigurements produced by lunatics and
degenerates which we have become acquainted with since the turn of the
century as Cubism and Dadaism.20 Even during the short life of the Council’s
Republic in Bavaria,21 this phenomenon began to appear. One could see how
all the official posters and propaganda cartoons in the newspapers bore the
stamp of political and cultural decay.
Sixty years ago, a political collapse as extensive as we are now
experiencing would have been unthinkable. Equally unthinkable would have
been a cultural collapse like we see in Futurist and Cubist art creations. Sixty
years ago, an exhibition of so-called Dada type “experiences” would have been
absolutely impossible and its promoters would have been sent to the insane
asylum. And yet today, they are made presidents of art associations. This
disease could not have made its appearance at that time because public
opinion would not have tolerated it, nor would the State have sat idly by. It is
the responsibility of government to prevent its people from being driven into
the arms of intellectual insanity. Today we would see complete intellectual
madness if this type of art had been accepted. On the day that this sort of art
was accepted and found its place in harmony with the public senses, that
would be the most momentous and horrible transformations of mankind that
20 These were abstract types of art using distorted images; however, the content especially of
Dadaist art was often an attack on Nationalists; it promoted pacifism and was often political in
nature.
21 Marxist control in Bavaria.
225
Mein Kampf
would ever occur. The human brain would regress from normality, which
would lead to an end that could hardly be imagined.
If we review the last twenty-five years of our cultural life from this
standpoint, we would be horrified to see how far we have already declined.
Everywhere we look, we find seeds that sooner or later grow and destroy
our civilization. Here is where we see the symptoms of the decay. We see a
slowly rotting world. Woe to the nations who can no longer master this
disease and fail to halt its spread! Such disturbed thought processes could be
seen throughout art and culture in Germany. Everything seemed to have
passed its prime and to be accelerating toward the abyss. The theater declined
visibly and would probably have disappeared as a cultural factor even earlier
if the Royal Court theaters had not stood their ground against the prostitution
of art. Aside from them and a few other praiseworthy exceptions, the offerings
of the theater stage was in such a shambles that patrons would have benefited
more if they quit attending completely. It was a sorry sign of inner decay that
one was no longer allowed to send young people to most of these alleged
“shrines of art.” This decline was openly admitted with shameless candor in
the warning signs seen outside cinemas which proclaimed “for adults only.”
Remember that such cautionary signs were hung outside the very places
which should have existed primarily for the education of young people and
should not exist for the amusement of sophisticated adults. What would the
great dramatists of past ages have said about the need for this kind of
regulation and to the deplorable conditions which made it necessary? How
Schiller22 would have blazed! How Goethe23 would have turned away in
disgust! How do Schiller, Goethe, or Shakespeare compare to the heroes of
modern German literature? Old, thread-bare, and worn out, actually you can
say they have been discarded. In this age you only see the production of filth,
but it does not stop with its own creations. In addition, this generation
slandered everything truly great from the past. This is, of course, not an
unusual historic occurrence. The more vile and contemptible the products of
an age and its men are, the more they despise and disparage the
226
Causes of the Collapse
227
Mein Kampf
shine, and then they only shine as a result of the sun. All new moons of
humanity have a deep hatred for the fixed stars which shine on their own. If
Fate throws one of these nobodies into temporary leadership, they
immediately dishonor and slander the past with diligent enthusiasm. Blaming
the past leaders for problems on their watch takes them out of the line of fire
for public criticism. As an example, we can look at the Legislation to Protect
the Republic which was passed in the new German Reich.
If some new idea, doctrine, new World-Concept, or political or economic
movement tries to deny the accomplishments of the past by calling it bad and
worthless, we must be extremely careful and suspicious, and we must
question their reason for such slander. This hatred sprouts from its own
worthlessness or because its true intention is to cause harm. A truly
productive movement will always begin to build on the spot where the last
good foundation stopped. They will not be ashamed of using those truths
which already exist as their cornerstone. All of human culture and man himself
are only the product of one long continuous development in which each
generation has added a new stone to the structure. The purpose of revolution
is not to tear down the whole building, but to remove only those parts, which
are poorly attached or unsuitable for their purpose and to build a better
structure onward and upward from the spot that is left bare.
Today we can talk about the progress of mankind because it is built on
past accomplishments. Otherwise, the world would never be rescued from
chaos and each generation would reject the past and destroy its works to
make way for the creations of the new generation.
The saddest thing about the condition of our German civilization before
the war was not only the absolute weakness of artistic and cultural creative
power, but how the memory of a greater past was polluted, befouled, and
smothered by hatred. At the turn of the century, in almost every area of art,
particularly in theater and literature, people began to defame the best of the
old, saying it was inferior and worn out. They were more interested in trashing
the old works than in creating new works. This was a disgraceful and inferior
era that was unable to produce anything new or significant and had no right
to belittle the great works! Their striving to put the past out of sight of the
228
Causes of the Collapse
present revealed plainly and distinctly the evil intent of these apostles of the
future. People should have been able to see this was not a matter of
something new, even if it was wrong. It was part of a process meant to destroy
the foundation of our civilization.
The confusion that then surrounded what was previously a healthy art
community made it possible to lay the intellectual groundwork for political
Bolshevism. If the Age of Pericles was embodied in the Parthenon, the
Bolshevist era was embodied in the travesty of the Cubist grimace.
At this point we must focus our attention on the cowardice among those
of our people who, by virtue of their education and position, had the
responsibility of standing firm against this cultural outrage. They chose to
avoid a confrontation on the chance the Bolshevists might raise a commotion.
The Bolshevist art-apostles violently attacked everyone who failed to
recognize them as the peak of creation, branding opponents as old-fashioned
and a Philistine. No one would stand up against these Bolshevist art-apostles
out of fear. They surrendered themselves to what seemed to be the inevitable.
These people trembled, frightened that they might be accused of being
simple minded or worse, lacking artistic appreciation by these half-lunatics or
frauds as if it were a disgrace not to understand the products of these mental
degenerates or sly imitators! These apostles of culture did have one very
simple way to stamp their nonsense with the illusion of high quality and
greatness. All their incomprehensible and obviously insane garbage was
presented to an open-mouthed public and labeled as what they called an
“inner experience.” In this cheap method, they kept the people’s criticism
silent.
Of course, no one had the slightest doubt that these inner experiences
could be from their Bolshevist minds. However, one must seriously doubt that
there could be any justification for exposing the hallucinations of crazy men
or criminals to the healthy minded public. The works of a Moritz von Schwind27
27 An Austrian painter born in Vienna who painted highly detailed, realistic works.
229
Mein Kampf
or a Böcklin28 were inner experiences too, but these were the experiences of
artists favored by Heaven, not clowns.
This was a fine demonstration of the pitiful spinelessness of our so-called
intellectuals who did not resist this poisoning of our people’s sound instincts
and left it to the people to formulate their opinion about this disrespectful
nonsense. To avoid being considered artistically illiterate, people accepted any
mockery of art and eventually became unsure in their own judgment. They
could no longer determine what was good or bad. Taken together, these were
signs of an evil time to come.
Another suspicious sign is the following: In the nineteenth century, our
cities began to lose their character as centers of culture and declined into
mere human settlements. The working class has a very small emotional
connection to the place where they live. This is because their living quarters is
an accidental abode, a collection of people in a place and nothing more. This
is mostly because they must frequently move due to social conditions and a
man has no time to develop a close relation to his city. Another cause is the
general cultural insignificance and the poverty of modern cities themselves.
At the time of the Wars of Liberation,29 German cities numbered very few
and those were small. Most of the really big cities were royal residences which
gave them a certain cultural value and usually a definite artistic impression.
The few towns of more than fifty thousand inhabitants were rich in treasures
of science and art compared to cities of the same population today. When
Munich reached sixty thousand in population, it was already on its way to
being one of the leading German art centers. By now, almost every factory
town has reached that size or larger, but often without having the slightest
elements of true value to call its own. They are collections of tenement houses
and dwellings that are like barracks and nothing more. It is no wonder why the
people do not become emotionally attached to the meaningless place where
they live. No one is going to be particularly attached to a city which offers
nothing more than any other city and which lacks any individuality and where
28 Arnold Böcklin, a Swiss painter known for Mythology and Renaissance styles who later
influenced Surrealistic painters.
29 Part of the Napoleonic Wars 1813-14.
230
Causes of the Collapse
30Ludwig the First is well known for creating a cultural center in Munich of great classical
architecture.
231
Mein Kampf
These buildings were owned by the community. Even in late Rome, it was
not the villas and palaces of individual citizens that were most important, but
the temples and baths, the stadiums, the circuses, bridges, and cathedrals of
the state, of the whole people.
Even the Germanic Middle Ages maintained the same guiding principle,
though their approach to art was entirely different from the Romans. What
had been expressed in the Acropolis or the Pantheon now took on the form of
the Gothic cathedral in Germany. Like giants, these monumental structures
towered above the little hive of half-timbered, wooden or brick buildings in
the medieval city. They became landmarks, which stamp the character and the
skyline of these towns even today, while apartment houses are sprouting up
all around them and obscuring their greatness. Cathedrals, town halls,
granaries and defense towers are the visible signs of an old idea, and outward
expression which had its counterpart in the ancient world but which is missing
today.
The relation between public and private buildings today is truly sad! If
Berlin should suffer the fate of Rome, future generations would admire the
department stores of a few Jews and the hotels of a few corporations as the
mightiest works of our age believing those to be the characteristic expression
of this civilization. Compare the obvious imbalance between the buildings of
the Reich and the finance and commerce buildings in a city like Berlin.
The amount of money spent on government buildings is inadequate and
ridiculous.
These buildings are not made for eternity, but only to satisfy the need of
the moment. No one thinks about greatness when they commission a building.
When the Castle at Berlin was built, it was a great work possessing a
significance that is lacking in the new library of our time. That great show-
place cost about sixty million marks while less than half that amount was spent
on the Reichstag. This is the most imposing structure, yet built for the Reich,
and it should have been built to last through the ages. Then, when the
question of the interior came to a vote, the Exalted House voted against the
use of stone and ordered the walls be covered with plaster. Fortunately, for
232
Causes of the Collapse
once, the parliamentarians did the right thing. Plaster statues are certainly out
of place among stone walls.
Our present-day cities lack any towering landmarks to represent the
people’s community and we cannot be surprised if the community does not
see its cities as a representation of itself. Unhappiness is the result and we can
see this in the complete disinterest toward the concerns of the citizen’s city.
This is also a sign of our declining civilization and our general collapse.
This generation is smothered in the pettiest practices or in slavery to money.
It is hardly surprising that there is no sense of heroism under this deity. Today
we reap what the recent past has sown.
All these symptoms of decay result from the lack of a definite, universally
recognized World-Concept. We have no plan and this results in general
uncertainty when it comes to handling the great questions of the time. This is
why everything, beginning with education, is half-hearted and indecisive
because it shies away from responsibility and winds up in cowardly tolerance
of obvious abuses which are known to be destructive. The desire to be
humane— this craze—has become fashionable. By weakly submitting to this
deviance and sparing the feelings of individuals from hurt, we have sacrificed
the future of millions.
The spread of disunity can be seen in the religious conditions before the
war. Here, the various parts of the nation had long abandoned their unified
convictions which might have amounted to a World-Concept. In this matter, it
is important to note that the small number who officially left the church were
not as important as the much larger number who were simply indifferent.
Both Churches maintained missions in Asia and Africa to gain new converts for
their Faith. In Europe, they were losing millions upon millions of followers who
had either given up on religious life or preferred to follow their own
interpretation. The consequences definitely impacted the moral life of the
country. On a side note, the progress made by the missions spreading the
Christian Faith abroad was only modest when compared to the spread of
Islam. The results from a moral perspective are especially poor.
There is something else that is important to note. Violent attacks upon
the basic principles of Church teachings have increased steadily. It would be
233
Mein Kampf
234
Causes of the Collapse
235
Mein Kampf
31 A British political philosopher whose work affected Nazi racial platforms and pan-German
movements. He was a German supporter in the First World War, and he also married the
daughter of composer Richard Wagner.
32 Axel Gustafsson Oxenstierna, a Swedish Chancellor who played an important role in the
organization that sought to assassinate officials or overthrow the government and prohibits
insults to officials and the flag. The law was passed after Walter Rathenau, the Weimar
Foreign Minister, was assassinated.
236
Causes of the Collapse
34 A territory created by German annexation in the Franco Prussian War and lost to France
with the Treaty of Versailles.
35 The Center party in the Reichstag and the separatist Center Party of the Alsace-Lorraine
territory were partly but never fully merged, then they completely split over the Alsace-
237
Mein Kampf
the general half-heartedness had not also sacrificed the power of the army,
on which the existence and survival of the Empire depended.
Those who were supposed to be the “German Parliament” were forever
cursed by the German nation for their crimes. For the most disgraceful,
contemptible reasons, the party henchmen stole from our people’s hands the
weapon they needed for self-preservation, the sole protection of our people’s
freedom and independence, and by various means they destroyed the army.
If the graves spread over the Flanders plains were to open today, the bloody
accusers would rise from them to point the finger of blame at the Reichstag.
Hundreds of thousands of the best young Germans, who were sent poorly
trained and half-prepared into the arms of death by these conscienceless
parliamentary criminals, paid dearly. The Fatherland simply lost these poor
souls. These and millions of others were crippled and killed, lost to the
Fatherland, lost solely to allow a few hundred deceivers and swindlers of the
people to carry out their political maneuvers, enforce their excessive
demands, or even test their theories of political doctrine. They are traitors.
The Jewry, through its Marxist democratic press, shouted the lie of
“German militarism” to the world, hoping to paint Germany as an aggressor.
They tied Germany’s hands by every means available. The Marxist and
Democratic parties refused to approve funding for comprehensive training of
the German defense forces. Yet this monstrous crime must have been
immediately clear to anyone who saw that in a war, the whole nation may
have to take up arms. Consequently, the mischief of these fine
“representatives of the people” would drive millions of Germans into the face
of the enemy while they were only half-trained and poorly equipped. Even if
we set aside the result of the crude and brutal lack of principles in these
parliamentary fancy-men, anyone could see the absence of properly trained
soldiers at the beginning of war might easily lead to defeat. This result was
frighteningly confirmed in the course of the First World War.
The German nation’s loss of the struggle for freedom and independence
was the result of half-way measures and weakness. It began during peacetime
Lorraine constitution passed by the Reichstag. Mr. Wetterlé referrs to Abbé Wetterlé, the
leader of the Alsace-Lorraine Center party who was forced to flee to France in 1914.
238
Causes of the Collapse
36 British ships were allowed by treaty a larger tonnage based on the argument that they
needed to carry more fuel to reach colonies The German Navy was also kept small to avoid an
appearance of threatening England.
37 The British gun suffered from accuracy and weapon-longevity problems, and the German
239
Mein Kampf
that time. Any fortresses would probably have crumbled for the 30.5
centimeter field artillery, but the Command of the army was logical and
reasoned correctly when they chose their artillery, while the navy,
unfortunately, was not so logical.
The navy’s rejection of superior artillery and of superior speed was based
on the completely mistaken so-called “concept of risk.”38 The Naval Command
assessed their needs based on the idea of defense and completely abandoned
offensive planning. From the beginning of the war they were surrendering any
chance of success, of victory, because those can only come from attacking,
from offense, not defense.
A ship of slower speed and inferior weaponry will be quickly blown out of
the water by its faster and better-armed adversary who can fire effectively
from a greater distance. A considerable number of our cruisers discovered this
to their bitter sorrow. The peace-time views of the Naval Command were
completely mistaken as shown by the war. This forced the re-equipment of
old ships and the use of better weapons on new ships whenever they had the
chance. If in the battle of the Skagerrak39 the German ships had had the same
tonnage, the same armament, and the same speed as the English ships, the
British navy would have gone to a watery grave under the hurricane of
accurate and more effective German 38 centimeter shells.
Japan chose a different naval policy. Their entire emphasis was put on
building a fighting strength in each new ship that was superior to their
eventual adversary. The offensive capabilities of the fleet in battle was their
reward.
While the Army Command still kept itself free from such fundamentally
erroneous reasoning, the navy had more “parliamentary” representation and
succumbed to the spirit of Parliament. The navy was organized and run using
their method of doing everything half way, and it was later used in the same
way. The immortal glory the navy did earn can only be credited to the good
38 A military term describing the level of danger or risk in an engagement versus what is
required to counter that danger.
39 The strait of Skagerrak between Norway and Sweden was strategically important to
Germany.
240
Causes of the Collapse
241
Mein Kampf
It was most peculiar that the dark faults of old Germany were only
exposed when doing so had the potential to harm the inner stability of the
nation. In such cases, the unpleasant truths were shouted at the great masses
while many other things were bashfully kept quiet and hushed up or simply
denied.
Denial or silence were the clear choices when the open discussion a
problem might have brought improvement. The competent members of the
government understood next to nothing about the value and nature of
propaganda. Only the Jew knew that the clever and persistent use of
propaganda could make Heaven seem like Hell and Hell appear as Heaven
itself, or make the most miserable type of life seem like a paradise. The Jew
knew what to do and he acted on that knowledge. The German, or rather his
government, didn’t have the faintest idea how to use propaganda or what it
truly was. As a result, we saw the most severe results during the War as
penance for such ignorance.
In German life before the War, we experienced the problems I have
discussed but there were also many advantages. To evaluate things fairly, we
must recognize that most of the problems we experienced were also present
in other countries and peoples. Their problems were sometimes so great that
it often put us in the shade of their gloom because we enjoyed advantages
they lacked.
The leader among these virtues was the fact that, when compared to
almost all European peoples, Germany tried the hardest to preserve our
national economic character. This gave Germany a clear superiority. It reduced
our exposure to the control of international finance, though there were
symptoms to indicate its presence. This virtue turned out to be dangerous
because it became a major cause of the First World War. Putting this and other
things aside, three institutions must be pointed out that were unequaled in
their perfection. They helped us stand apart from the other great nations and
made it possible to restore the nation when it was damaged.
The first was the form the State took and the special way it developed in
the Germany of modern times. We may reasonably overlook individual
monarchs who, as human beings, were subject to all the weaknesses common
242
Causes of the Collapse
to humans and shared with the children of this earth. If we were not
understanding and indulgent to these weaknesses, we would be in total
despair at the present time because there would be very few people left to
run the country. The representatives of the present regime are considered as
no more than celebrities, personalities, and are morally and intellectually
probably the least developed that one can imagine. Anyone who measures the
“quality” or merit of the German Revolution by the merit and stature of the
people it has given to the German nation as leaders since November 191840
will hide his head in shame before the judgment of future generations. Future
generations will not be bound by the Law for Protection of the Republic and
cannot be silenced by such protective laws. They will say what we all realize
even now; that the brains and virtues of our new German leaders are a lot
smaller than their big mouths and their big vices.
Many people, especially the common people, lost touch with the
Monarchy. This was because the Monarchy was not always surrounded by the,
shall we say, most alert and especially not the most upright characters. The
Monarchy preferred flatterers above straight-talking, honest men. The
flatterers were the ones who kept the Monarchy “informed.” This caused
serious damage at a time when the world was undergoing a transformation
and many old opinions were cast off while new ideas replaced them to sit in
judgment upon a variety of ancient Royal Court traditions.
By the turn of the century opinions had shifted. How could an ordinary
man or woman feel a surge of enthusiasm for a Princess who was riding on
horseback and wearing a uniform as soldiers filed past on parade? Apparently,
no one in these upper circles had any idea as to how this sort of flamboyancy
looked to the people. If they did, such awkward performances would have
never happened. The pretentious trend for showing insincere
humanitarianism in these circles also repelled more than it attracted. For
instance, at one time, if Princess X descended to sample the product of a soup
kitchen, of course finding it to be excellent as expected, so she could show
how strongly she felt a familiarity with the people, it might have made a
40
The end of the First World War and start of the Weimar Republic, a reference to the
November Criminals.
243
Mein Kampf
perfectly good impression in the past, but the current result was the opposite.
It is safe to assume that Her Highness never dreamed that on the day she
tasted the soup, it was just a little different from what it usually was, but it
was enough that everybody else knew this to be the case. What may have
been the best of intentions became ridiculous, if not absolutely offensive.
Descriptions of the proverbial frugality of the Monarch generated many
ominous conversations. We were told how he woke up much too early, how
he absolutely slaved till late at night, and of the ever-present danger of
pending undernourishment resulting from his devotion to duty. Nobody wants
to know what and how much the Monarch ate. Nobody begrudged him a
“square” meal. No one was trying to deny him a full night’s sleep. People were
satisfied if he honored the name of his House and his nation as a man and a
public servant who fulfilled his duties as a ruler. The telling of fairy tales about
him did more harm than good.
All the flamboyancy and fairy-tales as well as other events like them were
insignificant compared to the spreading lethargy. Growing throughout a large
part of the nation was the terrible belief that governing was taken care of from
above automatically, and that the individual didn’t need to think about it. As
long as the government was really a good one, or at least had the best of
intentions, they could continue without anyone objecting. But, beware! When
the fundamentally well-meaning old government was replaced by a new gang
of lower quality leaders, then the existing meek, docile obedience and child-
like faith became the most fatal evils that could possibly be imagined.
To offset these and many other weaknesses, there were undeniable
positive effects of the Monarchy. One was the stability of rule imposed by a
Monarchy form of government. This removed the highest posts in the State
from the reach of ambitious politicians. Further, there were the respect and
authority of the institution in itself that elevated government civil servants by
association with the Monarchy, especially the army, above the level of mere
political party obligations.
There was the further advantage that the Monarch himself was a person
who held the head of the State position, and the example set by the Monarch
in bearing sole responsibility is more than that which is assumed by the chance
244
Causes of the Collapse
41 Versailles Treaty.
245
Mein Kampf
nation was considered to be stupid and weak-minded while the only man who
seemed sensible was the man who could shield and advance his own self
interests. The school of the army still taught the individual German to seek
salvation in the nation, not in the lying insincerity of international brotherhood
among negroes, Germans, Chinese, Frenchmen, Englishmen, etc., but in the
strength and unity of his own nationality.
The army bred decisiveness, while everywhere else in life, indecision and
skepticism determined men’s actions. In an age when the smart-alecks
everywhere set the tone, it meant something to maintain the principle that
doing something is better than doing nothing. This one principle symbolized a
vigorous healthy force that would have been lost in our lives a long time ago
if the army and its training had not constantly renewed this fundamental
concept. One only has to look at the horrible inability of our present leadership
to make a decision. They cannot shake off their mental and moral lethargy to
decide on a definite action except when they are forced to sign some new
order for the exploitation of the German people. In that case, they decline all
responsibility and sign with the speed of a court stenographer anything that is
put in front of them. In this case, the decision is easily made because they do
not have to reach a decision; the decision is dictated to them.
The army bred idealism and devotion to the Fatherland and its greatness,
while in civil life, greed and materialism were out of control. The army trained
a united people and united the classes. Perhaps its only fault was the
institution of one-year military service for high-school graduates.42 This was a
fault because it broke through the principle of absolute equality and put the
better-educated individuals outside the circles of their more common
comrades. Actually, the very opposite policy would have been better. Our
upper classes are so isolated from the real world and they are becoming more
and more alienated from their own people, that the army could have had a
beneficial effect if it had avoided any preferential treatment in the ranks of
the intellectuals. The failure to treat everyone equally was a mistake, but
where can you find any institution in the world that doesn’t make a mistake?
42
Those who completed higher education only had to serve one year instead of the full
military term.
246
Causes of the Collapse
In any case, the good aspects of the army greatly outweighed the defects. The
few flaws that existed were far below the average level of human
imperfection.
We must consider it a great credit to the army of the old Empire that it
placed the individual above mob-rule at a time when majorities were
everything, and everyone based their beliefs on the mob’s conscience. The
army’s teaching was in direct opposition to the Jewish Democratic idea that
one should blindly worship whatever the greatest number of people believed.
Instead, the army upheld faith in the personal values of the individual above
the collective values of the mob. It even trained what was most urgently
needed: real men. In the swamp of a universally spreading softness and
femininity, three hundred and fifty thousand young, well-trained men sprang
every year from the ranks of the army and mixed with the population. In two
years of training, they had lost the softness of youth and gained bodies as hard
as steel. The young man who practiced obedience during this time was now
ready to command. One could distinguish a soldier who had done his service
by the way he walked.
The army was the great school of the German nation. This was the reason
for the fierce hatred of all those who, through envy and greed, wanted and
needed to make the Empire weak and defenseless. The world could see what
many Germans in their blindness or evil intentions chose not to see; the
German army was the mightiest weapon that served to defend the freedom
of the German nation and guard the livelihood of its children.
Along with the Monarchy and the army, there was a third foot to the
tripod: the incomparable body of civil servants in the old Empire.
Germany was the best organized and best administered country in the
world. It was easy to criticize the German civil service because of bureaucratic
red tape, but other nations were no better off and many were actually worse.
But what the other nations did not possess was the wonderful strength of the
machine and the incorruptible, honorable spirit of those who served. Better
to wade through a little red tape with honest and faithful men, than suffer
through enlightened and modern characters who were ignorant, exercised
poor judgment, and incompetent. To those who like to pretend now that pre-
247
Mein Kampf
248
Causes of the Collapse
249
CHAPTER ELEVEN
There are certain truths which are so completely obvious that, for the very
reason that they are so common, the average person does not see them or at
least does not recognize them. A man may often pass blindly by such obvious
truths and be utterly astonished when someone suddenly discovers a fact that
everybody should have already known. Columbus’ eggs are lying around by
the hundreds of thousands, but a Columbus is rare indeed.1 All men, without
exception, stroll about the garden of Nature, arrogantly assuming they know
and are familiar with all of it. Yet, with few exceptions, they pass blindly over
one of the most striking principles of Nature’s rule: the inner separation of the
various species of all earth’s living creatures.
Even the most casual observer can see a firm, basic law that rules all the
countless creatures in which Nature expresses her will to live. All of the
different forms of animals keep within specific boundaries, within their own
species, when propagating or multiplying their kind. Every animal only mates
with another of the same species. The titmouse pairs with the titmouse, the
finch with the finch, the stork with the stork, the field-mouse with the field-
mouse, the house-mouse with the house-mouse, the wolf with the she wolf,
etc.
Only extraordinary circumstances can alter this boundary rule and then it
only happens under the pressure of captivity or for some other reason that
makes mating within the same species impossible. But, even then, Nature
begins to resist with all her might. Her clearest protest is demonstrated in the
infertility of the bastard creature or in restricting the fertility of later
1The egg of Columbus refers to an idea or discovery that appears obvious after it is made; the
reference is based on a common story about Christopher Columbus.
250
People and Race
descendants. In most cases, she deprives them of the ability to resist disease
or deprives these unfortunates the means to defend against attacks from
enemies. This is natural.
Every breeding between two creatures that are not from the same level
produces a result mid-way between the levels of the two parents. The
offspring will be on a higher level than the racially lower one of its parents, but
not as high as the higher one. Consequently, in battle, it will eventually yield
to the higher species because of its deficiencies. That sort of mating runs
counter to Nature’s will to breed life upwards. Nature’s will is accomplished
by complete victory of the higher species, not by uniting superiority and
inferiority. The stronger must rule. It must not unite with the weaker, thus
sacrificing its own higher nature. Only those who are born as the weaker being
can think this cruel and that is why he is a weak and defective man. If this Law
did not hold, the evolution of life would be unthinkable.
The consequence of this instinct for race purity, which is found universally
throughout Nature, is not only the sharp outward difference between the
separate races, but their uniform nature within themselves of their character
that is unique to each species. The fox is always a fox, the goose a goose, the
tiger a tiger, etc. The only possible difference is in varying degrees of health,
strength, understanding, cleverness, and endurance among individual
specimens. We will never find a fox which naturally has moments of kindness
toward geese, just as there is no cat with a friendly affection for mice.
The battle is born out of hunger and love, not because of any native
hostility. In both cases, Nature watches with calm satisfaction. The struggle for
daily bread conquers the weak, sickly, and undecided, while the males who
win the contest for the female win the right or at least the opportunity of
reproduction for the healthiest individuals. Struggle is the means that
improves the health, strength, and stamina of the species and the reason for
its evolution to a higher quality of being.
If any other process were the choice of Nature, all development and
evolution would cease and the progress so far achieved would reverse. There
are always more inferior beings than the best examples of a species. This is
simply a matter of numbers and the fact that only some can be the Best among
251
Mein Kampf
them. Given equal opportunities for survival and reproduction, the worst part
of a species would increase so much faster than the smaller number of quality
members until eventually the best would be crowded into the background. A
correction that favors the dominance of the better individual must take place.
Nature takes care of this by subjecting the weaker part to difficult living-
conditions. That alone is sufficient to restrict their number to some degree.
But these cannot be allowed to increase in number randomly. A new,
ruthless selection method is made and only the strongest and most sound will
make the cut.2.
The result of any crossing of races is this:
A. A decline in the level or quality of the superior race.
B. A slow but certain wasting disease of physical and intellectual
degeneration begins.
252
People and Race
To commit such a deviation is nothing more or less than to sin against the
will of the Eternal Creator. This action is rewarded with vengeance.
In attempting to rebel against the iron logic of Nature, man comes into
conflict with the principles to which he owes his very existence as a human
being. His defiance of Nature is bound to lead to his own downfall.
To this we always hear the arrogant objection of the modern pacifist
which is truly Jewish in its inspiration, and correspondingly stupid: “But, man
can conquer Nature!” Millions thoughtlessly babble this Jewish nonsense and
end by imagining themselves as conquerors of Nature, but their only weapon
is an idea, and this is such a preposterous one that it would be impossible to
imagine the world could exist if it were true. Man has never once conquered
Nature, but at most has caught hold of and tried to lift one corner of her giant
veil which conceals her eternal mysteries. He is never able to create anything.
He can only discover things. He does not rule Nature, but has only learned to
dominate some of Nature’s creatures who lack the knowledge he has gained.
An idea cannot conquer the foundations of mankind’s growth and his being
since the idea itself depends completely on man. Without man, there can be
no human idea in the world. Therefore, the idea is always dependent on the
existence of men, and he in turn is subject to all the laws that created the
conditions essential for that existence.
There is more to the matter. Certain ideas cannot be separated from the
man who conceived them. This is particularly true of thoughts which are not
based on science but based on feelings or an “inner experience.” All these
ideas are chained to the existence of the men whose intellectual imagination
and creative power spawned the idea and have nothing to do with pure logic.
Such ideas represent mere manifestations of feeling, such as ethical and moral
concepts, etc. The preservation of those particular races and men is the
essential element for the existence of the ideas they have created. If someone
should truly desire, with all his heart, for the pacifist idea to be victorious in
this world, he would have to do his best in every way to help Germans conquer
the world. If the reverse should happen and Germany should be extinguished,
the last pacifist would very likely die out with the last German. I say this
because the rest of the world has not been so completely fooled as our own
253
Mein Kampf
3Woodrow Wilson who was elected President on a peace-at-all-costs platform, but was
forced to join the First World War later.
254
People and Race
and the way they deal with external influences. What brings one race to
starvation will train another to work hard.
The great civilizations of the past have all been destroyed simply because
the original creative race died out as a result of pollution of their blood lines.
In every case, the original cause of the downfall has been the failure to
remember that all civilization depends on men, and not vice-versa. In order to
preserve a particular civilization, the type of men who created it must also be
preserved. But this preservation is dependent on the inflexible law that it is
necessary and just for the best and strongest men to be the victor and only
they have the right to continue. The many, who would desire to live, must
fight.
Any man who will not fight for his place in this world of constant struggle,
does not deserve to live.
Even though this may sound harsh, it is the way things truly are. It will be
an even harsher fate that befalls the man who believes he can conquer Nature,
for he only insults her. Suffering, disaster, misfortune, and disease will be
Nature’s response to him.
The man who makes the mistake of ignoring the law of race cheats
himself of the happiness which is fated to be his. He blocks the triumphant
advance of the greater race, and thus the sine qua non4 of all human progress.
Burdened with humanitarian interests and human sentiment, he falls back
among the helpless beasts.
It is useless to argue over what race or races were the original flag-
bearers of human civilization and the real founders of everything we consider
as the world’s humanity. It is simpler to ask this question about the present
time. Now, the answer is plain and simple. All human culture, art, science, and
invention which surround us are almost exclusively the creative product of the
Aryan race. This very fact justifies the deduction that the Aryan alone was the
founder of a superior type of human life and is the prototype of what we mean
by the word “man” today. He is the Prometheus5 of humanity from whose
brilliant mind the divine spark of genius has always sprung, ever rekindling the
255
Mein Kampf
fire which, in the form of knowledge, has illuminated the night of unspeakable
mysteries, and thus sent man up the road to lordship over the other creatures
of this earth. Take him away, and perhaps within a few thousand years,
profound darkness will descend again upon earth, human civilization will
vanish, and the world will become a desert.
If we were to divide humanity into three classes, the founders of
civilization, the maintainers of civilization, and destroyers of civilization, the
Aryan would be the only possible representative of the first class. He laid the
foundation and built the great walls of all human creations, and only the
outward shape and color are determined by the particular characteristics of
the individual peoples. It is the Aryan who furnished the great building-stones
and plans for all human progress, and only the execution depends on the
character of the various races. Within a few decades the whole of Eastern Asia,
for example, will call a single culture its own, however this culture is not its
own creation but was built on the foundation of Hellenistic spirit,6 but it was
also built with Germanic technology, just as in our own case. Only the outward
form will show traits of Asian character; the foundation is Aryan. It is not true
that Japan is superimposing European technical progress on her own
civilization as many people assume. Original European science and technology
have long been decorated with Japanese style. The basis of life in Japan is not
the product of a purely native Japanese civilization, but it is instead built on
the tremendous scientific and technical work from Europe and America, that
is to say from Aryan peoples.
However, this civilization does choose the color of their contemporary
life, which because of the inner difference of the culture, is more obvious to
the European who sees the outside. Only by integrating these Aryan
achievements can the Orient take a place along with other countries in general
human progress. Aryan scientific and technical achievements provide the
foundation that supports their general life and struggle for daily bread in
Japan. Only the outward decoration has gradually changed to fit the Japanese
character.
256
People and Race
If, starting today, all future Aryan influence on Japan were to end, as if
Europe and America were both destroyed, Japan’s present advance in science
and technology might continue for a short while, but within a few years, the
well would run dry. The Japanese internal character would gain hold again,
and the present civilization would become stagnant and would sink back into
the sleep that it was awakened from seven decades ago by the wave of Aryan
civilization. Just as the present Japanese development and culture owes its
existence to the influence of Europe and America, we can also be assured that
in the distant past an outside influence, an outside culture, brought into
existence the Japanese culture of that day. The best proof of this is the fact
that their culture later suffered stagnation and paralysis when the influence
stopped, and it remained this way until it was revived seven decades ago. This
can happen to a race if the original creative racial core has been lost, or if the
outside influence which supplied the stimulus and the materials for the first
cultural development is removed. If it is known that a race receives and
absorbs the fundamental substance of a civilization from alien races, and
progress comes to a halt each time the external influence ceases, the race may
indeed be called a “sustainer” of civilization, but never a “creator.”
Examination of the various peoples around the world from this
standpoint shows that almost none of them are creators; they are nearly
always sustainers; they are merely the recipients of another culture.
This is usually how their development occurs: Often, amazingly small
groups of Aryan tribes overpowered other peoples and caused the dormant
intellectual and organizing powers of the conquered people to surface. These
abilities were unexercised until the Aryans awoke these abilities in the lesser
race. The benefits of the particular living conditions in the new territory, such
as the fertility of the soil, climate, etc., made it possible for them to accomplish
this cultural reawakening by using the large number of available workers from
the inferior race. Often in a few thousand or maybe just a few hundred years,
they built up civilizations which originally displayed every inner mark of their
founder’s character but were adapted to fit within the special qualities of the
local area and the characteristics of the subjugated people.
257
Mein Kampf
But eventually, the conquerors violate the first principle, keeping their
blood pure and not mixing with lower racial stock. They begin to interact with
the conquered inhabitants and in doing so, put an end to their own existence.
Even for the original sin of man, the penalty was expulsion from Paradise.
After a thousand years or more, the last visible trace of the former ruling
people appears only in the lighter skin coloration that its blood bestows on
the subjugated race. It is a stagnated culture of which the Aryans had been the
true founder. Just as the physical and spiritual aspects of the conqueror were
submerged and lost in the blood of the conquered race, so too was the fuel
for the torch of human cultural progress extinguished. The blood of the former
masters has left a faint glow in the complexion as a sign, and the night of the
inferior cultural life is gently illumined by the surviving creations of the ancient
bringers of that light. They shine throughout the uncivilized state and can
easily make the observer who passes by think he is looking at the image of the
present people, but he is just looking into the mirror of the past; he actually
sees the glow radiated from the original bearers of the fire of culture.
It may be that throughout history such a people have come into contact
a second time, or even more often, with the race that once brought it
civilization, without any surviving memory of this past. Unconsciously, the
small shred of the old master’s blood which remains will be drawn toward the
newly arriving race, and what had originally been possible only by force may
now happen through free will. A new wave of civilization explodes and lasts
until those who carry the mantle of progress are adulterated and again go
down in the blood of alien peoples.
It will be the responsibility of those who study future cultural and world
history to make their discoveries from this point of view and not to smother
themselves in descriptions of outward events, as our present historical
scientific education does too often.
Even this short sketch of the development of “culture-sustaining” nations
also reveals the growth, work, and decline of the real culture-founders of this
earth, the Aryans themselves.
Just as in daily life, the one we call a genius needs a special occasion or
even a regular jolt to cause him to shine. A race of people also need such a jolt
258
People and Race
to bring out the dormant genius. In the monotony of daily life, even
outstanding men may appear insignificant. They never rise above the average
level of those who surround them. But take that same person and let him face
a situation where others would give up or freeze in fear and the genius rises
visibly out of this unnoticed, average man, often to the astonishment of
everyone who knows him in his everyday life. This is why the prophet is seldom
thought about much in his own country. There is no better opportunity to
observe this than in war. In times of testing and trial, when others surrender
to despair, those who are apparently innocent children spring up into heroes,
headstrong in determination and ice cold in judgment. If the hour of stress
had not been inflicted, no one would have dreamed that inside that beardless
boy was a young hero. Some sort of impact is almost always necessary to
arouse the genius. The hammer-blow of Fate will knock one man down and
strike against steel in another. Once the everyday outer shell breaks, the
hidden core is exposed to an astonished world. Then the world cringes,
refusing to believe that what had seemed to be a man of its own average rank
is now, suddenly, a greater being. This process occurs almost every time an
outstanding son of the race appears.
Although an inventor does not establish his greatness until the day his
invention is created, it is a mistake to think that genius itself had never taken
hold of the man until then. The spark of genius exists in the brain of a truly
creative and gifted man from the hour of his birth. True genius is always
present from birth and never taught or learned. This applies, as I have already
emphasized, not only in the individual, but in the entire race. Actively creative
peoples have fundamental creative gifts from the beginning, even though the
outside observer may not recognize it. Outward recognition only results from
the accomplishment because the rest of the world is not capable of
recognizing genius by itself. They only see its visible expression in the form of
inventions, discoveries, buildings, pictures, etc. Even then, it may be a long
time before the world recognizes the genius that drove the accomplishment.
Just as the genius or the outstanding individual man with extraordinary
talent is unable to bring out his ability until it is set in motion by particular
259
Mein Kampf
stimuli, a race is only able to bring out its creative powers and abilities when
the right conditions stimulate the peoples into action.
These abilities are the clearest in the race which has been, and is, the
bearer of human cultural development: The Aryans. The moment Fate
imposes special conditions on them, their inborn abilities surface at a quicker
pace and their genius is shown through the physical result. The cultures they
create are almost always determined by the soil, the climate, and the
conquered people. The last of these elements is the most important. The more
primitive and the greater the technical limitations of any acquired culture, the
more effort will be required for the civilizing activity and therefore the more
man-power will be needed. When the man-power is organized, concentrated,
and applied, it can substitute for the power of mechanical machines. Without
the availability of lower ranked men, the Aryan could never have taken the
first step toward his later civilizing of those people. It is the same as if he had
never tamed and used various domesticated animals to help build the
foundation of civilization. Then he would have never arrived at a level of
technical development which now is gradually permitting him to do without
these very animals. The saying, “The Moor has finished his job, so let him now
depart”7 has an unfortunate meaning which is deeply true today. For
thousands of years, the horse was forced to serve man and help him lay the
foundations of a civilization. Now, thanks to the automobile and mechanical
devices, the horse himself has become unnecessary. Within a few years, the
horse will no longer be used, but without his help in days gone by, man would
have had difficulty in arriving where he is today.
Therefore, the availability of inferior races was one of the most important
elements in the formation of higher cultures. Their labor could compensate
for the lack of technical tools and machines, without which advanced
development is unthinkable. Without question, the first civilization of
humanity depended less on domesticated animals and more on the use of
racially inferior human beings.
7Possibly a paraphrase from Shakespeare’s Othello, also attributed to the German poet
Schiller.
260
People and Race
261
Mein Kampf
cultural substance he had built, but then stagnation set in and finally, oblivion
claimed his race.
The ultimate result is that civilizations and empires collapse to make way
for new structures. Mixing of blood and the decline in racial quality that it
causes is the main reason for the dying-out of old cultures. Civilizations are
not destroyed by war but because they lose that stamina inherent in a pure
bloodline. Anything in this world that is not of sound racial stock is a useless
husk which is blown away in the wind. Every event in world history is an
expression of the racial instinct for self-preservation, whether for prosperity
or suffering.
The question of why the Aryan is so important is found in how his instincts
are expressed and not because he has a stronger instinct for self-preservation.
The individual’s will to live is equally great everywhere. Only the actual
form it takes will vary. In the most primitive creatures, the instinct of self-
preservation does not go beyond caring for itself. This selfishness extends to
include time, so that the immediate moment is the most important and
nothing is planned for the future. In this state, the animal lives for itself alone,
seeks food when it is hungry, and fights only when forced to defend its own
life. As long as the instinct of self-preservation takes this form, there is no basis
to form a community or even a primitive family.
Once the partnership between male and female becomes a true
partnership, not just for the purpose of mating, it then requires that the self-
preservation instinct be extended. The care and struggle for only self now
extends to protect the mate. The male often hunts for food, but when a child
is produced, they will both work to feed their young. One will almost always
fight to defend the other. This exemplifies the first forms of self-sacrifice, even
though this is infinitely primitive. When this feeling spreads beyond the limits
of the immediate family, we have the essentials required for the formation of
larger groups, and finally, of nations.
In the most primitive men on earth, this quality is present only to a very
limited degree, often not going beyond the formation of the family. As the
willingness to put aside purely personal interests increases, the more
advanced the ability to set up extensive communities will become.
262
People and Race
This will to sacrifice, to devote personal labor and, if necessary, life itself
to others, is most highly developed in the Aryan. The Aryan’s greatest power
is not in his mental qualities necessarily, but in the extent of his readiness to
devote all his abilities to the service of the community. In him, the instinct of
self-preservation can reach its noblest form because he willingly subordinates
his own ego for the prosperity of the community and is even willing to sacrifice
his own life for it, if necessary.
The reason for the Aryan’s constructive ability and especially his ability to
create civilizations does not lie in his intellectual gifts. If he only had
intellectual abilities, they might easily be destructive and he would never be
able to organize and build. The essential character of the individual depends
on his ability to forfeit his personal opinions and interests and to offer them
instead for the service of the community. Only by serving his community and
assuring its prosperity does he receive his own rewards. He no longer works
only for himself, but takes his place within the structure of the community,
not only for his own benefit, but for the benefit of all. The most wonderful
demonstration of this spirit is through Work. He understands that his labor is
not just for his livelihood, but his labor serves the interests of the community
without conflicting with community’s interests. Otherwise, the goal of his
work is only self-preservation without consideration for the welfare of the
community. In such a case his work for his own self-interest would be properly
called theft, robbery, burglary, or usury.
This spirit of placing the community’s prosperity before the self-interests
of one’s own ego, is the first essential element for every truly human culture.
This spirit alone has brought about all the great works of humanity. It
brings only a small reward to the originator, but rich blessings to future
generations.
This alone makes it possible to understand how so many people can bear
a shabby but honest life filled with nothing but poverty and insignificance;
they know they are laying the foundation for the existence of the community.
Every workman, every peasant, every inventor, and every civil servant who
labors without ever attaining happiness and prosperity is a pillar of this high
263
Mein Kampf
ideal, even though the deeper meaning of his actions are forever hidden from
him.
What is true about work as the basis of human survival and of all human
progress is true to an even higher degree when it is done for the protection of
man and his civilization. The surrender of one’s own life for the existence of
the community is the height of all self-sacrifice. Only in this way can we assure
that what we have built is not destroyed by Nature or human hands.
Our German language has a word that precisely and splendidly describes
that principle: Pflichterfüllung or performance of duty. That means service to
the common good of the community ahead of personal self-interests. The
fundamental spirit that creates this action is what we call idealism. It is the
opposite of egotism or selfishness. It means exclusively the individual’s ability
to sacrifice himself for the community, for his fellow-men. It is necessary for
us to realize that idealism is not superficial emotional gut-reaction or
humanitarianism, but that it is, was, and always will be the necessary
precondition for what we call human civilization. It is the source that provides
meaning to the word “human.” To this spirit, the Aryan owes his position in
this world, and to the Aryan the world owes the creation of “mankind.” For
this spirit alone shaped a creative force from a pure mind, which was a unique
marriage of muscular power and great intellect and this built the monuments
of human civilization.
Without its idealistic spirit, all the mental capabilities of the mind, no
matter how brilliant, would remain mere inner thoughts or technical
knowledge without any outward expression of the inner value and therefore
it would never become a creative force.
True idealism is the subordination of one’s self, of the individual’s interest
and life to the community; which is in accordance with the ultimate will of
Nature. This is the first essential element for the development of any kind of
organization. It leads men voluntarily to recognize the dominance of power
and strength and makes them into grains of sand within the realm of creation
from which the whole universe is made. The purest idealism unconsciously
becomes the perfect counterpart to the most profound wisdom.
264
People and Race
We can immediately see how true this is and how little genuine idealism
has to do with a fantasy-utopia by asking an unspoiled child, a healthy boy, for
instance.
This boy can listen to the rantings of an “idealistic pacifist” without
understanding a word he says, but the same boy will immediately be ready to
turn on his heel and sacrifice his young life for the ideal of his people.
This willingness results from an instinct in the unconscious which obeys a
deeper understanding, a need to preserve the species at the expense of the
individual if necessary. He naturally protests against the prophetic speech of
the pacifist, who tries to disguise himself as something other than the selfish
coward that he is, and is constantly seeking ways to violate the laws of Nature.
It is a necessary part of human evolution that the individual has a spirit of self-
sacrifice which favors the prosperity of the community and not on the
disgusting dreams of cowardly wise guys and critics who pretend to know
more than Nature and seek to violate her decrees.
When self-interest threatens to replace idealism, we notice an immediate
weakening in the force that maintains the community. When the community
breaks, so falls civilization. Once we let self-interest become the ruler of a
people, the bonds of social order are broken. When man focuses on chasing
his own happiness, he falls from Heaven straight to Hell.
Future generations do not remember the men who pursued their own
self-interests, but they glorify the heroes who sacrifice their own happiness.
The most extreme contrast to the Aryan is the Jew. The self-preservation
instinct is developed more strongly in the so-called “chosen people” than in
any other people in the world. The best proof of this is the mere fact that the
race still exists. What other people have undergone so few changes of mind
and of character in the last two thousand years as the Jew? What people have
gone through greater upheavals and yet always come through the most
tremendous catastrophes of humanity unchanged? An infinitely tenacious will
to live and to preserve one’s species is demonstrated by this fact! The
intellectual qualities of the Jew have been trained through thousands of years.
He is considered “cunning” today and, in a certain sense, always has been. But
his intellectual ability is not the product of his own evolution, but of object-
265
Mein Kampf
lessons from others. The human mind cannot climb without steps on which to
stand. The spirit requires successive steps to climb upward. Every upward
stride needs a foundation, one which is laid in the developments of the past,
and this can only be found in a civilization of people. Knowledge rests only to
a small degree on one’s own experience and predominately relies on the
accumulated past experiences and knowledge of others. The general level of
civilization provides the individual with this wealth of preliminary knowledge
which allows him to easily take further steps of progress on his own. This is
primarily done without the individual even being aware of it. The boy of today,
for instance, grows up surrounded by an absolute multitude of technical
achievements from past centuries. He takes these achievements for granted,
without noticing things that only a hundred years ago were a mystery to the
greatest minds. However, these achievements are critically important to him
if he is ever to understand our progress in a certain area or to improve on it. If
a genius from the 1820’s were suddenly to return from the grave today, he
would encounter a monumental intellectual adjustment before he could hope
to understand present time. Facing a new piece of technology would be more
difficult and confusing for the genius than it is for a modern average fifteen-
year old boy. This genius would lack all the endless preliminary knowledge
which the present day population absorbs automatically, as they grow up
among the technological products of their particular civilization.
For reasons which will immediately be apparent, the Jew has never
possessed a culture of his own and the basis for his knowledge has always
been furnished by the civilizations of others.
In every age, his intellect has developed by using the civilization
surrounding him. The reverse of that process has never taken place. The self-
preservation instinct of the Jewish people is greater than that of other
peoples. Even if their intellectual powers at first appear to be equal to other
races, they completely lack the all-important requirement of a civilized people,
the spirit of idealism.
The Jewish people’s willingness to self-sacrifice does not go beyond the
basic instinct of individual self-preservation. Their strong feeling of racial
solidarity is based on a very primitive “herd” instinct like you see in many other
266
People and Race
forms of life. It is worth mentioning that this herd instinct leads to mutual
support only as long as a common danger makes it seem useful or
unavoidable. The same pack of wolves which a moment before was united in
devouring its prey breaks up into individuals once their hunger has been
satisfied. The same is true of horses. They will band together in order to
defend themselves against attack and then scatter again when the danger is
past.
The same holds true for the Jew. His apparent will to self-sacrifice is
deceptive. It exists only when the life of each individual is at stake and an
alliance becomes absolutely necessary for the preservation of the individual.
The moment the common enemy is defeated, the common danger avoided,
or the plunder secured, the apparent harmony of the Jews’ pact among
themselves comes to an end, giving way once more to their original natural
tendencies.
The Jews are in agreement only when a common danger forces them, or
when a common prey tempts them. When they are not faced with either case,
their most insensitive selfish qualities take over and in an instant, these united
people become a swarm of rats carrying on bloody battle, bitterly fighting
against each other.
If the Jews were alone in the world, they would smother in filth and slop
and would try to outwit and exterminate one another in a bitter battle.
However, the lack of any willingness for self-sacrifice and the expression of
their own cowardice turns even this battle into a pretense.
It is a complete mistake to assume an idealistic self-sacrifice is seen in the
Jews when they come together to fight, or rather, when they come together
to exploit their fellow-men. Even here, the Jew is guided by nothing but
blatant individual selfishness. For that reason, the Jewish “State,” which
should be a vital organization aimed at the preservation and increase of a race,
has no boundaries. In order to have definite borders for a state, which give it
structure, one must have an idealistic spirit within the state’s race and a
proper understanding of the idea of labor. Any attempt to form or even to
preserve a state that has no boundaries will fail if this attitude towards work
is missing. Without a State, the sole foundation which a culture needs to grow
267
Mein Kampf
8Meaning the organ-grinder man of the time period, a street performer of questionable
morality who cranks a barrel-organ playing a repetitive tune as his monkey collects tips from
the crowd.
268
People and Race
becomes twisted into the model for the poet’s words: “The power whose will
is always evil but who ends up doing good.”9 It is not through the Jew’s
assistance that humanity progresses, but in spite of him.
Since the Jew has never had a state with definite territorial boundaries
and could never call a civilization his own, some have said they are nomads.
That idea is a deceptive mistake. The nomad definitely has a clearly
defined territory, although he does not cultivate; however, he is unlike the
farmer who settles on a piece of land. Instead he lives off his herds which he
follows as they wander about his territory. The reason he wanders is because
the soil is infertile and therefore cannot support a settlement. The deeper
cause, however, lies in the lack of a technical civilization which is needed to
compensate for the sparse resources. There are areas where development has
taken place over more than a thousand years, and it was only possible because
of the technology of the Aryan, who is able to make himself the master over
large areas and establish solid settlements that can support him. If he did not
have this technology, he would either have to avoid these areas or live as a
constantly wandering nomad. That is if, after thousands of years of living with
his technical developments, the idea of a sedentary nomadic life was not
intolerable to him. We must remember that at the time when the American
continent was being settled, many Aryans struggled for a livelihood as
trappers and hunters etc. They were often in large groups with their wives and
children and always on the move. Their existence was exactly like that of
nomads. But, as soon as their numbers grew to a certain point and better
equipment made it possible to tame the land and resist the natives, more and
more settlements sprang up throughout the country.
The Aryan was probably the original nomad and, over the course of time,
settled in one place. But even so, he was never a Jew! No, the Jew is not a
nomad. Even the nomad had a definite concept of “work,” which would serve
as the basis which he built his civilization on. There is a certain amount of
9Originally in German: kraft, die stets das böse will und stets das gute schafft, is a paraphrase
of a riddle from Faust which, based on what is happening in the play where Mephistopheles
makes this statement, appears to imply here that Jews do bad things which have the
unintentional result of producing something good.
269
Mein Kampf
idealism in the attitude of the nomad, even though it is primitive. His whole
nature may be foreign to the Aryan, but it is not disgusting to him. However,
this attitude simply does not exist in the Jew. Therefore, the Jew has never
been the nomad, but instead has always been a parasite fattening himself on
the body of other peoples. The fact that he has abandoned previous regions
was not by choice. He was driven out by his hosts who had become tired of
having their hospitality abused by these “guests.” Jewish expansion is an act
typical of all parasites. He is constantly looking for a new land for his race.
This has nothing to do with being a nomad because the Jew never dreams
of leaving an area or vacating a territory once he is there. He stays where he
is, and he holds on to it so intently that he is very hard to get rid of even by
force. He only spreads to new countries when conditions necessary for his
existence attract him. However, unlike the nomad, he doesn’t change his
previous residence. He remains a typical parasite, spreading like a harmful
bacteria wherever he finds a suitable place to grow. The effect of this parasite,
wherever he happens to be, causes the host nation to die off sooner or later.
The Jew has always lived in the states of other races and within that state
he has created his own state. This state within a state sailed under the colors
of a “religious community” and continued to do so as long as he was not forced
to reveal his true nature. Once he thought he was strong enough and no longer
needed to hide, he would drop the veil and suddenly all would see what so
many had refused to see and to believe previously, the real character of the
Jew.
The Jew’s life as a parasite within the body of other nations and states is
the origin of an unusual characteristic which caused Schopenhauer to describe
the Jew as the “great master of lies.” This kind of existence drives the Jew to
lie and to lie regularly and methodically in an orderly, businesslike way which
comes as naturally to them as warm clothes to those who live in cold climates.
His life within a nation can only continue if he convinces the people that
Jews are not a separate people, but merely a “religious community,” although
an unusual one. But this itself is the first great lie.
In order to carry on his existence as a parasite among other nations, he
must conceal his inner character. The more intelligent the individual Jew is,
270
People and Race
the more successful his deception will be. This deception may even convince
parts of the host nation that the Jew is really a Frenchman, an Englishman, a
German, or an Italian, just a person of a different religious persuasion.
Government offices are particularly easy victims of this notorious trick
because bureaucrats have little sense when it comes to history and only react
to a fraction of actual history. In such circles, independent thinking is often
considered a sin against sacred rules that determine who is promoted and who
is not. Because of this, we must not be surprised that the Bavarian State
Ministry, for instance, even today doesn’t have the faintest idea that the Jews
are members of a separate people and not of a simple “religious group.”
One glance at the world of Jewish newspapers immediately proves this,
even to someone of the most ordinary intellect. Of course, the Jewish Echo10
is not yet an official government journal, so in the mind of these government
officials they have no need to read it.
Jewry has always been a nation with definite racial characteristics and it
has never been identified solely as a religion. Their need to advance in the
world caused the Jew to search for a method that would distract undesirable
attention from its members. What could have been more effective and more
innocent in appearance than a religious community? Even here, everything is
borrowed, or rather stolen..
In fact, the Talmud11 is a book that explains how to prepare for a practical and
prosperous life in this world and it says nothing about preparation for the
hereafter.
The Jewish religious teachings consist mainly of rules to keep the blood
of Jews pure and to regulate the dealings of Jews among themselves and even
more with the rest of the world, with the non-Jews. Even here, their rules
consist of extremely petty economic guides and are not concerned with ethical
10 A Jewish newspaper.
11 The record of Jewish Law, ethics, customs, and history.
271
Mein Kampf
problems. For a long time, there have been very detailed studies made which
reviewed the moral value of Jewish religious teachings. These studies were
certainly not made by Jews because the Jews twist their statements to suit
their own purpose. The Aryans who conducted these studies found this kind
of “religion” to be detestable. The clearest indication of what this religious
education can produce is the Jew himself.. Christ was
nailed to the cross for his intolerance of the Jews, while our present Christian
political parties lower themselves in elections by begging for Jewish votes.
Afterwards, they try to hatch deceitful political plots with the Jewish atheist
parties and against its own nationality.
On this first and biggest lie, that Jewry is not a race but a religion, the Jew
builds subsequent lies. To him, language is not a way to express his thoughts,
but a way to conceal them. When he speaks French, his thinking is Jewish.
While he is fabricating German rhymes, nothing he says can be believed
because he is just expressing the nature of his own race, that of the lie. As long
as the Jew has not become the master of the other peoples, he must speak
their languages, but the instant they become his slaves, they will have to learn
an artificial universal language like Esperanto12 so that Jewry could rule them
more easily.
The whole existence of these people completely depends on one
continuous lie and this is uniquely proven in the “Protocols of the Elders of
Zion”13 that is so bitterly hated by the Jews. The Frankfurter Zeitung keeps
groaning to the world they are a forgery which is the best proof that they are
genuine. What many Jews wish to do unconsciously is consciously made clear
here. It does not matter what Jewish mind these revelations come from. What
12
Esperanto is an artificial international language based on word roots common in Europe.
13Which is an antisemitic work outlining a plot by Jewish and Masonic elements to achieve
world domination. Today the manuscript is known to be a forgery.
272
People and Race
matters is that they uncover the nature and activity of the Jewish people with
absolutely horrible accuracy and show their inner connections, as well as their
ultimate goal. This book shows how the Jewish mind works, and the activities
described, as well as the methods, are characteristic of the Jewish people. The
best test of the authenticity of these documents is by studying current events.
Anyone who examines the historical development of the last hundred years
with the revelations in this book will immediately understand why the Jewish
press is so upset and denounces it constantly. Once the contents of this book
have become general public knowledge, the Jewish threat can be considered
destroyed.
In order to know the Jew properly, it is best to study the road he has taken
through other nations during recent centuries. It will be enough to follow
through one example in order to fully understand. Since his career has always
been the same, just as the peoples he devours have remained the same, in the
interest of simplicity we will break up his development into definite steps,
which I will indicate by letters of the alphabet.
The first Jew came to what is now Germany during the advance of the
Romans. As always, they came as traders. During the turmoil resulting from
the great migration of German tribes, they seemed to disappear again. Jews
reappeared with the first formation of a Germanic state and this may be
considered the beginning of the new, and this time permanent, Jew infiltration
of Central and Northern Europe. The same process has occurred wherever
Jewry came into contact with Aryan peoples.
Letter A. With the foundation of the first permanent settlement, the Jew
is suddenly “there.” He appears as a trader at first and does not bother to hide
his nationality. He lives openly as a Jew. This is evident because of the extreme
physical racial difference between him and his hosts. His knowledge of the
local languages is minimal, and the clannish nature of the local people is too
strong for him to risk appearing to be anything but a foreign trader. With his
cunning he knew his lack of experience in the host nation was no
disadvantage, but rather an advantage, so it was in his interest to retain his
character as a Jew. The stranger finds a friendly reception among his hosts.
273
Mein Kampf
274
People and Race
come to know the Jew and in times of trouble, they saw his very existence as
a danger like the plague.
Letter E. Now the Jew begins to reveal his true character. Using the
disgusting tool of flattery, he pays homage to governments, puts his money to
work to dig deeper into the community, and in this manner keeps his license
to rob his victims. Even though the people’s rage against the perpetual leech
often blazes up, that does not stop him from returning again a few years later
in the same town and resuming his old life all over again. No amount of
persecution changed his ways and he continued taking advantage of men. No
matter how loudly the people shouted and yelled, no one could run him off.
Every time the Jew is chased away, he soon returns and is up to his old
tricks again. To prevent the very worst from happening, Jews were forbidden
by law from possessing land.
Letter F. As the power of the princes and kings grew, the Jew elbowed his
way closer and closer to them. He begs for deeds to property and for special
privileges. The noble lords were always facing financial problems which made
it easy for him to obtain these courtesies once he has made satisfactory
payment. It did not matter what this cost him because, within a few years, he
knew he would receive his money back with interest compounded many
times. This Jew is an absolute leech who fastens himself to the body of the
unfortunate people where they cannot remove him. There he feeds until the
princes need money again and, with their own dignified hands, they draw off
the blood he has sucked from the people.
This game keeps repeating itself. The role the German princes played is
just as disgraceful as that of the Jews themselves. These rulers became the
punishment of God on their dearly beloved people and we can still find their
kind among the various government ministers of today. It is because of the
German princes that the German nation could not free itself from the Jewish
troublemaker. Unfortunately, this never changed, so they received a reward
from the Jew that they had earned a thousand times over for the sins they
committed against their people. They associated with the devil and later found
themselves in his power.
275
Mein Kampf
Letter G. The Jewish entanglement of the princes soon leads to their own
destruction. Slowly, but surely, their support among the people grows weaker
as they cease to represent the people’s interests, and spend their time
exploiting their subjects. The Jew carefully watched for the time when the
princes would fall and when he sees it coming close, he does all he can to
speed up the collapse. He feeds their constant financial problems by
preventing them from honoring their true duty to the people, by boot licking
and using the most blatant flattery, by introducing them to vices, and in the
process he makes himself more and more indispensable. His skillfulness, or
rather deceitfulness, in all financial matters succeeds in sweeping, no, I should
say horsewhipping, new funds from the robbed subjects. These exploited
subjects find themselves driven down the road to poverty faster and faster.
Each court has its “Court Jews,” as the monsters are called, who torture the
people to the point of hopelessness and arrange the endless pleasures of the
princes. How can anyone be surprised that these “assets” of the human race
receive official honors and climb into the upper class by joining their families,
they not only make nobility look ridiculous, but they actually contaminate it
from the inside.
Now the Jew is in a better position, politically and socially, to push his
own advancement forward. Finally, he allows himself to be baptized and in
doing so he gains all the opportunities and rights of the native people. This act
of “business” delights the churches which believe they have a new son of Faith
among their flock, and this business also delights Israel14 when they see the
successful fraud they have accomplished.
Letter H. In the world of Jewry, a transformation now begins to take
place. Up until now, they have been Jews. That is to say that they had no
interest in appearing to be anything else, and, in fact, could not have done so
considering the very pronounced racial characteristics which differentiated
them from the native race. As late as the time of Frederick the Great,15
everyone regarded Jews as an “alien” people. Even Goethe16 was horrified at
14 The Jewish people, not the country, the country did not exist yet.
15 In the mid to late 1700’s.
16 Johann Wolfgang von Goethe, a famous German writer.
276
People and Race
the thought that someday, marriage between Christian and Jew may no longer
be legally forbidden. Goethe, Heaven knows, was no extreme conservative
and not against progress and certainly not a blind follower of philosophy.
What he felt was nothing but the voice of blood and reason. His race’s blood
and common sense spoke the truth to his ears. Even without all the disgraceful
actions occurring in the Royal Courts, the people instinctively saw the Jew as
a foreign substance in its own body and formed an appropriate attitude in
response.
Now was the time for a change to take place. Over the course of more
than a thousand years, the Jew has learned the language of his hosts so well
that he shows his Judaism less and dares to put his “German” side in the
foreground. As ridiculous and stupid as it may at first seem, he has the
audacity to transform himself into a “Teuton”17 or an actual “German.” This
was the beginning of one of the most notorious deceptions that can be
imagined. Since he possesses none of the qualities of German character and
can only abuse and twist its language and otherwise has never mixed with the
Germans to absorb their character traits, his ability to pretend to have a
German identity depends on his ability to emulate the language alone. A race
is not bound by their language, but entirely by their blood. This is something
the Jew knows better than anyone. The Jew doesn’t care about the
preservation of his own language, but he does care deeply about the purity of
his blood. A man may change languages and easily learn a new one, but his
new language will only express his old ideas. His inner nature is not changed.
The best proof of this is the Jew, who can speak a thousand languages, and yet
his Jewish nature remains intact; he is the same Jew. His characteristics have
always been the same, whether he spoke Latin two thousand years ago as a
grain merchant at Ostia18 or mumbles German gibberish today as a middle
man pushing adulterated flour. It is still the same Jew. It can be taken for
granted that this obvious fact is not understood by an average clerk’s
supervisor at any government office or by a police administrator today since
277
Mein Kampf
there is hardly anything with less instinct and intelligence running at large than
these civil servants chosen by our present model of a government.
The reason why the Jew suddenly decides to become a “German” is
obvious. He feels the power of the princes slowly beginning to waver, and acts
to strengthen his own standing. His financial domination over the entire
economic system has already advanced to a point that it can grow no further
until he gains the full rights of a citizen. He can no longer support the entire
enormous structure and his influence cannot increase anymore without this
critical piece. But not only does he want to preserve what he has, he wants to
expand further. The higher he climbs, the more tempting his old goal
becomes, just as it was promised to him in ancient times. With intense greed
and wide eyes, his alert mind sees the dream coming within reach again; the
dream of ruling the world. All his efforts are directed towards becoming a full
citizen which gives him full possession of civil and political rights.
This is why he cleansed himself from the Jewish Ghetto--so he could
become a full citizen.
Letter I. Through this process the Court Jew gradually developed into the
people’s Jew. This does not mean he lives among the people; no, it means that
the Jew remains among the noble lords as always and, in fact, tries more than
ever to worm his way deeper into their ruling circle. At the same time, another
part of his race begins to use flattery as their tool to gain approval with the
good, common people. When we consider what sins the Jew has committed
against the masses throughout the centuries, how he has persistently
squeezed and sucked them dry, how the people gradually learned to hate him
for it, and how the people finally came to see his existence as a punishment
on them from Heaven, we can understand how difficult this transformation
must be for the Jew. Yes, it is hard work to suddenly stand in front of those
victims you whipped raw and present yourself as a “friend of humanity.”
He begins by attempting to make amends in the eyes of the people for
his previous crimes. He starts his transformation by donning the cloak of a
“benefactor” to humanity. Since his new benevolence is very evident, he is
obviously unable to follow the teachings of the old quote from the Bible that
278
People and Race
the left hand should not know what the right hand is giving.19 He feels
compelled to let as many people as possible know how deeply he feels the
sufferings of the masses and what personal sacrifices he is making to help
them. With his innate “modesty,” the Jew drums his virtues into the minds of
the rest of the world until they actually begin to believe it is true. Anyone who
does not accept this belief is considered to be bitter and unfair to him. Within
a very short time, he begins to twist things to make it appear as if, up until
now, it was he who had suffered all of the wrongs and not the reverse. There
were many particularly stupid people who believed him and could not help
pitying the poor “unfortunate” Jew.
This, incidentally, is the place to remark that with all his fondness for self-
sacrifice, the Jew never becomes poor himself. He understands how to
manage his money. His benevolence can be compared to the manure that a
farmer spreads in the field. The farmer does not spread the manure because
he loves the field, but in anticipation of future benefits. In any case, everyone
knows within a fairly short time that the Jew has become a “benefactor and
philanthropist.” What a transformation! Generous actions are taken for
granted in others but they cause astonishment and frequently even
admiration in this case because it is so unusual for a Jew. People give him much
more credit for these deeds than they would give to any other member of
humanity. More than this, the Jew will suddenly become liberal and then he
begins to babble about the necessary progress of humanity and how it should
be encouraged. He slowly makes himself the herald of a new age.
It is also true that more and more, he completely undermines the pillars
of the economy which the people need the most. He used the stock exchanges
to buy shares of the national companies thereby breaking in to the cycle of
national production. He then changes production into an object to be bought
and sold by barter and exchange. This robs the factory workers of personal
ownership. With the introduction of the Jew, the split between employer and
employee occurs for the first time. This later leads to political class
resentment. Jewish influence on economic affairs through the stock exchange
19 Matthew 6:3, meaning do not flaunt generosity, not even in your own mind.
279
Mein Kampf
280
People and Race
He guards the Jewish nationality more than ever before. While he seems
to be overflowing with “enlightenment,” “progress,” “freedom,” and
“humanity,” etc., he practices the strictest isolation of his own race so they do
not mix with others. He may sometimes give one of his women to an
influential Christian, but as a matter of principle he always keeps his male line
pure. He poisons the blood of others, but preserves his own purity. The Jew
almost never marries a Christian woman while the Christian takes the Jewess
wife. But the bastards that result from this union always claim their place on
the Jewish side. As a result, part of the higher nobility has deteriorated
completely. The Jew knows this very well and they steadily use this method to
deceive and confuse the leading intellectuals of his racial enemies. To disguise
his actions and to soothe his victims, he talks more and more about the
equality of all men, regardless of race and color. Eventually, the simpletons
start to believe him.
The whole character of the Jew has the stink of a foreign being; therefore,
the great masses of the people do not fall into his snare so easily. He responds
by having his press paint a picture of him that is completely false yet useful for
his purpose. In comic journals, for instance, great pains are taken to represent
the Jews as a harmless little people who have their own unique peculiarities
just like everyone else. The comics portray a humorous, but always kind and
honest soul. In the same way, they are always careful to make him seem
insignificant rather than dangerous.
His goal at this stage is the victory of democracy, or rather, establishing
total dominance and rule by parliament which is democracy as the Jew
understands it. This is the system which is best fitted to his needs. It does away
with the personal element and puts a majority of stupidity, incompetence, and
cowardice in its place. The final result will be the downfall of the Monarchy,
which will eventually happen.
Letter J. The enormous change in economic development leads to a
change in the social levels of the people. The small craftsmen slowly disappear
as they are replaced by factory workers. This makes it impossible for the
individual workman to win any independence in his existence. As a result, he
sinks to the level of a day-laborer. The industrial factory-worker finds himself
281
Mein Kampf
282
People and Race
283
Mein Kampf
“against himself” because the “great master of lies” always succeeds in making
himself seem innocent and throwing the blame on others. Since he had the
audacity to lead the masses himself, it never occurred to the people that this
could be the most legendary fraud of all time. And yet, it was.
The new class barely had time to develop out of the economic
transformation before the Jew clearly recognized it as the new forerunner that
he could use to blaze the trail for his own further advancement. First, he used
the privileged-class to strike against the farm-based economy which created
the factory worker. Now, he uses the factory worker against the privileged-
class. Just as his craftiness helped him acquire civil rights in the shadow of the
privileged-class, now he hopes to find the road to his own power in the
workers’ struggle for existence.
When the time arrives, the workers’ only responsibility will be to fight for
the future of the Jewish people. Without being aware of it, the laborer is put
to work for the very power that he believes he is fighting against. He is led to
believe he is acting against capitalism, and therefore he is easily made to fight
for capitalism. The cry is heard against international capital, but the real target
is the national economy. The current economy must be destroyed so that the
international stock exchange can replace it on the corpse-strewn battlefield,
with Jewish financial world interests.
To achieve his goal, the Jew proceeds as follows: he creeps up on the
workers in order to win their confidence, pretending to have compassion for
their poverty and circumstances or even anger at their miserable lot in life. He
is careful to study all the real or even their imagined problems. Then he
arouses the desire for change. With infinite shrewdness, he stirs up the urge
for social justice, an innate desire that is sleeping within every Aryan. Once the
fire is burning, the Jew turns it into hatred toward those more fortunate and
puts the stamp of a very special World-Concept on the battle; he builds a
philosophy designed to correct social injustice. He founds the Marxist
doctrine.
By representing it as part of a series of socially justified demands, the Jew
is able to spread his message and inspire the people all the more easily.
284
People and Race
But at the same time he provoked the opposition of decent people who
rejected these demands after they recognized the fake philosophy, and
distorted form used to present the concepts. To these good people, it seemed
fundamentally unjust and a goal that was impossible to accomplish. Under this
covering of purely social ideas we find that extremely evil intentions are
present. In fact, they are openly presented, in full public view, with the most
bold insolence. This doctrine is an inseparable mixture of reason and
absurdity, but it is always arranged so that only the absurd parts could be put
into practice and never the parts of reason. By its absolute denial of the
personal value of the individual and of the nation and its racial substance, it
destroys the basic foundations of all human civilization which depends
precisely on those factors. This is the true core of the Marxist World-Concept,
if this creature of a criminal mind can be called a “World-Concept.” The
destruction of individuality and race removes the primary obstacle that
prevented domination by the inferior man, the Jew.
The very absurdity of the economic and political theories of Marxism give
it an unusual characteristic. These pseudo-theories prevent intelligent people
from supporting the cause, while the intellectually challenged and those who
lack any understanding of economics rush to it waving their flags furiously.
Even this movement needs intelligence in order to exist, but the intelligence
driving the movement is “sacrificed” by the Jew from his own ranks as a
glorious service to the masses. A movement made up of laborers was thereby
created but under Jewish leadership. It gives the impression that it aims to
improve the conditions the worker lives under, but its true intent is to enslave
him and thus totally destroy all non-Jewish peoples.
In the circles of the so-called intellectuals, Freemasonry spread their
pacifist teaching which paralyzed the instinct for national self-preservation.
This poison was then spread to the broad masses of workers as well as the
privileged-class by the mighty and unceasing Jewish press. A third weapon of
disintegration is added to these two and is by far the most fearful. It is the
organization of brute force. Marxism plans to attack and storm any shreds of
social order it has not yet undermined and to complete the collapse which was
started by the first two weapons.
285
Mein Kampf
286
People and Race
interested in a real and honest correction of social abuses, but only in forming
a blindly devoted economic fighting force that will shatter national economic
independence. The direction of a sound social policy will always balance
between the necessity of preserving the people’s health on the one hand and
of assuring an independent national economy on the other hand. These two
considerations are not part of the Jew’s plan, they are not even considered in
this struggle, only their complete elimination is the purpose of his life. He does
not want to preserve an independent national economy; he wants to destroy
it. Consequently, as leader of the trade-union movement, he has no
conscience or doubts to prevent him from making demands that go beyond
their declared purpose, or making demands that are either impossible to fulfill
or would mean the ruin of the national economy. He does not want to create
a solid and tough race of people as followers. He needs a decayed herd ready
for submission. This ultimate objective allows him to make the most absurd
and senseless demands because he knows that accomplishing them is
unrealistic or impossible. Making these demands, which cannot be
accomplished, will never produce any change in the status-quo. At best, it
would only create unrest and turbulence among the masses. This, however, is
what he is after and not a real and honest improvement in social conditions.
The Jew’s leadership in trade unions will continue until either a massive
education campaign opens the eyes of the broad masses and enlightens them
to the true source of their unending misery, or the State disposes of the Jew
and his work. As long as the masses lack the ability to understand, and the
State remains as indifferent as it is today, the masses will follow anyone who
makes the boldest promises in economic matters. In this, the Jew is a master
and he has no moral hesitations to interfere with his activities! In the trade
unions, he soon defeats every competitor and drives them away. His inner
nature of greedy brutality leads him to teach the union movement the most
brutal use of force. If anyone with sound judgment has been able to resist the
Jewish traps, his defiance and wisdom are broken by terrorism. The success of
this tool is tremendous.
287
Mein Kampf
288
People and Race
flare, and they will be judged as his enemy. Since the Jew is not the victim but
the aggressor, he sees his enemy not only in the man who attacks, but also in
any man who is capable of resisting him. The methods that he attempts to use
to break down such bold, but respectable souls are not the methods one
would consider part of honorable battle. His choice of weapons are lying and
slander.
The Jew is not frightened by anything and his cruelty becomes enormous.
As a result of this, we shouldn’t be surprised if our people someday view the
personification of the Devil, the symbol of all evil, as the Jew himself. The
ignorance of the broad masses when it comes to the inner nature of the Jew,
and the blindness and stupidity of our upper classes, makes the people an easy
victim of this Jewish campaign of lies. While natural cowardice makes the
upper classes turn away from any man the Jew attacks with lies and slander,
stupidity or simple-mindedness makes the broad masses believe everything
they hear. The State authorities either hide behind a wall of silence or
prosecute the victim of an unjust attack just to put an end to the Jewish
journalistic campaign, and that is what usually happens. The procedure of
quieting down any such trouble, which in the eyes of one of these jackasses in
office, is supposed to maintain governmental authority and safeguard peace
and good order. Gradually the Marxist weapon in the hands of the Jew
becomes a constant bogey-man to decent people. Fear looms like a nightmare
on the mind and soul of decent people. They begin to tremble in front of the
fearful enemy and in that moment they become his doomed victims.
Letter K. The Jew’s domination of the State government seems so assured
that he can now openly admit his basic racial and political beliefs and publicly
call himself as a Jew again. One part of the Jewish race quite openly admits to
being an alien people, though not without lying again, even here.
When Zionism tries to convince the world that the racial self-
determination of the Jew would be satisfied with the creation of their own
State in Palestine, the Jews are once again craftily pulling the wool over the
eyes of the stupid goyim.20 They never intended to build a Jewish State in
289
Mein Kampf
Palestine, not for the purpose of living in it anyway. They just want an
organization headquarters for their international swindling and cheating with
its own political power that is beyond the reach and interference from other
states. It would be a refuge for crooks who were exposed and a college for
future swindlers.
It is a sign of their growing confidence and security that some proclaim
themselves as part of the Jewish race and others are still falsely pretending to
be Germans, Frenchmen, or Englishmen. This impudence and the horrible way
they engage in relations with the people of other nations makes it obvious
that they see victory clearly approaching.
The black-haired Jewish boy waits, with Satanic delight on his face, for
the hour when he can corrupt the unsuspecting girl with his blood, and in
seducing her, steal her from her people. The Jew will attempt to undermine
the racial foundations of the nation to be conquered using every means
possible.
The Jew steadily works to ruin women and girls so that he can break down
the barriers of blood on an even larger scale. It was the Jews who brought the
negro to the Rhine. The motive behind this is clear and his intention is always
the same. He wants to destroy the hated white race through bastardization.
He continues to bring negroes in as a flood and force the mixing of races. This
corruption puts an end to white culture and political distinction and raises the
Jew up to be its masters. A racially pure people, which is conscious of its blood,
can never be defeated by the Jew. In this world, the Jew can only be the master
of bastards. This is why he continually tries to lower the racial quality by
poisoning the blood of individuals among the targeted peoples.
The Jew begins to replace the political idea of democracy with that of a
dictatorship for the working class. In the organized masses who follow
Marxism, the Jew finds he is holding a weapon that allows him to do without
democracy and permits him instead to conquer and rule the people through
the iron hand of a dictatorship. The Jew works systematically in two directions
for the revolution: economically and politically. Any nation that violently
resists his internal attack is surrounded by a net of countries which fall more
easily. This ring forms a network of enemies around his target and incites the
290
People and Race
nation into war, and finally, if necessary, when the troops are on the
battlefield, he raises the flag of revolution, right when the country is least
prepared.
Economically, the Jew shakes the State until its social services begin to
sway. They become so costly that they are transferred away from national
control and put under his financial control. Politically, he blocks funding and
denies the State access to the resources it needs for self-preservation, he
destroys the foundations of any national resistance or defense, he destroys
faith in the government leadership, he ridicules the nation’s history, and he
drags everything that is truly great into the gutter.
Culturally, the Jew corrupts art, literature, and theater. He makes fun of
national sentiment, upsets all ideas of beauty and nobility and idealism and
anything good. He drags people down into the realm of his own lowest nature.
Religion is made ridiculous and morals and decency are represented as old and
worn out. He continues his attack until the last support on which the national
being must rest, which the nation needs if it is to fight for survival in this world,
is gone.
Letter L. Now the Jew begins the great and final Revolution. As he battles
his final few steps to political power, he tosses aside the few veils he still
wears. The democratic Jew, the popular Jew, become the “Bloody Jew,” and
he reveals himself as a tyrant over the people. Within a very few years, he
attempts to eliminate the intelligent classes of the nation, and by robbing the
peoples of their natural, intellectual leadership, prepares them for the slave’s
destiny under his tyrannical dictatorship.
The most horrible example of this tyranny is Russia, where the Jew has
killed or starved close to thirty million people, sometimes using inhuman
tortures to enforce his savage fanaticism and assure domination over a great
people. This is done to satisfy a crowd of Jewish intellects and financier
bandits. The end does not mean just the end of the freedom for the people
oppressed by the Jew. It also means the end of the Jew himself as these
national parasites begin to disappear. After the death of the victim, the leech
itself also dies sooner or later.
291
Mein Kampf
292
People and Race
influences through the press, there is one truth that is present always and
everywhere— the bottom line is that the source of our problems is a neglect
of our own people’s racial concerns and a failure to see an approaching alien
racial threat.
Therefore, all attempts at reform, all social work and political efforts, all
economic advancement, and all apparent increases in spiritual knowledge
have ultimately failed to produce any results of value. The nation and that
being which makes it possible, the State, have failed to build inner strength.
They have not grown healthier, but have visibly wasted away from this
disease. All the false prosperity of the old Empire could not hide the inner
weakness, and every attempt to strengthen the Empire was abruptly halted
when this, the most important question, was ignored and set aside.
It would be a mistake to think that all of those who doctored the German
political body with various political ideas and their leaders were bad or
malicious men by nature. No matter what they did, their work was condemned
to fail because, at best, they only saw the symptoms of our general sickness
and tried to combat those obvious signs. They then walked blindly past the
root cause of this disease. Anyone who has calmly and systematically traced
the old Empire’s line of political development cannot help but realize that
even when the German nation was unified and on the rise, its inner decay was
already in full swing. Despite all the political successes that seemed to occur
and an increasing economic wealth, the general situation grew worse from
year to year. Even the rising tide of Marxist votes at the Reichstag elections
foreshadowed the ever-approaching inner and outer collapse. The successes
of the middle and upper class political parties meant nothing. This was not
only because they could not prevent the numerical growth of the Marxist
flood, even when they had so-called victorious middle-upper class elections,
but mostly because they already carried the seeds of degeneration within
themselves. The upper class world itself had no idea it was infected with the
rotting flesh virus of Marxist ideas. The occasional visible resistance to
Marxism was usually due to envy and competition between ambitious leaders
and not based on principals or beliefs by those determined to fight to the
bitter end. One figure alone fought throughout those long years with
293
Mein Kampf
unshakable perseverance, and this figure was the Jew. The Star of David rose
higher as the will for the self-preservation among our people disappeared.
In August of 1914, the battlefield was not stormed by a solid nation with
a determined spirit. Only a small glimmer of the nation’s self-preservation
instinct remained as a result of the Pacifist-Marxist paralysis inflicted on our
political body. In those days the enemy within remained unrecognized. This
failure to see the inner cause meant all outer resistance was useless. That is
why Providence did not deliver a sword of victory as the reward, but instead
followed the law of eternal retribution. From this realization came the guiding
principles and the tendency of our new Movement. We were convinced that,
only by recognizing these truths could we alone stop the decline of the
German people, and lay a solid foundation on which a new state may someday
exist. A state that will not be part of an alien machine of economic concerns
and interests, but a being of the people. A Germanic State in a German nation.
294
CHAPTER TWELVE
At the close of this first volume, I want to describe the early development of
our movement and briefly discuss a number of the problems we faced. I do
not intend to make this a full dissertation on the intellectual aims of the
movement. The intent and mission of the new movement is so tremendous
that they will have to be discussed in their own volume. In that second volume,
I will discuss at length the foundations of the movement’s program and
attempt to explain what we mean by the word “State.”
By “we,” I mean all the hundreds of thousands who see the same
fundamental goal in their mind’s eye, but can’t find the perfect words to
describe what is in their heart. All great reforms have a unique aspect where,
at first, one man steps forward as a champion to represent many millions of
supporters.
His goal is the same as the heart’s desire inside hundreds of thousands of
men from centuries before. The world waits until someone finally appears as
the herald of the masses to raise the flag of their deepest desire and lead them
to victory with a new idea.
Millions have a strong desire in their hearts to see a radical change in the
present condition of our nation. This fact is proven when we see the
unhappiness suffered by our people. This discontent is expressed in a
thousand forms. For one man, it is manifested as discouragement and despair.
In another, it appears as disgust, anger, and resentment. Still others may
become indifferent as a result of their profound discontent or their feelings
295
Mein Kampf
may be expressed as violent wrath. We can see even more of this inner
discontent in the people who have become election-weary and have quit
dropping their ballot altogether, while others may seek refuge in fanatical left-
wing extremes. Our young movement will appeal to all of these. Our aim was
not to be an organization of the contented, satisfied and well-fed, but instead
to unite the suffering and the discontented, the unhappy, and the dissatisfied,
those who could not find peace. Above all, our organization must not float on
the surface of the political body, but must have its roots in the foundation of
the people.
Taken purely from a political standpoint, the nation had been torn in half
by 1918. One half, which was by far the smallest, includes the classes of the
intellectuals and nobles. This class excludes all those who do physical labor. It
is outwardly a nationalist group, but they cannot understand the meaning of
nationalism except as a very flat and feeble method to defend so-called State
interests. These interests seem to be identical with the interests of the
Monarchy. This class tries to defend its ideas and aims with intellectual
weapons that are both incomplete and shallow with only a superficial effect.
Such weapons proved to be a complete failure when pitted against the
enemy’s brutality. With one violent blow, the ruling class of intellectuals was
now struck down. Trembling in cowardice, it swallowed every humiliation
from the cruel victor.
The second class is the great mass of the workers united in, more or less,
radically Marxist movements. These movements are determined to break
down any intellectual resistance using brute force. The Marxist movement
does not have any intention of being nationalist, but deliberately opposes any
advancement of national interests, and equally supports all foreign
oppression. This group is the largest in number and strength. It, most
importantly, includes those elements of the nation required for a national
revival. Without them, a revival is unthinkable and even impossible.
By 1918, it was obvious that any recovery of the German people could
only be possible by restoring the nation’s strength and then regaining outside
power. This does not require arms as our leader class of “Statesmen” keep
babbling, but strength of will. At one time the German people had more than
296
World-Concept and Party
enough weaponry. Those tools were not enough to protect our freedom
because the national instinct for self-preservation and the will to survive were
missing. The best weapon is a useless, lifeless clump if there is no spirit ready,
willing and determined to make use of it. Germany became defenseless
because the will to preserve the people’s survival was absent and not because
they lacked the weapons.
Today, when our left-wing politicians, in particular, try to point to
disarmament as the unavoidable cause of their cowardly, weak-willed,
submissive, or more accurately traitorous foreign policy, there is only one
answer to their claim: No. The truth is the other way around. Your anti-
national, criminal policy of surrendering national interests, was the reason you
delivered up our arms. Now, you try to claim that a lack of arms is the reason
why you behaved like disgraceful wretches. This, like everything else you do,
is a lie and a bogus claim.
This reproach must fall equally on the politicians of the Right. Thanks to
their miserable cowardice, the Jewish gang that came into power in 1918
could steal the nation’s arms. They have no reason or right to refer to the
present disarmament as the reason they are forced to exercise wise caution,
which is pronounced “cowardice,” when dealing with foreign policy matters.
The nation’s defenselessness is the result of their cowardice.
The question of regaining German power is not “How do we manufacture
arms?” the real question is, “How are we to produce the spirit that enables
our people to bear arms?” When a strong will rules the spirit of the people,
they will find a thousand ways, each of which ends with a weapon. Give a
coward ten pistols and, in an attack, he will still be unable to fire a single shot.
A wooden stick in the hands of a courageous man is worth more than ten
pistols in a coward’s hands.
Regaining our people’s political power is mainly a matter of recovering
our instinct for national self-preservation. If for no other reason, this instinct
is necessary because, as shown by experience, any foreign policy decisions of
the state are guided less by the armaments on hand, and more by the real or
supposed moral strength of a nation. A nation’s value in an alliance is
determined by the existence of an intense national will to survive and a heroic
297
Mein Kampf
298
World-Concept and Party
it any possibility of beneficial alliances. We are not the only ones who
recognize that our fifteen million Marxists, Democrats, Pacifists, and Centrists,
are a weakness. This same obstacle is seen even more by foreign countries,
who measure of the value of a possible alliance with us according to the
weight of this handicap.
No one is going to ally himself with a state in which the active part of its
population is, at the very least, passively against any decisive foreign policy.
We must also face the fact that an instinct of self-preservation will make
the leadership of these parties of national treason hostile toward any solution;
otherwise they would lose their current positions. A short look into history
makes it simply unthinkable that the German people could ever regain the
nation’s status without holding those who were responsible for the collapse
of our State accountable for their actions. When future generations sit in
judgment, November of 1918 will not be seen as mere rebellion, but as high
treason against the nation. Any recovery of German sovereignty and political
independence is linked to our people’s ability to recover their unified will.
Even from a purely technical standpoint, the idea of a German liberation
from outside control is obviously nonsense until the great masses are also
ready to support this idea of freedom. From a purely military point of view, it
must be clear, especially to any officer who gives it a little thought, that we
cannot carry on a foreign battle with student battalions. We need the strength
and might as well as the brains of the people. We must also keep in mind that
any national defense built solely on intellectual ranks is a waste of an
irreplaceable treasure. The young German intellectuals who joined the
volunteer regiments and met their deaths in the fall of 1914 on the plains of
Flanders were missed deeply later. They were the dearest treasure the nation
had and their loss was never made good during the war.
The battle itself cannot be fought unless the working masses are part of
the storm battalions. The technical preparation is also impossible to carry out
without the inner unity of will in the nation itself. Our people, in particular, are
living without a true military, completely disarmed, under the thousand eyes
of the Versailles Peace Treaty. The nation cannot make any practical
preparations to win its freedom and human independence unless the army of
299
Mein Kampf
spies on the inside is cut down to the nub. Only those whose native lack of
character allows them to betray anything and everything for the proverbial
thirty pieces of silver will remain. Those people can be taken care of; however,
there are millions who oppose the national recovery based on their political
convictions.
Those people are not so easily overcome. They cannot be defeated until
the cause of their opposition, the international Marxist World-Concept, is
combated and its teachings are torn from their hearts and minds.
From any standpoint where we examine the possibility of recovering our
independence as a state and a people or from the standpoint of establishing
foreign policy as an equal state among states, technical armament, or the
struggle itself, the one indispensable element we need is to win over the broad
masses of our people to the idea of national independence.
If we do not regain our freedom from the clutches of other nations, we
cannot hope to gain anything from inner reforms. Any changes that do occur
will only make us more profitable as a colony to our occupiers. The surplus
from any so-called economic improvement will go into the pocket of our
international masters, and any social improvement will increase our
productivity, which in turn benefits only them. Cultural progress will not be
the fortune of the German nation at all. Progress depends too much on the
political independence and dignity of a nation.
We can only obtain a satisfactory solution for the problem of Germany’s
future by winning over the broad masses of our people so they support a
national idea. Therefore, the work of educating the masses must be
considered our top priority. This priority must be pursued by a movement
which is not out to meet the needs of the movement itself but is forced to
consider the consequences of what it does, or does not do, based on what the
future result will be.
We realized as early as 1919 that the new movement’s highest aim must
be the nationalization of the masses. From that tactical point of view, a series
of requirements resulted: No social sacrifice would be considered too great if
it meant winning the masses to our side for a national revival. No matter what
economic concessions are made to our wage earners today, they cannot
300
World-Concept and Party
compare to the ultimate gain for the whole nation if they help bring back the
common people to their nationality. Only narrow-minded, short-sighted
people, like those found all too often among our employers, can fail to realize
that in the long run, there can be no economic improvement for them and no
further economic profit if the inward solidarity of our nation is not restored.
If during the war, the German trade-unions had ruthlessly protected the
interests of the workers, the war would not have been lost. Even if during the
war, they had fought the money-hungry employers for the demands of the
workers they represented by constant strikes, the war still would not have
been lost. At least this would be true, and the war would not have been lost.
If they had been as fanatical in their German nationality toward the nation’s
defense and had equal ruthlessness for the Fatherland and given what is due
the Fatherland, then the war would not have been lost. How trivial even the
greatest economic concession would have been when compared to the
enormous significance of winning the war! A movement that intends to
restore the German worker to the German people must realize that economic
sacrifices are no consideration at all as long as they do not threaten the
independence of the national economy.
1. The national education of the broad masses can only take place
through social improvement. This alone will create the general economic
conditions that allow the individual to share in the cultural treasures of the
nation.
2. The nationalization of the broad masses can never be accomplished by
half-way measures or by weakly arguing the so-called objective merits of your
position. It can only happen by ruthlessly and fanatically concentrating on
achieving a one-sided goal. A people cannot be made “nationalist” in the sense
of our modern upper and privileged-class; their arguments have too many
limitations and reservations. The people can only be made truly nationalistic
with the intensity that comes from taking an extreme position. Poison is driven
out only by counter-poison and only the shallowness of the privileged leader-
class spirit could ever think the middle road is the path to Heaven; the
Kingdom of Heaven is not obtained by compromise.
301
Mein Kampf
302
World-Concept and Party
5. All the great problems we face today are short-term difficulties that
result from simple origins which have clear and definite causes. But among
them all, there is only one with truly great importance. It is the problem of
preserving the nation’s race. The strength or weakness of man is deeply
rooted and dependent on his purity of blood. Nations that do not recognize
and respect the importance of their racial stock are like men who foolishly try
to train a poodle to be a greyhound. Such a man fails to understand that the
speed of the greyhound and the intelligence of the poodle are not qualities
that can be taught, but they are qualities which are inherent in race. A nation
that fails to preserve their racial purity also sacrifices the unity of their soul in
every way. The disunity of their nature is the inevitable result of the disunity
of their blood. The change in their intellectual and creative force is similarly
the result of the change in their racial foundations. The man who would free
the German people from those bad characteristics, characteristics which are
not part of its natural makeup and come from foreign sources, that man must
first release the nation from the origin of these foreign characteristics. Until
we clearly recognize and accept the race problem and the Jewish problem, the
German nation can never rise again. The race question is the key to world
history and to all human civilization.
6. Assigning the great mass of people who are now in the internationalist
camp to their proper place in a national community does not mean that we
will sacrifice the protection of their class interests; we will not abandon the
worker. Differing interests among labor and trade groups are not the same as
class division, but these differences are natural consequences of our economic
life. The grouping together of trade members and workers does not interfere
with the concept of a true national community. A national unity is one that
unifies all problems concerning the life of the nation so that no one is left out.
In order to bring into the national community or into the State one of the
new trade or worker classes means we must not lower our current upper
classes, but instead must raise the lower classes to a higher level. The higher
class can never be the one who starts this process. It must be the lower class
who is fighting for equal rights. The present privileged-class did not gain their
position within the State by legislation or action of the aristocracy.
303
Mein Kampf
They achieved their position through their own energy under their own
leadership.
A movement cannot help the German worker take his place among the
German community if that movement depends on weak displays of
brotherhood, with everyone patting each other on the back as they talk about
the problems of society before ending their meeting with a handshake. No,
the movement must deliberately improve the workers’ social and cultural
position, and this active role must continue until the greatest and most
difficult to bridge differences can be considered overcome. A movement
which has this kind of positive development as its aim will have to gain its
supporters primarily from the workers’ camp. It can recruit the intellectual
only if that person completely understands the goal the movement is working
toward. This transformation process will not be finished in ten or twenty
years. Experience shows that it will take many generations.
The obstacle that prevents today’s worker from taking his place in the
national community is not his worker interests, but rather the obstruction
comes from his international leadership and his attitude which is hostile to the
people and the Fatherland. If the very same trade unions had a leader who
was fanatically nationalist in political concerns, that leader would turn millions
of workers into precious members of their nationality. This would happen
regardless of individual battles over purely economic concerns.
A movement that aims to restore the German worker to his people in an
honorable way, and to relieve him from the internationalist madness his head
has been filled with, must make a forceful stand against a certain common
attitude in business circles. This attitude preaches that national community
means a complete surrender, without resistance, of all economic rights of the
wage-earner to the employer. This belief furthermore claims every attempt by
the workers to defend themselves, even when it comes to rightful and
necessary economic interests of the wage-earner, are attacks on the national
community. Those who uphold this attitude are deliberate liars. In a
community, all obligations for one side must be equally subject to the other
side.
304
World-Concept and Party
305
Mein Kampf
attitudes toward economic questions are still so great, that the moment the
excitement of the demonstration had died out, their presence and nature
would immediately become an obstacle to the movement.
Finally, the purpose of the Movement is not to produce a new set of levels
within the existing group of nationalists, but to win over those who are
antinational.
It is this perspective and strategy that will guide the whole movement.
7. This one-sided, but clear attitude must also be expressed in the
movement’s propaganda.
If the movement’s propaganda is to be effective, it must aim in one
direction only, that is to say at one class only. If it attempts to aim at both
upper and worker classes, the difference in their intellectual preparation, their
educational background, would either prevent the message from being
understood by one side, or be rejected because it appears to simply state
obvious and uninteresting truths by the other class.
Even the wording and the tone could never be equally effective on two
classes which are so noticeably different. If the propaganda sacrifices primitive
words and sharp expressions, the broad masses will not connect with the
message. But if the propaganda includes straightforward statements that
appeal to the masses’ feelings and uses expressions they commonly use, the
intellectuals will object and declare it to be coarse and vulgar. Among a
hundred public speakers, there wouldn’t even be ten who can speak with
equal effect in front of an audience of street-cleaners, mechanics, and sewer
workers today and tomorrow, give a lecture with the same intellectual
substance in front of an auditorium of college professors and students. In a
thousand speakers, there may be one who can address mechanics and college
professors at the same time, and in a style that not only speaks on both their
levels, but can influence both of them equally, or possibly even captivate them
so strongly that the result is a roaring storm of applause. We must never forget
that the greatest idea which embodies a noble spirit and supreme worth can
only be circulated to the public through the smallest of minds. The most
important point is not what the inspired vision of the creator of an idea was
when he set out to spread his message, but what the announcement of this
306
World-Concept and Party
idea to the masses translated into, how those who spread the message shape
its meaning and how successful they are in leading the masses to accept the
idea.
The ability of the Social Democracy movement, and the whole Marxist
movement, to attract followers depended on the unity and the one-sidedness
of the public it targeted. The more limited and narrow their argument’s line of
thought was, the more easily it was accepted and digested by masses whose
intellectual ability was on the same level with what they were told.
As a result of this knowledge, our new Movement laid down a clear and
simple guideline. The theme and form of the propaganda used to promote our
message is to be aimed at the broad masses exclusively and the quality of
propaganda can only be measured by its success.
The best speaker at a popular meeting of the common people is the one
who captures the heart of the masses and not the one who is able to
harmonize with the spirit of the intellectuals who attend. If an intellectual
attends this kind of meeting and complains about the low-brow level of the
speech, even though he can clearly see the lower class has been rallied and
moved by the speech, it proves that he is incapable of thinking and worthless
to the young movement. The only intellectual who is valuable to the
movement is the one who understands the mission and purpose so
completely that he has learned to judge the work of propaganda totally by its
success and not by the impression it makes on him personally. The purpose of
propaganda is to completely win over those who are against nationalism and
not to entertain intellectuals who are already nationally-minded.
In general, those lines of thought which I briefly summed up in the “War
Propaganda” chapter should be considered critical guiding rules for the young
movement. These concepts proved to be of great value when deciding on the
type of propaganda and how it would be distributed to best accomplish its
work of enlightenment. Success has proved these methods to be sound.
8. The aim of a political reform movement can never be attained by
explaining their views to the public or by influencing the ruling powers. A
movement can only obtain political reform by taking political power into its
own hands. Every idea that is meant to shake the world has the right and duty
307
Mein Kampf
to secure the means necessary to carry out its aims, and it must continue until
they are accomplished. Success is the only earthly judge of right and wrong in
such an undertaking. Success does not mean, as in 1918, the victory of gaining
power in itself. True success must be for the benefit of a nation. It must serve
the common interests of the people. Therefore, a coup d’état cannot be
considered successful, although thoughtless State’s Attorneys in Germany
today believe it should, merely because the revolutionaries have succeeded in
seizing governmental power. It is only successful when the basic purposes and
goals of the revolutionary action prove they can do the nation more good than
the previous regime did when they have been placed in practice. This is
something which cannot be claimed by the German Revolution, as that bandit
raid in the fall of 1918 called itself.
9. If the conquest of political power is what is required to accomplish the
movement’s goals and reform the state, then the movement must consider
from the very beginning that it is a movement of the masses, and that it is not
assembled for a tea party or a bowling game.
The young movement is by nature and inner organization anti-
parliamentarian. That means that both in general beliefs and in its own inner
structure, it is against majority rule where the leader is only a figurehead and
a puppet-executor of the will and opinion of others. When dealing with the
smallest and greatest problems, the movement upholds the principle of
absolute authority for the leader, who also carries the highest degree of
responsibility.
Here is how the results of this principal are applied in the Movement: The
chairman of a local group is appointed by the next higher leader. He is the
director of the local group and responsible for them. All the committees in the
local group are under his authority--he is not under their authority. There are
no voting committees, but only working committees. The director is the
chairman over the committees and he divides up the work for them. The same
principle holds true for the next superior organizational level above, the
district, the county, or the city. The leader is always appointed from above and
endowed with absolute power and authority. Only the leader of the entire
party is elected by the general assembly for the purpose of organization law.
308
World-Concept and Party
He is the exclusive leader of the movement. All the committees are under his
authority; he is not under the authority of any committee. He dictates and
bears the responsibility on his shoulders. The followers of the movement are
free to hold him accountable before a new election and to relieve him of his
office if he has not upheld the principles of the movement or has not served
its interests. He is then replaced by the new and more able man, who has the
same authority and the same responsibility.
One of the most important tasks of the movement is to put this principle
in force, not just within its own ranks, but throughout the entire State. The
man who would be leader has supreme and unlimited authority but also
carries the final and greatest responsibility. A man who is incapable of this kind
of responsibility or who is too cowardly to face the results of his action is
worthless as a leader. Only a man of heroic quality has the true talent for
leadership.
The progress and civilization of mankind are not products of the majority,
but they depend totally on the inspiration and strength of a single personality.
To encourage and promote this progress is one of the essentials for
regaining the greatness and power of our nationality.
Because of our principles we must be anti-parliamentary and any
participation in a legislative organization can only be for the purpose of
ultimately destroying it from within and thereby eliminate an institution
where we see one of the most serious symptoms of mankind’s decay.
10. The movement definitely refuses to take a stand on questions that
are outside the limits of its political work or immaterial to its aims because
they are of no importance in achieving our principle goals. The movement’s
job is not religious reformation but a political reorganization of our people. It
considers both religious denominations to be equally valuable and
acknowledges that they provide vital support for the existence of our people.
Therefore, the movement will attack those parties that try to degrade this
foundation by turning religious institutions into a tool for their own party
interests.
Those institutions provide our political body with religious and moral
support.
309
Mein Kampf
310
World-Concept and Party
a leader and guide them in the doctrine. When the group grows to a point
where it can no longer support one-on-one interaction, an organizational
structure is required. The ideal condition comes to an end and in its place we
have the necessary evil of organization. Small sub-units are formed by the
creation of local groups of members, for instance, and these represent the
nuclei for the growth of the political movement’s later organization.
However, if the unity of the doctrine is to be maintained, sub-groups
cannot be created until the authority of the intellectual founder and his beliefs
are accepted absolutely and completely. The next requirement is a centrally-
located headquarters and its importance for a movement cannot be
overestimated.
The location should be chosen such that it is surrounded by the magic
spell of a Mecca or a Rome. This place can give a movement a particular
strength that only comes from inner unity because it provides recognition that
there is one creator and leader who represents this unity.
In forming the first nuclei of the organization, it is critical to maintain the
importance of the place where the idea originated. This place must be
preserved and the importance must continue to ramp up until it is paramount
to the movement. This growth of the theoretical, moral, and actual dominance
of the place where the movement began must occur at the same rate that new
nuclei-groups are added and as they, in turn, demand new interconnections
between their cells. The increasing number of individual followers make it
impossible to continue direct dealings with them and that lead us to the
formation of our lowest level groupings. Eventually the number of followers
will increase dramatically, and the lowest form of organization will grow which
forces us to establish higher units, which may be politically described as an
area or district division.
It may be easy to maintain authority of the original headquarters over the
lowest local groups, but it will be very difficult to preserve this position when
the organization becomes more developed and has various levels of upper
management. However, maintaining the authority of the original
headquarters is the first essential for a unified movement. Without a unified
movement, the continuation of the organization and the ultimate
311
Mein Kampf
312
World-Concept and Party
leaders, who are trained, can only work full-time for the movement if they are
paid a salary.
2. Because of the financial limitations of a young movement, it is not in a
position to employ such leaders. Instead it must initially rely on those who will
serve on an honorary basis. This method is slower and more difficult.
Under these particular limitations, the movement’s leadership must let
large districts remain fallow and inactive if a man does not emerge from
among its followers who is able and willing to put himself at the disposal of
the central authority and to organize and lead the movement in that particular
district.
There may be some regions where no leader steps forward at all. Other
regions may have two or three potential leaders who are equally qualified.
This unequal distribution of potential leadership is frustrating and it will
take years to overcome. The essential element for the creation of any cell
organization is always finding a leader who is able to lead it. All the military
companies of an army are worthless without officers. In the same manner, a
political organization is equally worthless without the appropriate leader. It is
better for the movement not to form a local group than to allow it to be
created and then fail because a guiding and forceful leader’s personality was
missing.
The desire to be a leader is not an adequate qualification. A leader must
have ability. Energy and a strong will are more important than intellectual
genius. A combination of ability, determination, and perseverance is the most
valuable of all.
12. The future of a movement depends on the devotion, or more
correctly, the intolerance for other beliefs that its followers exhibit in defense
of it as the only true cause. They must be convinced and enforce the belief
that their own cause, as opposed to other similar causes, is the only just cause.
It is a huge mistake to believe that the strength of a movement can be
increased by uniting with another similar movement. Growth by merger
means an immediate increase in numbers which appears to outside observers
that the organization has increased in power and resources. In truth, the
organization has simply absorbed germs which will be a source of inner
313
Mein Kampf
weakness and this will cause suffering later on. No matter what anyone says
about the similarity of two movements, such closeness never really exists. If
they were truly so similar, there would be only one movement and not two. It
doesn’t matter where the differences are. Even if the difference is in the
inconsistent abilities of the leadership alone, then we have found the
difference.
The natural law of all development never accepts the joining of two
unequal beings. True joining only occurs when the stronger gains victory over
the weaker. When this natural selection happens, the strength and energy of
the victor is increased by the struggle itself.
Uniting two similar political party structures may produce momentary
advantages, but in the long run, any success gained in this way will cause inner
weaknesses to appear later. The greatness of a movement is only guaranteed
by the unhampered development of its inner strength, the protection of that
strength, and the constant increase of that strength until it achieves final
victory over all rivals. More than that, we may say that a movement’s strength
and its right to exist increases only when it recognizes that adherence to the
principle that struggle is necessary for growth and that it will only reach the
peak of its strength when complete victory is finally achieved. The movement
can never attempt to accomplish this victory through instant or short term
gains, but only through perseverance and absolute intolerance of any
opposition. Only in this way will the movement enjoy a long stretch of growth.
Movements which have expanded from the union of similar
organizations, where each made compromises to achieve the joining, are like
plants grown in a hot-house. They shoot up quickly, but they lack internal
strength and are not substantial enough to stand the test of time or to resist
violent storms..
314
World-Concept and Party
315
Mein Kampf
effectively opposes this deadly enemy of our nationality and who is also an
enemy of all Aryan humanity and civilization can expect to find the slanders of
the Jewish race and the war of these people pointed at him.
When these principles become second nature to our followers, the
movement will be unshakable and invincible.
14. The movement must encourage respect for individual personalities
using every means possible. The movement must never forget that all human
values are based on personal values. Every idea and every achievement is the
result of the creative power of one man, but the public’s admiration for great
men is not only a tribute of gratitude to that man, that same reverence is the
factor that binds them together into one group with a strong unifying bond.
Individuality is irreplaceable, particularly if that individual possesses the
vital cultural and creative elements and not the purely mechanical elements
where a man goes through the motions as if he were a puppet.
No student can replace a master painter and successfully complete his
half-finished painting. Neither can the great poet and thinker, the great
statesman, or the great general be replaced by another. Their activity is an art
in itself. What they accomplish cannot be taught mechanically, but such talent
is inborn and a gift of Divine grace. The world’s greatest revolutions and
achievements, its greatest cultural accomplishments and immortal deeds in
the field of statesmanship are all forever linked and inseparable from the
name that history has chosen to represent each achievement. If we do not
give proper respect and reverence to one of those great spirits, then we lose
the great source of strength that emerges from speaking the names of any and
all great men and women.
The Jew knows great souls as unworthy and brands such reverence as a “cult
316
World-Concept and Party
1A cult of personality occurs when the state uses the press to create a heroic image; it can
also be called manufactured hero worship.
317
Mein Kampf
the name of the party and the leading committee which consisted of all of the
party members. This felt like the very thing we wanted to combat, a miniature
parliament.
Here too, as in parliament, voting was the course to reaching a decision.
While the big parliaments shouted until they were hoarse for months, at least
they argued about large problems. In this little circle, even the reply to a letter
received great attention and such a wonderful event, as having someone write
to the party would initiate endless dialogue.
The public knew absolutely nothing of all this. Not a soul in Munich knew
the Party even by name, except for its handful of followers and their new
acquaintances.
Every Wednesday, there was a committee meeting in a Munich café, and
then once a week there was an evening where the group listened to a speaker.
Since the entire membership of the “movement” was represented in the
committee, the same people naturally showed up at both meetings.
What we had to do was finally break out of the little circle, gain new
followers, and above all, make the movement’s name known at all costs.
We used the following technique to accomplish this: We decided to hold
monthly meetings for the public. Later, we began meeting every two weeks.
The invitations were written on a typewriter or some were even written
by hand. We distributed or delivered them ourselves the first few times. Each
of us contacted his circle of acquaintances and tried to persuade some of them
to visit one of these meetings. The result was pitiful.
I can still remember how once, during those early days, I had delivered
close to eighty invitations and, that evening, we waited expectantly for the
crowd of people to come. After waiting for an hour after our regular starting
time, the chairman finally opened the meeting. There were seven of us, the
same old seven.
We began having the invitations typed and duplicated at a Munich
stationary shop. The result was that at the next meeting there were a few
more listeners. The number gradually rose from eleven to thirteen, to
seventeen, to twenty-three, to thirty-four listeners. By taking up little
collections among us poor devils, we were able to raise enough money to
318
World-Concept and Party
319
Mein Kampf
2 Krupp is a German family of steel and munitions manufacturers known as Krupp Works who
incidentally assisted in rearming Germany after the First World War.
320
World-Concept and Party
even at the largest privileged-class mass meetings, they would scatter and run
like rabbits being chased by dogs. The Reds hardly noticed meetings filled with
nothing more than privileged-class chatter. Those “clubs of the harmless”
presented no danger to the Reds and they realized that fact better than the
actual members of these organizations. However, they were much more
determined to wipe out a movement that seemed dangerous to them and
were willing to use any means possible. The most effective tool for them to
use at these times was always terrorism and violence.
To the Marxist betrayers of the people, any movement that announced it
planned to win over the masses, which had previously been in the exclusive
service of the international Marxist Jew and the Stock Exchange parties, was a
threat. The very name “German Workers’ Party” had the effect of issuing a
challenge. It was easy to see that conflict with the Marxist agitators, who were
still drunk with victory from the Revolution, would begin at the first
opportunity which presented itself to them.
At that time, the entire circle of the movement had a certain level of fear
when it faced the prospect of this kind of struggle. They wanted to appear in
public as little as possible because they were afraid of being beaten. In their
mind’s eye, they already saw the first large meeting being broken up and the
movement, perhaps, shattered forever. I had a hard fight for my argument
that we must not avoid this struggle, but must go out and meet it. We must
equip ourselves with the only shield that gives protection from violence.
Terrorism is not overcome by intellect, but by terrorism. The success of the
first public meeting strengthened my position in this respect. They
courageously planned for a second one on an even larger scale.
About October, 1919, the second large meeting took place in the
Eberlbräu cellar. The subject was Brest-Litovsk3 and Versailles.4 Four men
spoke. I spoke for nearly an hour and my success was greater than at the first
demonstration. The number attending had risen to more than a hundred and
thirty. An attempted disturbance was foiled by my friends. The would-be
troublemakers were “helped” downstairs with the benefit of broken heads.
3 Meaning the 1918 Treaty of Brest-Litovsk, which marked Russia’s exit from the war.
4 The Treaty of Versailles which ended the First World War.
321
Mein Kampf
Two weeks later, a second meeting took place in the same hall. The
attendance rose to more than a hundred and seventy. It was quite a good
crowd for the room. I spoke and again, my success was greater than at the
previous meeting.
I pushed for a larger hall. Finally, we found one at the other end of the
city in the German district of the Dachauer Road area. The first meeting in the
new hall was not attended as well as the previous ones. There were only a
hundred and forty people. Hope in the committee began to sink again. The
eternal doubters thought they knew why attendance was poor and claimed
that we were having too many demonstrations too frequently. There were
“spirited” disputes about the matter. During these disputes, I maintained the
position that a city of 700,000 inhabitants could handle not just one meeting
every two weeks, but ten meetings every week. I told them that we must not
be discouraged by setbacks, that the path we had chosen was right, and that
sooner or later, success was bound to come if we were persistent and stayed
strong.
Through the whole winter of 1919-1920 we faced one continuous
struggle to strengthen the victorious force of the young movement and to
raise the level of passion to the level of faith, a faith that is strong enough to
move mountains. The next meeting in the same hall proved I was right again.
The attendance rose above two hundred. The publicity was excellent and it
was also a financial success. I urged that we immediately arrange for another
meeting. It took place barely two weeks later and the crowd of listeners rose
to over two hundred and seventy.
Two weeks later, we called the followers and friends of the young
movement together for the seventh time. The same hall could barely hold all
the people. There were over four hundred. At that time, the inner shaping of
the young movement took place on a more serious level. The discussions often
caused some more or less violent disputes in the little circle. The various sides
discussed whether or not the young movement should even be called a Party.
I have always seen this attitude as proof of the incompetence and intellectual
pettiness of the critic. These are, and always have been, the people who
cannot distinguish outward appearance from inner strength and who try to
322
World-Concept and Party
judge the merits of a movement by how pompous and pretentious the name
is. The last straw was when they suggested we use the archaic vocabulary of
our forefathers.5
They had trouble understanding that even if a movement has not
accomplished its ideas and goals, it is still a party no matter what it calls itself.
When someone wants to carry out a bold idea that would benefit his
fellowmen, he must begin by finding followers who are ready to stand up and
fight for his goals. Even if this purpose is just to destroy the other parties that
exist at the time and to therefore end the disunity among them, the
supporters of this view and announcements of this decision form a party in
themselves until the objective has been achieved. Playing with words like this
is splitting hairs and shadowboxing for some advocate who likes to theorize
about the popularity of the party’s name, and whose practical success is
inversely proportional to his wisdom. It is ludicrous for him to imagine he can
change the character of every young party movement by simply changing its
title.
On the contrary, if there is anything unnatural to people, it is tossing
around ancient Germanic terms that don’t fit the present day and have no
significance to the modern listener. Reviving such terms can easily mislead
people into thinking the important element in a movement is in its outward
vocabulary instead of the internals of the party. This is a truly destructive
tendency, but one which is seen countless times today.
I have repeatedly warned our followers about these German tribal
wandering scholars who cannot show a single positive accomplishment except
for their ability to inflate their own abundant egos. The young movement had
and still has to beware of a number of such men who are known to say that
they have been fighting for this same idea for thirty or forty years. Well, if
anyone who has stood up for a so-called idea for forty years without producing
any results or without even preventing advancement of the enemy, then he
has spent forty years proving his own incompetence.
323
Mein Kampf
The primary danger from people of this character is that they do not want
to take their place as parts of the movement, as regular members fighting for
a cause. Instead they ramble on about circles of leadership that they see as
the appropriate place for their contribution based on their long-continuous
labors. It is disastrous and regrettable when a young movement hands itself
over to such people! A business man who has systematically driven a great
business into the ground through his forty years’ work is not up to the task of
founding a new one. Neither is a supporter of people’s rights who is as old as
Methuselah, and who has spent the same amount of time messing up a great
idea, until eventually he caused it to seize up so that it no longer worked or
made any progress. That person is not the right man to lead a new, young
movement! On top of that, only a fraction of all these people come into the
new movement to be a useful part that spreads the doctrine and serves the
idea of the new doctrine unselfishly. They are usually attracted by the chance
to bother the public once again with their own ideas under the protection of
the movement or through the opportunities it offers. They generally seem to
be incapable of describing exactly what these ideas are.
People with this kind of nature characteristically rave about ancient
Germanic heroism. They talk about the old times of primitive ages, stone
hatchets, a spear and buckler shield, but in reality, they are the most craven
cowards that can be imagined. The very people who wear bearskin tunics and
a helmet with the horns of oxen on their bearded heads and swing through
the breeze German tin swords made to carefully imitate the ancient ones in
every detail, preach nothing but an intellectual battle, and they quickly scatter
when faced with the first Communist rubber club. Future generations will have
little reason to glorify the heroic epics of these “warriors.”
I know these people well enough to be profoundly disgusted with their
pitiful playacting. They are the subjects of ridicule among the broad masses,
and the Jew has every reason to spare these comedic champions-of-people’s-
rights from criticism and even to prefer them to the real warriors of a coming
German State. Yet these buffoons are infinitely proud of themselves, claiming
to know what is best about everything despite all proof of their complete
incompetence. They become an absolute pest to all those straightforward and
324
World-Concept and Party
honorable fighters. Not only do they dilute the heroism of the past, but they
attempt to hand down to future generations a picture of their own acts as
heroism.
It is often difficult to tell which among these people are acting out of
stupidity or inability and which are, for some special reason, only pretending
to be stupid and actually have a hidden motive. This is especially true in the
case of the so-called religious reformers whose beliefs are based on ancient
Germanic customs. I always have the feeling they are sent by forces that do
not want the resurrection of our nation. Their activities actually lead the
people away from the struggle against the common enemy, the Jew. They
allow their strength to be sapped by inner religious disputes that are as
senseless as they are damaging.
For these very reasons, it is necessary to set up a strong central power
with absolute authority for the movement’s leadership. Only this strength can
put a stop to such harmful elements as these rabble-rousers. One of the
greatest enemies of a unified, strictly conducted and guided movement are
these activist Ahasueruses.6 What they truly hate about the movement is that
it has the power to put an end to their mischief.
There was a reason the young movement settled on a definite program
and avoided using the word “Racialist” in it.7
6 Ahasueruses means wandering Jews, a reference to the mythological story about a Jew who
taunted Christ and was cursed to wander the world until the second coming.
7 A Racialist is someone who is interested in race or makes decisions based on race or studies
325
Mein Kampf
stands for. It is outrageous that people are running around today with the
“Racial” symbol on their hats and how many of them have created their own
definition of what the idea means.
There is a well-known professor in Bavaria8 who is famous for fighting
with intellectual means and very successful in marches on Berlin, that is to say,
intellectual marches on Berlin. He has decided the racialist concept is
synonymous with a Monarchy. This educated mind has so far forgotten to
explain in more detail the identity of our German Monarchies of the past
which can be associated with the modern “racialist” concept or which
monarchies were for-the-people. I fear the gentleman will become confused
if he is required to give a precise answer. For it is impossible to imagine
anything more non-racialist than most of the German monarchical states of
the past. If they had been race-aware, if they were representative of the
people, they would never have disappeared or their disappearance would
furnish the proof of the instability of the race-based World-Concept..9.
8 In early Mein Kampf editions he was listed as Professor Bauer but the name was removed
from later editions.
9 Satirically meaning prophets of what is to come.
326
World-Concept and.10
10
Demosthenes was a Greek statesman and orator who was a major political speaker; here,
meaning even a great speaker can be easily silenced.
327
Mein Kampf.
At the beginning of 1920, I urged the scheduling of our first great mass
meeting. This resulted in differences of opinion in our group. Some of the
leading Party members thought the event was premature and would result in
disaster. The Marxist press had begun to show an interest in us and we were
fortunate enough to gradually to win their hatred. We started attending the
meetings of other parties and to speak during the discussion period at their
meetings. Of course, we were all shouted down immediately. But it did have
one good result. People learned about us. As the familiarity grew, their anger
and hatred for us rose. This gave us good reason to hope for large scale
attendance of our friends from the Red camp at our first great mass meeting.
I also realized that there was a real chance that our meeting would be
dispersed by the Marxists. But the battle had to be fought. If it wasn’t fought
now, then it would be a few months later. It was up to us to immortalize the
movement on the very first day by standing up for it blindly and ruthlessly. I
knew how the minds of the supporters of the Red camp worked too well, and
I was certain that an extreme resistance is the best way to make an impression
328
World-Concept and Party
and maybe even to win followers. We only needed the determination to make
that resistance happen.
The chairman of the party at that time, Mr. Harrer, felt that he could not
come to an agreement with my views about whether or not the time was right
for our first mass meeting and, as an honorable and upright man, he withdrew
from the leadership of the movement. Mr. Anton Drexler moved up into his
place. I remained in charge of the organization of propaganda myself and I
carried it through without compromise.
The date of this first great public meeting of our previously unknown
movement was set for February 24th, 1920.
I personally directed the preparations. They were very brief. The entire
organization was set up to make lightning-fast decisions. On questions
concerning the attitude we should display and the purpose of the meeting, we
had to reach the final answers before the mass meeting occurred which was
within twenty-four hours. These points were to be announced by posters and
leaflets based on our doctrine. I have already laid down the broad outlines in
my discourse on propaganda and these were now used. These guidelines
include effectiveness with the broad masses, concentration on a few points,
perpetual repetition of these points, self-assured and self-confident wording
of the text in the form of a positive statement. We circulated the leaflets with
great urgency and then waited patiently for results. For a color, we
deliberately chose red. It is the most inflammatory and was bound to provoke
and enrage our enemies the most, thus making them aware of us in one way
or another.
In Bavaria, the connection between Marxism and the Center political
party was plain to see when one looked at how the ruling Bavarian People’s
Party11 tried to weaken and later to destroy the effect of our posters on the
masses of workers who had been swayed to the Marxist side. If the police
could find no reason to take steps against us, then our rivals would ultimately
complain about the “traffic conditions.” Finally, so they could silence their Red
spiritual ally, the rival German National People’s Party was able to have these
329
Mein Kampf
posters completely forbidden. It was too late. The posters had already given
hundreds of thousands of misled and misguided Red workers a chance to
return to their German nationality. These posters are the best proof of the
tremendous struggle which the young movement went through at that time.
These posters will also bear witness to future generations of the
determination and justness of our principles and the illogical response of so-
called national authorities when they blocked an unwelcome nationalization
and, in doing so, blocked a redemption of the great mass of our nationality.
Our flyers will also help to destroy the misconception that there was a
nationalist government in Bavaria at the time and will document for future
generations the fact that the government in Bavaria during 1919, 1920, 1921,
1922, and 1923 was not the product of a nationalist inclinations, but was
compelled to take into consideration the mass of people who were gradually
becoming more nationalist-minded which forced the government to appear
nationalist as a result. The government did everything to hinder this process
of revival and make it impossible.
There are two outstanding men who we must acknowledge as
exceptions: The Police Chief at the time, Ernst Pöhner,12 and his devoted
advisor, Chief Bailiff Frick,13 were the only high-level state civil servants who
had the courage to be Germans first and officials second. Ernst Pöhner was
the only man in a responsible position who did not ask for the approval of the
masses, but felt himself answerable to his nationality and was ready to risk
everything and to sacrifice everything, even his personal existence if
necessary, for the resurrection of the German people, which he loved most of
all. He was always a thorn in the side of those bribe-seeking officials who acted
against the interests of their people and the necessary advancement of its
freedom, and who instead acted on the orders of their employer, without
considering the welfare of the people or the national property entrusted to
them. Above all, Pöhner was one of those rare men with a personal nature
which, in contrast to most of our so-called governmental guardians, did not
fear being hated by traitors of the people and of the country, but he instead
330
World-Concept and Party
hoped for that hatred and saw it as the natural property of a decent man. The
only happiness for him amid the misery of our people was the hatred he
received from Jews and Marxists, who fought their entire battle using lies and
slander.
Pöhner was a man of rock solid honesty, of Roman simplicity, and German
straightforwardness. To him, “better dead than a slave” was not a catchword
but the personification of his whole character. I consider him and his
colleague, Dr. Frick, as the only men holding positions in state government
who have the right to be called co-founders of a nationalist Bavaria.
Before we held our first mass meeting, we had to prepare the necessary
propaganda material and to have the guiding principles printed in the
program. The guiding principles that we had in mind when drawing up the
program is something I will discuss at great length in the second volume. Here,
I will merely say that the program was made to give form and substance to the
young movement and to present its aims in a manner that could be
understood by the broad masses. In intellectual circles, there have been
sneers and jokes about our program and attempts to criticize it. But the
soundness of our ideas were proven by the effectiveness of the program.
During those years, I saw dozens of new movements come and go
without a trace. Only one survived: the National Socialist German Workers’
Party.
Today, more than ever, I am convinced that even though people may fight
it and try to paralyze it and that petty party ministers may block our free
speech, it does not matter because they cannot prevent the ultimate victory
of our ideas. When the very names of the current State administration and
parties are forgotten, the foundations of the National Socialist program will
be the basis of a future State.
Our four months of meetings before January 1920 had slowly allowed us
to save up the money we needed to print our first leaflet, our first poster, and
our first program.
I will end this volume with the first great mass meeting of the movement
because that is when the Party burst through the narrow confines of being a
331
Mein Kampf
small club and extended its influence by reaching into the most tremendous
factor of our time, public opinion.
I had only one concern: Would the hall be filled or would we speak to an
empty room? I was firmly convinced that if the crowd came it would transform
the day into a great success for the young movement. So, I anxiously looked
forward to the evening.
The meeting was to begin at 7:30 P.M. At 7:15, I entered the banquet hall
of the Hofbräuhaus on the Place in Munich and my heart nearly burst with joy.
The meeting hall that before seemed so very large to me was now
overflowing with people, shoulder to shoulder, a mass of almost two
thousand. Most importantly, the very people we wished to reach were there.
More than half of the people in the hall seemed to be Communists or
Independents. They already expected our first great demonstration would
come to an abrupt end. But the result was not what they expected.
After the first speaker had finished, I took the floor. Within a few minutes,
there was a flood of interruptions from shouts and there were violent
episodes in the hall. A handful of devoted war comrades and other followers
removed the troublemakers and gradually succeeded in restoring some
semblance of order. I was able to resume speaking. After half an hour, the
applause slowly began to drown out the yelling and bellowing. Now I took up
the task of explaining our program for the first time.
As the minutes passed, the taunting was drowned out more and more by
shouts and applause. When I finally presented the twenty-five ideas, point by
point, to the crowd, asking them to make their own judgment on each one,
they accepted one after another amid growing cheers, unanimously and
unanimously again. When the last point had found its way to the heart of the
crowd, I had in front of me a hall full of people united by a new conviction, a
new faith, a new will.
After almost four hours, the hall began to empty. The mass of people
rolled, pushed, and crowded shoulder to shoulder like a slow river toward the
exit.
I knew they were going out into the German people and spreading the
principles of a movement that could no longer pass into oblivion.
332
World-Concept and Party
A fire had been started and from this flame, a sword would someday be
forged that would win back freedom for the Germanic Siegfried and life for
the German nation.14 In step with the coming revival, I could feel the marching
of the Goddess of Revenge who would bring vengeance for the treasonous
deed of November 9th, 1918. The hall gradually emptied. The movement had
started.
14Siegfried is both a German male name meaning peace by victory and an opera by Wagner
where a strong sword is forged and the main character is named Siegfried; it also means the
average man or a German John Smith.
333
VOLUME TWO
THE NATIONAL
SOCIALIST MOVEMENT
CHAPTER ONE
On the 24th of February, 1920, the first great public mass demonstration of
our young movement took place. In the Banquet Hall of the Munich
Hofbräuhaus,1 the twenty-five points of our program were presented to a
crowd of almost two thousand and every single point was received with
enthusiasm.
We finally had an opportunity to make the first principles clear and
explained our plan for action that would lead our struggle to clear away the
chaos of traditional views and ideas and the vague even harmful aims that
were ever present. A new force had appeared to split the corrupt and
cowardly privileged-class world and this force would shatter the Marxists’
wave of conquest. This new movement would ride the chariot of Fate in front
of the Marxists’ march to triumph and halt it at the last moment, before it
reached its goal.
It was obvious that the new movement’s only hope to achieve the
necessary significance and the required strength for the gigantic struggle
ahead was if it succeeded from the beginning in filling the hearts of its
followers with the sacred conviction that we were not simply spouting a new
election slogan into the political arena, but this new movement was placing a
new World-Concept, one of great importance, in front of the people. Think
about how pitiful the programs of these other so-called “party platforms” are.
They are usually stuck together and shined up or reshaped from time to time,
but one platform is basically the same as the next. To understand them, we
must look at the motives which drive their construction. These motives,
especially of the privileged-class “platform committees,” must be put under
335
Mein Kampf
the microscope so we can truly understand and judge how valuable these
outrageous beliefs they call platforms are.
There is only one reason which leads to the re-writing of party platforms
or the modification of existing ones: the concern over who will win the next
election. Whenever it begins to dawn on these parliamentary craftsmen that
the good old common people are about to abandon the party and slip out of
the harness of the old party bandwagon, the leaders repaint the bandwagon’s
wheels. Then, come the so-called “experienced” and “shrewd,” usually old,
parliamentarians. These are the star-gazers, the party astrologers, who can
recall a similar crisis, in their “long political apprenticeship,” when the people’s
patience ended and mass defections loomed. They feel the same kind of
calamity drawing dangerously near. So, they resort to the standard formulas:
form a “committee,” listen to what the good old common people are saying,
sniff at the newspapers and gradually smell out what the common people
want, what they hate, and what they hope for. Every trade and business group
and every class of employee is carefully studied as its most secret wishes are
examined. Even the “empty catchwords,” which are used by the now
dangerous opposition, are suddenly reexamined. Frequently, to the surprise
of those who first coined these phrases, they suddenly appear quite innocent,
as if the ideas were taken for granted or obvious. Some of them are even
found in the intellectual library of the old parties.
So, the committees meet, “revise” the old platform, and write a new one
in a way that gives everyone what he wants. This parliamentary class changes
their convictions just as the soldier changes his shirt in the field, whenever the
old one wears out. No one is left out, the farmer’s agriculture is protected, the
industrialist’s products are protected, the consumer is guaranteed stable
market prices, the teachers’ salaries are raised, and the civil servants’ pensions
are improved. The State is to take good care of widows and orphans,
commerce is promoted, prices are to be lowered, and taxes are to be
practically abolished. Sometimes, one group may have been forgotten or a
new demand among the people was not discovered by the party in time to
add this revision. Any overlooked concessions are stuck on, wherever there is
space, at the last moment. The patches are put in place until the party can
336
World-Concept and Party
faithfully hope that the army of middle-class Philistines and their wives are
soothed and satisfied once again. Now, armed with faith in the Lord and the
unshakable stupidity of the voting citizens, the party can begin the struggle for
“reshaping” the Reich, as it is called.
When election day is over and the parliamentarians have held their last
mass meeting for five years, with no further need to consider the commoners,
they focus on fulfillment of their higher and more pleasant duties. The
committee that created this new platform disbands again and the struggle for
reshaping assumes the form of a battle for one’s daily bread. Maybe this is
why gatherings of parliamentarians are called diets.2 The parliamentarians
draw their daily pay by simply showing up and the “struggle” degrades into a
humdrum “daily routine.”
Every morning the Honorable Gentleman, the Deputy of the parliament,
goes to the House and though he may not make it all the way in, he at least
goes as far as the entryway where the attendance lists are kept. He labors
strenuously for the people by entering his name there and receives his well-
deserved reward in the shape of a small payment for his long and exhausting
efforts.
After four years, just about the time their term of service is to expire, or
during other critical periods when the end of session for the parliamentary
body draws nearer and nearer, these gentlemen suddenly feel an irresistible
urge come over them and they have a desire to take action. Just as the
caterpillar cannot help turning into a butterfly, these parliamentary worms
leave the home of their species and flutter out on new found wings to the
good old common people. Once more they speak to the voters, telling them
about their own tremendous accomplishments and the stubbornness of their
opponents. But sometimes they encounter rude and unfriendly expressions
thrown at them from the stupid masses instead of grateful applause. If this
lack of gratitude from the people rises beyond a certain level, there is only one
thing that can save the day. The glory of the party must be shined up again
337
Mein Kampf
and surely the party platform needs more repairs. The party platform
committee is set up and the charade begins all over again.
Considering the rock solid stupidity of the public, we cannot be surprised
at the resulting success of these tactics. Steered by its newspapers and blinded
by the attractive new party program, the privileged-class and the working class
combine into a united voting herd as they go back into their old stalls and elect
the same old deceivers. Then the “man of the people” and the “candidate of
the working class” is transformed back into a parliamentary caterpillar where
he can continue gorging himself as he clasps to the branches of State life,
where he will only to be transformed into a glittering butterfly again four years
later.
There is nothing more depressing than watching the whole process in
sober reality and seeing the never-ending fraud for oneself.
The privileged-class camp of politicians cannot draw enough spiritual
strength from this kind of self-indulgent dealing to fight a battle with the
organized power of Marxism. These upper class people never seriously
thought of battling them at all. With the admitted limitations and intellectual
inferiority in these parliamentary snake-oil-salesmen, who are supposed to
represent the white race, how can they seriously expect to make any progress
using Western Democracy against a doctrine that, at best, is designed as the
means to destroy Democracy. Marxism is the means to an end, and that end
is the destruction of Western Democracy by paralyzing the political body,
which in turn leaves the path open for itself. For now, one part of Marxism
very shrewdly tries to pretend it is connected to the principles of democracy,
but we must never forget that when the critical moment is upon us and
Marxism is breathing down our necks, these privileged-class legislators did not
think a penny’s worth of their time could be sacrificed to reach a majority
decision on the protection of Western Democratic principles. These
privileged-class parliamentarians believe the security of the Reich is
guaranteed by the monumentally superior numbers on their side so they
remain blind while Marxism snatches power with a crowd of thugs, deserters,
political evangelists, and Jewish amateur intellects; these legislators are giving
338
World-Concept and Party
the current democracy a resounding slap in the face through their failure to
act.
Only a legislator with the devout spirit of a witch-doctor could possibly
believe that the wicked determination of those who support and profit from
this Marxist plague could be halted simply by uttering the magic spell of
Western Democracy.
Marxism will march alongside democracy until it indirectly succeeds in
gaining support for its criminal intentions from the very nationalist intellectual
world which Marxism has marked for extermination. If Marxist leaders
became convinced today that, somewhere in the witches cauldron of our
parliamentary democratic system, a numerical majority might suddenly be
brewed which would furiously combat Marxism, the parliamentary hocus-
pocus would be over in an instant. Instead of appealing to the democratic
conscience, the flag-bearers of the Red International movement would send
out a fiery call to action to the working class masses and their battle would
jump from the stuffy air of our Parliamentary chambers into the factories and
spill onto the streets. Democracy would immediately be over. What the
intellectual prowess of these parliamentary apostles-of-the-people had failed
to accomplish in the Parliament would now be accomplished by the crowbar
and the sledgehammer wielded by the excited working class masses who
would achieve the Marxist goals in a flash, just as in the fall of 1918. With one
crushing blow, they would teach the privileged-class world how crazy it was to
think that one can resist the Jewish world-conquest with the tools of Western
Democracy.
As I have said before, it requires a trusting soul to honor the rules of the
game, when he is faced with an opponent who sees the rules only as a
masquerade for his own benefit and then the instant he no longer finds those
rules give him advantage, he throws them overboard. In all political parties of
privileged-class orientation, the entire political struggle consists of a scramble
for individual seats in Parliament. During this time they adhere to convictions
and principles until those principles begin to weigh them down, and then they
are tossed overboard as easily as bags of sand. Naturally, their political
platforms and programs are setup in a similar way so they can be discarded
339
Mein Kampf
just as quickly. The party’s strength is measured by that scale, but in reverse,
the more weight they discard, the more bogged down they become and hence
the weaker they become. They don’t have that powerful magnetic attraction
which the great masses want to follow, that aura of an irresistible impression,
of great and outstanding principles, and of the convincing force of
unconditional faith in those principles, along with the fanatical fighting
courage to defend them..
If someone, especially one of the so-called nationalist privileged-class
ministers like a Bavarian Centrist, accuses our movement of working for an
“upheaval,” there is just one possible answer to such a political Tom Thumb:
“Right you are. We are trying to make good what you in your criminal stupidity
failed to do. You and your principles of parliamentary position-jockeying
helped to drag the nation into a black pit, but we will aggressively set up a new
World-Concept and with fanatical fervor, unshakably defend its principles. We
will build the steps that our people will one day be able to again climb to the
Temple of Freedom.”
When our movement was founded, we devoted our primary efforts
toward preventing our army of fighters, for a new and high conviction, from
turning into a mere society for the furthering of parliamentary interests. The
first preventive measure was the creation of a program that urged the
development of a party whose inner greatness was designed and calculated
to frighten off the petty and weak minds of our present party politicians. The
soundness and necessity of our idea, to establish a sharp definition of our
program’s aims, was best shown by those fatal problems which led to
Germany’s collapse. The recognition of the problems faced by Germany was
bound to give a shape to the new State-concept, which, in turn, is an essential
element in a new World-Concept.
340
World-Concept and Party
In the first volume, I dealt with the word “racialist,” pointing out that this
designation is too obscurely-defined as an idea to allow it to form a solid
fighting group. There are many groups that are as different as night and day
floating around at this time under the blanket name “racialist.” So before I go
on to explain the aims of the National Socialist German Workers’ Party, I would
like to clarify the idea “racialist” and its relation to the Party movement.
The word “racialist” is vague. It does not clearly express any specific idea
and it is subject to many interpretations, and it is as limitless in practical
application as, for instance, the word “religion.” It is also difficult for us to
create a clear picture in our mind about what it means, either for theoretical
or practical descriptions. The term “religious” becomes concrete only when it
is connected with a sharply defined form which is actually practiced. It sounds
very pretty to say someone is “deeply religious,” but that is usually a hollow
statement, for it says nothing about a man’s character. There may be a very
few individuals who feel themselves satisfied by such a general term and
others who may even assign to it a definite picture of a particular spiritual
state.
But the great masses are not made up of philosophers or saints. An
absolutely general and non-specific religious idea like this will be turned into
the listener’s personal interpretation. It does not lead to an effective inner
religious craving that one possesses when the purely abstract and unlimited
world of ideas shapes itself into a clearly defined faith. This is not an end in
itself, but only a means to the end. However, the means is the essential way
of attaining the end. This end is by no means solely a theoretical ideal, but the
bottom line is that it is extremely practical. In fact, we must realize that
generally, the highest ideals always correspond to a profound vital necessity
in our lives, just as the nobility we see in beauty is ultimately determined by a
form that is logical and useful in the end; [the beauty of form follows its
function.] Faith helps to raise man above the level of a mere animal existence,
and it contributes to strengthening and safeguarding his existence. His
religious training includes religious doctrine, but in practicality also includes
morals, ethics, and the principles it supports. If you eliminate this religious
training, it will result in a critical weakening of the foundations of his existence.
341
Mein Kampf
It is safe to say that man lives to serve higher ideals, but that these higher
ideals also are the essentials for his existence as a man. The circle is complete.
Even the general term “religious” implies certain basic ideas or
convictions. Some of these are the immortality of the soul, the belief in eternal
life, and the existence of a higher Being. These ideas, though firmly believed
as factual by the individual, are still subject to the interpretation of that
individual and subject to his acceptance or rejection of them if the emotional
power behind them does not take on the force of an undeniable law that is
the doctrine that defines a clear faith. More than anything else, this doctrine
is the fighting element which breaks through the outer appearance of
fundamental religious views and pushes those superficial, theoretical
trappings aside to clear the path for a deep and committed faith. Without a
clearly defined faith, the multiple vague forms of religious feeling followed by
individuals would not only be worthless for human life, but probably would
contribute to general disintegration.
The same analysis for “religion” is true for the term “racialist.” It too
embodies certain basic ideas. But these, even though of outstanding
importance, are so vague in form that they have no value beyond an opinion
more or less deserving of recognition. The ideals of a World-Concept and the
requirements deduced from them are not understood by pure feeling or
men’s inner will any more than freedom is conquered by a universal desire for
it.
No, only when the idealistic longing for independence is organized to
fight in the form of military force can the compelling desire of a people be
transformed into a splendid reality.
Even a World-Concept that is totally sound and of the utmost value for
humanity will never have any practical value and will never shape the people’s
lives until its principles have become the banner of a fighting movement. The
movement will remain a party until its work has been completed by bringing
its ideas victory, and its party doctrines form the new State whose principles
shape the community.
If an abstract intellectual concept is to serve as the foundation for future
development, the first requirement is to create a clear understanding of the
342
World-Concept and Party
nature, the character, and the extent of this idea. This is the only way a
movement can be founded so that it maintains the inner cohesion and
uniformity of its convictions and from this uniformity it will develop the
necessary strength for the battle. General concepts must be molded into a
political program, a general World-Concept into a definite political faith. Since
its aim must be one that is within reach and can be accomplished in the real
world, this faith must not only serve the idea, but must include the means that
will be used to fight and to win victory for the idea. Along with the theoretically
sound intellectual idea which was originally declared by the program maker,
the politician must use his practical insight to shape the idea into an achievable
plan. An eternal ideal that is the guiding star of humanity must adjust itself so
that it takes into account the weaknesses inherent in man because of general
human imperfection, and only then can it avoid failure the instant it begins.
The founder of the idea, the explorer of truth, must be joined by the man who
knows the people’s spirit, and they must work together in order to extract
what is humanly possible for tiny mortals from the realm of ideals and eternal
truth and to give it a shape that can be used in the fight.
This transformation of a general and idealistic World-Concept into a
definite, tightly organized, political, fighting brotherhood of faith, which is
unified in both mind and will, is the most significant achievement we can hope
for. Any chance of victory for the idea depends completely on this successful
transformation of an idea into a practical plan..
343
Mein Kampf
344
World-Concept and Party
345
Mein Kampf
346
World-Concept and Party
347
CHAPTER TWO
The State
348
The State
1The party that splintered from the main Center Party in 1919.
2Black and Gold were the royal colors of the House of Hapsburg and the Legitimists, who
supported a Monarchy system and believed in a succession of kings based on fixed rules.
349
Mein Kampf
The mere fact that the government has existed a long time does not protect it
against the criticism of the present. Beyond that, this concept expects the
state to provide economic stability and advantages for the individual, and,
therefore, the state is judged from the standpoint of how well it promotes
economic productivity. We find supporters of this view among our ordinary
German privileged-class, particularly the members of our liberal democracy.
C. The third group is the smallest in number. It sees the state as a way to
achieve political power. This power is mostly imagined in a vague and distant
way as an ethnic group of people within the state that is defined and unified
by a specific race and language. They desire a single state language to direct
nationalization in their own direction. However, this idea is completely
mistaken.
In the last hundred years, it has been a disaster to watch how the word
“Germanization” has been played with by those circles just mentioned, even
though they often did so with the best of intentions. I myself can still
remember how, in my youth, this particular term conjured up a host of
extremely mistaken ideas. Even in Pan-German circles at that time, one often
heard the opinion that Austrian Germans might, with the assistance of the
government, succeed in Germanizing the Austrian Slavs. They never realized
for a moment that Germanization can only be applied to a country and never
to a group of people. What most people thought the word meant was the
forced use of the German language. But it is an unimaginable mistake to think
that a negro or a Chinese can become a native German simply because he
learns the German language and speaks it in the future and perhaps will cast
his vote for a German political party.
The fact that any such Germanization is in reality a de-Germanization was
never clear to our privileged-class nationalist world. If forcing a common
language could today bridge and eventually wipe out previously obvious
differences between various races, it would be the beginning of bastardization
and, in our case, it is not a Germanization, but a destruction of the Germanic
element in our people. This has happened all too often in history when a
conquering people successfully force their language on the conquered, but
350
The State
then a thousand years later, when its language is spoken by a different people,
they find the conquerors have really become the conquered.
Nationality, or rather race, is not in the language, but in the blood. It could
only be possible to speak of Germanization if this process succeeded in
changing the blood of the inferior. But this is obviously impossible. A mingling
of blood would produce a change, but that change would mean a decline in
the quality of the superior race. The final result of such a process would be the
destruction of those very qualities which once made victory possible for the
conquering people. Cultural abilities would disappear if they were mated with
a lower race, even though the resulting mixed breed spoke the language a
thousand times better than the previous superior race. For a time, there will
still be some struggle between the differing spirits of the original races. It may
be that the declining people, in a last effort, produce surprising cultural
achievements. But these are only single products belonging to the remaining
elements of the higher race, or bastards of the first generation in whom the
better blood still predominates and strives to break through. Such cultural
masterpieces are never the products of the final descendants of such hybrids.
These mixes will always exhibit a cultural quality that moves backwards and
does not progress.
Today it is fortunate that the Germanization of Austria by Joseph II never
took place.3 Its result would probably have been the survival of the Austrian
State, but the price would have been the lowering of the racial quality of the
German nation from sharing the same language among several peoples. Over
the course of centuries, a certain herd instinct would probably have
crystallized, but the herd itself would have been inferior. A people constituting
a state might have been born, but the civilizing element in those people would
have been lost.
It was better for the German nation that this process of mixing didn’t
happen, even though it was not due to any noble insight, but to the narrow-
3Joseph II, Holy Roman Emperor over Austrian lands until 1790 imposed as part of the Age of
Enlightenment the requirement that German be spoken instead of Latin or local languages; it
was not well-accepted especially, with the massive number of reforms accompanying it.
351
Mein Kampf
4 Laissez faire is the belief in pursuing economic goals free from any government regulation.
352
The State
353
Mein Kampf
hand we can see, even from present-day examples, that state structures which
are founded by races that lack this cultural intellectual element in their tribal
beginnings cannot protect the members of their race from eventual
extinction.
Just as certain species of great prehistoric animals became extinct, so
man must give way if he lacks that certain intellectual strength which is
required to find the weapons necessary for his self-preservation.
The state does not advance cultural progress. The state can only preserve
the race which does bring about the advancement. Otherwise, the state may
continue to exist for centuries without taking any actions, while, as a result of
the state’s failure to prevent the mixture of races, the cultural capacity and
the resulting general quality of life among the people have suffered profound
change. The present state, for instance, may still maintain its own existence in
a mechanical way for a considerable length of time, but the racial poison of
inbreeding allowed by our political body produces a cultural decline that is
already horribly apparent today. The existence of a higher level of humanity
does not depend on the State, but on the race which is the nationality capable
of creating that improved level of humanity.
This capacity always exists and only needs to be awakened by certain
outside conditions. Culturally and creatively gifted nations or races have these
abilities hidden within them, even though, at the moment, unfavorable
outside circumstances do not allow the development of these tendencies. It is
an unbelievable outrage to represent the native Germans of pre-Christian
times as “uncivilized” or as barbarians. They were never barbarians. The
rugged climate of their northern home simply forced conditions on them that
prevented the development of their creative powers. If they had come to the
more favorable regions of the south, their previously undeveloped capabilities
would have blossomed just as what happened with the Hellenes. This would
have occurred even though there was no old history to build on and as long as
they were able to obtain basic mechanical assistance in the form of lower
races as workers. This inborn culture-building power did not come about just
354
The State
because of their presence in the northern climate. Had the Lapps5 been
brought to the South, they would have had no more culture-building capacity
than the Eskimo. No, this magnificent creative capacity and growth capacity
was granted to the Aryan. It may be dormant within him or it may be
awakened in his life. It depends on how favorable the circumstances are, or
whether an inhospitable force of Nature prevents it.
Therefore, the following conclusions result: The state is the means to an
end. This end is the preservation and advancement of a community which
consists of physically and spiritually similar beings. Part of this preservation
includes assuring the survival of the race and permits the free development of
all the forces sleeping within that race. The greatest part of the power of the
state will always be devoted to preserving the physical life and only the
remaining power assists in further intellectual development. We must
remember that the one is always vital to the other, physical and intellectual
must both be maintained. States that do not serve this purpose are faulty,
even outrages that cannot justify their existence. The fact that these
monstrosities do exist is not a justification for their existence any more than
the success of a crew of pirates can be a justification for high seas piracy.
We National Socialists, as the supporters of a new World-Concept, must
never take our stand on the celebrated “basis of facts,” and we must be
especially careful of mistaken facts. If we did so, we would no longer be the
supporters of a great new idea, but rather slaves of the existing system. We
must make a sharp distinction between the State as a bottle and the race as
its contents. The bottle has a purpose only as long as it can preserve and
protect the contents. If it fails in its purpose, it is worthless. The highest
purpose of the race-based state is to care for and preserve those racial
elements which are the creators of culture. They produce the beauty and
dignity of a higher humanity. As Aryans, we can view the state only as a living
organism made up of people. It does not merely assure the preservation of
this nationality, but the state must lead the people to the highest freedom
possible by continuing to develop its spiritual and intellectual capacities.
5Meaning Laplanders which is a derogatory term for the people of Sami, the cultural
equivalent of Eskimos living in Europe.
355
Mein Kampf | https://fr.scribd.com/document/386229765/Mein-Kampf | CC-MAIN-2019-22 | refinedweb | 95,421 | 59.23 |
/* class ATM * Author: Diana Franklin Purpose: Implement an ATM. */ import java.util.Scanner; public class ATM { public static void main(String args[]) { BankAccount acct; boolean overdrawn; Scanner input= new Scanner( System.in ); int option, amount; acct = new BankAccount();// create one bank account option = 0; // make sure we loop at least once // print out a welcome message System.out.println("Welcome to the ATM"); // keep session going until user says to exit while (option != 3) { // first give user options, then ask what user wants // to do System.out.println("Check Balance: 0\n Deposit: 1"); System.out.println("Withdrawal: 2\n Exit: 3"); System.out.print("What would you like to do next? "); option = input.nextInt(); if (option == 0) { System.out.printf("Your balance is %d\n", acct.getBalance()); } else if (option == 1) { System.out.print("How much would you like to deposit? "); // get amount to deposit from user amount = input.nextInt(); acct.deposit(amount); // make the deposit
View Full Document
This
preview
has intentionally blurred sections.
- Fall '09
- FRANKLIN
Click to edit the document details | https://www.coursehero.com/file/6649189/ATM/ | CC-MAIN-2018-05 | refinedweb | 175 | 53.17 |
With this project, C++ and .NET Windows programmers get a very versatile library to send and download emails via SMTP, POP3 and IMAP with TLS and SSL support.
I was searching for a SMTP/POP3/IMAP library. What I found were either very expensive commercial libraries or free libraries without encryption support. Today many SMTP servers demand a TLS or SSL connection. With an email library that does not support encryption you will not be able to send an email to a Gmail SMTP server.
Finally I found vmime, which is a multi platform library for SMTP, POP3, IMAP, SendMail and MailDir with very cleanly written code and hosted on Github, mainly written by Vincent Richard, who did a great work.
But this library is a Gnu project that was developed and tested mainly in the Mac / Linux world. Theoretically it should be possible to compile it on Windows with the Cmake compiler, but that threw a lot of cryptic error messages that I never saw before, so I gave up.
Additionally CMake is useless if you want to write a Managed C++ project for .NET. So I had to find a way to compile this stuff on Visual Studio. If you ever ported code from Linux to Windows you know what nightmare this is.
After eliminating all the errors in Visual Studio that you see whenever you compile a Linux project on Windows, I had the problem that the Config.hpp file was missing which contains all the project settings. I had to find out how to construct this file manually.
Then vmime depends on several other Gnu projects which I had to download separately:
All these libraries exist precompiled for Windows as DLLs and come with a Lib file for the linker. Some of them come with library files with names like "libgsasl.a". I never saw this file extension before and thought: These files are made for Windows so I change that to "libgsasl.lib". And the worst of all is that Visual Studio eats these files without complaining. But the compiled binary file will not run.
Finally I found out that these *.a files are for a Gnu compiler on Windows.
And where do I find the Lib files for Visual Studio?
They simply do not exist.
After investigating I found that I can create the Lib file from the Def file with a Visual Studio command line tool. See "libvmime\src\gsasl\CreateLIB.bat"
I started my first tests with GnuTLS which was an error, because:
I wasted a lot of time with this library, finally I moved to OpenSSL which works perfectly.
The iconv library also caused me problems because there is no precompiled 64 Bit version for Windows and this library has apparently never been compiled for 64 Bit. Finally I replaced it with my own code that uses the Windows Codepage conversion API instead.
Then I started struggling with vmime code itself:
A severe lack was that vmime had no Unicode support. All strings are std::string while std::wstring was used in no place. Filenames were translated with the current ANSI codepage and passed to the ANSI file API (e.g. CreateFileA).
To permit that vmime can also be used by chinese or japanese users I had to find a way to pass unicode into vmime. I ended up converting all input strings in a wrapper class into UTF-8. Then, in the windows platform handler I convert the UTF-8 strings back to Unicode and pass them to widechar API (CreateFileW).
Another severe lack of vmime was the missing Trace output. When an error occurred with the server you had no idea what was the reason because you did not see the communication with the server. I implemented Trace support as you see in the screenshots below.
Another lack was that vmime code was not abortable. If the server did not respond the user had to wait until the timeout elapsed - up to 30 seconds! I fixed that.
Another problem was that in vmime error handling was not properly implemented.
Then I found several bugs, like for example openssl throwing "SSL3_WRITE_PENDING:bad write retry". I contacted Vincent - the author of vmime - who gave me excellent support with all problems and fixed some of these bugs.
Then I added new features that are indispensable for an easy usage like automatic mime type detection by file extension and loading root certificates from the resources.
The vmime library has been designed to be very flexible and expandable. This is good but has the disadvantage that the usage becomes awkward. For a simple task like extracting the plain text of an email you have to write a loop, enumerate all message parts, use a MessageParser, use a OutputStreamStringAdapter, a ContentHandler, a SmartPointer class, dynamic casts and character set conversion. All this is clumsy and an experienced programmer - new to vmime - easily needs some hours to find out how to do this. And for C++ beginners it will be nearly impossible to use vmime.
So I added wrapper classes that hide all this complicated stuff in a single function. (KISS principle )
Then I discovered a VERY weird phenomenon: Whenever in vmime an exception was thrown, I had memory leaks and TCP sockets that were not closed because several destructors were never called (no stack unwinding). You can read on Stackoverfow how I solved this.
I did a lot more things but to mention all this would be too much here.....
All my changes in the source code are marked with a comment: // FIX by Elmue , if you search so you find more than 240 modifications.
...finally I was working two months on this project. I did really frustrating work and I nearly gave up more than once.
Now you are in the fortunate situation, that you can download a ready-to-use library that works perfectly and is very easy to use and intuitive.
With very few lines of code you can create a mime email with a plain text part, a Html part, embedded Html objects (e.g. images) and attachments. Both, plain text and Html text are optional. Modern email clients do not display the plain text part if a Html part is present.
C#
using vmimeNET;
using (EmailBuilder i_Email = new EmailBuilder("John Miller <jmiller@gmail.com>",
"vmime.NET Test Email"))
{
i_Email.AddTo("recipient1@gmail.com"); // or "Name <email>"
i_Email.AddTo("recipient2@gmail.com");
i_Email.SetPlainText("This is the plain message part.\r\n" +
"This is Chinese: \x65B9\x8A00\x5730\x9EDE");
i_Email.SetHtmlText ("This is the <b>HTML</b> message part.<br/>" +
"<img src=\"cid:VmimeLogo\"/><br/>" +
"(This image is an embedded object)<br/>" +
"This is Chinese: \x65B9\x8A00\x5730\x9EDE");
i_Email.AddEmbeddedObject("E:\\Images\\Logo.png", "", "VmimeLogo");
i_Email.AddAttachment("E:\\Documents\\ReadMe.txt", "", "");
i_Email.SetHeaderField(Email.eHeaderField.Organization, "ElmueSoft");
String s_Email = i_Email.Generate();
} // i_Email.Dispose()
C++
using namespace vmime::wrapper;
cEmailBuilder i_Email(L"John Miller <jmiller@gmail.com>", L"vmime.NET Test Email",
IDR_MIME_TYPES);
i_Email.AddTo(L"recipient1@gmail.com"); // or "Name <email>"
i_Email.AddTo(L"recipient2@gmail.com");
i_Email.SetPlainText(L"This is the plain message part.\r\n"
L"This is Chinese: \x65B9\x8A00\x5730\x9EDE");
i_Email.SetHtmlText (L"This is the <b>HTML</b> message part.<br/>"
L"<img src=\"cid:VmimeLogo\"/><br/>"
L"(This image is an embedded object)<br/>"
L"This is Chinese: \x65B9\x8A00\x5730\x9EDE");
i_Email.AddEmbeddedObject(L"E:\\Images\\Logo.png", L"", L"VmimeLogo");
i_Email.AddAttachment(L"E:\\Documents\\ReadMe.txt", L"", L"");
i_Email.SetHeaderField(cEmail::Head_Organization, L"ElmueSoft");
std::wstring s_Email = i_Email.Generate();
In this example "VmimeLogo" is the content identifier of the embedded image. In Html you can reference embedded images as: .
The above code will generate an email that looks like this in Thunderbird:
Here the source code in the variable s_Email printed to the console:
Sending our email is done with 3 lines of code: This could not be more simple. (KISS principle)
using (Smtp i_Smtp = new Smtp(s_Server, u16_Port, e_Security, b_AllowInvalidCertificate))
{
i_Smtp.SetAuthData(s_User, s_Password);
i_Smtp.Send(i_Email);
} // i_Smtp.Dispose()
cSmtp i_Smtp(u16_Server, u16_Port, e_Security, b_AllowInvalidCertificate, IDR_ROOT_CA);
i_Smtp.SetAuthData(u16_User, u16_Password);
i_Smtp.Send(&i_Email);
If u16_Port == 0 the default port is used.
u16_Port == 0
If the server sends an invalid certificate:
b_AllowInvalidCertificate == true
b_AllowInvalidCertificate == false
The Trace output you see above is returned by vmime.NET via a callback. You can do whatever you like with it: write it to the console or display it in a log window or save it to a logfile. Or you turn off the compiler switch VMIME_TRACE and Trace is completely disabled.
If you plan to send for example a newletter with 500 recipients you will encounter lots of problems:
These measures are indispensable to fight spam that is mainly sent by Trojans and Botnets via SMTP. (Read about Trojans and Botnets in my article)
So the best solution to send a newletter is to install your own email server. (I recommend MDaemon Email Server)
But even with this solution you must be carefull because when your IP address gets listed on a blacklist your server may get blocked for multiple days.
You have 4 options to send the email to the SMTP server: (enum e_Security)
enum e_Security
Both, SSL (Secure Sockets Layer) and TLS (Transport Layer Security) send the authentitication (user/password) and the email message encrypted.
SSL starts immediately an encrypted connection.
TLS is the successor of SSL. It starts with an unencrypted connection, sends the SMTP command "STARTTLS" and then encrypts the traffic on the same port.
Read Wikipedia about SSL and TLS.
When using SSL or TLS the server authenticates itself with a X.509 certificate. vmime.NET has 185 built-in root certificates and checks that the server certificate is digitally signed with one of these root authorities (e.g. Verisign), that the expiration date of the certificate has not expired and that the hostname of the server is the same as in the certificate. With this certificate the client can prove that there is no man-in-the-middle attack.
Read Wikipedia about X.509
IMPORTANT:
If you download this project several months after I published it (january 2014) you should update the certificates because they may expire, be revoked or new root authorities may exist:
This code enumerates all emails in the POP3 Inbox:
using (Pop3 i_Pop3 = new Pop3(s_Server, u16_Port, e_Security, b_AllowInvalidCertificate))
{
i_Pop3.SetAuthData(s_User, s_Password);
int s32_EmailCount = i_Pop3.GetEmailCount();
for (int M=0; M<s32_EmailCount; M++)
{
using (EmailParser i_Email = i_Pop3.FetchEmailAt(M))
{
// do something with the email...
} // i_Email.Dispose()
}
} // i_Pop3.Dispose()
cPop3 i_Pop3(u16_Server, u16_Port, e_Security, b_AllowInvalidCertificate, IDR_ROOT_CA);
i_Pop3.SetAuthData(u16_User, u16_Password);
int s32_EmailCount = i_Pop3.GetEmailCount();
for (int M=0; M<s32_EmailCount; M++)
{
GuardPtr<cEmailParser> i_Email = i_Pop3.FetchEmailAt(M);
// do something with the email...
}
i_Pop3.Close(); // Close connection to server
NOTE:
Some POP3 servers do not respond on port 110 (e.g. Gmail) or reject a connection.
The only possible security mode for these servers is SSL (port 995).
IMPORTANT:
Gmail has a very buggy POP3 behaviour: All emails can be downloaded only ONCE via POP3, no matter what setting you chose in your POP3/IMAP configuration! The emails are there in the web interface but pop.googlemail.com tells you that you have no emails in your Inbox. Or it may happen the opposite that POP3 shows you emails that have been deleted years ago (but only once)! Gmail's IMAP behaves normal.
The class EmailParser allows to extract any part of an email.
// ================== HEADER (POP3 command TOP) ==================
String s_Subject = i_Email.GetSubject(); // "vmime.NET Test Email"
// s_From[0] = "jmiller@gmail.com",
// s_From[1] = "John Miller"
String[] s_From = i_Email.GetFrom();
int s32_Timezone; // deviation (+/-) from GMT in minutes
DateTime i_Date = i_Email.GetDate(out s32_Timezone);
String s_UserAgent = i_Email.GetUserAgent(); // "vmime.NET 0.9.2 ()"
List<String> i_Emails = new List<String>(); // "jmiller@gmail.com", "ccastillo@gmail.com", ...
List<String> i_Names = new List<String>(); // "John Miller", "Cristina Castillo", ...
i_Email.GetTo(i_Emails, i_Names); // get all TO: recipients
// ================== Size (POP3 command LIST) ==================
UInt32 u32_Size = i_Email.GetSize(); // Email size in bytes
// ================== Uid (POP3 command UIDL) ==================
String s_UID = i_Email.GetUID(); // Unique identifier of this email on the server
// ================== Body (POP3 command RETR) ==================
String s_PlainText = i_Email.GetPlainText(); // "This is the plain message part..."
String s_HtmlText = i_Email.GetHtmlText(); // "This is the <b>HTML</b> message part..."
UInt32 u32_ObjCount = i_Email.GetEmbeddedObjectCount(); // number of embedded objects in the HTML part
String s_ObjId; // "VmimeLogo"
String s_ObjType; // "image/png"
Byte[] u8_ObjData;
UInt32 u32_Object = 0;
while (i_Email.GetEmbeddedObjectAt(u32_Object++, out s_ObjId, out s_ObjType, out u8_ObjData))
{
// do something with the embedded object
}
UInt32 u32_AttCount = i_Email.GetAttachmentCount(); // number of attachments
String s_AttName; // "Readme.txt"
String s_AttType; // "text/plain"
Byte[] u8_AttData;
UInt32 u32_Attach = 0;
while (i_Email.GetAttachmentAt(u32_Attach++, out s_AttName, out s_AttType, out u8_AttData))
{
// do something with the attachment
}
See DemoCpp project.
NOTE:
The console uses codepage 1252 and cannot display chinese characters.
When you fetch an email with i_Pop3.FetchEmailAt(M) only the mail header is downloaded (POP3 command "TOP"). This is quite fast and allows to access the Subject, From, To, Cc, Date, UserAgent, and more header fields.
i_Pop3.FetchEmailAt(M)
When you call i_Email.GetSize() the POP3 command "LIST" is sent to the server to obtain the size of the email.
i_Email.GetSize()
When you call i_Email.GetUID() the POP3 command "UIDL" is sent to the server to obtain the unique identifier of the email.
i_Email.GetUID()
And when you access the body part of the email, the POP3 command "RETR" retrieves the entire email which may be slow if the email has serveral megabytes. The body contains the plain text, HTML text, embedded objects and attachments.
So, to improve performance you should access the body part only if you really need it.
Imap has the same commands as Pop3.
Additionally there are:
// Enumerate all folders on the server
String[] s_Folders = i_Imap.EnumFolders();
// Select the folder to retrieve emails from
i_Imap.SelectFolder("[Gmail]/Sent Mail");
// Get the current folder
String s_CurFolder = i_Imap.GetCurrentFolder();
// Enumerate all folders on the server
void i_Imap.EnumFolders(vector<wstring>& i_FolderList);
// Select the folder to retrieve emails from
void i_Imap.SelectFolder(L"[Gmail]/Sent Mail");
// Get the current folder
wstring s_CurFolder = i_Imap.GetCurrentFolder();
As you see IMAP is far more complex than POP3. A new connection is established to the server each time a new folder is opened. (IMAP (1) is the first, IMAP (2) the second connection, etc...)
IMAP (1)
IMAP (2)
Here applies the same as for POP3, except that for obtaining Size and UID no additional command has to be sent to the server.
The following code shows how to delete all emails with the subject "vmime.NET Test Email" that you have sent by the SMTP demo before to yourself.
"vmime.NET Test Email"
// i_Service = POP3 or IMAP
int s32_EmailCount = i_Service.GetEmailCount();
// Run the loop reverse to avoid M indexing an already deleted email
for (int M=s32_EmailCount-1; M>=0; M--)
{
using (EmailParser i_Email = i_Service.FetchEmailAt(M))
{
if (i_Email.GetSubject() == "vmime.NET Test Email")
i_Email.Delete(); // POP3: mark for deletion, IMAP: Delete now
} // i_Email.Dispose()
}
i_Service.Close(); // POP3: Expunge all emails marked for deletion
// i_Service = POP3 or IMAP
int s32_EmailCount = i_Service.GetEmailCount();
// Run the loop reverse to avoid M indexing an already deleted email
for (int M=s32_EmailCount-1; M>=0; M--)
{
GuardPtr<cEmailParser> i_Email = i_Service.FetchEmailAt(M);
if (i_Email->GetSubject() == L"vmime.NET Test Email")
i_Email->Delete(); // POP3: mark for deletion, IMAP: Delete now
}
i_Service.Close(); // POP3: Expunge all emails marked for deletion
IMPORTANT:
POP3: When you call i_Pop3.Close() all emails marked for deletion are expunged definitely from the server. If you do not call Close() they will not be deleted!
IMAP: When you call i_Email.Delete() the email is deleted immediately.
i_Pop3.Close()
i_Email.Delete()
Here are the URL's where I downloaded the several components that are required to build the project.
You don't have to download them. This is just for your information.
vmime
I checked out version 0.9.2 with the GitHub tool
openssl
Downloadpage: (Source)
Downloadpage: (Binaries)
Sourcecode:
Win32Binaries:
Win64Binaries:
libgsasl
Downloadpage:
Sourcecode:
Win32Binaries:
Win64Binaries:
ATTENTION:
The binaries in gsasl-1.6.1-x64.zip and gsasl-1.8.0-x64.zip on the ftp server are wrongly compiled (they are 32 Bit, not 64 Bit!)
Mime types
If you use Visual Studio 2005 it is indispensable for this project to have VS Service Pack 1 installed. Otherwise you will see Intellisense hanging forever. This bug has been fixed in SP1. See MSDN.
vmime.NET can be compiled as x86 (Win32) or x64 (Win64) and as Debug or Release.
There are two dependencies: GNU Sasl and OpenSsl.
The file cCommon.cpp contains the #pragma comment commands that tell the linker which Lib files to include depending on the current project settings.
The GSASL library consists of libgsasl-7.dll and the LIB files libgsasl-7_32.lib and libgsasl-7_64.lib.
If you should replace the Dll with another version you must also replace the Def file and run the script CreateLIB.bat to create the Lib files anew. Additionally the header files may have changed.
The OpenSSL library may be compiled dynamic (using ssleay32.dll and libeay32.dll) or static (no Dll's required)
When you run the OpenSSL installer for Windows you get a lot of LIB files:
Dynamic for compiler switch /MD:
OpenSSL-Win32\lib\VC\libeay32MD.lib (800 kB) // Release
OpenSSL-Win32\lib\VC\libeay32MDd.lib (800 kB) // Debug
OpenSSL-Win32\lib\VC\ssleay32MD.lib (70 kB) // Release
OpenSSL-Win32\lib\VC\ssleay32MDd.lib (70 kB) // Debug
Static for compiler switch /MD:
OpenSSL-Win32\lib\VC\static\libeay32MD.lib (20 MB) // Release
OpenSSL-Win32\lib\VC\static\libeay32MDd.lib (20 MB) // Debug
OpenSSL-Win32\lib\VC\static\ssleay32MD.lib (4 MB) // Release
OpenSSL-Win32\lib\VC\static\ssleay32MDd.lib (4 MB) // Debug
The same amount of LIB files exist additionally for compiler switch /MT but this switch cannot be used in Managed C++ projects (vmime.NET.dll).
And the same amount of Lib files exists additionally for 64 Bit.
So there are totally 32 LIB files.
IMPORTANT:
If you should replace openssl with another version you must verify if the header files have changed.
I strongly recommend to link vmime.NET.dll statically because
If you compile on Visual Studio 2008 this does not matter because openssl is also compiled on VS2008, but on any other Visual Studio version it does:
vmime code itself also depends on the VC++ runtime but the version of the C++ runtime will depend on your Visual Studio version.
For example VS 2005 creates a dependency to Msvcp80.dll, Msvcr80.dll and Msvcm80.dll.
So, what would happen if you compile on VS 2005 and link dynamically to ssleay32.dll and libeay32.dll ?
Then your software would depend on Msvcp80.dll, Msvcr80.dll and Msvcm80.dll due to vmime and additionally on Msvcr90.dll which is required by ssleay32.dll and libeay32.dll.
This would mean that the users of your software have to install two VC++ runtimes!
All the above applies to vmime.NET.dll where the compiler switch /MT cannot be used (Visual Studio restriction).
But if you use vmime in a pure C++ project you can compile with /MT and use the openssl libraries libeay32MT.lib and ssleay32MT.lib instead.
This links the C++ runtime statically into your application and you do NOT need any of the MsvcXX.dll's.
If you are not sure on which Dlls your compiled binaries depend use DependencyWalker to check that:
This screenshot shows the depencies if compiled with openssl static LIB files on VS2005 as Release, 32 Bit.
The files in bold are included in the download on Codeproject.
IMPORTANT:
Microsoft's VC++ runtime installer does NOT install the Debug versions of these Dll's.
You MUST compile as Release before delivering your software!
ATTENTION:
If these DLL's are not installed on the target machine the user will NOT get an intelligent error message telling him what is wrong. Instead Microsoft .NET throws the most stupid exceptions like: "vmime.NETVcXX.dll!
There are 2 ways to assure that the MsVcr/MsVcp/MsVcm DLLs exist on the target computer:
Try this tool that checks which VC++ runtimes are installed.
This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)
i_Attach.getData()->extract(i_Stream);
F2g]?<.7Q4
F2g]?<..7Q4
--------------------------------------------
Message-ID: <002001d159ae$b7564180$2602c480$@irium-france.com>
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_0021_01D159B7.191B93E0"
X-Mailer: Microsoft Outlook 15.0
Thread-Index: AdFZrrb1TrtDWv5iQMiLM1KjXZthXg==
Content-Language: fr
This is a multipart message in MIME format.
------=_NextPart_000_0021_01D159B7.191B93E0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
=20
Votre message est pr=EAt =E0 =EAtre envoy=E9 avec les fichiers ou liens =
joints
suivants=A0:
1_10305279_15052009.pdf
Message de s=E9curit=E9
------=_NextPart_000_0021_01D159B7.191B93E0
Content-Type: application/pdf;
name="1_10305279_15052009.pdf"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
filename="1_10305279_15052009.pdf"
%PDF-1.3
%=F5=E4=F6=FC
7 0 obj << /Type /XObject
/Subtype /Image
/Name /I1
/Width 282
/Height 88
/BitsPerComponent 8
/ColorSpace /DeviceRGB
/Length 7319 /Filter [ /ASCII85Decode /DCTDecode ] >>
stream
-----------SNIP----------------
startxref
50237
%%EOF
------=_NextPart_000_0021_01D159B7.191B93E0--
String emailText = emailBuilder.Generate();
File.WriteAllText(@"E:\Temp\SentEmail.eml", emailText);
String emailText = emailParser.GetEmail();
File.WriteAllText(@"E:\Temp\RecvEmail.eml", emailText);.
void PrintMailToConsole(cEmailParser* pi_Email){
vmime_uint32 u32_Email = pi_Email->GetIndex() +1;
wstring s_Subject = pi_Email->GetSubject();//There is the problem.
...
}
GBK
windowsCodepages.hpp
<startup>
<startup useLegacyV2RuntimeActivationPolicy="true">
DemoC#\DemoCSharp.csproj: Error migrating project file. Cannot evaluate the item metadata "%(Filename)". The item metadata "%(Filename)" cannot be applied to the path "obj\Debug|x86\Debug\DemoCSharp.pdb". Illegal characters in path. C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets
i_Email.AddTo("recipient1@gmail.com");
List<String> i_Emails = new List<String>(); // "jmiller@gmail.com", "ccastillo@gmail.com", ...
i_Email.GetTo(i_Emails, i_Names);
class Email {
public List<string> To;
}
X509Certificate_OpenSSL::verifyHostName()
strcasecmp()
cnMatch()
for (int j = 0 ; j < sk_CONF_VALUE_num(val) ; ++j)
{
CONF_VALUE* cnf = sk_CONF_VALUE_value(val, j);
if ((strcasecmp(cnf->name, "DNS") == 0 &&
cnMatch(cnf->value, hostname.c_str()))
||
(strncasecmp(cnf->name, "IP", 2) == 0 &&
cnMatch(cnf->value, hostname.c_str())))
{
return true;
}
if (s_NoMatch.length())
s_NoMatch += ", ";
s_NoMatch += cnf->value;
}
if (!transport->isSMTPS() && tls)
if (!transport->isSMTPS())// && tls)
if (me_Security == cCommon::Secur_SSL) s8_Protocol = "smtps";
else s8_Protocol = "smtp";
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/719490/vmime-NET-Smtp-Pop-Imap-Library-for-Cplusplus-and?msg=4883001 | CC-MAIN-2016-40 | refinedweb | 3,731 | 58.99 |
Anatomy of SparkSQL
In addition to the ability to write, transform, and aggregate our data all over the place, manually, Spark also has a useful SQL-like API that we can leverage to interface with our data.
Not only does this provide a familiar logical-clarity to those with SQL, but like the language it’s based on, we get a lot of bang for our buck by describing what we want our final dataset to look like and let the optimizer figure out the rest.
import findspark findspark.init() import pyspark sc = pyspark.SparkContext()
In the same way that the
SparkContext handles all of the
RDDs, task scheduling, and resource negotiation behind the scenes, the
SparkSession extends this abstraction to handle the
SparkSQL API. This includes keeping track of the metadata, schemas, user-defined functions, and various other components powering the API.
We’ll instantiate a
SparkSession by tying it to the
SparkContext object that we’re working with.
spark = pyspark.sql.SparkSession(sc)
DataTypes
Native python datatypes such as
float,
str, or
int don’t exist in Spark. Instead, Spark figures out how to translate the Python that we know to the underlying Java objects that all of the data is mapped in.
We can inspect everything that’s available, as well as access for type-casting operations, by using the
pyspark.sql.types module.
from pyspark.sql import types [x for x in dir(types) if x[0].isupper()]
['ArrayType', 'AtomicType', 'BinaryType', 'BooleanType', 'ByteType', 'CloudPickleSerializer', 'DataType', 'DataTypeSingleton', 'DateConverter', 'DateType', 'DatetimeConverter', 'DecimalType', 'DoubleType', 'FloatType', 'FractionalType', 'IntegerType', 'IntegralType', 'JavaClass', 'LongType', 'MapType', 'NullType', 'NumericType', 'Row', 'ShortType', 'SparkContext', 'StringType', 'StructField', 'StructType', 'TimestampType', 'UserDefinedType']
One weird feature of referencing these types is that you usually have to call them. For instance, look at
FloatType. The
__repr__ just points to its module path.
types.FloatType
pyspark.sql.types.FloatType
But what
type is it?
type(types.FloatType)
type
Now look what happens when we call
FloatType
type(types.FloatType())
pyspark.sql.types.FloatType
That looks more acurate. Indeed, these two objects– called and not-called– are different objects
types.FloatType() is types.FloatType
False
One of them inherits from the Base Java
DataType class
# called isinstance(types.FloatType(), types.DataType)
True
And one of them doesn’t.
# not-called isinstance(types.FloatType, types.DataType)
False
Again, every time you want to work with data types in Spark, you should be using something that’s tied to the underlying Java implementation via the
DataType superclass.
Making Simple Datasets
Most of the time, when we work with Spark SQL, it’ll be a result of reading data from some source, but we can also manually build smaller datasets to toy around with, such as
A range of numbers
nums = spark.range(5, 15).show()
+---+ | id| +---+ | 5| | 6| | 7| | 8| | 9| | 10| | 11| | 12| | 13| | 14| +---+
Or a vanilla tabular DataFrame
Where the
data is a list of tupes and the
schema is a list of column names
df = spark.createDataFrame(data=[('a', 1), ('b', 2),('c', 3)], schema=['letter', 'number'] )
And
Spark intuits the datatype from the records we gave it.
df.dtypes
[('letter', 'string'), ('number', 'bigint')]
Additionally, we can be more explicit with our schema by using the
StructType dataset and feeding it tuples of
(colName, dtype, nullable)
schema = types.StructType([ types.StructField('letter', types.StringType(), True), types.StructField('number', types.StringType(), True) ])
And passing that into the
schema argument instead of a list
df = spark.createDataFrame(data=[('a', 1), ('b', 2),('c', 3)], schema=schema )
df.dtypes
[('letter', 'string'), ('number', 'string')]
Rows
Each row of data is stored as a
Spark-unique datatype called a
Row.
Selecting the top
2 rows of data yields not the values, but a
list of
Rows containing them.
twoRows = df.take(2) twoRows
[Row(letter='a', number='1'), Row(letter='b', number='2')]
From there, we can use
dict-like operations to access the fields that we want.
oneRow = twoRows[0] oneRow['letter'], oneRow['number']
('a', '1')
Or just get the fields/values themselves as a
dict
oneRow.asDict()
{'letter': 'a', 'number': '1'}
Cols
These are a bit more complicated and merit their own workbook, I think. For now, let’s figure out how to select them.
We can access columns of our data like we might have done using
pandas. But it gives this cryptic, unhelpful
__repr__ when you do.
df['number']
Column<b'number'>
And doesn’t have a
collect() or
show() implementation
df['number'].collect()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-20-b0024827437e> in <module>() ----> 1 df['number'].collect() TypeError: 'Column' object is not callable
df['number'].show()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-21-1aaab6c11f19> in <module>() ----> 1 df['number'].show() TypeError: 'Column' object is not callable
Instead, you need to use the
df.select() and
collect methods to actually select and collect the column.
df.select(df['number']).collect()
[Row(number='1'), Row(number='2'), Row(number='3')]
Which, again, returns a list of
Row variables containing the data. | https://napsterinblue.github.io/notes/spark/sparksql/overview/ | CC-MAIN-2021-04 | refinedweb | 831 | 54.83 |
I’m senior software engineer specialized in declarative designs and S.O.L.I.D. and Agile lover.
Yet more code smells? More? Where do they come from?
We see several symptoms and situations that make us doubt the quality of our development.
Let's look at some possible solutions.
Most of these smells are just hints of something that might be wrong. They are not rigid rules.
Previous Parts
Let's continue...
Code Smell 56 - Preprocessors
We want our code to behave different on different environments, operating systems, so taking decisions at compile time is the best decision, isn't it?.
Photo by CDC on Unsplash
Photo by CDC on Unsplash
Problems
- Readability
- Premature Optimization
- Unnecessary complexity
- Debugging
Solutions
- Remove all compiler directives.
- If you want different behavior, model it with objects
- If you think there's a performance penalty, make a serious benchmark instead of doing premature optimization.
Sample Code
Wrong
#if VERBOSE >= 2 printf("trace message"); #endif
Right
if (runtimeEnvironment->traceDebug()){ printf("trace message"); } ## even better with polymorphism and we avoid annoying ifs runtimeEnvironment->traceDebug("trace message"); must leave premature optimization buried in the past.
Bjarne Stroustrup, in his book The Design and Evolution of C++, regrets on the pre-processor directives he created years before.
More info
C++ is designed to allow you to express ideas, but if you don't have ideas or don't have any clue about how to express them, C++ doesn't offer much help.
Bjarne Stroustrup
Code Smell 57 - Versioned Functions
sort, sortOld, sort20210117, workingSort, It is great to have them all. Just in case
Photo by K8 on Unsplash
Photo by K8 on Unsplash
Problems
- Readability
- Maintainability
Solutions
- Keep just one working version of your artefact (class, method, attribute).
- Leave time control to your version control system.
Sample Code
Wrong
findMatch() findMatch_new() findMatch_newer() findMatch_newest() findMatch_version2() findMatch_old() findMatch_working() findMatch_for_real() findMatch_20200229() findMatch_thisoneisnewer() findMatch_themostnewestone() findMatch_thisisit() findMatch_thisisit_for_real()
Right
findMatch()
Detection
We can add automatic rules to find versioned methods with patterns.
Like many other patters we might create an internal policy and communicate.
- Versioning
Conclusion
Time and code evolution management is always present in software development. Luckily nowadays we have mature tools to address this problem.
Credits
That's why I write, because life never works except in retrospect. You can't control life, at least you can control your version.
Chuck Palahniuk
Code Smell 58 - Yo-yo Problem
Searching.
More info
An error arises from treating object variables (instance variables) as if they were data attributes and then creating your hierarchy based on shared attributes. Always create hierarchies based on shared behaviors, side.
David West
Code Smell 59 - Basic / Do Functions
sort, doSort, basicSort, doBasicSort, primitiveSort, superBasicPrimitiveSort, who does the real work?
Photo by Roger Bradshaw on Unsplash
Photo by Roger Bradshaw on Unsplash
The primary disadvantage of Wrap Method is that it can lead to poor names. In the previous example, we renamed the pay method dispatchPay() just because we needed a different name for code in the original method.
Michael Feathers
Code Smell 60 - Global Classes
Classes are handy. We can call them and invoke them any time. Is this good?
Photo by Mae Mu on Unsplash
Photo by Mae Mu on Unsplash
TL;DR: Don't use your classes as a global point of access.
Problems
- Coupling
- Classes are global unless we use Namespaces.
- Name polluting
- Static Methods
- Static Constants
- Singletons
Solutions
- Use namespaces, module qualifiers or similar
- To avoid namespace polluting, keep the Global names as short as possible.
- Class single Responsibility is to create instances.
Sample Code
Wrong
<? final class StringUtilHelper { static function reformatYYYYDDMMtoYYYYMMDD($date) { } } class Singleton { } final class DatabaseAccessor extends Singleton { }
Right
<? namespace Date; final class DateFormatter { function reformatYYYYDDMMtoYYYYMMDD(Date $date) { } //function is not static since class single responsibility is to create instances and not be a library of utils } namespace OracleDatabase; class DatabaseAccessor { //Database is not a singleton and it is namespace scoped }
Detection
We can use almost any linter or create dependency rules searching for bad class references.
- Globals
Conclusion
We should restrict our classes to small domains and expose just facades to the outside. This greatly reduces coupling.
More info
Write shy code — modules that don't reveal anything unnecessary to other modules and that don't rely on other modules' implementations.
Dave Thomas
We are done for some time (not many).
But we are pretty sure we will come across even more smells very soon!
I keep getting more suggestions on twitter, so they won't be the last!
Send me your own! | https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xii?ref=hackernoon.com | CC-MAIN-2022-33 | refinedweb | 751 | 55.84 |
On Thu, Dec 21, 2017 at 05:44:11PM -0500, John Snow wrote: > I don't think there's a legitimate reason to open directories as if > they were files. This prevents QEMU from opening and attempting to probe > a directory inode, which can break in exciting ways. One of those ways > is lseek on ext4/xfs, which will return 0x7fffffffffffffff as the file > size instead of EISDIR. This can coax QEMU into responding with a > confusing "file too big" instead of "Hey, that's not a file". > > See: > Signed-off-by: John Snow <address@hidden> > --- > block/file-posix.c | 5 +++++ > 1 file changed, 5 insertions(+) > > diff --git a/block/file-posix.c b/block/file-posix.c > index 36ee89e940..bd29bdada6 100644 > --- a/block/file-posix.c > +++ b/block/file-posix.c > @@ -589,6 +589,11 @@ static int raw_open_common(BlockDriverState *bs, QDict > *options, > s->needs_alignment = true; > } > #endif > + if (S_ISDIR(st.st_mode)) { > + ret = -EISDIR; > + error_setg_errno(errp, errno, "Cannot open directory as file"); > + goto fail; > + } Should we also do the same for S_ISCHR & S_ISFIFO, because neither of them allow seeking, which IIUC would prevent usage in the file driver for random I/O. It would be fine todo that in a followup patch though, so from this patch pov Reviewed-by: Daniel P. Berrange <address@hidden> Regards, Daniel -- |: -o- :| |: -o- :| |: -o- :| | https://lists.gnu.org/archive/html/qemu-block/2017-12/msg00770.html | CC-MAIN-2019-35 | refinedweb | 219 | 64.71 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
I have Confluence 4.1 and Crowd 2.3.3 in my environment and was trying to get SSO to work. I followed everything in the documentation and SSO worked. But when I login to Confluence, part of the system no longer work. And i am puzzled what the heck is going on.
Have anyone faced this problem before?
Confluence SSO config is correct or else i can't login, isn't it? Hmm...
Confluence Log:
2012-02-09 23:38:38,293 ERROR [http-80-8] [atlassian.confluence.servlet.ConfluenceServletDispatcher] serviceAction There is no Action mapped for namespace /status and action name update
-- referer: | url: /status/update.action | userName: tester
Doesn't look like and issue with SSO. Did you see it only after enabling SSO? What is the language you have in your profile now? Seems internationalization is broken somehow!
Yes, this happens after enabling SSO. I'll probably file for a support request to ask what's going on. Thanks. | https://community.atlassian.com/t5/Confluence-questions/Confluence-Crowd-SSO-Problem/qaq-p/437854 | CC-MAIN-2019-13 | refinedweb | 185 | 61.73 |
I took one of NVIDIA's on site labs at the DC GPU Tech Conference, which used Digits, and would highly recommend anyone interested in Deep Learning do the same. Some of their Deep Learning Insitute labs are available online here:.
Digits is also setup to use their AMIs on AWS, as an easy way to experiment without your own modern GPU at home.
In a typical day 02 hours of meetings working as a developer independent contractor. I don't count occasional DMing on Slack in that figure.
I think this might be more personality-based than age-related. I'm in my mid-20s and have similar feelings about most meetings. The kind of meetings I like and that are really productive for me are short, for a purpose (there are explicit questions one side has for the other), and with a small number of attendees, for me it's typically 13. Working with people you really like to be around I think helps as well.
Looks like we have at least 5 people interested. Someone might still point us at an existing community. In the meantime I created a slack channel and a forum.
HN does not seem to have a way to PM. Let me know how to invite you?
Best thing I could come up with is for people to send me their email to this throwaway account:52txhw+21xn2yhez22ozgcdc@sharklasers.com
Forum channel
There are, however, some upcoming developments which will change the situation in the next couple of months:
1) The main matrix.org client, Riot () has end-to-end encryption now in beta. This will offer Signal-strength encryption, but in a decentralized, e-mail-like system with federated servers. This will create an ecosystem where people are no longer dependent on the goodwill (and solvency) of a single entity to use a good, encrypted messaging app.
2) Briar () is a new (Android-only) app, designed for people with an especially high need for privacy. It works without central servers (through Tor hidden services, but hides the complexity of that), even works when the internet is down (e.g. when mobile networks are shut down during a protest) via Bluetooth and direct Wi-Fi connections, and it offers extra features, like a panic button that deletes all your data. It's in beta at the moment, with a planned release early next year.
TL;DR: Use Signal or Wire for now, but be ready to switch to a better system when available.
It has text (one-on-one and groups) and voice calls. Things that could use improvement: group management, switching to a new device. It doesn't have some of the features some people like (stickers and whatnot), but personally I don't care much about those. Video calls would also be nice.
edit: clarification
First of all, if you want total encryption, you'll need to make sure your connection is encrypted and secured as well (meaning following you back is not trivial), so the whole messaging should go through Tor[1].
There are plugin solutions for bitlbee[2], for Pidgin[3], and many other clients supporting OTR and similar encryptions.
If you want all-in-one solutions, you probably should look at Tox[4], which is a protocol, not just an app, built to be encrypted by default. It's complicated and nasty to use and set up, but it's pretty secure.
Other ideas might be drawn from the prism-break Communications list[5], listing apps like Chatsecure[6] or Xabber[7], both encryption-capable jabber apps.
[1]:[2]:[3]:...[4]:[5]:[6]:[7]:
Mobile only, paid, end-to-end encrypted with in-person verification. Team and infrastructure is based in Switzerland
Personally I use Signal and Whatsapp from that list.
Refer to which specifies that RSA 1280-bit keypairs are used, and the private key is held on the device. So in terms of transit - the protocol should be secure.
The only remaining option would be to question whether iOS is secure/insecure.
Apple claims:"Apple does not log messages or attachments, and their contents are protected by end-to-end encryption so no one but the sender and receiver can access them. Apple cannot decrypt the data."
Encryption, fantastic stickers, photo editor, tons of interesting channels, probably the best bots platform out there.
+ all mobile platforms and desktop version (as well as web based)
You can also find it's code on github.
- Encrypted local on-device storage. We have an always-on mechanism and never store the entire local storage decryption key on the device. It's half on the device and half on the server. In case of lost or stolen device, all data is still safe. In fact you can effectively "wipe" your biocoded app data even if the device is offline by deleting the server part of the decryption key.
- We allow private servers (not for free).
- Double ratchet algorithm for communication.
Interesting to see what others are using too.
[1][2]...
I would warn that (as of 1.5 years ago), JIRA Cloud is very slow. We've since moved to JIRA Server and solved the speed issues.
For me Xamarin Native was slow and rigid. I highly doubt I could make 'innovative' apps with Xamarin. Maybe it is okay for people who want simple things like a "to-do app" or somethign that fetches list of images and displays it.
I wanted more and found no solution for things I needed, so I gave up and started xcode (swift + some objective c).
And let me be clear here, if I had spent same amonut of time on xcode as xamarin I would have been iOS dev master :)
Things just works much better. You can do anything you imagine with Xcode and swift. With Xamarin its more like find whatever library is out there and try to create something by combining these. Too many bugs.
This is no sly dig on Xamarin or Microsoft as I use alot of MS products myself. I have also tried phonegap, react native etc. and Xamarin is the best when it comes to cross platform without a question, but none of these can match true native coding (xcode swift/objc)
The real problem is that I can write a native iOS app in a fraction of the time it took to write a Xamarin app. Swift has improved iOS development speed so much I'm not convinced we need cross platform app engines (excluding games).
As for Android, yeah, native Android sucks. Activities and fragments are the worst idea anyone has ever had and no one agrees on best practices. But even with cross platform high levels of abstraction like Unity3D you still need to understand them. So, my current advice is to suck it up and write it native twice. Pick your favorite OS, start with that, and then port the logic.
However, in my experience, both Xamarin Studio and the build system are buggy as hell. Random or inexplicable build errors, things that break during updates, incompatibilities with official Android support libraries... I find myself doing 'clean project and rebuild' to fix random errors, or switching between alpha, beta and 'stable' channels all the time depending on which one does not have the bugs that I'm running in to.
Xamarin.Forms is simply a disaster. Because it aims to unify the apis for the UIs for various platforms it boils down to only the most common denominator of those platforms. And then makes it worse. Not only is it buggy, it is also very slow and incredibly limited. In our office we're keeping a list of all of Xamarin's silliness we encounter, here is just one of those:.
"Clicking a Button changes its text alignment from center to left-aligned; it requires writing a custom Renderer to solve this."
I'd love to hear from someone using Visual Studio if their experience is more positive, but my advise is: please stay away from Xamarin.Forms and Xamarin Studio as much as possible.
* Xcode = iOS bugs + UIKit bugs
* Xamarin = iOS bugs + UIKit bugs + different runtime, language, memory model abstractions + .NET bugs + P/Invoke bugs & overheads + GC inter-op bugs & overheads + C# bugs + slow followup of platform updates
* Xamarin Forms = iOS bugs + UIKit bugs + different runtime, language, memory model abstractions + .NET bugs + P/Invoke bugs & overheads + GC inter-op bugs & overheads + C# bugs + slow followup of platform updates + extra UI abstraction layers + lack of fine level controls & features
I've tried Cordova/Ionic, Xamarin, Dropbox Djinni, and native iOS development. C++ is the closest I've got the a performant cross-platform solution, even though it go it's own quirks.
The problem with Xamarin is it'll always play second fiddle to quick moving targets of Android and iOS toolchains. In my case the Reactive Extensions support was utterly broken, and Visual Studio kept crashing on MvvmCross, Android SDK updates would make things hell, and I would waste at least 8 hours a week to fight the toolchain. The promise of cross-platform doesn't deliver much as you're trying to tweak your MVVM solution to Android/iOSs whims and fancies, which leave you with a fragile common logic.
If you want to write a TODO list of simple CRUD app, it might work, but for professional iOS/Android development, Xamarin is not enough. Xamarin doesn't free you from learning ViewController lifecycle etc and platform specific implementation details. So you're stuck on a foreign platform, with extra overload of learning C#/F# along with Android/iOS platform overhead.
My Advice: Learn Swift and Kotlin, and do native development. Cross-Platform is a illusion, and the road is paved with dead and failed projects.
Xamarin Forms is not Xamarin, it is a DSL. You do not need to use it. At its core Xamarin is c# with pinvoke to the underlying native platform implementation. You'll still need that platform knowledge but now you can share the core business logic between platforms.
To get maximum code share you'll need a MVVM framework such as ReactiveUI which is based on the Reactive Extensions and modeled on functional reactive principals check out or
Also I would like to recommend to focus more on Xamarin.Forms, it's using more modern approach. XAML (it's a xml-derived language) is actually quite good for writing UI part. Add there some MVVM framework and you'd love it.
Edit: fixed spelling
The team is made up of a few React core devs and some ex-FB folks. They actually helped organize the last official React conf. The scope of what can be built using Exponent is expanding rapidly. And you can build apps that are virtually indistinguishable from Swift/Java apps.
If you want an example, I'd encourage you to download the Android version of this app:
In no particular order:
Stay the hell away from Xam.Forms, unless it's improved drastically in the last 6 months. Though I also think the whole idea is misguided.
For Android, go with Xamarin or Kotlin. I would take C# over Kotlin because of the maturity of the language, the tooling around the language, and the ecosystem. Either way, having a powerful modern language will be a godsend.
Concurrency on Android is much easier to deal with in Xamarin than with native. This extends to things like complex orchestration of animations.
You will do backflips trying to get startup-time down. But once your app is in memory performance is basically native-level.
Xamarin gives you some nice framework-level things that native Android doesn't. A good API for sqlite and http. Proper data-binding. MvvmCross and ReactiveUI are light-years ahead of anything that is available in native-land.
Xamarin builds are faster and more reliable than Gradle.
Xamarin introduces its own layer of bugs and glitches. You've added another slice of Swiss cheese to the stack.
Xamarin plugin for Visual Studio is crash/glitch city. Xamarin Studio is tolerable at best. Either way, your tooling will be faster but less feature-rich than Android Studio.
Every time you want to use an existing third party library, you will go through this process: Has anyone done an official binding for it? If yes, use awkward Java syntax in C#. If no, try to find an unofficial binding. If not found, try to bind on your own - 50% chance it just works, 50% chance you fiddle for half the day and then fail. If it's the latter, try to decide if you want to do a code-level port, or abandon your idea. Code-level ports are possible nearly line-by-line, it's slow brainless work.
One thing I love is that because it maps so closely to native Android development, you don't need to look specifically for Xamarin.Android tutorials/SO Answers/blog posts etc to learn how to do something.
Most of the time, information targeted towards native Android development will apply to Xamarin.Android also, and you can basically map example Java code to C# because they use the same classes/namespaces.
I'm going to be getting into Xamarin.IOS soon, hopefully the experience is as nice.
In the beginning, i thought about making a hybrid app, because it could save me time on the long run, but starting to developing with Cordova and EmberJS or even Xamarin was frustrating.
My major reason for frustration is the tooling, cordova emulator just sucks (Ripple?) and working with javascript mvc frameworks isn't just for me (too complex IMHO).
Xamarin on VS has some bugs that would only go away if i restarted the IDE in order for things to work. Also, i'm concerning about being dependant to a third party framework.Can they keep up to speed with Google,Apple and MS?
Another valid concern is app size distribution that seems to be considerably higher with cordova and Xamarin.
Since i started on Android, using Android Studio made my life a lot easier and i'm progressing daily and enjoying it, something that was a PITA with other tools.
In my experience i would say that it will be more time consuming (expensive) to develop a single solution for each platform as well as giving support, but the tooling is a lot better, also you can give users a better experience because you end up developing native apps for each platform that can take better advantage of it's ecosystem.
I'll find out in the future if i'm right or wrong.
My main complaints are:
* It's full of bugs
* The build system is unreliable and mysteriously breaks, which generally takes a full day to fix
* Basic functionality such as merging resource dictionaries (which are stylesheets, kinda) is missing
* No graphical UI designer or preview, so every layout change requires a recompile and deploy before you can see it
* Apps feel sluggish and crash at runtime without specific error messages
* It makes VS crash all the time. I'm not a regular VS user so I'm not sure if VS:CE2015 is a POS or if Xamarin is.
Obviously I think it's worth it, I learned it well enough to teach others. We have a bunch of free Self Paced Learning modules and videos at Xam University, as well as obviously the paid stuff that pays my salary ;-)
There is a ton of investment and effort from a small team, remember, we've only been with a "big company" a few months, so the improvements come at a blistering start-up pace. If you haven't seen it in a couple years, you should really check back.
If you are going to develop "all platforms" or even just iOS and Android, it is _certainly_ worth a long look. Access to every API you get access to in their native languages and the ability to avoid that language "context switching" pain. Plus, some amount of shared code (varies wildly, 25% - 75% depending on how heavily your app is just about custom UI and animations ).
Because we use the same APIs (except when we have better ones), you can leverage the same documentation and StackOverflow posts when you need to (yes with a little language translation), but you often don't need to because Xamarin has a _lot_ of great documentation as well.
And, as has been mentioned, "Xamarin Forms" does not equal "Xamarin". Although it is a valid choice for developing in Xamarin, it is only one option. Here is a super shallow comparison:
Xamarin Forms: Super fast for super simple UI's and interactions with common elements. It is highly opinionated on what it should do and look like on all platforms. Customization is do-able but starts to increase the complexity of the app quickly to the point where the below would have been a better choice.
"Xamarin" aka "Xamarin.iOS and Xamarin.Android": Use essentially the same development patterns as Native Android and iOS developers and use the same API's (plus .NET library, and many .NET 3rd party libraries). You get code sharing (as noted, amount varies considerably), ability to "think in one language (often including your server, which might also be c#), and access to some additional libraries (because we support both the Native libraries _and_ the .NET ecosystem).
Hope this helps :)
Oh, and a quick plug. Xamarin University is live classes taught by real, very experienced developers who can actually help you learn and understand, so we are, you know, worth asking questions of. Also, we'll be doing a free presentation all day on November 18th as part of Visual Studio Connect, so check us out there and see what you think of Xamarin _and_ Xamarin University!
However, as others have pointed out, Xamarin Forms is a bit of let down.
In my experience, if you try to create custom designed UI (which is quite common in the native apps), then you find that Xamarin Forms is very limited. To overcome this limitation you need to write something called as a custom renderer for each OS you want to support. So it doesn't really save you much time.
Xamarin has something called as Xamarin Labs project on Github: But it's progress has been very slow.
If you have a business data collection / reporting app, where how things look is not very important, Xamarin can save a lot of time while creating cross-platform apps.
However, I wouldn't recommend Xamarin Forms for B2C apps.
Microsoft's strategy with bringing a phone to market appears to have failed so they're going to have to take the next best thing which is owning the development tools. I expect the outlook for the software to be extremely bright and if you plan to be a professional mobile developer I strongly suggest learning it.
Of course, this does not excuse you from learning how to develop for iOS and Android natively, but it is a great addition to your toolkit as a developer. It's also another box to tick for the recruiter or hiring manager.
The answer to whether or not you should learn Xamarin depends largely on what you are trying to accomplish. Let me explain.
If you were to approach me as someone interested in Xamarin, I would start by asking what kinds of apps you are looking to build, how complex they are, and how much you care about UI quality and customization. This is to help decide between Xamarin and other xplat solutions, but also between Xamarin native and Xamarin.Forms, our cross-platform UI toolkit. Id ask what you hope to gain from a cross-platform approach, so we can optimize for that. Id ask what parts of your app you are looking to share, and how you plan on architecting your app to allow that.
Id ask how much experience you have with .NET, and if being able to use C# and/or Visual Studio makes you more productive. Id ask if you have an existing codebase you want to connect to. Your familiarity with native iOS development is a plus - the particulars of iOS and Android add to the learning curve, but you cant make good native apps without knowing the basics of the platforms youre building for.
From these considerations, we would decide if Xamarin is a good fit for you. It would be naive to say that Xamarin is the ideal solution for everyone, but it is a very good solution for many people.
At the end of the day, Xamarin is free, and it takes less time to get a handle on developing with Xamarin than it does to read this thread. I encourage you to try it out and decide for yourself.
With that said, I've made a number of apps in it, and it works well enough, but the more abstractions, the more problems, and you want to do anything outside of simple UI apps, you are likely going to have to learn how the native methods work anyway.
Then I had a .dll that I could use in my Xamarin project. The Xamarin project was razor thin and I only used C# to connect my XIBs or Storyboard (I forgot what I used, but it was in Interface Builder) to the existing .dll calls and a specific type of hardware scanner.
The hardest part was getting that scanner to work, which would be not so easy for me even in Objective-C. But I basically had to create an Objective-C wrapper wrapped in some kind of C# wrapper. It wasn't easy but it was doable.
The hardest part was getting everything signed correctly, since I was using all kinds of layers you usually wouldn't use in "just software" project.
The overall experience was really good despite that the native editor for macOS wasn't that spectacular. I did the meat of my programming in Visual Studio and Visual Studio is a really great tool. Another part was done in Interface Builder which is a great tool in my opinion.
A friend uses it a lot for a cross-platform app written in Xamarin Forms. The thing with Forms is that unless you keep it simple you will run into Xamarin bugs, iOS specific bugs or Android specific bugs in your layouts and that can be challenging sometimes.
I would say that if you would make the UI in native code or storyboards and it still seems like an attractive idea to use Xamarin, use Xamarin. Don't use Forms.
One nice thing about it is that all the methods/classes are named almost the same thing as native android. If you want to know how to do something, you can find the android solution and just change a few small things.
So my vote would be to not do Xamarin and to choose a different cross platform development environment. Cross platform is the key. If you do choose Xamarin, I would spend some time and do a little bit of training before jumping in. It's not like the ease of building windows applications in VS.
The downside to this is that making a UI seems to even out your gained time--it's extremely messy and even complicated. Code that's valid in C# produces vague underwater bugs in Java code, which makes you keep hacking around until you find a working solution.
Not to mention the docs: some parts of the documentation are completely outdated to the point of not even compiling on an older version of Xamarin. For example, the tutorials on using Google Maps in your Xamarin.Droid application are way out of date, ignoring the fact that the "Google Play Services" component has split off into thirty-or-so components. Some of the most used API's are not documented at all, simply having a "To be added" description.
All in all I find much potential in Xamarin, and I really want to love it, but it's a messy nightmare to use, and it only makes me want to use Java and Swift separately for apps.
I must say that, having its own quirks and nuisances (specially in Xamarin Studio, which was pretty buggy until version 6.x), it does the job pretty well.
In fact, when we wrote our iOS and Android clients, Xamarin was still pretty immature. But if we had to rewrite them today, it would be one our of first options, right after using the native frameworks (which ensures the best results, but drastically increases the costs).
Purely by coincidence, I have four blog posts on this out this week. The first one (on React Native and Xamarin) is here:...
Had huge pain in full screen mode dynamically for all the devices.
Calendar with colors forced me to create a new custom control from 0.
To be stable with the controls if you make a tab control in one version should be the same in other versions also, not reinvent and change the wheel.
Easy and clear documentation. Forums all with lots of no one cares why it works int works on my machine stuff.
To new technology and has to get mature and stable. If you are not in the same versions of Xamarin in mac and windows it just not works properly.
Proper error message. I am getting an error like There were deployment errors. Continue. (Not run in administrative mode the vs 2015, closing the emulator or it was opened by other vs before, or you closed the emulator before finished the deploy)There are lots of errors like "aapt exited with code 1" that means there is some bad character in image or in files like -.... or files starts with number.
Also sometimes out of memory exception when loading images larger then 1mb or in android 4.2 larger than 300kb, even going lover to 100kb having problems in 4.2 android.
Proper editor for Xamarin.Forms is a must have if you want to develop. You can't see the design what you are doing with vs 2015.
Also designer is crashing all the time if i open multiple times and make some adjustments.
With both Xamarin and React Native there was a honeymoon period where everything seemed so easy and great. But at some point I always hit a problem where there was limited documentation, or unsupported features, and that really hurt my productivity and motivation.
The learning curve for Swift/ObjC always seemed much higher, with a lot more upfront investment required before I could make anything resembling a functional app. The iOS layout system in particular was an obstacle, as well as managing the tooling and dev environments.
If I had a free 6 months, I would just learn full native, but keep an eye on React Native. The dev experience in React Native is unparalleled, and it seems easy to drop down to native code (assuming you know it). Also the ability to easily contribute back to the community with NPM and react-native "link", makes me hopeful limitations will quickly be erased.
Overall I've been very happy. Code re-use hasn't been stellar, but good enough to repay the investment. We have re-use not only between apps, but also between mobile apps, Windows desktop apps, and our application backends. I also feel I'm more productive than if I had so swap between Java/Swift/ObjC/Andorid Studio/Xcode.
Stability has improved a lot in the last year. Paid-for support was pretty good (esp. guys like @jonpryor), but the self-serve forums can be a bit hat-and-miss. I never had any killer bugs (but then I never used Xamarin.Forms...)
Overall: 85% happy with Xamarin.
Xamarin wins if you need something for Enterprise. A lot of entry fields, validation, integrations with SSO, Sharepoint, other rest API. If you use MVVM well, it will lead to ~75% of code reuse between iOS and Android. Even more with XamarinForms. No complex effects, no complex animations, just enterprise.
Native wins if you want to make it more beautiful for end-users and you need to have a lot of customization. For example, customize map, pins and callout views. You will hate everything if you do it in Xamarin. No code reuse here
In general, Xamarin has very great chance to be #1 choise when you choose platform for Enterprise development.
It has not been an easy road. After 2 years, I'm finally beginning to reap the benefits. The simple problem is this: this is another layer over the existing layers and it's very hard to get it right, especially if the underlying layers suck.
Just because you've learnt Xamarin Forms doesn't mean you can choose not to learn the underlying native platforms. You can skip over most of the details, but something will always come back to bite you, and then you have to go figure it out. Xamarin Forms works on top of Xamarin Android, that works on top of Android SDK and Android Tooling, which works on top of the JDK, which works on top of the OS you're developing on. So many places for something to go wrong, and usually presents itself in the form of a cryptic error at the top. Developing for iOS is considerably easier.
So there's still a fair amount of expertise to develop if you're completely new to mobile development. Take it for what it is -- an abstraction, and as with any abstraction, any concrete manifestation will have its issues, and you must be ready to roll up your sleeves to figure it out. And it does get keep getting better with every subsequent release.
But it does eventually help -- we have to get the complex bit right once, and then it simply works. Don't approach this like you would approach an Android app -- make sure you understand UI design best practices -- especially reactive design and data binding.
We also have .NET stack, so I'm finally in this beautiful world where all my logic is represented as C# Expression Trees on the server side, that gets serialized and pushed down to our Xamarin Forms Apps. Looking forward to WASM adoption, so I can finally get rid of that JavaScript mess.
So if you're writing a one-time app, and you just want to target Android/iOS, and you don't care how you've done it, no it doesn't make too much sense.
But if you're trying to make a long-term bet, in this awful fragmented device-oriented world, (and having to write the same app twice goes against the very nature of your existence), well that's my bet, I will be cautiously optimistic. If you're on .NET, it's a no-brainer -- there are simply too many other benefits to ignore, and philosophically very true.
The architecture itself (Forms, Xamarin.Android, Xamarin.iOS, Custom Renderers, Platform Effects, Bindings to access native libraries) is theoretically flawless (or very close to it), a work of art -- and I'm a sucker for theory, no matter the real world pain.
Xamarin is nothing more than a C# wrapper around the native iOS and Android APIs. Everything you're familiar with (UIViewController, UIView, UITextField, UIButton, etc) remains the same. The main benefit (other than using C#) is that all non-UI code can be shared across platforms (iOS, Android, Windows, server, etc).
Xamarin.Forms is built on top of Xamarin and lets you reuse the same code for UI as well (using their own abstraction that's similar to WPF/UWP). I would only recommend this for relatively simple apps as you lose some control over platform specific details.
1. If you don't use Xamarin and you don't have a team in-house that uses C#, don't bother. You'll be better off doing native development on iOS and Android platforms.
2. Your app won't be as pretty, and it won't adhere to platform native UI conventions as well if you use Xamarin.
3. Xamarin does a better job of it than most but it will still be lagging in access to the latest features.
4. BUT, if you are doing a vertical market app that wants to be cross-platform AND you have C# coders you can apply to that task, Xamarin is the best choice.
There are a lot of places where choosing Xamarin makes a lot of sense. And the people who created Xamarin are excellent. And now that Xamarin is owned by MS, it won't die because it is hard to make money as a cross-platform startup. But as with every other cross-platform tool for non-game apps I've seen, it isn't the best choice in green-field situations.
Recommended workflow:0. Never ever use Xamarin.Forms other than quick prototyping. If you develop applications with other cross-platform frameworks, you already know all of them sucks and Xamarin.Forms is not an exception.
1. Create PCL / Shared project for your business logic (also your view models if you're using MVVM architecture). Believe me most of your application is platform independent (except the view layer). Your api communication, storage operations all handled here. See 3rd article to how to make storage/network platform independent.
2. Create native projects for each platform (iOS, Android, Windows) implement native views here (use xcode, android studio if you need visual designer). This part should be exactly the same as your swift/java code. For iOS you're just implementing an ApplicationDelegate class and UIViewControllers as same as your swift code. Same for Android part, nothing special to xamarin just implement your activity classes. At this level you have the full power of your native platform with one exception 3rd party native libraries. It's possible to use (yes i used some swift/java libraries for youtube player) them but really hard to integrate to your project, that part has to be improved and better documented.
3. Your shared code base need native features, for example storage implementations are totally different for each platform, or changing views (navigation) will be implemented differently for each platform. Since shared code base shouldn't know anything about native platform. You should abstract these functionalities with interfaces. For example create a storage interface with methods like saving/reading/creating files. Another example might be network communication. Abstract it as an interface on your PCL and implement this interface in your native project with full control of your platform. Your shared code base only knows how to use that interface. And then each of your native projects should implement these interfaces. At this point dependency injection may help to register implementations easily. Actually that part is what makes you share your business logic. Writing idiomatic cocoa navigation code is much better than using any cross platform implementations, you have full control but in the same time your shared code base using them without knowing anything about the platform.
In the free version you app expires after 24 hours AND it has to be below a certain size, I dont remember maybe 2 MB or something.
To make something you have to cough up a lot of money, and the sad part is this information is incredibly hard to find, you only stumble upon it when you download GBs of files.
You don't say what your side project is, but you have to ask your self whether you need liability protection, that is what are the chances someone is going to sue you for damages. If you feel you need liability protection, then you should form an entity. I recommend an LLC in most cases. It is a pass-through entity for taxes which means you pay taxes on your individual return (though it still must file a business tax return). Also buy insurance.
The other reason is ease of administration. A legal entity will have some form of controlling document. In an LLC, it is the Operating Agreement. This spells out the rights and duties of the principals in the business. It also allows for common ownership of the business assets. As principals come and go, the LLC continues on. Finally, if you get big and you bring on investors, they will want to see a legal entity for their protection.
The drawbacks of forming an LLC are the time and effort of drafting and filing all the proper incorporating documents, paying the filing fees (in California $800 per year), and the extra tax forms.
This is a complicated topic and I have given a high level view. There are lots of resources on the internet and in bookstores on this topic. Nolo.com would be a good place to start.
No I operate as a sole proprietor.
> 2. Do you pay quarterly taxes?
Nope, I pay the penalty since my income and ability to shelter it vary from year to year. The penalty is something like 3% on the total taxes you owe. Not too bad given the flexibility holding your money provides. Maybe I can load up a i401K that year or need to save for some big purchase which is more valuable then just giving the IRS the money.
> 3. Do you list it as other, unreported income on your returns?
I file a Schedule C
I do it all using TaxAct. Super easy and cheap. Helped me to understand taxes as well.
I haven't incorporated any of them, I see that as an unnecessary hassle.
I'm in England, and (as far as I'm aware) quarterly taxes aren't a thing here. Until this year the income was negligible enough not to bother paying taxes, but this year I've been keeping track of finances with ledger[2] and I intend to pay taxes as "self-employed" for the first time at the end of this tax year.
And to make sure I'm going in the right direction (not going to run out of money) I add up my net worth, split by category (bank account, peer-to-peer lending, stocks and shares, Bitcoin) at the start of every month and keep track of it in a big text file.
[1] currently focusing on SMS Privacy, read my Indie Hackers interview at
[2]
I have to say that Atlas might be one of the easiest, and least expensive, ways to deal with the incorporation and the rest.
I've got an LLC for basic liability protection.
PayPal is my business system. All sales come in through PP, and I use the PP credit card for my purchases. All documents are electronic. At tax time, I download the entire year's transactions into a spreadsheet, add things up, and enter the totals into a Schedule C.
Rather than filing quarterly taxes, I've simply bumped up the amount of withholding from my regular day job.
Lawyer and Accountant. Budget about $10k/yr
Start as LLC then move to C-Corp as it grows and takes investment money. Accountant files quarterly federal and state taxes. My wages are taken out on W2.
When smaller the project is an LLC. Accountant still files paper but under $100k only annual. Just take the money out as distribution.
Tax implications from either route. Encourage you to find a trusted advisor on those matters
If you're making more than a few grand (net) then you might consider having your LLC taxed as a corporation and enjoy the 15% tax treatment. If Trump gets his way, corporate taxes might finally be reduced and you'll get even more favorable tax treatment.
However, if your intent is to enjoy the income but you expect a narrow net income or loss (lots of expenses can be attributed to your business), then stick with a single-member, disregarded entity, LLC.
While the annual cost of $800 minimum tax plus maybe another $500 in administrative fees (accountants, legal, etc.) is real money spent, you can make it back in tax deductions and potential liability. If you have a structure in place (another entity that is not you personally), it is much easier to deduct expenses (less red flags) IF you make an attempt to actually generate income -- the government cannot stop you from being a bad business person :)
If you are in a 50% tax bracket, this could easily be offset by $3000 in expenses such as hosting fees, domain names, costco membership, cell phone, even your car lease. If you are renting, you can possibly deduct some portion (~20%) of your rent (do not do this if you own a house). Get a separate bank account + debit card, a separate credit card (maybe a business one with rewards) and pay everything using that entity. You will end up making "owner contribution" from your personal bank account to your business account every month.
The extra wrinkle if you have multiple projects is that you can further separate your different projects into "DBA"s (Doing Business As) which costs an extra $100/yr (County Clerk Recorder, Publish in Magazine, separate bank account, credit card, domain name) 100% owned by your LLC (or S-Corp). If you shut down a DBA, it will cost maybe another $50. You will need a DBA to open a bank account under that name.
While this may look like overkill, this keeps everything clean and if your side project does take off, you will have some history with the business.
On a day-to-day basis, what I usually end up doing is setting aside a day to deal with all these entities. Most bills are on each "company" credit card and I call all the credit card companies to align the closing date. For example, all my credit cards close around the 22nd or 23rd of every month. On the 12th of every month, I pull up each account and pay them all using one screen of online billpay if you have all your business accounts tied together using your SSN.
Note: I have other companies that are their own entity as they are generating income & have other partners. The setup here is specifically just for my side projects.
My state LLC
>Do you pay quarterly taxes?
Absolutely, mail a check with the coupon based on income earned.
>Do you list it as other, unreported income on your returns?
Schedule C and income from business, you pay Self-Employment Tax, SEPs are nice to push off the income to retirement and see a tax benefit if it's supplementary.
I also carry worker's comp and liability insurance, pricey, annoying to setup and deal with but worth it from my perspective.
As I'm an Aussie, I register an ABN (being a sole trader is free) and ensure I pay/charge GST. I'm only required to file taxes if the business is earning in excess of $10,000 annually. So most projects that go nowhere don't put any onnus on me to be hyper vigilant.
If you have a small side project with low risk then I recommend sole proprietor for sure.
In any case, soon as you start generating income you need to track income/expenses, register your business, register for HST and setup a separate bank account. I think TD here charges $25/mo just for that privilege.
So yeah, sometimes a fun side project loses its excitement when your stuck doing paperwork and start adding up the expenses, it's not worth it.
As for taxes, the penalties are not particularly punitive if you screw up and you have years to manage the situation before anything critical happens. In particular, if you go one year without making quarterly tax payments you will probably walk away with no penality.
The $800/year is indeed painful but it's cost of doing business (and maintaining continuity).
EDIT: specifically, in the index entry for "business structures" and the chapter on taxes. I also bought a few "personal MBA" books, & on marketing etc, but this seemed clearly the best one to start with; those others I think I'll come back to, later.
I ran my businesses for the first ~6 years as unincorporated sole proprietorships. The exact mechanisms of doing this are different based on where you are (both at a national and local level). Japan and the US are fairly similar: a sole proprietorship exists as soon as you say it does. (In Japan, you should probably walk down to the local tax office and file a form announcing your intention to file next year if you plan on making more than $30k revenue. They'll know which form to file and you are capable of doing it write if you can read Japanese.) Some US localities will want you to file for an assumed name / "doing business as" (DBA) with your local county clerk or have a city business license -- you can usually find out about that with some quick Googling. I filed a one-page form with Lake County, IL saying that I was doing business as Kalzumeus Software (several years before I had that LLC) and then had to pay ~$50 or so to put an ad in the newspaper for a few weeks saying "Heads up Kalzumeus Software is actually Patrick."
You pay taxes on the profits of the business, not on the revenue of the business, which is a crucially important distinction that many HNers do not know when they start and which many do not properly operationalize even if they know it. I cannot underline this enough: no software entrepreneur I've ever met had a good handle on this when starting. If you sell $10k of software and think "Hmm my profits are maybe $9.5k -- the only expense was a DigitalOcean server" I think your profits are ~$0 after you spend a few hours with an accountant walking through credit card receipts. They're going to walk you through things like e.g. depreciation, apportioning business and personal use of your Internet/cell phone, conferences, business entertaining, (potentially!) home office use [+], etc etc. (A thing your accountant will probably tell you, in the US, is that if you want to decrease your tax burden for 2016 buying a Macbook for the business
You should ordinarily be listing income from a side business as business income, at least in the US and Japan, and not as any other type of income. This is both a) correct and b) gives you the ability to deduct expenses, which is not possible on all types of income reported on e.g. one's 1040 or .
The US has you pay quarterly estimated taxes. There are safe harbors which are likely to cover you in the first year of running your side project.... The calculation of these can occasionally be complicated; this is a great "ask an accountant" question because this is their bread-and-butter and that particularly calculation is something that most accountants would do for free, on spec, as part of soliciting your business for next year. The penalties for not paying estimated tax in a timely manner are very small -- many entrepreneurs of my acquaintance treat timely tax payment as a small discount to the "real" tax bill and elect to simplify their lives by paying taxes once a year rather than by calculating quarterly.
The chief reason to put a side project in an LLC is to reduce the risk of liability of the side project flowing to you. Most side projects have vanishingly little liability. Ask me for a citation some other time, but even software development freelancing is low-risk -- my insurance company calculates than ~0.5% of freelancers/consultants get sued in any given year. Downside: when they do get sued, win or lose, that averages $40k in costs. If you're doing something where you have non-trivial liability or if the prospect of $40k+ vanishing just makes you unable to sleep at night, incorporate and get an general liability / E&O policy. (Costs $1k or so per year as a floor; mine as a comparable is $3k and has the words "patient health information" and "HIPAA" on it, which contribute expense and underwriting fun times.)
If you have additional questions about this sort of thing, I'm writing about it this week (in my employed capacity) and would love to hear what you're thinking about.
[+] Home offices are historically a contentious deduction in the US, but one of the reasons you have an accountant is so that they tell you consequential things about the difference between the regs as written and the regs as customarily applied like "You don't have an office? Oh, in Japan, we just deduct 40% of your rent then. Substantiation requirement? Ah you Americans are such kidders. There's the law on the books which is $CALCULATION but the tax agency basically feels like you don't screw them too much on being aggressive and they won't screw you too much on bringing out a tape measure to your kitchen.")
Front end: We use Ember because of its balanced focus on progress and stability. The team behind it is solid and batteries are included.
Application: Ruby/Rails, Elixir/Phoenix. Rails is great for getting up and running quickly, and your problems with #scale won't be on the application later. Elixir (really Erlang's BEAM) is great at quickly spinning up/down lightweight processes that handle raw data. So if you want to build a CRM and, say, manage emails, then it could be a good fit. Or if you want to process a 1,000,000 row CSV import, etc.
Database: Postgres. Binary JSON columns give you flexibility, plus PostGIS for all of your geospatial needs. Structure as much as possible to take advantage of the smart people who have spent countless hours building a world class database. You'll appreciate their focus on correctness.
My overarching advice: push everything as far down the stack as possible. If you can do it in Postgres, do so. Data correctness is your life; better that your DB throws a fit than your application serving bogus data.
Happy to answer any specific questions!
(And I wouldn't be a YC CEO if I didn't take the opportunity to mention that we're hiring!)
I've been dealing with different CRMs recently (SFDC, Netsuite, MS Dynamics, AgileCRM) and I don't think tools really matter, architecture that will allow you to customize everything is the key for CRM
As my personal choice it would be (I'm a full-time Python dev)
* Java/C# (there's nothing really dynamic in crm, entities, fields, etc with different "name" and "display_name" for each customer, IDE would allow me to manage complexity)
* PostgreSQL (no NoSQL, CRM is all about relations)
* Vue.js
* ElasticSearch (with Kafka for replication from db)
* RabbitMQ for offline jobs
I've gone over Angular 2, React, Vue.js, Ember, Polymer, and so many more. The one I really connected with is Vue. While I realize it's only been gaining popularity in recent months, there are some big companies who start to make use of it in big scale production sites (Alibaba, Laraval, ...), this makes me pretty confident that support will not be an issue.
For the db I would definitely choose Postgres, but I would go for plain old relational tables, and maybe use its JSON features for data which is isolated and does not relate to other data (e.g.saving spreadsheets data).
For the server I would choose NodeJS + Express + SequelizeJS, and I will probably make use of some GraphQL library up ahead too.But honestly, if you choose to make your system a SPA, then your server will not do much of the heavy lifting anyways - it will probably expose an API point and be used as an interface to the database, so I think any back-end stack would fit in. I would also consider Python + Flask + SQLAlchemy, which used to be my stack of choice few years back.
Any stack will get the job done. Use the one that yields you a shippable product in the end.
My stack is ExpressJS, AngularJS, PostgreSQL, NGINX, DigitalOcean, Route53, PM2. And I fly through it.
[0]
Stack is two separately hosted apps.
Frontend: react, redux, webpack as a single page appBackend: Rails for an API
Why? I wanted to learn react and redux and I like using Rails for my backend and was comfortable with that.
For our team that would be Node.js with a React frontend, with probably MongoDB as the database, but every team is different.
As a side note: APIs are very important for CRMs, but as long as you design your API well you can swap out, move around, and refactor your backend as it makes sense.
It'll answer all technical questions, make it easier to hire, and make it easier to fundraise. Oh! And easier to get customers.
Then think about how people get info into your system - if its email, use Nylas (it's gonna be email to start). If it's voice, use Twilio. If it's directly, then abstract all the complexity and use the right terms for your market.
I don't work for Salesforce, I never have in the past, and I barely use it now. But choosing anything else is nuts.
The main parts are:
- type safety, in the hope that it speeds up development. TypeScript 2 is my main contender here.
- on demand module loading, so I can shrink the initial page loads, will go with Webpack 2, because it lets me use System.import() and automatically splits these imports into it's own files
- interaction flow control completely based on observables, because they compose nicely and with genertic types ease development quite a bit. Will go for Cycle.js (+xstream), because it's rather tiny and really everything there is an observable, data and UI, also it's written in TypeScript. Feels a bit like Angular2-lite.
- WebComponents based UI-widgets, because I think they should be independent from the rest of the application, don't know yet if I'd go for Skate.js or Polymer, maybe I'd even use custom components directly. But I like the Skate API much more than Polymer or the "native" API.
- data retrieval will be based on GraphQL with the hope that it will lower data-on-the-wire if the client has more control on that. I also hope that the GraphQL subscriptions (based on WebSockets) will integrate nicely with the observables. Apollo-Client is my fav here, it's framework independent and written in TypeScript, too. I'll probably use their GraphQL-server, too.
Every part is pretty much independent of each other (besides everything being written in TypeScript, haha) so I think I can use parts of it in future projects.
Server side rendering would be a nice to have, because it would enable the basic app functions on clients without JavaScript.
Although there are a lot of different tech stacks, I think that most of this boils down to SPA vs integrated views with some javascript. In the rails world, this generally means either Rails plus jQuery, unobtrusive javascript, coffee script, and so forth, vs rails-api and Ember (or another javascript front-end).
Right now, I lean more toward the integrated views than most of my fellow developers. Very few people would take an always/never position on single page apps, so this generally boils down more to how far people want to take them. Some are more eager to apply them in a wider range of scenarios than others.
I personally lean toward the integrated view approach, and I advice caution around SPAs - in my opinion, very much an opinion here, I think they add a lot of complexity compared to the integrated approach, and are still in a state of flux. If what you are writing really is mainly a set of forms that you'd like to enhance a bit with automatic page refreshes, drop downs, drag and drop elements, autofill and so forth, you may want to stick with a more stable stack that isn't evolving as rapidly as SPA javascript frameworks.
There are situations where you can find yourself in a real mess with an integrated view, that would be far easier to manage with Ember or another javascript framework, keeping your backend logic in a relatively simple API. Not sure if that's going to happen in a CRM - they tend to be pretty form-ish apps, but perhaps that's because up to now, difficulties with javascript have led us to think of them that way. The rapid evolution of JS frameworks may, for all I know, have opened up an opportunity for serious innovation here.
One other thing - remember that it is relatively easy to expose a rails method as an API even in the absence of rails-api. My guess is that this is true of most integrated frameworks that provide a view tier. You won't be locked into an integrated app provided you keep logic out of those views! You should be doing that anyway. Also, make sure your tests don't rely exclusively on the views to verify logic that isn't in the view (again, you shouldn't be doing this, but I've seen it a-plenty). That'll keep you flexible enough to transition away should you want to at a later date.
Good luck!
For our JavaScript stack we will also look into ScalaJS and/or Vue.JS, React and Ember, but at the end we probably handroll our own at this stage, since our feature set is really different from what these provide (we don't need any mobile stuff, really...), at the moment we have zero mobile clients and we looking to build an app for a small inventory service, but thats all.
On the backend, ASP.Net core is looking good to me. Although, Go and Elixir are picking up fast. Heck, ignore the haters and use Node if you want.
Finally, don't be scared to use something "old" like Java (EE or Spring) or even Rails (personally, I believe the whole performance fiasco is not as bad as you would think)
If latter, I would probably choose vuejs/Play2/MongoDB. (Replace Play2 with RoR or Django or anything else).
2. ReactJS
3. Foundation for Rails
4. MySQL
This is literally everything you need to get it off the ground as soon as possible.
This is what has helped me build Allt.in () and UnderstandBetter ()
Starcounter () is an in-memory application platform, which is comprised of an in-memory database (ACID-compliant) with a built-in app server.
You can compose a complex business system out of small apps (micro apps if you will). Apps don't pull the data from the db - they run in the db. Multiple apps that run in the same db share the data in real time. Our first clients are retail, CRM and advertising tech.
From dev perspective, we like to call our approach "collapsing the stack". There is no ORM. Your code classes become the database tables. You can use our (Web Components based) approach to create thin client HTML views that bind to the data using JSON Patch. This saves you from running huge amounts of glue code, which is typical for traditional software stacks.
Right now we are on Windows/C#. Linux and macOS is coming next year. Other languages will follow.
I've built the framework to a CRM (Python and Flask) and I wonder how it'd line up with your needs. I'm not currently using it, as it needs a bit more work, but I'd love to talk to you about your project.
If you're a profitable company with a sizeable userbase, just buy Salesforce. It's clunky, it's expensive, but you can find contractors really easily to make it do whatever it is you want. Or you can learn the Salesforce platform yourself and build your final CRM on top of that. Welcome to enterprise IT!
If you're a scrappy start-up, or non-profit, with a small number of people to serve, you can use whatever you're most comfortable with. A single database (perhaps with hot replica,) a single application server (perhaps with load balancing for good measure) and you have everything you need. Use whatever you already know. PHP and Bootstrap? Ruby and Rails? Node and Angular? Doesn't matter.
If I were in the middle area -- successful company, lots of customers, but not actually at the point where I need the Salesforce behind-covering and easy contractor access -- then I would probably use React for the front-end GUI, and Haskell with Warp for the back-end services, hosted on top of MySQL or Postgres, with Redis for data caching, plus some scripts to make creating bread-and-butter tables/indices/queries simpler and less repetitive.Like the poster above, I kind of like having an "escape column" for "annottation data" stored in JSON, although it can simply be a plain TEXT. As long as you don't need indexing, it makes adding new columns easy even if you have a table that's too big to change online.
Now, the question of will anyone look at what you wrote is a bit harder to answer and it depends on the size of your organization. My firm will not really look unless there is a HR or legal request or you pop up in some reporting of malicious site visits.
Do we wanna play the "spot both mistakes" game?
Everybody says they are "gearing up for a series A" and many many business never get a series A, never mind one that sounds like it is in such a mess.
Unless you have some insider knowledge (hockey stick growth, profit, etc) that the series A is guaranteed, it's not coming and will be used to bait you along.
- I want to have from now on x% more salary, kind of a PITA bonus because I have to deal with amateurs
- maybe (more) equity, because if I have to tell a founder how he has to do his own job I am not only an employee any more
- to claim the right (maybe include it also in your contract) to refuse breaking sprints
And of course I would start for looking for a new job, just in case.
Overall, are you ok with the job? Do you enjoy what you're doing? Are you learning new things? It's likely that you can't fix the situation with the higher ups, but you can certainly do what you can to make sure that you aren't going to be left stranded.
If you don't still believe, pull off the band aid and tell the founders you plan to leave. However, tell them you'll stay with them through the new year to 1) buy you time and 2) not burn bridges with them.
Ultimately, leaving is easy. A bigger challenge is learning how to handle Micro-managing superiors. You'll likely run into some form of micro-manager type anywhere you work>
To me, I doubt you can fix the situation. The founders have to desire to change the culture and make doing so a priority. If people walking out en masse doesn't inspire such change, then it ain't likely to change.
Good luck.
(a) enough influence with the company leadership to make a real difference to the culture in the immediate future
AND
(b) the company has good prospects if only the management issues could be resolved
AND
(c) the risk of staying is balanced by a huge potential upside for you personally (such as already having a potentially life-changing level of equity AND a bulletproof contract)
then I would suggest you make plans to leave as well. Loyalty is a fine character trait, but so is pragmatism. There's no need to burn bridges or screw anyone, just find a better option, give a reasonable amount of notice, and do what you reasonably can to hand over to whoever is taking over your responsibilities for as long as you're still there.
Now, to your question: If you get to the series A, how much do you benefit? Is it enough to be worth the headaches?
I'd consider installing it and using it to test my content against, even if you're not using WP as a part of your stack.
Also check out Alex Becker's youtube channel(he is the founder of Source Wave). He is really awesome and shares a lot of amazing things....-...
- Google Webmasters[1]
- Matt Cutts' blog[2]
- Search Console Help[3]
You also gain a lot by listing the major players (Google, Bing, Alexa, etc) and then telling them about your site (domain verification, etc).
Needless to say that good content and being a good citizen help.
[0]...
[1]
[2]
[3]
If it is program based, keeping screenshots or recording of what the software did can also be of help.
My third and final tip would be to write some form of post explaining what the project was and maybe why you think it didn't take off.
Lately, I've been thinking a lot about potential consulting niches in the software industry at large. With many of my clients there seem to be recurring patterns and challenges regarding software development processes and software products:
- dealing with complexity
- improving code quality
- writing reusable code vs. writing disposable code (i.e. code that can be adapted and replaced quickly)
- communication and knowledge transfer
- having to write huge amounts of boilerplate / 'plumbing' code over and over again
Overall, managing complexity, improving communication, doing away with repetitive processes are huge problems. It's not like nobody is addressing them (IDEs, agile processes focussing on communication alleviate those issues to some extent) but these issues probably are still the most prevalent impediments to efficiently developing software that fits the requirements.
So, I think there's an opportunity for consulting companies in terms of reducing the complexity of their software and processes. I'm just not sure exactly how to package this as a productised service.Then again, consulting firms like McKinsey have been doing similar work in the general context of business management for decades - with varying degrees of success.
Writing a book (leanpub is a good place to start) can provide you with some credentials.
I've met a few fractional CTOs who work with startups/smaller groups within a company to provide technical leadership.
Join a startup as a CTO (I've seen 2-3 startups looking for CTOs/founding engineers, and I haven't looked that hard). Of course, the issue here is your risk, and I don't know your risk profile at all....
1) 70-80 work weeks. Get in at 8:30 leave at 11. Sometimes work weekends. This is typical for some of the more competitive jobs in law or finance. Definitely also applies to some startups, especially for founders and early employees.
2) 40 hour work weeks. People get in strictly at 9 and leave at 5. Much of the workforce operates this way.
3) Variable workweeks going from 40-60 hours. Most startup employees seem to be in this bucket from what I've seen.
In my first job, I did 70-80 work weeks almost every week (a bit lighter around holidays) and it was brutal, but by far the hardest thing were the unpredictability of my hours. I never knew whether I was gonna get out of work at 9pm or 2am or if I would have to work over the weekend, so I could never make plans. This was harder than the long hours themselves.
I worked at a company where people were pretty strict about the 9-to-5 thing. The work-life balance was great, but sometimes it's a hassle if people don't work at all outside of work hours; for instance, when you need something from someone and they don't check their emails.
In general, I think that flexibility and predictability is the most important thing for me in what I consider a sane workweek. I wanna know that if I make dinner plans with my wife, I can keep them. If I need to go to the doctor in the morning that it's not a problem. I don't mind going online for a few hours at night afterwards to make up for time missed, but I hate having to cancel plans.
Last week:
The week before:
I typically work around 40-45 hours a week, flexible hours when I work from home and normal hours when I'm at the office (twice a week).
When I am not injured (like now), I have 10-15 hours on the bike a week doing anywhere between 150-250miles a week and racing over the weekend.
I never work weekend, ever. I do however sometimes hack weekend nights after the kids are in bed and I am inspired.
This is - I think - an arbitrary question. What is "sane" in this context is simply what's culturally normative: it varies from place to place, and has no practical or logical reason for being set at any certain number other than the cultural history of that place and happenstance.
People are very good at adapting to and becoming comfortable with what is considered normative.
[0]
I've heard working in chunks of time throughout the week is useful, but also only 4-6 hours a day could be nice.
I doubt any place would pay you the same rate to work less though (most places seem like butt's in chairs types of places)
- 40 hours for almost all weeks. If there's a crisis, that's different, but there better not be a crisis all the time.
- Most of the time, I can actually get work done. I'm not in meetings all week.
- My coworkers' personalities do not need too much debugging. The work culture is not highly dysfunctional.
We've caught issues ranging from expired passwords, missing files / files with incorrect permissions / write failures, sync issues and other obscure gotchas.
Catching a failed step during deployment can sometimes prevent a huge rollback effort and save a lot of time.
Don't rush new features or code into production. Don't deploy anything after 5pm on a Friday.
Documentation, documentation, documentation. If there's a piece of knowledge for your app that's only in your head, you have failed.
But if you're happy to take a lower salary in exchange for some other perk then that's OK. I took low salaries to work for start-ups for the first 4 years of my career and that worked out very well for me, as I was given a higher level of responsibility than most companies and I now feel I am further ahead than my peers.
A company should be able to be very specific about what it will offer you. If not, it might be in the early stages and run by inexperienced people, which can be either a good or bad thing depending on your career goals.
If in doubt, negotiate or reject. It sounds like you're in a comfortable position anyway.
1900 euros/month is peanuts. Even considering that you're fresh CS graduate, you're worth more.
Also, the fact that the contract is "non-negotiable" is a huge red flag. This company doesn't respect their employees. Trust me, you don't want to work in the environment like that.
Keep looking for job, the market is huge, you'll definitely find something decent.
Honesty is a huge deal in any employment situation. If you feel like that before you even start, the likelihood is that it will only get worse.
If you have no immediate need for the money, take your time and find something that feels right. You'll know it when you do.
A job hunt is a variation on the dating problem. Here's a popular account:-...
20k/yr is a average salary for a junir developer in Spain. 30-35k/yr for an experienced one (5+ years). 35-45k for a manager.
The red flag for me is the lack of information about your role in the company. This means peope in HR don't have a clue about what is going on. Probably you'd be outsourced to a client (a sign of the non-negotiable money amount).
We are currently searching for more developers at talkwalker.com in Luxembourg.
If you are interested, please send me your resume to tbritz@talkwalker.com and reference this thread, and if all is fine, I will you invite you for an interview. It would require you to move to Luxembourg though.
But as the other comment states, B tends to be more exciting, and allows for deeper social connections more frequently. Sure, millions of people might know java and you can say, "Hey I know java too!" But I doubt the conversation will go any further than that. However, if you have experience with a less popular language and meet (or are interviewed by) someone that also knows that language, it will create a much deeper connection.
All in all, do both if you can. If you have to choose one or the other, learn something new and become a part of a smaller community and watch it rise or fall.
But if you want to look at it from a purely economic standpoint, the factors you mentioned interact in a complex way. Another one to consider is the salary curve for a language over years of experience. Not every language has the same pay. I would also consider the number of entry-level jobs over the total number of jobs.
I have an article exploring all these factors here if you're interested.[1] Enjoy!
[1]:...
If you're going to focus on a specific language, make sure you're applying it to a problem where it makes sense.
That may not be a language. That may be a programming style (functional? reactive?). It may be a library or a framework. It may be a platform (Android?). It may be a "language" that we don't think of as a language (SQL?).
My current answer is Android (not that I'm making much progress on it...)
Credit where due: I got my version of the question from my wife. She's asked it a couple of times over my career.
First, as you point out, less competition.
Second, these languages are usually a little younger, and there is a chance to be part of a nice community from the beginning
Third, learning an "exotic" language is sometimes a great asset on a resume even if you interview for a position involving a different technology. It shows intellectual curiosity.
If you're looking for classes I'd recommend checking out SCET, the club community around it seems to be growing too.
Unfortunately Crowdspring ruled it wasn't a refundable issue, so I lost around ~$4k on a design I can't trademark. Would be nice to be able to do something about that, but I currently lack the resources necessary to persue it legally.
Indirectly, a lot of good things have happened to me because of HN as well. Things change very quickly in tech space. Yesterday's anti-patterns are today's best practises and best practises of today will become tomorrow's anti-patterns. I owe a lot to HN which keeps me updated with ever changing tech ecosystem. Being a full-stack developer, I've to keep up with both frontend and backend changes happening everyday. Without HN, I'd not have found out lots of things for sure.
I will try to use a gross misrepresentation of a new-comer, but chances are they will ask trivial question that do not concern the project ( or are already answered ), some resources ( developer time ) will be used in favor of answering/guiding the newcomer ( who probably did not have search the usual sources before asking the question ).
Documentation is quite a pain to maintain, as it requires a good grasp of the English language ( mostly ), and quite a lot of empathy to figure out who the documentation is for.Additionally you have to make sure the documentation is accurate as the software change.
Returning the question: do you accurately comment the code you write for fun ?
My wild-assed guess? Based only on the ridiculous amount of computation needed to simulate neurons, the first roughly human-like AI will stretch the hardware it's running on, and the budget of the organization responsible, to its absolute limit. It will probably not even run in real time, more like 1:100 or worse, with its creators rationalizing that ratio as actually being good for their scientific purposes (a slow-motion process is easier to control, study, debug). Hardware is hard and expensive, and attempts to scale up to real time will only be made once there is a convincing case that there are no easy design gains left to be had. It will take years.
And once that happens, you will have a roughly human-like AI who has no more of a clue how to make itself smarter than you and I do.
[1]
[2]
[3]
If you work interactively with data, you might also enjoy Slimux (), a vim plugin that allows you to send lines from vim to an arbitrary tmux pane. I usually have IPython running in such a pane so I never have to copy+paste. I've got an ebook I've been kicking around describing this workflow in more detail here (...).
As far as plugins, if one sounds interesting or useful to you, install it. If it doesn't work out, then you can delete it later. Over the years I have tried all of the popular plugins, but I have managed to whittle it down to 4 plus a couple of language specific plugins
Here are a couple of handy youtube videosVim Navigation Commands to Do 90% of What Plugins Do (With Just Vim)
(i.e., "iz u ded?")
I made this because I adopted a puppy and realized that, if I got hit by a bus on a Friday, he could be stuck in his crate for days before anyone realized. Morbid, but useful.
It texts you every X days and asks, "u ded?" -- if you don't click "naw" before X days pass, it'll notify your contacts.
It's a portfolio project to show what I've learned in the realm of "serverless" architecture. Details about its construction here:
I have migrated my wife's (then girlfriend) computer to Linux and sometimes I had to configure something on her computer (e.g. a printer). This ended up generating lots of back and forth on the phone with me telling her commands to write in the terminal, and she reading the output out loud. I wanted an easy way to see her terminal. So shellshare was born.
Shellshare allows you to run a single command line and share your terminal online (read-only)That'll give you an URL others can join and watch your terminal live. No sessions, no recordings, and the data is deleted every day.
There aren't many users, but I use it almost every week.
Lets you share the content of a text file and stream changes to everyone who's watching.
Useful for live coding demos, teaching programming, etc.
Works without installation.
I am very, very proud of the (very simple) platform that we've built there. It's a basic tool that "just works" - and just works exactly like you'd expect it to.
If I were a consumer of cloud storage, this is what I would want it to look like.
It pleases me so greatly to know that, right now, someone is doing something like this:... while simultaneously, someone else is doing this: It's been 15 years now since we started providing this service - almost 11 since we branded it rsync.net - and the first warrant canary is now 10 years old. This appears to be, for now, my lifes work.
I created this favicon generator a few weeks ago to generate minimal favicons for my side projects. I'm not good with design tools so it saves me time when I start a new project and want a simple favicon in ICO format.
I'm proud of it because it's server-less. I generate the multi-BMP ICO file in binary using ArrayBuffers and Typed Arrays in JavaScript. I use a <canvas> element to create the images/design.
It's not very polished and I'm sure there are bugs, but feedback would be appreciated!
There is a thriving community of core devs and a ton of users. I'm happy with both creations and made a lot of online friends.
These projects also led me to create a standalone python library for doing fuzzy matching. I'm quite proud of this one since the resulting code ended up being ridiculously small but produced really good results.
I work in security and have a paranoia of shortened links (bit.ly, t.co). I got frustrated with the options out there that forced me to right click every shortened link or paste it into a site so I made this Chrome extension / web app. It is pretty simple and keeps a list of 300+ shortened link services to check against. If your browser ever visits one it redirects you to the site to expand the link. It will also hit the Google Safebrowsing API to see if it is known to be malware plus will strip out tracking cookies.
It's been fun and rewarding watching my little extension grow to global use of over 4k users.
* I converted a rotary phone into a cellphone:
* I wrote a personal bookmark search engine:
* A site that talks to spammers so you don't have to:
* A pastebin:
* A remote-controlled GSM irrigation controller for farmers:
* A button that orders food when pressed:
* A python library and cli utility for controlling YeeLight RGB LED bulbs (a cheaper and nicer version of Hue bulbs) that I wrote this weekend:
* A secure communications library for IoT devices:
* I took some non-terrible photos and made a site for them:
* A hardware library for the A6 GSM modem:
* Expounder, a better way to explain things in text:
* Dead man's switch, a website to email people after you die:
* I can't even remember the rest.
I made it as a simple joke, but for some reason it rapidly gained popularity among Emacs users, and now I sometimes find it or hear about it in unexpected places.
(Also I fear that on my deathbed I'll look back and realize that the most used thing I've ever made in my life was an animated cat for a text editor... sigh)
The simple tool which has probably had the largest impact is bsdiff -- now found used in hundreds of millions of devices -- but I'm not particularly proud of it because it was a quick hack and horrible code written by a C novice.
The non-simple product which I'm most proud of is Tarsnap, of course; I've spent a decade of my life on it, and don't expect to stop any time soon.
I started working with VMs several years ago, manually setting up a Virtualbox image. It would take around 30 minutes, and whenever I'd screw something up I'd have to delete it and redo the whole thing. Sometimes I'd fat-finger a command and have to start the process all over again.
Once I got tired of that I started to look into Vagrant, which recommended using a tool like Puppet or Chef. That led me down the rabbit hole of learning Puppet, which made me want to have a GUI to be able to easily change some choices around without having to mess with the code itself.
So I created a simple HTML form with drop downs and buttons and released it thinking that maybe 10 people or so would find it useful.
Almost 4,000,000 servers created later, and I'm quite happy with how it's been received!
We decided to hack on it together, and we've since grown Cronitor from a tool built for our own needs into a small business with a couple hundred paying customers.
I see it as the beginning of a platform to change how individuals (or mankind) manage knowledge overall. I'm now working on exploiting the internals for collaboration (linking instances, sharing data, subscribing to each others' data, mobile, etc).
For current org-mode or evernote users: The app has export (& finicky import) features to convert anything to (or from) an indented plain-text outline. The FAQs have links to a discussion of a more detailed comparison with org-mode that seemed somewhat well-received at the time (the link is on this page which also discusses evernote: ).
Feedback or participation are appreciated. If one has any interest at all, I suggest signing up for the (~monthly?) announcements list at least. More details are at the web site, including some FAQs.
I'm really proud of it for a few reasons:
1. It was a response to an observed need. I was getting daily emails from devs asking me about product marketing. I believed that devs who learned marketing could be unstoppable when it comes to launching products.
2. I created it on the side, while working full-time.
3. In its first 3 months it did $28,433 in revenue. This allowed me to go full-time on my own projects this January.
If you build an audience, and earn a good reputation, selling your expertise is a good option.
lnks: List, Save, or Instapaper your Google Chrome links from the terminal. It uses a small amount of Applescript, so it is OS X/MacOS only for now. I'm working on getting around this.
aliaser: a tiny directory traversal/command aliasing tool.
I've been toying with using the idea for forums so that it is easier to keep track of who is replying to whom[2]. I also would like to try using it as a layer on top of traditional syntax highlighting, perhaps as an emacs minor mode - if those can provide colors to the buffer; I've written hardly any elisp and don't know what capabilities are available.
[1][2]
Plain-text todo list:
1. To create a project, type a line ending with a colon.
2. To create a task, type a line starting with a dash followed by a space.
3. Everything else is a note.
4. To create a tag, type the @ symbol followed by a name.
5. Tab to indent and create outline structure.
TaskPaper started as few days TextEdit hack in 2006. It's no longer a "tiny" project in terms lines of code. But the original simple ideaplain text todos with 5 formatting rulesremains the core of what TaskPaper is.
I'm very proud of that!...
Real time tracking of Boston subways, buses and commuter rails.
Made mostly in a weekend and available free and open source [1]. Though it's simple, I think it gives a nice overview of the trains and buses. Boston has stop prediction so in some sense it's kind of frivolous. I think the biggest 'innovation' was to integrate the "map icons" into a nicely visualized open street map [2].
Not super popular but it's been running for around 2 years with ~20 hits per weekday.
[1]
[2]
EDIT - Whoa. Getting lots of traffic. This site is like 3 days old and I taught myself python and django to build it. Open to any recommendations at jonathan at averageweather dot io
EDIT 2 - Back up... Site crash ... Google apps shutdown smtmp connections which crashed my entire site.
I've been poking at this for 4 or 5 years now. It started as a simple simplified air pressure simulator for teaching logic programming. But now you can make all sorts of stuff with it, like logic gates, adders and I'm working on a replica 4004. (Links below)
The website is awful for new users - It doesn't work on mobile, there's no tutorial and no real documentation on how to use the editor. Instead of fixing that I'm working on making a dedicated puzzle game built around the engine to teach all the concepts up to and including getting players to build their own CPUs.
The backend is powered by a FRP compiler, which I'm really happy with. You can have huge steam powered worlds and incrementally edit parts of them, and it does fancy incremental recompilation.
Logic gates:
2 full adders:
Miniaturised 8 bit ALU:
Work in progress CPU: - a collection of amazing science fiction stories. - discovery platform for educational videos. - several rigs that I have made, for practicing 3D animation in SideFX Houdini.
Single scripts: - sends me a daily email digest of my rss feeds. - scrapes /r/WritingPrompts, and compiles a list of the top writers and their best stories() - ANN that generates Harry Potter fanfiction.
[1]:...
My co-founder and I moved on to a new project a year ago, but this thing is still buzzing along on a cheap DO box and works like a charm with basically zero maintenance. Frontend is vanilla JS, backend in Go and the protocol is our slight modification of differential sync[0] to (re-)synchronize all text and metadata.
[0]
I've been using it for 3 years now, but keep forgetting to tell anyone about it. It's a simple bash script that detects what kind of project your current directory is and runs the appropriate command to start the development server.
I created it, because I found myself constantly switching between projects of different types, and it always took me a few moments to remember if the current project was Rails 2 or Rails 3/4, Node, Jekyll, Rack app, etc. and starting the development server on port 3000 was starting to take 2 or 3 tries before getting it right.
Now, I just cd into any project and run `start`. It currently detects Foreman projects, Rails (old and new), Jekyll (old and new), Gollum, plain Rack apps, and Node; and it's easy to add new things as well.
I made a simple firefox/chrome extension for people that horde tabs as temp bookmarks. You might find it useful to find tabs and quickly navigate to them by clicking on the link in the list. It's free and open source. The github page has a gif showing usage. You can also type cmd-shift-e or ctrl-shift-e to switch to it.
Chrome Extension:...
Firefox Extension:
source code:
Let me know if you find it useful or have any suggestions.
* cookies.js, a simple cookies library that uses a getter/setter style that I (and many people) like more. I'm considering taking the format and extend some other libraries like store.js.
* drive-db, a tool that converts a Google spreadsheet into a small database for Node.js:
A tool that helps you learn languages by reading public domain books. I should continue working on that...
I built it to learn JBoss Seam, and recently re-wrote it using DeltaSpike. I personally use it almost every day!
I made this 4 years ago for those times when you just need an invoice. Today 10s of thousands of individuals and businesses use this each day to get paid. It's free to use with no login required. Instead it uses localStorage to remember data. photos => save => share (you can add .gif to the URL)
I made them because they were useful for me, and I am still happily using them almost every day, especially scri.ch: nothing beats typing scri.ch in a browser from anywhere to quickly sketch an idea (except a napkin and a pen of course).
Its nice to see other people using them too! :-)
I run a media website and people are always asking me, what will X or Y look like? How do I know what size I want? I send them there.
I did this project by hand one or two times and then asked the manager to let me research the possibility of automating it. After a week or so of fiddling around, I was able to bring it down to 2h10m. Just in the past week, I was able to bring it down to 15m and reduce the number of steps where a human is needed.
I wind up using it in almost every project I work on, since just about every app has a list of some kind, and many lists need to support being sorted, having items added, etc.
It's a simple tool, but the internal logic is surprisingly complex. The DOM is a tricky beast!
Helps people read more easily on-screen. Originally designed as a speed-reading tool for lifehack types, but it turns out to also be super effective as an assistive technology for people with dyslexia, vision impairments, and executive function disorders.
Started it over six years ago and have been sending it every week since. Have about 39,000 subscribers and still see a 45% open rate. It has been a lot of fun, and even better, I have made connections with a lot of great people.
Sms Lists is an sms craigslist for refugee camps. I made it after visiting a couple of refugee camps and realizing that it was really hard for business owners who made <$1/day to have any extra money left over to re-invest in marketing their businesses. Code is here:
It's without a doubt the most enjoyable thing I've done and it came from feeling a little loss of humanity with FB coopting birthdays.
I developed "Eskndereyya", a comprehensive writing system of Arabic in Latin alphabet to help Arabic learners esp. beginners to improve their reading and writing skills in Arabic without the immediate need to be familiar with the Arabic script.
Please try it out and let me know what you think.
Show HN:
It started as a small explanation on the basics of Bezier curves in 2011 and then kept growing until it's basically a full book now, hitting hacker news every year/half year, and getting lots of thanks for having made it by a very diverse crowd - from kids doing homework to engineers at software companies who have a question not covered by the material (yet).
It's been a mostly low effort investment and I could have just as easily not bothered, but just adding small bits at a slow pace parts of on the internet: five years of improvement would not have happened if I'd simply not bothered, and now there is an amazingly popular free resource for this material easily findable online.
I started knowing next to zero in assembly, reverse engineering and crypto. Took me about two months -spread accross 2 years- of work and learning to do it. The game uses a modified AES crypto, just the key expansion was modified, probably so it can be different enough to not look like AES, but still benefit from hardware acceleration. It's probably less secure than regular AES.
Netnode. It is a little like a unix pipe, a little like netcat, a little like tcpdump. But really simple.
You create a graph of communicating entities with netnode. The terminal nodes of the graph are external data sources/sinks (user input, udp/tcp servers and clients, shell pipes, named pipes, /dev/tty*, etc.) The internal nodes are a mesh of instances of netnode.
It is easy to insert a little instance of netnode anywhere, and have it print the traffic going through it.
I think it turned out really well, and I use it for everything. It feels like "connective tissue" similar to classic Unix pipes, but for the network age.
./netnode -h
The basic JSON API request and response formats are unchanged since day 0, although we've added a few new features in response to customers' demands over the years.
athena is an elegant, minimalist, light-weight static blog generator written in Python. It's just over 50 lines of code. athena tightly integrates with Tufte's design and typography rules. Have a look! [1]
[0]:[1]:
I made it because I couldn't find a developer to do a larger project I wanted to do based on the same principle.
So I paid a developer to do this and now he is my partner and we are building the project I wanted to do to begin with. It's quite profitable for a small tool.
It's based on the idea of contextual note taking which basically allow you to attach notes to all sorts of things like website, folders, files etc.
The contextual engine is part of my new project.
After having multiple clients change their DNS settings without warning and then email us when shit hits the fan I knew I needed some type of warning system.
This checks every X minutes and saves each version so you can see the revision history for all your DNS zones across many providers.
It's essentially just a file based IRC client. Using FIFO files as input, andspitting out the loggs into an out file. I really enjoy the simplicity of theidea and how easy it is to script. Been using it to learn goroutines and somemore go, the code isn't the best but it's fun.
Planning to create something like "wii" where you can use the same structurebut with HTTP requests. POST to send data into the FIFO file, and GET to readthe out file.
[1]
It can either generate an HTML report with various stats and graphs or create a draft invoice in Freshbooks for sending to the client. It used to take me a couple of hours a week to invoice, and now it basically takes no time at all.
I can't really share it because it's got some hardcoded client details, but I'm considering generalizing it into a txt2invoice utility other people can use. It's also massively over engineered because I used it as a learning project for Elixir. Every time I learned how to something new I tried it out on this tool, which means it spins up lots of processes it doesn't need and does fancy stuff with messaging, genservers and supervision trees which are entirely unnecessary, but that's part of the fun.
GNU project sites:
It tries to compact simple objects and spaces all delimiters. It also attempts to align array children. The idea was to produce the most compact, yet still easily readable form of a JSON document.
I was creeped out when trying to find something like this online, because there are many which send your JSON document to the backend instead of doing it on the client.
But if you want more, you can use note-folding, a whole bunch of text manipulation changes and best of all, it's automatically written to disk (no saving needed ever) in a real text file, so syncing and backup is really simple.
It's the missing invite system for Slack.
Let's anyone create invite pages that can accept payment (monthly, one-time) for access to a Slack community.
It's been a blast to work on. Learned React, Redux, and got into Flow and Tcombs while building it. Interest so far has lead me to realize more people are interested in creating private/paid communities online than I had previously expected.
For example, this URL contains code for a flame texture.-*5*dx4**y3*p%2By!-...
When Android was pretty new, I got the myTouch (the second public Android device) and was surprised that there was no way to easily see the exact battery level. I'd been a hobbyist programmer for quite some time, and it seemed like a problem I might be able to tackle. The result was Android's first battery indicator app, which remains by far the most-used piece of software I've ever built, with over 8 million downloads....
My little open source app which converts HTML to PDF.
Useful when generating PDF invoices, legal documents. I am using it in my own projects.
I'm not so proud of a tool that transforms images to pure css () but it's by far my most popular tool \_()_/
Elixir's OTP was a fantastic fit, I scrape stuff really quickly with minimal orchestration code. There are bugs here and there, and I haven't had time to circle back and patch a lot of the issues I noticed, but it "works".
I'm proud of it because it broke the 200 star barrier on my Github profile. With Elixir to boot! I love this language.
Its simple, useful, and I learned a lot while I was building it. And people use it (which is always a plus).
Draw something and share it.
Like jsFiddle for drawings. In need of a rewrite and mobile support, but pretty useful if you just want to scribble something down and share it. And I like the borderless canvas :)
My business partner and I often needed clients to sort things (features, objectives, pains, restaurants, you name it).
Eventually we built this tool together. You can create a list, sort it, then invite others to sort the same list and create an aggregate sorted list. There's lots we'd like to improve but it's pretty useful right now.
Hidden behind the JS front end is a Clojure sort-api server that provides an API to sort arbitrary data. We've no idea when that might turn out to be useful.
Android app and Chrome and Firefox addons that lists live and upcoming programming competitions on sites like Codeforces, Topcoder, Hackerrank, Hackerearth, Codechef etc /bageaffklfkikjigoclfgengklfnidll...
Has 7k+ users all together :) - Free web cron - what's my IP? - URL shortener that generates mobile type friendly URLs
Part of the point was a) to aggregate everything in one report to reduce the temptation of looking at something multiple times per day, b) to avoid visiting multiple pages in order to find all the information, and c) to find changes in things that I may have forgotten about since they rarely change.
I've thought about making it available for others, but it'd take a bunch of work, and I'm not sure what the demand would be like.
It parses DSV data like Awk does, runs SQL queries against it and formats the output in one of several ways. An example I am particularly fond of is using this tool as a poor man's libxo ():I started a list of command line tools for querying, processing and converting structured text data:.
updawg [] had the distinction of being the only wordsearch tool on the nokia n900. featurewise, it was a clone of lexpert, a popular app that ran on a few other mobile platforms. it was a vala/gtk/hildon wrapper around some open source wordsearch code, and it all just worked. the nice thing was after i wrote i for my own use, another scrabbler bought an n900 and was delighted to find she could get a wordsearch app for it.
varix [] is my from-scratch rewrite of the same thing in ocaml, with more powerful searches. it's a linux TUI app so i haven't really tried to interest anyone else in using it, but i use it all the time and i love it.
Markdown manuscript input with high quality epub, mobi, and print-ready PDF output.
It's a wrapper (your choice of Rake, Bash, or Docker) combining Jekyll + Pandoc with custom PDF LaTeX templates for print-ready (valid PDF-X1A 5x8 and 6x9) and professional epub/mobi ebooks.
Up to nearly 2k installs these days!
This tool already helped me a lot.
Which is a tool so people who don't know anything about programming or fancy excel usage can still do SQL join type things.
And this version of the classic game mastermind, which I use in conversation to make the point that "machine learning" can be tremendously approachable -- the computer here just picks a random potentially correct guess and does very well.
And this, which is massively pointless but has gotten more comments than anything else:...
Osh (Object SHell) is a python application giving you a set of Linux like commands which can be composed similar to pipes. However, it is objects, not strings, that are passed from one command to the next.
It includes typical shell stuff, listing files and processes; database access, in which queries yield Python tuples; and distributed access, which distributes commands to the nodes of a cluster and then combines the results. For example, to submit a SQL query to each node of a cluster, getting a count on each, and combining the results:- osh: Invoke the interpreter.
- @cluster: Relay the bracketed command to each node of the cluster. The bracketed command returns (node, count) tuples.
- sql: Submit a sql query (on a cluster node).
- ^: Denotes piping results from one command to the next.
- f: For each result from the cluster, run a function on (node, count) which returns just the count.
- red +: Reduce using +, summing up all the counts.
- $: Print result on the console.... - copy photos from some common camera media locations.-... - wrap Byzanz and Festival to record a gif of a screen region (and tell me what it's doing so I know when to do stuff).... - an alias for navigating directory history.
Bash is such a pain because of all the incompatible utilities. Its much nicer just to think about logic than to be searching for command switches and dealing with corner cases like .. file names that contain spaces(!)
Free for personal use, $5 / month commercial
It's a simple chrome extension to jump between top-level comments on hacker news using the arrow keys.
I've been meaning to publish it to the extension store, but that process looks like it'll take longer than actually writing it did :)
The reason it's my proudest "achievement" is just because it's so useful to me (solves an actual problem)
Shpotify, a command-line interface to Spotify on a Mac. :)
- [ByteSize]() (.NET/C#) library which is a utility class that makes byte size representation in code easier by removing ambiguity of the value being represented. ByteSize is to bytes what System.TimeSpan is to time.
- [PS1 Gen]() is a simple bash PS1 generator and reference so you can soup up your command line. I created this after trying to research how to create a cool PS1 string.
Enter a word, and this site will make up some puns for you based on that word. I'm way more proud than I have reason to be of this.
I built a utility for python programmers - pipreqs which helps to generate pip requirements.txt file based on imports of any project
Couple years later the app has made close to a million dollars with me pocketing about 60% of that and the other 40% to the ad company.
It's one of my favorite projects because it was so simple and literally took less than 2 hours but I was able to pretty much make a 1000x on it which to this day is better than anything I have ever done.
I'm chronic news junkie and wanted a perpetual drip of viral news on my phone. Addiction satisfied :)
It helps you remember the things you read and learn by sending you timely email reminders based on spaced repetition (memory theory).
Secure (browser-encrypted) dumb file storage with self-destruct. By default, it self-destructs on first access. The server can't read your files and it will delete them anyway after a week (or less, if you like).
It's a good way to quickly send a file to someone else and to know if it's been accessed in the interim.
It was really just our own attempt to build something that can do very simple secure file sharing that anyone can use, as an alternative to so many broken practices (such as clearnet emailing sensitive docs).
It's turned into something pretty cool for a few reasons:
1. We get emails all the time from people who love how simple it is
2. It's a great testbed for new web technologies; I rebuilt it once using Polymer and intend to rebuild using Elm when I have the time
3. It's a great testbed for web crypto & webworkers.
My wife and I made it so that I could quickly paste timestamps from various log files and see the relative time between then and now. It also allows for a pretty basic relative time entry, like "2 weeks ago", etc...
Super-fast lookups and filtering - 50,000 within second(s), support for regular expressions and the derivated ontologies.
People don't seem to get it though (even my co-workers struggle with basic regexps).
move with arrow keys, attack with "A"
there's a ton to work on and I've been busy with other things, so sadly the game has taken the back seat. Hopefully I'll be able to put more time into it next month
Create Countdown Timers to an Event in the Future and Share them with others. Includes Timer and Progress Bar.
I created this years ago because I wanted a quick way to create bookmarklets. Since putting it online I have had good months in terms of visitors (1000+) and worse (50), but I am still very happy that people keep coming to bookmarkify to create helpful bookmarklets for themselves and others.
By now it has been around longer than 4 years, despite what the banner says.
[]
A small directory for finding informal household services in Jakarta. Old service, ticking along - still proud of the mobile UI :)
[]
A simple, server less, offline-capable web app for practicing reading music. I've always been slow at sight reading, and this lets me plug in a MIDI piano and do drills.
It was also a good catalyst project for getting to play with: React, Webpack, Service Workers, Web MIDI, Web Audio, and the Progressive Web Application paradigm.
I also have some unpublished ones for doing worst case setup/hold analysis in point-to-point DRAM interfaces.
Hits the API for Philadelphia's Regional Rail and displays real-time data on the system as a whole as well as historical data on specific trains and train stations. It's useful to tell, for example, that the evening train I normally want to take home () is almost never on time, for example.
There's more I want to do, such as displaying more detailed stats and train data (on-time percentages, for example). And hopefully get some interest from SEPTA so they can use it to determinate the "biggest offenders" and what can be done about them.
In the same vain I put together a little archive for storing bookmarks under revision control:
Finally I put together a small archive of tools which seems to be quite popular for reasons I don't fully understand:
I spent most of my free time the last 1.5 years to make this 4-player iPad game together with my brother (developer) and two cousins (graphics).
Considering that it was our first Swift and SpriteKit project (my dayjob is programming business applications in Java), I am pretty proud of the outcome. It even got some reviews (one with a 92% rating!).
The only problem is, we completely underestimated how hard it is these days to get downloads for an old-fashioned "pay once for the whole thing" game. Currently we are in the process of converting it to a free to play model, hoping that more people try it. Wish us luck!
It would sound an alarm every time a new item came up for sale, with a special sound for their highly sought after "Bag of Crap" [2].
It had over 25,000 downloads after its first Woot-Off. Sounds so bizarre in hindsight, but a partner at Polaris Venture Partners asked to meethe wouldn't say how he found me, but I'm sure Woot Agent was how.
[1][2]
There's currently a Link Shortener, UTM Campaign Builder, Parser and Validators for 15+ RFC implementations for different URI components.
I have a lot of continuing work to do, such as better analytics, a user system, and more tools.
I haven't got any feedback yet, I would love to hear just about anything, it would be encouraging. Feedback about my implementations would be greatly appreciated. Thanks!
Definitely different from the ones here since it hasn't made me loads of money, but definitely proud of it.
The first web application I ever made, which was actually based on one of those Ask HN threads we had 2+ years go about looking for furniture the fit a specific size. I actually did make a few sales, shockingly.
At this point, it's pretty much dead as I've taken in other projects and independent security consulting engagements. It was extremely useful understanding the entire stack, and I've found it to be something I've been able to use to build a bridge to developers.
I'm pretty proud of this simple tool because it eventually made its way to the repositories of all mayor distributions: Debian[2], RedHat, Arch, you name it.
I've received many emails from users, questions, suggestions, bug reports, people offering to translate it in their language... I'm super thankful to all of them (unfortunately I could not answer all of them!).
It's been unmaintained for a while, but it's on my To-Do list to refactor it, clean it up and add some missing features. It's been 10 years so I'm hopefully a better programmer now.
[1][2]
I fear I'm going to get chewed out for my crap code on this one but I'm really not a webdev... I hacked this together after getting sick of celeb gossip links and trash ads for facebook games. I'd rather get a random pic of a cat or a supercar than irrelevant junk.
EDIT: Pic for how it looks when loaded:
I built it because I wanted to able to make websites in Objective-C and I didn't like any of the stuff that existed when I started.
I've learned a lot making it and enjoyed it. I don't know if I would start something like this again. Reading the RFCs and implementing FastCGI and HTTP was a lengthy and tiresome process. I enjoyed it though.
Sure, now you have a bazillion Swift server-side frameworks, but at the time Swift didn't even exist. Call me a dinosaur, but I like ObjC and the Cocoa stack and I think it deserves its place on the web.
This is one of the internal tools that we built at Mobile Jazz as we always had the problem of being a remote team and therefore physically detached from our clients. Many times they had problems that we couldn't reproduce on our devices. With Bugfender we now can get access to their device's app logs and figure out what's wrong.
From being initially just a clunky internal tool, Bugfender is now a whole platform with a nice admin interface and many filtering and search options. The result is great and we're having quite some success with as not only we, but also the whole mobile developer community really loves it. And that is what makes us proud! :-)
It was just cool to be able to contribute to a small package I used a lot at the time.
The extensions first implementation was basically just a ternary operator! Now it's got a little more to it, but it's still super simple.
[0]...
[1]
It would auto-wrap code comments to a specified column number. It would also auto-wrap on delete or backspace. Still miss it because I want it for existing editors but I'm not interested in learning some random plugin API just to rewrite it.
I use it so much I nearly forgot I made it myself. With Freud you can apply 'behaviours' to DOM-elements. What this does is that it enables you to work with your DOM-elements in a more object oriented way.
What I use it most for is applying pieces of javascript on the page only when the DOM-elements that I apply freud to are on the page. This way all you get a lot less code in one big js file.
Send a fax, pay for it with Bitcoin. That is all.
I like it (and Bitcoin) because you can transact online without signing up.
A simple warmup calculator for my workouts. Use it multiple times a week.
When Turntable.fm folded, I was sad. I wanted to learn sockets, so I built this. It's like Turntable, but uses YouTube videos instead of actual songs. Bugs galore, but I use it at work almost every day.
My responsive demo, resize the screen ;)
Also, a dirt simple what.cd web interface similar to Couchpotato or Sickbeard, but without the terrible performance and extra features of Headphones.
I just use it every day and I guess a lot of people too.
Toying around with productizing it as
We currently have almost 25k users and I'm proud of the fact that people really do find it useful. A friend recently mentioned to me that he used Jarvis to remind him about his dentist appointment.
Not sure it's the project I'm most proud of, but as far as a simple tool I use everyday, this is it.
One reload shows you the site in multiple sized iframes, so you can quickly test breakpoints.
* - Started because I couldn't find a resume that I liked.
* - A more advanced artist radio style playlist maker.
* - Automatically save Spotify discover weekly playlists.
Search Wikimedia Commons: canweimage.com (300 - 600 searches a day)
Testing flexbox rules: flexbox.help
Googley Eyes Firefox addon:
Can We Image got included in a listicle on Buffer's blog. flexbox.help started getting use after I posted it as a Show HN and it got picked up by HTML Weekly.
* dotenv-safe:
* gitlab-letsencrypt:
* Editor for Volca Keys synthesizers: (work in progress)
Simple single function tool decision maker. I made this because my co-workers and I always had trouble deciding where to go for lunch. It was kind of a joke but then the traffic kept growing and I now consider it a huge success as a side project.
Also a utility I made for myself to graph my bank transactions. For some reason USAA doesn't have that feature on its site so I made it for myself. Very bare right now but it does want I need it to, which is to visualize my spending. Eventually want to be able to look at transaction names from within the graph.
I'm not the original creator but currently maintaining Antigen: A plugin manager for zsh, inspired by oh-my-zsh and vundle.
Back in the days I made and found quite useful Dumpr: Command line download tool written in bash....
Not my most impressive feat but I love it :D
It's been a fun project, because I've had to build tools to come up with a lot of quality measures for the dataset.
I built it years ago because I thought RVM was doing it wrong. It replaces all the ${lang}env switchers on my machine that I still use every day. The best thing is to see users adopting it without me doing much PR and contributing back with useful features.
Other than that, I've gotten alot of use out of my dockerized minecraft project
And more recently, in line with what the OP is looking for is a quick project to extract code from a markdown file(GH READ.md) and create files. I use it to create the yaml files which I otherwise develop/comment straight in the READ.md of
This is a deceptively simple rule engine that I built for some side projects but has has since been picked up for many things that the big guns would have been overkill for. Clobbered the first version together in less than 5 days too!
Auto-detects Unicode mistakes (particularly mojibake), and if there's enough information left to fix them, it fixes them.
Particularly useful for Web scraping and dealing with Unicode that was incorrectly exported from Excel (which is nearly all Unicode exported from Excel).
It's not the most polished-off looking thing in the world, but it gave me an excuse to write a short fiction highlighting the importance of Black Lives Matter. It also allowed me to experiment with Greensock to put together some dodgy ass animations to go with the story. And it meant having to hear my own damn voice, urg, for some of the narration.
Also I learned a ton about BLM while making this.
Tamarind is a CGI-based web service which manages throw-away mail aliases.
You log in, and manage a list of generated aliases which instantly go into service when created, and out of service when deleted.
It runs on a Debian setup (I use Courier IMAPD + Exim MTA).
Tamarind is written in my own programming language, TXR, without any web framework: it includes all the code for processing requests from Apache, and doing session management with cookies, etc.
I've made this because all the companies that my co-founder and I met had scripts glued together in build tools to get code metrics and static analysis.
We ended up discovering a significant amount of people and companies interested in having a nice product constantly running code analysis and linked to Github.
Successful. That's what I want for my SaaS developers. Whatever your core product is, it's always going to need
- billing integration with Stripe
- user authentication (for your customers)
- access control (so you can drop in support)
You can pull this off (of course!) but do you really want to deal with this portion at all? Wouldn't you rather focus on driving traffic, writing blogs, adding new features to your core product with the time that you would spend on maintaining the non-product portions?
Here's how we are doing it:
- We would be your go-to resource for all of your SaaS website issues, fixes, CSS changes, anything related!
- SaaS website never enters your cognitive load, we are keeping it up!
- Send us an email at hi@saasful.com and we'll work on any request you send us in 48 hours. This is nice because months down the road you want to quickly change CSS
- Never deal with hiring from freelancer.com!
This is the tool that my devs and I have been working on this quarter. Would love some feedbacks.
edit: Care to explain the drive by downvotes? The thread is about sharing what tools we are working on right? Or did I not do it properly? Please let me know!
Wanted a command line tool to show OS X stats. Browse Stack Overflow and a bunch of forums to find that nothing existed. I believe it is now the go-to tool for this.
(Edited: removed markdown elements)
I'm quite big on QA, but it's always been a problem for us, due to lack of tools. We have tons (millions) of time series being churned into proprietary files (neither of which can readily change). We've always had issues analysing these, be it analytically or visually. Two years ago, I wrote a parser in Python, which feeds the data into a browser interface. There, one can select values in a few (<select multiple>) dropdowns - which denote dimensions, compare multiple files across these dimensions, and further manipulate these subsets of data. But the core are simple line charts from these data slices.
The whole thing is under 500 SLOC, it's blazing fast and it lets users cut through our data in no time. It has helped streamline our verification workflows, catch bugs, and allowed our clients to better understand the large amounts of data we send their way.
Command line tool for OSX to upload images to imgur:
Copy and paste for Windows command line:
Mac App to set Philips Hue bulbs colour temperature to match the sun:...
It's a library for parsing, constructing, and wildcard-matching of common-style URLs. Aside from being crazy useful, the fun part is that I wrote it for Ruby, Elixir, and JS with the same basic interface. Kind of like writing a poem that works in three languages. :)
It's a periodic table that you can interact with like Google maps or similar. Zooming in progressively reveals more information about each chemical weekend element including images, video and Wikipedia content
Select text, activate script (by shortcut button on bar or global control key combo), and a little window pops up with spelling suggestions.
It is a wrapper over DuckDuckGo which redirects all searches without bangs to Google. It also changes the bang operator (!) to the open square bracket ([) because it is easier to type.
Very simple but effective time saver!
You can basically filter everything to get a .csv file in the end with the links for the given domain, the source for that links, link number, link depth, timestamp, HTTP Request Codes (200, 404 etc) that fits that filter.
Filters: Number of concurrent http(s) requests, max link number, max link depth, must include path, must include word(s), must exclude word(s), local or global search (for links with path, local means you only search for fitting links on that site and the found sites instead of crawling the whole homepage) etc.
It was my first Go project and I always wanted to do multithreading and Go made it so easy. Can't opensource the code because it's company property.
But damn is it fast if you let it run, one homepage didn't throttle me and I got up to 96 Mb/s (on my 100 Mb/s connection) with set to 2000 connections per second.
DDosed our office wifi a few times before I implemented a token bucket for rate limiting (and sometimes just for fun after that :>).
There were (and are still) a number of other similar programs with the same name.
It was my first experience in working with users world-wide, conversing with them both electronically and through postal mail.
A python clone of an old disk space visualizer that I used before I migrated away from windows. Nobody else has used mine, and it's very much a work in progress, but it works and I use it frequently.
I started with the official Angular CLI (for Angular 2) back when it was still using system.js and it was painfully slow on a windows machine. I realised that 95% of what I needed the official CLI was for generating components/modules/pipes...etc. So over a weekend a friend and I wrote our own CLI tools that generate components and decided to use a simple webpack seed for our projects. Been using our own CLI ever since for (m)any Angular 2 projects.
I heard that the official CLI has gotten better but I don't have a reason to go down that route any more.
I learned a lot about stainless steel (303, 304, 316, 316L...), CNC machining, stamping, polishing, etc. but what's really cool is designing something on a computer and receive a metal object some time later that does exactly what you hoped it would do.
(For prototyping purposes I first 3D print each design, but the plastic version is waaay less interesting than the metal one.)
Should go on sale in 3-4 weeks; super excited.
- - -
Some time ago I made a rich text to markdown transformation that runs completely client side; it's available here
It would probably need a serious face-lift, but it's still used by many, apparently.
A hyper specific tool, to be sure, but useful if you are trying to code sign Qt apps on the Mac.
It shows you all HTTP redirects that a certain URL leads to, with all cookies that are set at each of the steps.
I built it to help my online marketeer colleagues get insights in what is hiding behind short URLs. Before building this tool, they routinely came to me with URLs asking me to trace them.The back-end is a websocket API that returns each step as it discovers it and the front-end is an Angular (1.x) application. I also built a small Chrome extension[1] that adds a followww. context menu item to all links on the web.
[1]:...
It's a pretty simple tool that lets you bookmark and jump to directories. It's not that complicated but I use it pretty much constantly and it gives me a strange sense of satisfaction to have a project I can call "done". Everything I want to add to is merely packaging enhancements so that more people can use it.
Probably not the best example of a "tool", but it does have an API and a Slack integration. Probably one of the more favorite things I've published.
Really simple, yet I use it a lot, e.g. for remote mounts where Emacs can slow down if I "cd" into it, or in loops `for DIR in submodules/*; do inDir "$DIR" git pull --all; done`
When I used to do Web development, I found... to be super useful. When opening a URL in Chrome, it switches to an existing tab with that URL if there is one.
I also made a simple Chrome extension which let me navigate Drupal test output using the left/right arrow keys. Can't find it now though :(
It's simple, but I think I think I made it nice to use. A couple minor details I added: you can change its keyboard shortcut directly from the menubar, and it flashes the keyboard backlight to get your attention.
It's a simple time tracker. No cloud BS. It just uses local storage to track how long you've been working on any task.
I still have some features I'd like to add (like a countdown timer and clearing individual tasks), but I'm real happy with it and I've been using it at work to track my project time.
It is a proxy for irc bots on twitch.tv because connections can die and more than 1 connection will make things possible like going around rate limiting. Also joining a lot of channels at once is made easier so the user of our proxy needs to worry less about what he is sending when, we handle that.
Made it together with 2 friends who of mine we all 3 use it everyday for our bots. It was fun to write and learn go while doing so. I wanna improve it everyday but I'm never sure where or what.
Scientific plotting in the terminal. I didn't come up with the idea of abusing unicode characters in such a way, just fyi.
Example:...
No registration, unlimited notifications, send messages via curl.
I made it because I like simplicity and all other tools were overly complicated (require registration and so on).
Learning Touch Typing with instant visual feedbacks.
I initially made it for Mozilla Dev Derby, and now released as an Chrome App.
Less proud of making it than I am of the fact that thousands of people use it to accomplish their goals every day, which is neat.
I created a Weather extension using DarkSky.net api. I wanted a quick/accurate way to check the weather without ads. I have a Chrome, Firefox and Opera version. Let me know what you think!
Chrome version is most popular:...
I'm pretty sure this is best quality user session recorder out there. Just gotta work on the marketing bit :)
- Sensorama for iOS: it's meant to be an open-source data science platform for obtaining data from your iPhone's sensors. And you get the JSON file with data e-mailed to you (and I get a copy too!).
Install:
Read code: (main repo) (artwork, scripted: generates all JPEGs from cmd line)
I did everything myself: coding and design for it.
- LastPass for SSH: You keep your SSH keys protected with a cryptic pass-phrases and you store them in LastPass.
- Asset toolbox: My attempt to improve the workflow with asset on iOS. I've used that multiple times to get all the resolutions/sizes during random moments of weakness.
- Finite Automata Simulator written in QT/Graphviz:
- Network Simulator written in C, with visualisation in Graphviz:
- Other stuff from my junkyard: (feel free to let me know what's the most interesting, or fiddle with GitHub stars)
My next target would be to get some paid online projects done and delivered to users, so that I could pay my phone bill with software.
Great thread. Thanks for making it.
It's easy to be proud of things you take all the way. Congrats to everyone!
It allows people to create playtest cards for a strategy card game, so people can test out decks before purchasing cards to play with in a tournament.
I made it because my wife is a Twitch streamer, and she needed a way for the card name to be visible even though the usual printed size is quite small. It ends up looking like this:
SelfControl - a free Mac focus app that helps users block their own access to distracting websites
It's dramatically reduced the amount of annoying recruiter spam that I get. I'm proud that it was initially just a test-bed for new technologies, that actually became useful.
I made this in a few days to learn React + Redux and it turns out a bunch of people now use it and have personally thanked me for building it. It's a web UI for Deis (an Heroku like PaaS that runs on Kubernetes).
Splitons is a simple Offline web application to split costs between friends ().
It has been a mobile first development using AngularJs, Bootstrap and font-awesome.
Splitons takes advantage of AppCache, websockets and local storage to provide the best user experience possible.There is a clear separation between the Ui and the service thanks to a simple reusable Api.
At this moment, the application takes care of about 150 projects, users are regularly providing feedbacks and thanks email.They really enjoyed not having to install another application and how easy it is to share a project.
Because it is an open source project (), one user sent me a pull request that I accepted to improve the Ui some months ago.
Please try and give me a feedback!
Ridiculously simple chrome extension I built while learning how to build one. Tells you the Google pagespeed insights score for the website of current tab.
Very simple but I use it daily....
Simple story: I've been involved with a lot of SaaS in my career and unless you're running the latest and greatest, it can be hard to host customer websites on a plurality of custom domains. This just makes that really simple by hosting it for you.
Disclaimer: I posted this earlier today as a Show HN, but posting here as well in case anyone is interested.
A little history. Back in the day when I started looking into Usenet there were no proper clients for Linux. There was pan but it had huge problems dealing with large volume binary groups. I figured it can't be that hard and started working on my own client which slowly evolved into the current 4th major version. Ten years in the making already :)
The 3x series was the most successful with perhaps around 50-60k installs. In general the field is very competitive and there are several clients for Windows especially. or Love Game started as an app here on HN, then a crowdfunded card game that ended up in Urban Outfitters, Ritz Carlton Hotels & Amazon. took those images from NASA / JPL and created a series of 17 journals as part of a crowdfund. They are super beautiful and really incredible as a full set.
I'm pretty proud of it any many users use this extensions, from private to commercial. It's free and open source and I never charged for it (sadly). WPF is now dying and my work will eventually die as well...
Basic, but my first dive into krypto and security. Droped it a while after. Not that interesting. Still using this link for random pwds.
Despite the site being free and open source, people still send me a few bucks each month, and very nice thank-you emails. And there are at least 2-3 sites out there that I'm personally a fan of that used it.
I made a simple endless swing game for Android with Unity 5. It was my first experience with Unity or C#. I needed units for college, and I was able to have a professor oversee the project for 4 units. I'm so glad he did because I had a ton of fun making it!
Took a quatter to make and I'm pretty proud of it even though the only users nowadays are friends and family members who keep it installed and accidentally open it, and a couple of Russians :)
I made this because I was trying to introduce friends to Chromium for Android and loosing most of them at 'unzip'. It makes installing the official latest build of Chromium reasonably easy.
One of the auto generated microservices backend/documentation/playground/sample code all in one sweet pa(cka)ge.
I'm proud of it because it's completely scripted, I can generate/deploy any CRUD Restful microservice in under a minute, it's Lambda powered and multi-tenant cloud-hosted. A mouthful of buzzwords :)
Back when I was in school I hacked this together as a diversion from lab reports and as a convenient tool for myself. You can drag xlsx files onto it and it converts them to LaTeX tables (all done client-side).
Even though it has some really glaring flaws (no numerical formatting support), it has a loyal following of grad students from around the world who find it useful and occasionally email me to say thanks. Feels great :)
Hardly game-changing, to be sure. I did it for fun and to see whether it was possible at all, and as far as I know nobody actually uses it for anything. But there's something about synthesizing audio a byte at a time and playing it back in a web browser that tickles the same sense of magical possibility that I first experienced as a kid learning BASIC on an Apple IIc. Our industry's grown up a lot since then, of course, and I've grown up with it - but, every now and again, it's delightful to be reminded of what led so many of us into this line of work in the first place.
I wrote back in uni some 20+ years ago. Since then I've seen it copy-pasted, remixed, translated to different languages and integrated into little projects hundreds of times. It's falling out of favor lately. But, there was a time when it seemed like for each implementation of Marching Cubes, there was a 50:50 chance it was a derivative of that file.
Its pretty basic, it reverse engineers code and scans strings.xml and AndroidManifest.xml to look for random strings and print it on the UI.
I made this because every time I decide to post something on HN, I hang on for a moment making my mind up on whether it's the right time to post on HN.
So, I made this live visualization, showing activity levels on HN. Now there's this data driven decision instead of a vague hope.
It's a hosted code analysis solution for Python. It tracks code quality issues using our own code analyzer.
We have developed an AST/flow-graph based code analyzer which allows users to write their own code pattern queries using YAML.
BTW I have been working on an OS version for the last four months which I will release soon, if you are interested in helping me please write: andreas@quantifiedcode.com
When I was researching face recognition, I absolutely hated the labeling system that we were given, and couldn't really find anything better (mind you, this was about 6 years ago). So I started building Landmarker. It let you plot points, identify segments, zoom and rotate.
It never served any real purpose besides the few times I've wanted to make vector art.
Still, it's nice to have a project which results in a little less carbon going into the atmosphere :)...
Other than that, I also made a Apple ADB to USB converter so I can use my old Apple Extended keyboard II with my new computer. Hard to believe newer keyboards are worse compared to that one.
I worked at a startup doing mobile games but often business people needed very basic landing pages - so I did the point-and-click Wap Prototype Maker! Screenshot still available here:
I remember I was happy drawing the toolbar icons, because it reminded me of working in Deluxe Paint.
Downloadable, printable version is here:
[0] -...
Long-term reminders emailed to you. It keeps these tasks out of sight until you need to be reminded.
It lets you look up download statistics for packages on npm. You can pick a date range, or aggregate all downloads for an author.
They are mostly python and shell scripts (with one PHP), and most of them are still useful today :)
I'm proud of it because it's something I've always wanted to use and create....
Definitely not the one that gives me most pride from a technical standpoint, but it is used by a thousand people every day and that's more than enough to make me happy about that small hack.
I did a web scrapper which auto login to my university portal to detect any changes on news board (like lecturer post a class cancel notice), if change detected it will send a push notification to a mobile app.
Did this app in few weeks because I got pissed by lecturer suddenly canceling class and post the news at last minute. I shared it to my classmates and it jumped to 2200 active users before got shut down.
Also, this small templating library for python:
Also, a chrome extension that display images like firefox do, people seems to like it:...
- Bringing notifications into Slack that aren't possible out of the box. This includes some services that only send updates via email, and others that enable webhook subscriptions, which can be parsed, filtered, augmented, and formatted.
- Creating Slack slash commands that let you do simple things in Slack instead of opening another browser tab.
- Connecting one service to another behind the scenes, assisting with data centralization for all sorts of downstream benefits.
Proud of it because it's the first basic thing I've built from, mostly, the ground up. It's just basic HTML and uses Materialize CSS for the styling. I hope to learn enough JavaScript soon to add a dynamic component to it which highlights the next departure times for ease of use, so the visitor doesn't have to scroll through every time.
A build tool predating js modules, grunt, ES6. While it hasn't been touched for years, I still go back to it from time to time because it's so simple to use.
Google Chrome Extension to download YouTube videos. It was growing in popularity quite well at one point. It still works and gets notice. I use it frequently.
A simple tool to compare different investment platforms......
Allows you to quickly save a new file to a location in Sublime Text's input bar by pressing CMD+S, instead of opening the OS dialog which takes a lot longer (especially on OSX).
Originally built to help an internal project but we later open sourced it. It's great to see the stars go up!
1) Sherlock, a JavaScript natural language parser for entering events that I hacked the bulk of in a particularly productive all-nighter many years ago.
2) Exceptionally, a super simple Rails API exception handling library that is tiny but has proven very useful on every project I've worked on.
Restores the little counter next to Twitter's "tweet this" button that shows you how often your article has been tweeted. Also available as drop-in replacement for Twitter's old undocumented API endpoint that provided this info.
link:...
Created initially for Raspberry PI, but ported to most linux based OSs. There's also a Django app for it
A polling tool for quickly getting opinions on logo designs, product ideas, etc. I thought other people might like it too, but 5 months after publishing it I'm still making about 95% of the polls.
The 5,000 app users have now basically become my personal soundboard for ideas, which I'm more than happy to pay for.
The place I work at is not ready to use something like docker, so I made a cloneish of docker for us to use. We are still in the early stages of it right now. Brocker is a combination of docker and kubernetes. Sorry for the bad documentation, I'm slowly adding more.
It's running on the Heroku free tier with a cheap domain, so it only costs me a few cups of coffee every year. (sorry for the crappy design!)
Open for feedback!
* I'm aware that Swatch had this for the day only long time ago, it was called `swatch @beats`.
[0] -...
I plan to add more projects to teach people to code in this type of way. I think the best way to learn is to actually build small apps and then altering them to make them better.
After getting chew out by my last boss regarding scrapping job post off of oil and gas industry. I created this site to practices what I have learn so far on web scraping with c# by using selenium, phantomjs and htmlagilitypack. Its a site where I scraped job posting from major oil companies....
I hate how long it takes me to find a name for my new projects so I made launchaco. It's super simple but has saved me so much time when ever exploring names for new projects.
I also made a firefox extension about 10 years ago that let you restart an animated gif (there's a config option to make them only play once). I was surprised to learn people were still using in FF 3.6.
Mostly because I wanted to share reddit links with friends, but they didnt make sense without the accompanying title of the post.
This was scratching and itch, yet get used by 1000s of people every day.
Bonus: I made this for my friend and I to log our surf sessions
Use it daily when working with Linux to execute old commands as alternative to ctrl+r, AWESOME tool :)
I got bored of trawling eBay so decided to make my own tool to make it faster. StoreSlider has been going for a few years now and has been really useful.
I wrote a PHP CLI script to test directories of images for image integrity and log or take action on found issues....
* fuzzpy: a fuzzer for the Python interpreter itself (specifically CPython) [2]
[1]
[2]
Now it has word-count goals, writing timers, built in resources and custom theme support. I'm working on a follow up with lots of incremental improvements and new features.
I'm proud because people love it. They give it amazing reviews that I feel like I don't deserve. People are super nice about it.
It hasn't really taken off like I had hoped, but I still stand by the idea, and I think I really nailed the UX. For something fairly complex there's no account to create, no configuration, no installer, just open it once and you're done. Anything my 95-year-old grandma can use without help is a success in my book.
It tracks your Twitch unfollowers. I would never recommend anybody to care about unfollowers, but I was just always so curious to find out who unfollowed me (and hunt him until he refollows).
I also plan to add YouTube support soon. :)
Edit: It's still a little bit in development.
We enable anyone to easily create their one-of-a-kind Art, T-shirts, Lifestyle products via "Remixing" Copyrighted works.Products are printed on-demand. No minimums.
Think "Forking" for IRL design....
It's supposed to be a simple S3 file uploader GUI for non-techy people... 'proud' is questionable :)
Really simple but fun meme maker. It makes 'new style' memes, as opposed to the old image macros on Reddit.
Text to speech engine I built a while back. It was a fun project because I got to do some front end programming with React.
A very simple search tool for the command line, aiming to replace very common cases. It's pretty minimal, but I use it every single day and love it... it unsurprisingly 9i developed it) fits very well my daily flow (90% of the times based in vim, at and ffind)
It's a simple diff-as-you-type tool. I realized that I often had two strings (test output, code samples, etc.) and wanted to compare them in as few keystrokes as possible, from any computer.
A software based keyboard and mouse lock for your computer so you can have a small child sitting on your lap (for example during a video call) and not have to worry about them pressing random keys.
I wanted a simple frontend for Stripe to charge whatever amount. As a web designer and developer this is what I use to get paid, work as a charm.
A simple timer. The colors represent an hour block of time. Its designed for your peripheral vision, put it on a secondary screen. Just drag or use the keyboard.
I know there are a bunch of similar sites outside however I wanted something simple with no ads but all information.
Here are some handy apps / cool demos that we've made: (the full list is here:)
- (73b+ speech synthetizer)
- (100b+ speech recognition)
- (1kb periodic table)
- (compute Pi in ~256b!)
- (170b regex tester)
- (tiny bookmarklets)
- (512b shadertoy clone)
- (1kb shadertoy clone)
- (1kb js beautifier)
- (Unicode slideshows in 64b and up)
- (JS KeyCode finder in less than 128b)
- (a JSperf clone in less than 300b)
- (a spreadsheet app in 221 bytes)
- (hexadecimal viewer and editor in 243+ bytes)
- (file-to-dataURI converter in 99 bytes)
- (HTML/CSS/JS editor in 156+ bytes)
- (drawing with braille on Twitter in less than 1k)
- (HTML/CSS/JS minifiers in 128+ bytes)
- (26 games in 13kb)
An easy to use wallpaper/config manager and themer for GNU/Linux which takes it's colorscheme from the wallpaper and applies it to things like the terminal, tint2, openbox, GTK2/3 and optional config files too, so the color scheme affects all the config files specified. It's compatible with everything that uses written config files and hex colors!
Pay more than the person before you and you get... to be the person that paid the most. That's it. Well, you get a message on the front page along with your name, but still.
People tend to react positively to it, though I can't for the life of me figure out how to market it. I've tried Reddit/Facebook ads, mentioning on relevant Subreddits and such, and nothing has really taken off. Maybe someday I'll figure it out.
Online marketing tools - conversion tracking, etc. Rather unique in the way these as are defined as "rules" which can be concatenated.
It used Mozilla Persona for authentication, which is now gone. Switched to Github OAuth, which went surprisingly well.
It's a video mapping application that started as a super simple tool, this is why artist love it.
WoofJS is a simple JS canvas library and IDE I built for my students so they can learn JavaScript.
I created it because I use Quickbooks a lot and many banks don't support the QBO file format.
Small, simple and free
This is something I am working on now. Simple graphic tool for adding text to images.
Notifies you (via email, slack or text), before your domain's cert expires.
A search engine that attempts to find thematic lineage between films. Warning: not mobile friendly.
it provides the possibility to easily visualize internal informal networks. Especially simple using mobile phones.
Aggregation of bar trivia events in your area.
A small script to ease chrooting (or docker running) into a development environment with usual set of workarounds (toggleable) like passing virtual filesystems, SSH/X11 env, home directory, etc.
Command-line tool for mass-downloading scientific literature that matches a search query. The crazy thing is that it didn't exist already.
Code is hacky, but hey, 350 downloads a month for something I threw together, and have never promoted...
Proud? Not really, but thought someone here might find it useful.
It's a simple website that randomly picks someone to pay for the entire bill when eating as a group. But unlike credit card roulette, your odds of paying are proportional to your meal's cost, so your expected value is fair.
I know it's simple, but it was my first foray into javascript and d3 and angular. I am proud of how it turned out.
Converts CSS hex colour codes in to well named Sass colour variables f.x #fafafa -> $alabaster or #a6a6a6 -> $silver-chalice
A simple google chrome extension for UFC fans.
Also created Helium,, a tool to help frontend devs clean up old CSS.
They're relatively popular.
An IBM developerWorks article: Developing a Linux command-line utility (selpg)...
It's a tutorial on how to write a Linux command-line utility in C. Was up on the IBM dW site for long; now archived. Got some stars etc. Code and article text now available via (links in) the above post on my blog. Uses as a case study / demo, a real-life utility I wrote for a client, to print only selected pages from a text file, specified by line number range or page range (form-feed-delimited pages, a common industry format for line printers). It was for a very large company with huge print jobs, so if the paper jammed in mid-job, this utility could save them a lot of time and paper, by letting them print only the un-printed pages. They might still be using it several years after it was written. I had also shared it on the HP-UX mailing list, and people said it was useful.
This post shows how to use that utility (selpg) with xtopdf (another project of mine, for PDF generation from Python):
Print selected text pages to PDF with Python, selpg and xtopdf on Linux-...
PySiteCreator was a bit innovative and fun to do. It lets you create simple web sites by writing them purely in Python. I designed it to impose as few requirements or constraints on the user as I could, so that it would be more generally useful, i.e. more like a library than a framework, though it is a sort of framework, since it calls code you write.
Early release of PySiteCreator - v0.1...
That post describes the ways it can be used. I originally created it with the goal of creating simple wikis using Python, but then realized that it generalized to any web site, so changed the name from DSLWiki (a DSL for wikis) to PySiteCreator :)
And while this one - pipe_controller - is not really a tool or product (it is an experiment), I enjoyed seeing what I could do with it - like running a pipe incrementally and swapping pipe components at runtime. There are few posts describing those experiments, in reverse chronological order, starting from this last post:
Swapping pipe components at runtime with pipe_controller:...
Edit: I'm working a few other products, some for sale, some free, so anyone interested in checking them out, is welcome to follow me for email updates here on Gumroad:
(There are a few small free utilities in early versions there now too.)
I only send out a few updates a month (if that), and only if I have a new product or an update to an existing one to announce.
Edited for typos / re-wording.
The Dread Space Pirate Richard. a comedy ebook. 1st book on Amazon, 2nd being written. sells copies:
Software Performance & Scalability Cheatsheet. free download. geek out on it. revise and expand from time to time:
lots more in the distant past. (eg. once wrote a pretty decent clone of Empire Deluxe, but with more unit types, and for Linux. shoutout to @WalterBright!)
my next one might be Maxitize. but we'll see, its very early.
* cfgen, a config files generator that is fed with config templates andparameters to fill them
* CronBuilder, to pull a repository, run building command, and save theresults in another repository
* flowmon, which shows bandwith usage of different streams, each defined byBPF filter (a.k.a. "tcpdump syntax")
* sftponly, a shell for jailing in chroot accounts meant for data transferonly (for scp, sFTP, and rsync)
* xmlrpcd and its spiritual successor HarpCaller, RPC daemons for sysadmins
* logdevourer, log parsing daemon
These are just the public ones, the ones that were generic enough to be opensourced. I have few others that are/were too specific to the environment theywere written for.
Multiple others I can't remember off top of my head | http://hackerbra.in/ask/1479272701 | CC-MAIN-2018-51 | refinedweb | 26,675 | 70.84 |
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.
how to restrict number of records to create
Hi friendz,
Is there any way to restrict the number of records to be created for a single object or table
My requirement needs me to create only 3 contacts for my company. Is there any way to do so.
Thanks & Regards, Atchuthan
Hello,
You can do this by def create() like:
class test(osv.osv):
_name = "test" def create(self, cr, uid, vals, context=None): limit = len(self.search(cr, uid, [], context=context)) if(limit >= 15): raise osv.except_osv(_("Warning!"), _("Message to display")) else: return super(test, self).create(cr, uid, vals, context=context)
Here, test should be name of your object. I have given to 15 record's creation.
Exactly what i would have answering. Maybe you must overwritten the write too.
def write() is used to update the record. And in question it's to restrict number of records to create., So no needed to overwrite write().
When you add a contact to an already existing Customer, it don't pass by Customer write ?
@Xsias I have fetched all the records of 'test' object. We need to pass domain according to our requirement.
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-restrict-number-of-records-to-create-27099 | CC-MAIN-2017-17 | refinedweb | 251 | 68.47 |
Config::Merge - load a configuration directory tree containing YAML, JSON, XML, Perl, INI or Config::General files
OO style ------------------------------------------------------- use Config::Merge(); my $config = Config::Merge->new('/path/to/config'); @hosts = $config->('db.hosts.session'); $hosts_ref = $config->('db.hosts.session'); @cloned_hosts = $config->clone('db.hosts.session'); -------------------------------------------------------
OR
Functional style ------------------------------------------------------- # On startup use Config::Merge('My::Config' => '/path/to/config'); # Then, in any module where you want to use the config package My::Module; use My::Config; @hosts = C('db.hosts.sesssion'); $hosts_ref = C('db.hosts.sesssion'); @cloned_hosts = My::Config::clone('db.hosts.session'); $config = My::Config::object; -------------------------------------------------------
ADVANCED USAGE
OO style ------------------------------------------------------- my $config = Config::Merge->new( path => '/path/to/config', skip => sub {} | regex | {} , is_local => sub {} | regex | {} , load_as => sub {} | regex , sort => sub {} , debug => 1 | 0 ); ------------------------------------------------------- Functional style ------------------------------------------------------- use Config::Merge( 'My::Config' => '/path/to/config', { skip => sub {} | regex | {} , is_local => sub {} | regex | {} , load_as => sub {} | regex , sort => sub {} , debug => 1 | 0 } ); # Also, you can subclass these: package My::Config; sub skip { ... } -------------------------------------------------------
Config::Merge is a configuration module which has six goals:
Store all configuration in your format(s) of choice (YAML, JSON, INI, XML, Perl, Config::General / Apache-style config) broken down into individual files in a configuration directory tree, for easy maintenance. See "CONFIG TREE LAYOUT"
Provide a simple, easy to read, concise way of accessing the configuration values (similar to Template). See "ACCESSING CONFIG DATA"
Specify the location of the configuration files only once per application, so that it requires minimal effort to relocate. See "USING Config::Merge"
Provide a way for overriding configuration values on a development machine, so that differences between the dev environment and the live environment do not get copied over accidentally. See "OVERRIDING CONFIG LOCALLY"
Load all config at startup so that (eg in the mod_perl environment) the data is shared between all child processes. See "MINIMISING MEMORY USE"
You may want to use a different schema for your configuration files, so you can pass in (or subclass) methods for determining how your files are merged. See "ADVANCED USAGE".
Config::Merge
There are two ways to use
Config::Merge:
use Config::Merge(); my $config = Config::Merge->new('/path/to/config'); @hosts = $config->('db.hosts.session'); $hosts_ref = $config->('db.hosts.session'); @cloned_hosts = $config->clone('db.hosts.session');
Also, see "ADVANCED USAGE".
The following code:
# On startup use Config::Merge('My::Config' => '/path/to/config');
My::Config
'/path/to/config'
My::Config::C,
My::Config::cloneand
My::Config::object.
Then when you want your application to have access to your configuration data, you add this (eg in your class
My::Module):
package My::Module; use My::Config; # Note, no ()
This exports the sub
C into your current package, which allows you to access your configuation data as follows:
@hosts = C('db.hosts.sesssion'); $hosts_ref = C('db.hosts.sesssion'); @cloned_hosts = My::Config::clone('db.hosts.session'); $config = My::Config::object;
Config::Merge reads the data from any number (and type) of config files stored in a directory tree. File names and directory names are used as keys in the configuration hash.
It uses file extensions to decide what type of data the file contains, so:
YAML : .yaml .yml JSON : .json .jsn XML : .xml INI : .ini Perl : .perl .pl Config::General : .conf .cnf
When loading your config data, Config::Merge starts at the directory specified at startup (see "USING Config::Merge") and looks through all the sub-directories for files ending in one of the above extensions.
The name of the file or subdirectory is used as the first key. So:
global/ db.yaml: username : admin hosts: - host1 - host2 password: host1: password1 host2: password2
would be loaded as :
$Config = { global => { db => { username => 'admin', password => { host1 => 'password1', host2 => 'password2'}, hosts => ['host1','host2'], } } }
Subdirectories are processed before the current directory, so you can have a directory and a config file with the same name, and the values will be merged into a single hash, so for instance, you can have:
confdir: syndication/ --data_types/ --traffic.yaml --headlines.yaml --data_types.ini syndication.conf
The config items in syndication.conf will be added to (or overwrite) the items loaded into the syndication namespace via the subdirectory called syndication.
The situation often arises where it is necessary to specify different config values on different machines. For instance, the database host on a dev machine may be different from the host on the live application. Also, see "ADVANCED USAGE" which provides you with other means to merge local data.
Instead of changing this data during dev and then having to remember to change it back before putting the new code live, we have a mechanism for overriding config locally in a
local.* file and then, as long as that file never gets uploaded to live, you are protected.
You can put a file called
local.* (where * is any of the recognised extensions) in any sub-directory, and the data in this file will be merged with the existing data.
Just make sure that the
local.* files are never checked into your live code.
For instance, if we have:
confdir: db.yaml local.yaml
and db.yaml has :
connections: default_settings: host: localhost table: abc password: 123
And in local.yaml:
db: connections: default_settings: password: 456
the resulting configuration will look like this:
db: connections: default_settings: host: localhost table: abc password: 456
All configuration data is loaded into a single hash, eg:
$config = { db => { hosts => { session => ['host1','host2','host3'], images => ['host1','host2','host3'], etc... } } }
If you want to access it via standard Perl dereferences, you can just ask for the hash:
OO: $data_ref = $config->(); $hosts_ref = $data_ref->{db}{hosts}{session}; $host_1 = $data_ref->{db}{hosts}{session}[0]; Functional: $data_ref = C(); $hosts_ref = $data_ref->{db}{hosts}{session}; $host_1 = $data_ref->{db}{hosts}{session}[0];
However,
Config::Merge also provides an easy to read dot-notation in the style of Template Toolkit:
('key1.key2.keyn').
A key can be the key of a hash or the index of an array. The return value is context sensitive, so if called in list context, a hash ref or array ref will be dereferenced.
OO: @hosts = $config->('db.hosts.session'); $hosts_ref = $config->('db.hosts.session'); $host_1 = $config->('db.hosts.session.0'); Functional: @hosts = C('db.hosts.session'); $hosts_ref = C('db.hosts.session'); $host_1 = C('db.hosts.session.0');
These lookups are memo'ised, so lookups are fast.
If the specified key is not found, then an error is thrown.
The more configuration data you load, the more memory you use. In order to keep the memory use as low as possible for mod_perl (or other forking applications), the configuration data should be loaded at startup in the parent process.
As long as the data is never changed by the children, the configuration hash will be stored in shared memory, rather than there being a separate copy in each child process.
(See)
new()
$conf = Config::Merge->new($config_dir);
new() instantiates a config object, loads the config from the directory specified, and returns the object.
C()
$val = $config->C('key1.key2.keyn'); $val = $config->C('key1.key2.keyn',$hash_ref);
Config::Merge objects are overloaded so that this also works:
$val = $config->('key1.key2.keyn'); $val = $config->('key1.key2.keyn',$hash_ref);
Or, if used in the functional style (see "USING Config::Merge"):
$val = C('key1.key2.keyn'); $val = C('key1.key2.keyn',$hash_ref);
key1 etc can be keys in a hash, or indexes of an array.
C('key1.key2.keyn') returns everything from
keyn down, so you can use the return value just as you would any normal Perl variable.
The return values are context-sensitive, so if called in list context, an array ref or hash ref will be returned as lists. Scalar values, code refs, regexes and blessed objects will always be returned as themselves.
So for example:
$password = C('database.main.password'); $regex = C('database.main.password_regex'); @countries = C('lists.countries'); $countries_array_ref = C('lists.countries'); etc
If called with a hash ref as the second parameter, then that hash ref will be examined, rather than the
$config data.
clone()
This works exactly the same way as "C()" but it performs a deep clone of the data before returning it.
This means that the returned data can be changed without affecting the data stored in the $conf object;
The data is deep cloned, using Storable, so the bigger the data, the more performance hit. That said, Storable's dclone is very fast.
register_loader()
Config::Merge->register_loader( 'Config::Merge::XYZ'); Config::Merge->register_loader( 'Config::Merge::XYZ' => 'xyz','xxx');
By default,
Config::Merge uses the
Config::Any plugins to support YAML, JSON, INI, XML, Perl and Config::General configuration files, using the standard file extensions to recognise the file type. (See "CONFIG TREE LAYOUT").
If you would like to change the handler for an extension (eg, you want
.conf and
.cnf files to be treated as YAML), do the following:
Config::Merge->register_loader ('Config::Any::YAML' => 'conf', 'cnf');
If you would like to add a new config style, then your module should have two methods:
extensions() (which returns a list of the extensions it handles), and
load() which accepts the name of the file to load, and returns a hash ref containing the data in the file. See Config::Any for details.
Alternatively, you can specify the extensions when you load it:
Config::Merge->register_loader ('My::Merge' => 'conf', 'cnf');
load_config()
$config->load_config();
Will reload the config files located in the directory specified at object creation (see "new()").
BEWARE : If you are using this in a mod_perl environment, you will lose the benefit of shared memory by calling this in a child process - each child will have its own copy of the data. See "MINIMISING MEMORY USE".
Returns the config hash ref.
clear_cache()
$config->clear_cache();
Config data is generally not supposed to be changed at runtime. However, if you do make changes, you may get inconsistent results, because lookups are cached.
For instance:
print $config->C('db.hosts.session'); # Caches this lookup > "host1 host2 host3" $data = $config->C('db.hosts'); $data->{session} = 123; print $config->C('db.hosts.session'); # uses cached value > "host1 host2 host3" $config->clear_cache(); print $config->C('db.hosts.session'); # uses actual value > "123"
import()
import() will normally be called automatically when you
use Config::Merge. However, you may want to do this:
use Config::Merge(); Config::Merge->register_loader('My::Plugin' => 'ext'); Config::Merge->import('My::Config' => '/path/to/config/dir');
If called with two params:
$config_class and
$config_dir, it generates the new class (which inherits from Config::Merge) specified in
$config_class, creates a new object of that class and creates 4 subs:
C()
As a function: C('keys...') is the equivalent of: $config->C('keys...');
clone()
As a function: clone('keys...') is the equivalent of: $config->clone('keys...');
object()
$config = My::Config->object();
Returns the
$config object,
import()
When you use your generated config class, it exports the
C() sub into your package:
use My::Config; $hosts = C('db.hosts.session');
The items in the section allow you to customise how Config::Merge loads your data. You may never need them.
You can:
Overriding hash values is easy, however arrays are more complex. it may be simpler to copy and paste and edit the array you want to change locally.
However, if your array is too long, and you want to make small changes, then you can use the following:
In the main config:
{ cron => [qw( job1 job2 job3 job4)] }
In the local file
{ cron => { '3' => 'newjob4', # changes 'job4' -> 'newjob4' '!' => { # signals an array override '-' => [1], # deletes 'job2' '+' => ['job5'], # appends 'job5' OR '+' => { # inserts 'job3a' after 'job3' 2 => 'job3a' } } }
{ '!' => {} }to signal an array override
'-'key should contain an array ref, with the indexes of the elements to remove from the array.
'+'key contains an array ref, then its contents are appended to the original array.
'+'key contains a hash ref, then each value is inserted into the original array at the index given in the key
skip()
$c = Config::Merge->new( path => '/path/to/config', skip => qr/regex/, | [ qr/regex1/, qr/regex2/...] | { name1 => 1, name2 => 2} | sub {} );
skip() allows you to skip the loading of parts of your config tree. For instance, if you don't need a list of cron jobs when running your web server, you can skip it.
The decision is made based on the path to that value, eg 'app.db.hosts' rather than on filenames. Also, the check is only performed for each new directory or filename - it doesn't check the data within each file.
To use
skip(), you can either subclass it, or pass in a parameter to new:
qr/regex/or
[qr/regex1/, qr/regex2]
Each regex will be checked against the key path, and if it matches then the loading of that tree will be skipped
{key_path => 1}
If the key path exists in the hash, then loading will be skipped
sub {}or subclassed
skip
sub { my ($self,$key_path) = @_; ...make decision... return 1 | 0; }
is_local()
$c = Config::Merge->new( path => '/path/to/config', is_local => qr/regex/, | [ qr/regex1/, qr/regex2/...] | { name1 => 1, name2 => 2} | sub {} );
is_local() indicates whether a file or dir should be considered part of the main config (and thus loaded normally) or part of the local config (and thus merged into the main config).
The decision is made based on the name of the file / dir, without any extension.
To use
is_local(), you can either subclass it, or pass in a parameter to new:
qr/regex/or
[qr/regex1/, qr/regex2]
Each regex will be checked against the file/dir name, and if it matches then that tree will be merged
{filename => 1, dirname => 1}
If the file/dir name exists in the hash, then that tree will be merged
sub {}or subclassed
is_local
sub { my ($self,$name) = @_; ...make decision... return 1 | 0; }
See "EXAMPLE USING is_local() AND load_as()".
load_as()
$c = Config::Merge->new( path => '/path/to/config', load_as => qr/(regex)/, | sub {} );
load_as() returns the name of the key to use when loading the file / dir. By default, it returns the
$name for main config files, or
'' for local files.
The decision is made based on the name of the file / dir, without any extension.
If
load_as() returns an empty string, then each key in the file/tree is merged separately. This is how the
local.* files work by default. See "OVERRIDING CONFIG LOCALLY".
For instance:
main.yaml: key1: value key2: value db.yaml: key3: value key4: value local.yaml: main: key1: new_value db: key4: new_value
To use
load_as(), you can either subclass it, or pass in a parameter to new:
qr/(regex)/
The regex will be checked against the file/dir name, and if it matches then it returns the string captured in the regex, otherwise it returns the original name.
sub {}or subclassed
is_local
sub { my ($self,$name,$is_local) = @_; ...make decision... return 'string'; # string is used as the keyname return ''; # acts like local.* (see above) return undef; # don't load this file/dir }
Also, see "EXAMPLE USING is_local() AND load_as()".
is_local()AND
load_as()
For instance, instead of using
local.* files, you may want to keep versioned copies of local configs for different machines, and so use:
app.yaml app-(dev1.domain.com).yaml app-(dev2.domain.com).yaml
You would implement this as follows:
my $config = Config::Merge->new( path => '/path/to/config', # If matches 'xxx-(yyy)' is_local => sub { my ( $self, $name ) = @_; return $name=~/- [(] .+ [)]/x ? 1 : 0; }, # If local and matches 'xxx-(hostname)', return xxx load_as => sub { my ( $self, $name, $is_local ) = @_; if ($is_local) { if ( $name=~/(.*) - [(] ($hostname) [)] /x ) { return $1; } return undef; } return $name; } );
See
examples/advanced.pl for a working illustration.
sort()
$c = Config::Merge->new( path => '/path/to/config', sort => sub {} );
By default, directory entries are sorted alphabetically, with directories before filenames.
This would be the order for these directory entries:
api/ api-(dev1)/ api.yaml api-(dev1).yaml
To override this, you can subclass
sort() or pass it in as a parameter to new:
sub { my ($self,$names_array_ref) = @_ ...sort... return $names_array_ref; }
debug()
my $config = Config::Merge->new( path => '/path/to/config', debug => 1 | 0 );
If
debug is true, then Config::Merge prints out an explanation of what it is doing on STDERR.
Storable, Config::Any, Config::Any::YAML, Config::Any::JSON, Config::Any::INI, Config::Any::XML, Config::Any::General
Thanks to Hasanuddin Tamir [HASANT] for vacating the Config::Merge namespace, which allowed me to rename Config::Loader to the more meaningful Config::Merge.
His version of Config::Merge can be found in.
Thanks to Joel Bernstein and Brian Cassidy for the interface to the various configuration modules. Also to Ewan Edwards for his suggestions about how to make Config::Merge more flexible.
No bugs have been reported.
Please report any bugs or feature requests to.
Clinton Gormley, <clinton@traveljury.com>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.7 or, at your option, any later version of Perl 5 you may have available. | http://search.cpan.org/dist/Config-Merge/lib/Config/Merge.pm | CC-MAIN-2017-09 | refinedweb | 2,813 | 55.03 |
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.
How do I override dispatch_rpc function in netsvc.py with a module in openerp 7?
I need to override dispatch_rpc function in server/openerp/netsvc.py to add code that sends error log by email. I have a function that do it and works, but I want to be able to apply this modification in future by applying a module with this. Thanks :)
PD. dispatch_rpc function is not part of any class, how can I inherit it?
This is pretty straight forward but you need to do a couple of things (assuming OpenERP 7)
1 Create your new module.
2 Create a class that inherits osv.Model
3 Add an _inherit = 'xxxxxxx'
4 Implement your new dispatch_rpc function.
5 Install your module and it should work.
A typical pattern is to call super and then process the results.
class MyModel(osv.Model):
_inherit = 'sale.order.line'
def product_id_change(self, cr, uid, ids, ...):
res = super(MyModel, self).product_id_change(cr, uid, ids...)
# do stuff with res.
return res
Here is an other useful link:
Regards.
thanks for your answer, but dispatch_rpc is not part of any class or module, is part from base, what can I inherit?
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-do-i-override-dispatch-rpc-function-in-netsvc-py-with-a-module-in-openerp-7-89412 | CC-MAIN-2018-17 | refinedweb | 250 | 69.28 |
Just a small example:
class MyView(ctn.AbstractCTNView):
ctn_accept_binding = {
'text/html': 'html_handler',
'text/*': 'plain_handler',
'*/*': 'plain_handler',
}
def html_handler(self, request, *args, **kwargs):
return HttpResponse('Hello World', mimetype='text/html')
def plain_handler(self, request, *args, **kwargs):
return HttpResponse('Hello World', mimetype='text/plain')
myview = oopviews.create_view(MyView)
This view would accept basically every request for text and give only for text/html provides a different output. Please note, though, that this is by no means a complete implementation of content-type negotiation. The specs also mention additional type-parameters, that are no further described, so I couldn't really add support for them. But for most cases, this implementation should suffice :-)
Google won't like it... What is that for?
Sept. 2, 2008, 8:59 a.m.
Uhm... what does Google not like about it?
Sept. 3, 2008, 9:22 a.m. | http://zerokspot.com/weblog/2008/08/30/something-new-in-django-zsutils/ | crawl-002 | refinedweb | 140 | 51.04 |
UseFile is about just running a piece of code that lives somewhere the language can find (on sys.path for Python) and returning the new ScriptScope that it was executed in - it doesn't do anything with namespaces so it won't help here. It's supposed to be an easy way to just run some one-off code. From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Leo Carbajal Sent: Friday, October 10, 2008 2:50 PM To: Discussion of IronPython Subject: Re: [IronPython] Can I pre-add namespaces? Would it be possible to use scriptSource.IncludeFile(path) instead to get the same effect? I was perusing the hostingAPI and the Runtime has a whole paragraph for UseFile but when you look at the class declaration (again on the hostingAPI doc) it's not listed there, so I'm not sure if that's just a leftover ghost - I can't confirm it from work. Mostly I'm curious about the first, as thats how I would have approached it. On Fri, Oct 10, 2008 at 3:38 PM, Marty Nelson <Marty.Nelson at symyx.com<mailto:Marty.Nelson at symyx.com>> wrote: Maybe> [mailto> [mailto:users-bounces at lists.ironpython.com<mailto:users-bounces at lists.ironpython.com>] On Behalf Of Marty Nelson Sent: Friday, October 10, 2008 1:02 PM To: users at lists.ironpython.com<mailto<mailto:Users at lists.ironpython.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/ironpython-users/2008-October/008631.html | CC-MAIN-2016-30 | refinedweb | 252 | 68.26 |
How can we restrict dynamic allocation of objects of a class using new?
(A) By overloading new operator
(B) By making an empty private new operator.
(C) By making an empty private new and new[] operators
(D) By overloading new operator and new[] operators
Answer: (C)
Explanation: If we declare new and [] new operators, then the objects cannot be created anywhere (within the class and outside the class)
See the following example. We can not allocate an object of type Test using new.
#include <stdlib.h> #include <stdio.h> #include <iostream> using namespace std; class Test { private: void* operator new(size_t size) {} void* operator new[](size_t size) {} }; int main() { Test *obj = new Test; Test *arr = new Test[10]; return 0; } | https://www.geeksforgeeks.org/c-operator-overloading-question-1/ | CC-MAIN-2018-09 | refinedweb | 120 | 51.99 |
Back to article
September 9, 2004
by Allen
One of the very common
questions appearing on various developer forums is that of comparing the pros
and cons of MySQL and MS SQL. While comparisons have been made by many, mostly on technical issues, I personally find that they are difficult
to compare, especially regarding their performance.
It is not true that MS
SQL is better than MySQL or vice versa. Both products can be used to build
stable and efficient systems. The stability and effectiveness of your databases
vitally depends on your experience rather than the database itself. Both of
database have their own advantages over the another. When deciding which server to
use, it truly depends on your needs.
Despite the fact that MS
SQL and MySQL both have their own strengths, a significant number of businesses
have shifted their databases to MySQL because they keep finding good reasons to
take advantage of MySQL's openness.
While proprietary
software still has a larger portion of the market share, Open Source Software
is waiting to conquer the market and has the potential to do so. Netcraft reported that although Apache is one
of the more recent web servers, it has more market share than other web servers,
put together do. Linux is also increasing in numbers; it is estimated as the
fastest growing operating system. While exact numbers are indeed difficult to
ascertain, most researchers estimate around 8 to 10 million Linux installations. Among the millions of
installations, the number of exact users may even exceed this figure, as Linux
is a multi-user system. This number is growing at around 40% per year. With
such rising figures, we should admit that Open Source Software does have its
advantages over closed software.
In 2000, NASA's Marshall
Space Flight Center finished the
transition of the NASA Acquisition Internet Service to MySQL.
Representatives from NASA admitted that it may be unconventional for federal
agencies to use open-source software, however, due to the limited budget on its
massive data repository, MySQL is definitely the most robust product available.
You may wonder
why this open source revolution has been occurring in recent years. The most
visible influential reason is the Internet. The Internet makes numerous
processes possible, which are essential for the growth of the open source
movement. Among the major advantages, the Internet makes for a wonderful
accelerant of code and idea dissemination. This includes spreading the idea
that open source is good.
Now, Open Source Software
becomes a compelling alternative to commercial software due to the following
advantages:
Cost Effective:
Open Source Software is often distributed free or under the General Public
License. Reasonable and inexpensive prices are charged for commercial organizations.
The cost saved can be spent on other development and support.
Transparency:
Because you can access the source code, you can always find out how the code is
working. It enables unlimited tuning and improvement of a software product.
In addition, it makes it possible to port the code to new hardware and to adapt it
to changing conditions such that it integrates perfectly with your existing
systems.
Reliability:
Open Source Software generally offers good reliability and stability. This is
due to a worldwide group of contributors who help to debug the software. Any
bugs found will tend to affect the product on a more superficial level and
require less recoding.
If you
are ready to experience the rewards of Open Source Software, why not migrate
your MS SQL to MySQL? Conversion of MS SQL to MySQL can be complicated with
lengthy commands. If you do not feel comfortable with the black-and-white
command prompt, you can try out some MySQL database administration GUIs
available on the market.
Navicat is a powerful MySQL database
administration and development tool. It provides a powerful set of tools, which
help you to administer MySQL databases locally or remotely. It also contains
import features, which allow the user to import files into MySQL databases from
ten different formats, including MS Access, MS Excel, MS Word (RTF), HTML, XML,
TXT, CSV, DBF, etc.
The Network for Technology Professionals
About Internet.com
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers | http://www.databasejournal.com/features/mysql/print.php/3405841 | CC-MAIN-2014-41 | refinedweb | 700 | 53.92 |
Tutorial: drawRect animation using POP
In this tutorial we will create Youtube play button animation using Facebook POP. The source code will be shared on Github, it also includes an alternative way of doing this animation using CoreAnimation.
For this tutorial we need CocoaPods. If you are not familiar with that, I would recommend to read this tutorial or at least CocoaPods Getting Started.
To begin with, we need to create a new Single View Application project (File -> New -> Project). After project is created, we need to add CocoaPods. Add this pod and install it:
pod 'pop'
POP still does not have Swift support, so we have to create bridging header which allows us to user Swift and Objective-C in the same project:
- Create .h file (File -> New -> File -> Source -> Header File) and name it BridgingHeader;
- Go to target build settings and search for Objective-C Bridging Header;
- Provide path to your bridging header. It should be ProjectName/BridgingHeader.h
Add this import to your BridgingHeader.h:
#import "POP.h"
Build the project to make sure that bridging header works properly and there are no warnings. It may fail because of enabled bitcode, as POP does not support it yet. To fix this error, you have to disable bitcode by going to your Target -> Build Settings -> Search for “bitcode”:
For animation we need to create a new UIButton and call it PlayButton.
As you have seen, this button will animate between two states: Paused and Playing. We need to define them using enum. Copy and paste this code above class declaration:
enum PlayButtonState {
case Paused
case Playing
var value: CGFloat {
return (self == .Paused) ? 1.0 : 0.0
}
}
The reason why I added var value: CGFloat will be described later.
Now I would like to go threw the theory of how button will animate between these two states.
POP allows us to create animatable property — and that is exactly what we are going to do. We will create CGFloat variable named animationValue and will animate it from 1.0 to 0.0 when button state is changed from Paused to Playing, and animate from 0.0 to 1.0 when button state is changed from Playing to Paused. Every time value has changed we will call setNeedsDisplay which will force our view to redraw. I think, now is a good time to try it!
Okay, lets declare some variables! Put this code at the beginning of class declaration:
// MARK: -
// MARK: Vars
private(set) var buttonState = PlayButtonState.Paused
private var animationValue: CGFloat = 1.0 {
didSet {
setNeedsDisplay()
}
}
Now we have two variables. First one is buttonState. This value can be accessed outside the class, but it can be set only inside the class. Second variable is animationValue. As you can see, we call setNeedsDisplay on didSet as it was explained above.
Next step is to create method which will be responsible for setting up animation or only updating animationValue when animation is not needed. The only reason why I added animated: Bool to this method is that if you will use this button in table view or collection view you will have to set state without animation when cell displayed.
// MARK: -
// MARK: Methods
func setButtonState(buttonState: PlayButtonState, animated: Bool) {
// 1
if self.buttonState == buttonState {
return
}
self.buttonState = buttonState
// 2
if pop_animationForKey("animationValue") != nil {
pop_removeAnimationForKey("animationValue")
}
// 3
let toValue: CGFloat = buttonState.value
// 4
if animated {
let animation: POPBasicAnimation = POPBasicAnimation()
if let property = POPAnimatableProperty.propertyWithName("animationValue", initializer: { (prop: POPMutableAnimatableProperty!) -> Void in
prop.readBlock = { (object: AnyObject!, values: UnsafeMutablePointer<CGFloat>) -> Void in
if let button = object as? PlayButton {
values[0] = button.animationValue
}
}
prop.writeBlock = { (object: AnyObject!, values: UnsafePointer<CGFloat>) -> Void in
if let button = object as? PlayButton {
button.animationValue = values[0]
}
}
prop.threshold = 0.01
}) as? POPAnimatableProperty {
animation.property = property
}
animation.fromValue = NSNumber(float: Float(self.animationValue))
animation.toValue = NSNumber(float: Float(toValue))
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.duration = 0.25
pop_addAnimation(animation, forKey: "percentage")
} else {
animationValue = toValue
}
}
- We return if buttonState has not changed, and update buttonState if it has changed;
- We remove previous animation if it exists;
- We create immutable variable toValue and set value of the buttonState which is calculated in var value: CGFloat (Swift allows us to have very clean and nice implementation of vars in enumerations);
- If animated == true, then we initialise POPBasicAnimation with POPAnimatableProperty. Otherwise we only set animationValue.
Lets understand how we initialised POPBasicAnimation in our example. FromValue, toValue, timingFunction, duration — everything is simple and does not require explanation, right? All these parameters can be used in CABasicAnimation. The only complex part of POPBasicAnimation is POPAnimatableProperty. As we animate our own property, we have to initialise our own animation block which contains:
- readBlock — reads values from a property and stores in an array of floats (CGFloat values[]);
- writeBlock — writes values from array of floats into property;
- threshold —defines the smallest increment of the value.
More information can be found in here.
If we would like to animate built-in property it would be easier — we could just use
POPAnimatableProperty.propertyWithName(kPOPViewAlpha)
to animate view alpha. List of built-in properties can be found here.
Now we have everything we need to animate property and I would like to explain logic of animation, so we understand what to write in drawRect.
Assume, that we are going to animate from Paused to Playing (1 to 3). Our “triangle” button will split in two halves — trapeziums (2), and will animate them to rectangles. The easiest way to achieve this effect is to always have 2 geometrical figures consisting of four points:
Next step is to understand which values we need to calculate. I have prepared special image which describes all values very well:
- minWidth — this value never changes, it defines minimum width of left and right halves (I like when it is equal to 32% of full button width);
- aWidth — this value is calculated using animationValue. When animationValue = 1, this value will be zero. When animationValue = 0, this value will be equal to half of button width minus minimum width;
- width — equals to minimum width plus additional width (minWidth + aWidth);
- H1 — padding from top to the left half top right point and the right half top left point, AND padding from bottom to the left half bottom right point and the right half bottom left point. When animationValue = 0, this value will be equal height / 4. When animationValue = 1, this value will be equal 0;
- H2 — padding from top to the right half top right point AND padding from bottom to the right half bottom right point. When animationValue = 0, this value will be equal height / 2. When animation value = 1, this value will be equal 0.
Okay, I think it is enough theory and good time to start. Even if you did not understand something — please do not be scared, you will understand it once we override drawRect. Copy and paste this code in PlayButton:
// MARK: -
// MARK: Draw
override func drawRect(rect: CGRect) {
super.drawRect(rect)
// 1
let height = rect.height
let minWidth = rect.width * 0.32
let aWidth = (rect.width / 2.0 - minWidth) * animationValue
let width = minWidth + aWidth
let h1 = height / 4.0 * animationValue
let h2 = height / 2.0 * animationValue
// 2
let context = UIGraphicsGetCurrentContext()
// 3
CGContextMoveToPoint(context, 0.0, 0.0)
CGContextAddLineToPoint(context, width, h1)
CGContextAddLineToPoint(context, width, height - h1)
CGContextAddLineToPoint(context, 0.0, height)
CGContextMoveToPoint(context, rect.width - width, h1)
CGContextAddLineToPoint(context, rect.width, h2)
CGContextAddLineToPoint(context, rect.width, height - h2)
CGContextAddLineToPoint(context, rect.width - width, height - h1)
// 4
CGContextSetFillColorWithColor(context, tintColor.CGColor)
CGContextFillPath(context)
}
This code is straightforward:
- We calculate all values as per image above. As I mentioned before, minWidth value is always the same, despite the fact that animationValue changes. I like when it is equal to 32 percent of the whole width. You can adjust this value as you want, but keep in mind, that it should be less or equal to half of width;
- As we are overriding drawRect, we should not to create a new context — we should get and use existing;
- Create CGPath of two trapezius, as it was described before;
- Set fill colour (I am using tintColor, feel free to change it).
The last step is to add PlayButton to our ViewController and test how it animates. Delete everything inside ViewController class and paste this:
// MARK: -
// MARK: Vars
private var playButton: PlayButton!
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
playButton = PlayButton()
playButton.frame = CGRect(x: floor((view.bounds.width - 150.0) / 2.0), y: 50.0, width: 150.0, height: 150.0)
playButton.addTarget(self, action: Selector("playButtonPressed"), forControlEvents: .TouchUpInside)
view.addSubview(playButton)
}
// MARK: -
// MARK: Methods
func playButtonPressed() {
if playButton.buttonState == .Playing {
playButton.setButtonState(.Paused, animated: true)
} else {
playButton.setButtonState(.Playing, animated: true)
}
}
Now build your project and enjoy! This animation is unbreakable — you can tap button as quick as possible and it will always smoothly animate between two states without any visual breaks. Pretty good, isn’t it?
If you are excited about drawRect animations, please let me know, I will write second part of this tutorial with 2 more nice animations!
All source code from this tutorial PLUS CoreAnimation implementation can be found here.
Thank you for reading, I hope you enjoyed! Please let me know which animation would you use in your project — drawRect, or CA. Cannot wait to read your comments! | https://medium.com/@gontovnik/tutorial-drawrect-animation-using-pop-9e43d8d00bf6 | CC-MAIN-2017-34 | refinedweb | 1,544 | 50.12 |
Hi,
I am working on integration between HDID v6.6.2, HCP v8.1 and HCI v1.3.45.
Using HDID I uploaded 210 documents to HCP namespace initially and ran the workflow successfully in HCI. I was able to search the document using Search apps.
But then I deleted the HCP namespace from HDID and created a new namespace. Using this new namespace, I have uploaded only one word document file into HCP. Although search apps still displaying old namespace documents. I have also made changes in the data connection in my workflow. I have already pointed out new namespace there.
Is there any way to reset the search index in HCI? I am little stuck here. I need your help on this.
HCI link for your reference: (admin/p@ssw0rd)@
not sure what you mean by reset, but you really have two options.
A) if all you want is the workflow stats reset you can go into the workflow and clear/ start over. This will reset it back to zero
B) if you are referring to the index itself and not having the data in it/ search the easiest answer is to copy it as index 2, which will carry over your index settings but not the actual fields that were indexed.
Workflow and index settings troy notes
Adding multiple fields to an index
HCI index options-20171224 1534-2.mp4
HCI workflow settings-20171226 1359-1.mp4 | https://community.hitachivantara.com/thread/14581-how-to-reset-the-search-index-in-hci-v-13 | CC-MAIN-2018-43 | refinedweb | 240 | 75.61 |
Write.
Algorithm to find if linked list contains loops or cycles
Two pointers, fast. Here is the exact algorithm
1) Use two pointers fast and slow
2) Move fast two nodes and slow one node in each iteration
3) If fast and slow meet then linked list contains cycle
4) if fast points to null or fast.next points to null then linked list is not cyclic
Next section contains Java program to check if linked list contains loop or cycle, which is exact implementation of above algorithm. This algorithm is also known as Floyd’s cycle finding algorithm and popularly known as tortoise and hare algorithm to find cycles in linked list.
Java program to check if linked list is circular or not.
This Java program uses LinkedList(not java.util.LinkedList) and Node class from previous example of Linked List, with modification of adding toString() method and appendToTail() method. Also, isCyclic() method of linked list is used to implement logic to find if linked list contains cycle or not. Subsequently isCyclic() returns true if linked list is cyclic otherwise it return false.
/* * Java class to represent linked list data structure. */ public class LinkedList { private Node head; public LinkedList() { this.head = new Node("head"); } public Node head() { return head;} public void appendIntoTail(Node node) { Node current = head; //find last element of LinkedList i.e. tail while(current.next() != null){ current = current.next(); } //appending new node to tail in LinkedList current.setNext(node); } /* * If singly LinkedList contains Cycle then following would be true * 1) slow and fast will point to same node i.e. they meet * On the other hand if fast will point to null or next node of * fast will point to null then LinkedList does not contains cycle. */ public boolean isCyclic(){ Node fast = head; Node slow = head; while(fast!= null && fast.next != null){ fast = fast.next.next; slow = slow.next; //if fast and slow pointers are meeting then LinkedList is cyclic if(fast == slow ){ return true; } } return false; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); Node current = head.next(); while(current != null){ sb.append(current).append("-->"); current = current.next(); } sb.delete(sb.length() - 3, sb.length()); // to remove --> from last node return sb; } } }
Testing linked list for cycle or loop
In this section we will test linked list using Java main method with two linked list, one contains cycle and other is not cyclic. You can even write JUnit test cases for isCyclic() method to test different linked list with circles and loops at different positions. Here is first test where linked list does not contain any cycle.
/** * * Java program to find if LinkedList contains loop or cycle or not. * This example uses two pointer approach to detect cycle in linked list. * Fast pointer moves two node at a time while slow pointer moves one node. * If linked list contains any cycle or loop then both pointer will meet some time. * * @author Javin Paul */ public class LinkedListTest { public static void main(String args[]) { //creating LinkedList with 5 elements including head LinkedList linkedList = new LinkedList(); linkedList.appendIntoTail(new LinkedList.Node("101")); linkedList.appendIntoTail(new LinkedList.Node("201")); linkedList.appendIntoTail(new LinkedList.Node("301")); linkedList.appendIntoTail(new LinkedList.Node("401")); System.out.println("Linked List : " + linkedList); if(linkedList.isCyclic()){ System.out.println("Linked List is cyclic as it contains cycles or loop"); }else{ System.out.println("LinkedList is not cyclic, no loop or cycle found"); } } } Output: Linked List : 101-->201-->301-->401 LinkedList is not cyclic, no loop or cycle found
Now let's change the linked list so that it contains cycle or loop,
//creating LinkedList with 5 elements including head LinkedList linkedList = new LinkedList(); linkedList.appendIntoTail(new LinkedList.Node("101")); LinkedList.Node cycle = new LinkedList.Node("201"); linkedList.appendIntoTail(cycle); linkedList.appendIntoTail(new LinkedList.Node("301")); linkedList.appendIntoTail(new LinkedList.Node("401")); linkedList.appendIntoTail(cycle); //don't call toString method in case of cyclic linked list, it will throw OutOfMemoryError //System.out.println("Linked List : " + linkedList); if(linkedList.isCyclic()){ System.out.println("Linked List is cyclic as it contains cycles or loop"); }else{ System.out.println("LinkedList is not cyclic, no loop or cycle found"); } Output: Linked List is cyclic as it contains cycles or loop
Let me show you an interesting point here, in case you have not noticed already. This is also asked in interviews as, do you see anything suspicious? toString() method of LinkedList class is not checking for cycles or loop and it will throw Exception in thread "main" java.lang.OutOfMemoryError: Java heap space, if you try to print a linked list with cycles. Now, if you are really lucky then they may ask you to find start of loop in linked list. That's exercise for you, but let me give you a hint, look at below diagram of a linked list which contains cycle, red element is the start of cycle. What is special about it? If you look closely, you can see that it's the only node in whole linked list which is next node of other two pointers.
Further Reading
Algorithms and Data Structures - Part 1 and 2
Java Fundamentals, Part 1 and 2
Cracking the Coding Interview - 189 Questions and Solutions
Related Data Structure and Algorithm Interview Questions from Javarevisited Blog
- Difference between array and linked list data structure? (answer)
- Difference between a binary tree)
19 comments :
This same question of cycle detection in linked list is asked to me in Polaris Interview, I didn't know the trick of two pointers :(, Now it seems so easy.
Inside the while loop of isCyclic(), do you need to check whether fast is null after fast forward? like,
if(fast==null || fast == slow ){
return true;
}
.
Javin,
Good post and helps many interviewees.
I think, a (fast == null) check is required as also pointed by @Anonymous. Otherwise, the next condition check at beginning of while loop will throw NPE if fast becomes null
Hello @Ramesh, @Anonymous and @Peter, yes, fast== null check is missing in while loop, my bad. It's updated now. Thanks for pointing that.
For last exercise question, doubly linked list can be used to check loop. If parent pointer is not null it's already messed up.
the link list was circular but it said not circular
the data is like :
101-->201-->301-->401-->501-->601-->701-->201
I think the best way to find the cycles is
traverse from the begining and check in map if the node pointer is in hashmap if present then its cyclic else put the node pointer and move to next.
if you reach till end and you didnt find any duplicate entry in hashmap/hashtable then its not cyclic.. correct me if I am wrong.. ???
Nice post - slow and fast pointer approach is the best. Here is my code from
/**
*;
} ???
Answer :-
1) store value of A3 in some variable (temp).
2) copy the value of A4 to A3.
3) Delete the node A4 (can do that as we can refer to A4 and A5)
4) return temp
how can learn datastructures in java?
@javin I have been asked in recent interview. why the fast pointer is move by 2 node not by 3 or 4 node..
static boolean hasCycle(LinkedList linkedList){
LinkedList.Node slow = linkedList.head().next();
LinkedList.Node fast = linkedList.head().next().next();
while(fast!=null && fast.next()!=null && fast!=slow){
fast = fast.next().next();
slow = slow.next();
}
return fast==slow;
}, yes you are correct. This fast and slow pointer approach is also known as Floyd's Cycle finding algorithm. One more name of this algorithm is "tortoise and hare" cycle detection algorithm.
Copy the A4 data into A3 and remove A4(A3.next = A3.next.next)
Did anybody knows how to check if the linked list is circular without using head,tail or size of the linked list
Hey what if Head is null? That case is not handled!
public static boolean findLoop(Node head) {
boolean retVal = false;
if(head != null) {
Node fst_ptr = head, slw_ptr = head;
while(fst_ptr != null && fst_ptr.next != null) {
fst_ptr = fst_ptr.next.next;
slw_ptr = slw_ptr.next;
if(slw_ptr == fst_ptr) {
retVal = true;
}
}
}
return retVal;
}
This is my code, please let me know where have I been wrong.
The program I have written seems to go in an infinite loop.
Thanks in advance! | http://javarevisited.blogspot.com/2013/05/find-if-linked-list-contains-loops-cycle-cyclic-circular-check.html?showComment=1383696138003 | CC-MAIN-2017-43 | refinedweb | 1,380 | 73.47 |
Contains
struct picotm_treemap and helpers.
More...
#include <stdint.h>
#include "compiler.h"
The data stucture
struct picotm_treemap maps keys to values on single threads. Concurrent look-up by multiple transactions is not supported. Keys can be up to 64 bit in length, values are of type
uintptr_t, so unsigned integers or pointers can be stored.
Initialize a treemap with a call to
picotm_treemap_init().
The second argument is the number of key bits handled per level of the tree hierarchy. Ideally this number is a remainder-free divider of the maximum key length. The maximum key length itself does not have ot be specified. The treemap's implementation will grow the internal tree to adapt to any key.
Call
picotm_treemap_find_value() to retrieve a key's value from the treemap. If the key/value pair is not in the treemap, a creator function can generate a new value as part of the lookup. If you don't supply a creator function, 0 is returned for non-existing values.
The following example returns the value for the key 0x1234 from the treemap, or inserts a new value if the key/value pair is not present.
You can iterate over all key/value pairs stored in the treemap with
picotm_treemap_for_each_value(). It invokes a call-back function for each value. Values will be sorted by their keys' order. The following example prints all key/value pairs to the terminal.
To uninitialize a treemap, call
picotm_treemap_uninit(). This function requires a destroy function for the values. It walk over all keys in the treemap and invokes the destroy function on each key's value.
Invoked by picotm's treemap to call a value.
Invoked by picotm's treemap to create a new value.
Invoked by picotm's treemap to destroy a value.
Retrieves the value for a key from a treemap.
Iterates over all values stored in a treemap.
Initializes a treemap.
Uninitializes a treemap. | http://picotm.org/docs/picotm-doc-0.4.0/dd/dfe/picotm-lib-treemap_8h.html | CC-MAIN-2022-05 | refinedweb | 318 | 68.97 |
Please someone can explain me what's wrong why am I getting this error:
error: control may reach end of non-void function
linearsearch()
#include <stdio.h>
#include <string.h>
#include <cs50.h>
int linearsearch(int key, int array[]);
int main(int argc , string argv[])
{
int key = 0;
int table[]={2,4,5,1,3};
printf("%i is found in index %i\n",key,linearsearch(1,table));
}
int linearsearch(int key, int array[])
{
for(int i = 0;i<5;i++){
if(array[i] == key)
{
return i;
}
else{
return -1;
}
}
}
In the last for loop you're returning something from the function either way, so there shouldn't be any problem (except that your algorithm is wrong: it shouldn't return immediately if not found).
The problem is: the compiler doesn't necessarily see that you're returning whatever the data is. It just sees that don't end your routine by returning something.
Most compilers can figure out simple cases like:
if (x) return 0; else return 1; // not returning anything in the main branch but ok as it's seen as unreachable }
but in your case, you have a
for loop wrapping the return instructions. Compilers are not control flow analysers. They do basic things, but certainly not formal execution. So sometimes they issue a warning where it's "OK" from your point of view.
Anyway, your algorithm is incorrect as mentioned earlier. Fix it by returning -1 only when the loop ends without finding anything.
In that case, you fix your bug AND the warning. So you see the warning was rightly detecting something fishy in your code.
Fixed code:
for (int i = 0; i < 5; i++) { if (array[i] == key) { // found return & exit loop return i; } } // not found, end of loop: return -1 return -1; | https://codedump.io/share/O6tz6lQMMqC3/1/error-control-may-reach-end-of-non-void-function | CC-MAIN-2017-51 | refinedweb | 298 | 70.53 |
Evan Prodromou surprised a number of free software microbloggers in
December 2012 when he announced
that he would be closing down Status.Net, the "Twitter like" software
service he launched in 2008, in favor of his new project, pump.io. But Status.Net's flagship site, Identi.ca has grown into a
popular social-networking hub for the free and open source
software community, and a number of Identi.ca users took the
announcement to mean that Identi.ca would disappear, much to the
community's detriment. Prodromou has reassured users Identi.ca will
live on, though it will move from StatusNet (the software package, as
distinguished from Status.Net, the company) over to pump.io. Since then,
pump.io has rolled out to some test sites, but it is still in heavy
development, and remains something of an unknown quantity to users.
Prodromou has
some markedly different goals in mind for pump.io. The underlying
protocol is different, but more importantly, StatusNet never quite
reached its original goal of becoming a decentralized, multi-site
platform—instead, the debut site Identi.ca was quickly branded
as an open source "Twitter replacement." That misconception hampered
StatusNet's adoption as a federated solution, putting the bulk of the
emphasis on Identi.ca as the sole destination, with relatively few
independent StatusNet sites. The pump.io rollout is progressing
more slowly than StatusNet's, but that strategy is designed to avoid
some of the problems encountered by StatusNet and Identi.ca.
The December announcement started off by saying that Status.Net
would stop registering new hosted sites (e.g., foo.status.net) and
was discontinuing its "premium" commercial services. The software
itself would remain available, and site maintainers would be able to
download the full contents of their databases. Evidently, the
announcement concerned a number of Identi.ca
users, though, because Prodromou posted a follow-up
in January, reassuring users that the Identi.ca site would remain
operational.
But there were changes afoot. The January post indicated that
Identi.ca would be migrated over to run on pump.io (which necessarily
would involve some changes in the feature set, given that it was not
the same platform), and that all accounts which had been active in the
past year would be moved, but that at some point no new registrations
would be accepted.
Indeed Identi.ca stopped accepting new user registrations on March 26. The shutdown of new registrations was timed so that new
users could be redirected to one of several free, public pump.io sites
instead. Visiting
redirects the browser to a randomly-selected pump.io site, currently
chosen from a pool of ten. Users can set up an account on one of the
public servers, but getting used to pump.io may be a learning
experience, seeing as it presents a distinctly different experience
than the Twitter-like StatusNet.
At its core, StatusNet was designed as an implementation of the OStatus
microblogging standard. An OStatus server
produces an Atom feed of status-update messages, which are pushed to
subscribers using PubSubHubbub.
Replies to status updates are sent using the Salmon protocol, while the
other features of Twitter-like microblogging, such as
follower/following relationships and "favoriting" posts, are
implemented as Activity Streams.
The system is straightforward enough, but with a little
contemplation it becomes obvious that the 140-character limit
inherited from Twitter is a completely artificial constraint.
StatusNet did evolve to support longer messages, but ultimately there
is no reason why the same software could not deliver pictures
à la Pinterest or Instagram, too, or handle other types
of Activity Stream.
And that is essentially what pump.io is;.
The code is available at Github; the
wiki explains that the
server currently understands a subset of Activity Streams verbs that
describe common social networking actions: follow,
stop-following, like, unlike,
post, update, and so on. However, pump.io will
process any properly-formatted Activity Streams message, which means
that application authors can write interoperable software simply by
sending compliant JSON objects. There is an example of this as well;
a Facebook-like farming game called Open Farm Game. The game
produces messages with its own set of verbs (for planting, watering,
and harvesting crops); the pump.io test sites will consume and display
these messages in the user's feed with no additional configuration.
The pump.io documentation outlines the other primitives understood
by the server—such as the predefined objects (messages, images,
users, collections, etc.) on which the verbs can act, and the API
endpoints (such as the per-user inbox and outbox). Currently, the demo
servers allow users to send status updates, post images, like or
favorite posts, and reply to updates. Users on the demo servers can
follow one another, although at the moment the UI to do so is
decidedly unintuitive (one must visit the other user's page and click
on the "Log in" link; only then does a "Follow" button become
visible). But Prodromou said in an email that more is still to come.
For those users and developers who genuinely prefer StatusNet, the
good news is that the software will indeed live on. There are
currently two actively-developed forks, GNU social and Free & Social. Prodromou said there
was a strong possibility the two would merge, although there will be a
public announcement with all of the details when and if that happens.
Pump.io itself (and its web interface) are the focus of
development, but they are not the whole story. Prodromou is keen to
avoid the situation encountered at the StatusNet launch, where the
vast majority of new users joined the first demo site (Identi.ca), and
it became its own social network, which ended up consuming a
significant portion of StatusNet's company resources. Directing new
registrations to a randomly-selected pump.io service is one tactic to
mitigate the risk; another is intentionally limiting what pump.io
itself will do.
For instance, while StatusNet could be linked to Twitter or other
services via server-side plugins, pump.io will rely on third-party applications for bridging to
other services. Prodromou cited TwitterFeed and IFTTT as
examples. "My hope is that hackers find pump.io fun to develop
for," he said, "and that they can 'scratch an itch' with
cool bridges and other apps." The narrow scope of pump.io also
means that a pump.io service only serves up per-user content; that is
to say, each user has an activity stream outbox and an inbox
consisting of the activities the user follows, but there is no site-wide
"public" stream—no tag feeds, no "popular notices."
That may frustrate Identi.ca users at the beginning, Prodromou
says, but he reiterates that the goal is to make such second-tier
services easy for others to develop and deploy, by focusing on the
core pump.io API. For example, the pump.io sites forward all messages
marked as "public" to the ofirehose.com site; any developer could
subscribe to this "fire hose" feed and do something interesting with
it. Ultimately, Prodromou said, he hopes to de-emphasize the
importance of "sites" as entities, in favor of users. Users do not care
much about SMTP servers, he said; they care about the emails sent and
received, not about enumerating all of the accounts on the server.
That is true in the SMTP world (one might argue that the only
people who care to enumerate the user accounts on a server probably
have nefarious goals in mind), but it does present some practical
problems in social networking. Finding other users and searching (both on message content
and on metadata) have yet to be solved in pump.io. Prodromou said he
is working on "find your friend" sites for popular services (like
Facebook and Twitter) where users already have accounts, but that
search will be trickier.
Eventually, the plan is for Identi.ca to become just one more
pump.io service among many; the decentralization will mean it is no
harder to follow users on another pump.io server or to carry on a
conversation across several servers than it is to interact with others
on a monolithic site like Twitter. But getting to that future will
place a heavier burden on the client applications, be they mobile,
web-based, or desktop.
Prodromou has not set out a firm timeline for the process; he is
working on the pump.io web application (which itself should be
mobile-friendly HTML5) and simple apps for iOS and Android. In the
medium term, the number of public pump.io sites is slated to ramp up
from ten to 15 or 20. But at some point Prodromou will start directing
new registrations to a free Platform-as-a-Service (PaaS) provider that
offers pump.io as a one-click-install instead (AppFog and OpenShift
were both mentioned, but only as hypothetical examples).
Where pump.io goes from there is hard to predict. Prodromou is
focused on building a product developers will like; he deliberately
chose the permissive Apache 2.0 license over the AGPL because the
Node.js and JavaScript development communities prefer it, he said.
Applications, aggregation, and PaaS delivery are in other people's
hands, but that is evidently what he wants. As he explained it,
running Status.Net took considerable resources (both human and server)
to manage hosted instances and public services like Identi.ca, which
slowed down development of the software itself. "I want to get
out of the business of operating social networking sites and into the
business of writing social networking software."
At some point in the next few months, Identi.ca will switch over
from delivering OStatus with StatusNet to running pump.io. That will
be a real watershed moment; as any social-networking theorist will
tell you, the value of a particular site is measured by the community
that uses it, not the software underneath. Identi.ca has grown into a
valued social-networking hub for the free software community;
hopefully that user community survives the changeover, even if it
takes a while to find its bearings again on the new software platform.
Scott Moreau is an established contributor to both Wayland (the protocol
definition and implementation) and Weston (the reference compositor
implementation for Wayland). A quick search of the project's repositories
shows that he contributed 84 changes to the project since the beginning of
2012 — about 2% of the
total. Until recently, he was an active and often helpful presence on the
project's mailing lists. So it might come as a surprise to learn that
Scott was recently banned from the Wayland IRC
channel and, subsequently, the project's mailing list. A simple
reading of the story might suggest that the project kicked him out for
creating his own fork of the code; when one looks closer, though, the story
appears to be even simpler than that.
Last October, Wayland project leader Kristian Høgsberg suggested that it might be time to add a
"next" branch to the Weston repository for new feature development. He
listed a few patches that could go there, including "Scott's minimize etc
work." Scott responded favorably at the
time, but suggested that Wayland, too, could use a "next" branch. It does
not appear that any such branch was created in the official repositories,
though. So, for some months, the idea of a playground
repository for new features remained unimplemented.
In mid-March 2013, Scott announced the creation
of staging repositories for both Wayland and Weston, and started responding
to patch postings with statements that they had been merged into
"gh next". Two days later, he complained that "Kristian has
expressed no interest in the gh next series or the benefits that it
might provide" and that Kristian had not merged his latest patches.
He also let
it be known that he thought that Weston could be developed into a full
desktop environment — a goal the Wayland developers, who are busy enough
just getting the display manager implemented properly, do not share.
The series of messages continued with this
lengthy posting comparing the "gh next" work with the Compiz window
manager and its Beryl fork, claiming that, after the two projects merged back together, most of
the interesting development had come from the Beryl side. Similarly, Scott
intends "gh next" to be a place where developers can experiment with shiny
new features, the best of which can eventually be merged back into the
Wayland and Weston repositories. Scott's desire to "run ahead" is seen as
a distraction by many Wayland developers who would rather focus on
delivering a solid platform first, but that is not where the real
discord lies.
There was, for example, a certain amount of disagreement with Scott's
interpretation of the Compiz story. More importantly, he was asked to, if
possible, avoid forking Wayland and making incompatible protocol changes
that would be hard to integrate later. When Scott was shown how his
changes could be made in a more cooperative manner, he responded "This sounds great but this is
not the solution I have come up with." Meanwhile, the lengthy
missives to the mailing list continued. And, evidently, he continued a pattern of behavior
on the project's IRC channel that fell somewhere between "unpleasant" and
"abusive." Things reached a point where other Wayland developers were
quite vocal about their unwillingness to deal with Scott.
What developers in the project are saying now is that the fork had nothing
to do with Scott's banishment from the Wayland project. Even his plans to
make incompatible changes could have been overlooked, and his eventual
results judged on their merits when the time came. But behavior that made
it hard for everybody else to get their work done was not something that
the project could accept.
There is no point in trying to second-guess the project's leadership here
with regard to whether Scott is the sort of "poisonous person" that needs
to be excluded from a development community. But there can be no doubt
that such people can, indeed, have a detrimental effect on how a community
works. When a community's communication channels turn unpleasant or
abusive, most people who do not have a strong desire to be there will find
somewhere else to be — and a different project to work on. Functioning
communities are fragile things; they cannot take that kind of stress
indefinitely.
Did this community truly need to expel one of its members as an act of self
preservation? Expulsion is not an act without cost; Wayland has, in this
case, lost an enthusiastic contributor. So such actions are not to be
taken lightly; the good news is that our community cannot be accused of
doing that. But, as long as our communities are made up of humans, we will
have difficult interactions to deal with. So stories like those outlined
above will be heard again in the future.
Python core developer Raymond Hettinger's PyCon 2013 keynote had elements of a revival meeting
sermon, but it was also meant to spread the "religion" well beyond those
inside the meeting tent. Hettinger specifically tasked attendees to use
his "What makes Python awesome?" talk as a sales tool with
management and other Python
skeptics. While he may have used the word "awesome" a few too many times
in the talk,
Hettinger is clearly an excellent advocate of the language from a
technical—not just cheerleading—perspective.
He started the talk by noting that he teaches "Python 140 characters at a
time" on Twitter (@raymondh).
He has been a core developer for twelve years, working on builtins, the
standard library, and a few core language features. For the last year and
a half, Hettinger has had a chance to
"teach a lot of people Python". Teaching has given him a perspective on
what is good and bad in Python.
Python has a "context for success", he said, starting with
its license. He and many others would never have heard of Python if it
were not available under an open source license. It is also important for
a "serious language" to have commercial distributions and the support that
comes with those.
Python also has a "Zen", he said, which is
also true of some other languages, like Ruby, but "C++ does not have Zen".
Community is another area
where Python excels. "C is a wonderful language", but it doesn't have a
community, Hettinger said.
The PyPI repository for Python
modules and packages is another important piece of the puzzle. Python also
has a "killer app", in fact it has more than one. Zope, Django, and pandas are all killer apps, he said.
Windows support is another important attribute of Python. While many in the
audience may be "Linux weenies" and look down on Windows users, most of the
computers in the world are running Windows, so it is important for Python
to run there too, he said. There are lots of Python books available,
unlike some other languages. Hettinger is interested in Go, but there
aren't many books on that language.
All of these attributes make up a
context for success, and any language that has them
is poised to succeed. But, he asked, why is he talking about the good
points of
Python at PyCon, where
everyone there is likely to already know much of what he is saying? It is
because attendees will often be in a position to recommend or defend
Python. Hettinger's goal is for attendees to be able to articulate what is
special about the language.
The Python language itself has certain qualities that make it special, he
said, starting with "ease of learning". He noted that David Beazley runs
classes where students are able to write "amazing code" by the end of the
second day. One of the exercises in those classes is to write a web log
summarizing tool, which shows how quickly non-programmers can learn Python.
Python allows for a rapid development cycle as well. Hettinger used to
work at a high-frequency trading company that could come up with a trading
strategy in the morning and be using it by the afternoon because of
Python. Though he was a good Java programmer, he could never get that
kind of rapid turnaround using Java.
Readability and beauty in a language is important, he said, because it
means that programmers will want to program in the language. Python
programmers will write code on evenings and weekends, but "I never code C++
on the weekend" because it is "not fun, not beautiful". Python is both, he
said.
The "batteries included" philosophy of Python, where the standard library
is part of the language, is another important quality. Finally, one of
Hettinger's favorite Python qualities is the protocols that it defines,
such as the database
and WSGI
protocols. The database protocol means that you can swap
out the underlying database system, switching to or from MySQL, Oracle,
or PostgreSQL without changing the code to access the database. Once you
know how to access one of them through Python, you know how to access them all.
As an example of the expressiveness and development speed of the language,
Hettinger put up a slide
with a short program. In a class he was teaching, someone asked how he
would deduplicate a disk full of photos, and in five minutes he was able to
come up with a fifteen-line program to do so. It is a real testament to
the language that he could write that program live in class, but even more
importantly, he can teach others to do the same. That one slide shows
"a killer feature of the language: its productivity, and its beauty and
brevity", he said.
But, there is a problem with that example. A similar slide could be
created for Ruby or Perl, with roughly the same brevity. That would be
evidence for the "all scripting languages are basically the same, just with
different syntax" argument that he hears frequently from software
executives. But all scripting languages are not the same, he said.
That may have
been true in 2000, but "we've grown since then"; there are lots of features
that separate Python from the pack.
First up on Hettinger's list of "winning language features" is the required
indentation of the language. It was an "audacious move" to make that choice
for the language, but it contributes to the "clean, uncluttered" appearance
of the code. He claimed that Python was the first to use indentation that
way, though he later received a "Miranda warning" from an audience member
as the Miranda language uses indentation and predates Python. People new to
the language sometimes react negatively to the forced indentation, but it
is a net positive. He showed some standard examples of where C programs
can go wrong because the indentation doesn't actually match the control
flow, which is impossible with Python. Python "never lies with its visual
appearance", which is a winning feature, he said.
The iterator protocol is one of his favorite parts of the language. It is
a "design pattern" that can be replicated in languages like Java and C++,
but it is "effortless to use" in Python. The yield statement can
create iterators everywhere. Because iterators are so deeply wired into
the language, they can be used somewhat like Unix pipes. So the shell
construct:
cat filename | sort | uniq
sorted(set(open(filename)))
sum(shares*price for symbol, shares, price in port)
SELECT SUM(shares*price) FROM port;
One of his favorite things to teach about Python are list comprehensions.
The idea came from mathematical set building notation. They "profoundly
improve the expressiveness of Python", Hettinger said. While list
comprehensions might at first appear to violate the "don't put too much on
one line" advice given to new programmers, it is actually a way to build up a
higher-level view. The examples he gave can fairly easily be expressed as
natural
language sentences:
[line.lower() for line in open(filename) if 'INFO' in line]
sum([x**3 for x in range(10000)])
The generators feature is a "masterpiece" that was stolen from the Icon language.
Now that Python has generators, other languages are adding them as
well. Generators allow Python functions to "freeze their execution" at a
particular point and to resume execution later. Using generators makes
both iterators
and coroutines easier to implement in a "clean, readable, beautiful" form.
Doing things that way is something that Python has "that others don't".
His simple example
showed some of the power of the feature:
def pager(lines, pagelen=60):
for lineno, line in enumerate(lines):
yield line
if lineno % pagelen == 0:
yield FORMFEED
Generator expressions come from Hettinger's idea of combining generators
and list comprehensions. Rather than requiring the creation of a list,
generators can be used in expressions directly:
sum(x**3 for x in range(10000))
But generators have a problem: they are a "bad date". Like a date that can
only talk about themselves, generators can only talk, not listen. That led
to the idea of two-way generators. Now
generators can accept inputs in the form of send(),
throw(), and close() methods. It is a feature that is
unique to Python, he said, and is useful for implementing coroutines. It
also helps "tame" some of the constructs in Twisted.
Decorators have an interesting history in Python. They don't really add
new functionality that can't be done other ways, so the first few times
they were proposed, they were turned down. But they kept being proposed, so
Guido van Rossum (Python's benevolent dictator for life) used a tried and
true strategy to make the problem go away: he said that if everyone could
agree on a syntax for decorators, he would consider adding them. For the
first time ever, the entire community came together and agreed on a
syntax. It
presented that agreement to Van Rossum, who agreed: "you shall have
decorators, but not the syntax you asked for".
In retrospect,
the resistance to decorators (from Van Rossum and other core developers)
was wrong, Hettinger said, as they have turned out to be a "profound
improvement to the language". He pointed to the lightweight web frameworks
(naming itty, Flask, and CherryPy) as examples of how decorators
can be used to create simple web applications. His one
slide example of an itty-based web service uses decorators for
routing. Each new service is usually a matter of adding three lines or so:
@get('/freespace')
def compute_free_disk_space(request):
return subprocess.check_output('df')
"Who's digging Python now?", he asked with a big grin, as he did in spots
throughout the
talk—to much applause.
The features he had mentioned are reasons to pick Python over languages
like Ruby, he said. While back in 2000, Python may have been the
equivalent of other scripting languages, that has clearly changed.
There are even more features that make Python compelling, such as the
with
statement. Hettinger thinks that "context managers" using
with may turn
out to be as
important to programming as was the invention of the subroutine. The
with statement is a
tool for making code "clean and beautiful" by setting up a temporary
context where the entry and exit conditions can be ensured (e.g. files
closed or locks unlocked) without sprinkling try/finally
blocks all over. Other languages have a with, but they are
not at all the same as Python's. The best uses for it have not yet
been discovered, he said, and suggested that audience members "prove to the
world that they are awesome", so that other languages get them.
The last winning feature that he mentioned was one that he initially didn't
want to be added: abstract base classes. Van Rossum had done six months of
programming in Java and "came back" with abstract base classes. Hettinger
has come to embrace them. Abstract base classes help clarify what a sequence
or a mapping
actually is by defining the interfaces used by those types. They are
also useful for
mixing in different classes to better organize programs and modules.
There is something odd that comes with abstract base classes, though.
Python uses "duck typing", which means that using isinstance() is
frowned upon. In fact, novice Python programmers spend their first six
months adding isinstance() calls, he said, and then spend the next
six months taking them back out.
With abstract base classes, there is an addition to the
usual "looks like a duck, walks like a duck, quacks like a duck" test
because isinstance() can lie. That leads to code that uses:
"well, it said it was
a duck, and that's good enough for me", he said with a laugh. He thought
this was "incredibly weird", but it turns out there are some good use cases
for the feature. He showed an example
of using the collections.Set abstract base class to create a
complete list-based set just by implementing a few basic operations. All
of the
normal set operations (subset and superset tests, set equality, etc.) are
simply inherited from the base class.
Hettinger wrapped up his keynote with a request: "Please take this
presentation and go be me". He suggested that attendees present it to
explain what Python has that other languages are missing, thus why Python
should be
chosen over a language like Ruby. He also had "one more thing" to note:
the Python community has a lot of both "established superstars" as
well as "rising young superstars". Other languages have "one or two
stars", he said, but Python has many; just one more thing that Python has
that other languages don't.
Page editor: Jonathan Corbet
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/543791/ | CC-MAIN-2013-48 | refinedweb | 4,645 | 61.67 |
In this lecture, we discuss threads and in particular the use if AsyncTask.
Your UI runs on a single thread to interact with the user -- this is the main thread. Therefore all code will run in this thread which might result in poor performance if you have a computationally intensive operation that could be run in another thread; for example, if your code is loading a file over the Internet you UI is completely blocked. This is not smart design.
The solution to this is simple: If you have computationally demanding functions or slow running operations the best solution if to run those tasks asynchronously from the UI threads.
Note, we will want to off load processing for inserting and querying the database for MyRuns3. We'll use an AsyncTask to insert and a loader (i.e., specifically AsyncTaskLoader) get database entries. For more on Loaders read the course book or:
We have discussed a number of AsyncTask examples in class:
AsyncTaskCountDownDemo.zip app to demonstrate how to create an AsyncTask. As discussed below this simple example counts down in the background thread and posts the current count to the UI thread. We disuss this in the notes below.
AsyncTaskListViewOfProfs.zip as shown in class updates the UI threads ListView by adding to the adapter in the onPostExecute() method. It emulates, what looks like, a terribly janky UI. onProgressUpdate() updates the UI.
DownloadImageFromWeb.zip downloads a large image from a webserver in the doInBackground() thread then when the image is completely downloaded onPostExecute() set of the image on the UI (a scaled version) using imageView.setImageBitmap(bitmap).
DatabaseWithLoader.zip uses an AsyncTaskLoader to offload getAllComments() fom the UI thread to a worker thread. We update the DatabaseDemo code we looked at last week to do this.
The notes below relate specifically to the AsyncTaskCountDownDemo example, but more generally to all the code examples listed above.
Some excellent references.
In this lecture, we discuss AsyncTask: the AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started via the execute() method. AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.). The method calls the doInBackground() and the onPostExecute() method. The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread. The onPostExecute() method synchronize itself again with the user interface thread and allows to update it. This method is called by the framework once the doInBackground() method finishes.
To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask
The demo app include in the lecture includes an activity that starts a AsyncTask to first count down from 15, as shown below. Different text is rewritten out to the UI in different thread components of the UI and background thread, as shown below.
A service needs to be defined in the manifest as shown below.
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Starts the CountDownTask new CountDownTask().execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
In the code below we first see how the AsyncTask operates.
AsyncTask's generic types The three types used by an asynchronous task are the following:
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
When an asynchronous task is executed, the task goes through 4 steps:
We use AsyncTasks in MyRuns:
For MyRun5, you can use an AsyncTask to run the activity classifier at the background because it is computationally intensive and you do not want to block the UI thread.
For MyRuns6, you can use another AsyncTasks to upload history entries to the cloud. Again, if you did this in the main UI thread the user experience would be poor.
Now let's look at the code for the AsyncTask demo app example.
In the first snippet of code text for starting the count down is displayed using on preExecute(), which is invoked on the UI thread before the task is executed. This step is normally used to setup the task, by showing START in the user interface.
private class CountDownTask extends AsyncTask<Void, Integer, Void>{ // A callback method executed on UI thread on starting the task @Override protected void onPreExecute() { // Getting reference to the TextView tv_counter of the layout activity_main TextView tvCounter = (TextView) findViewById(R.id.tv_counter); tvCounter.setText("*START*"); }
This is the main worker thread of the task. doInBackground() is invoked on the background thread (which is different from the UI thread) immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. Typically.
In the case of the code example, we do not return anything but we publish the count value to the UI thread using publishProgress(i) which invokes onProgressUpdate() as shown below in the snippet of code.
// A callback method executed on non UI thread, invoked after // onPreExecute method if exists // Takes a set of parameters of the type defined in your class implementation. This method will be // executed on the background thread, so it must not attempt to interact with UI objects. @Override protected Void doInBackground (Void... params) { for(int i=15;i>=0;i--){ try { Thread.sleep(1000); publishProgress(i); // Invokes onProgressUpdate() } catch (InterruptedException e) { } } return null; }
As mentioned above onProgressUpdate(Progress...) is invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. In our case publishProgress(Progress...) displays the current count to the UI layout in large font.
// A callback method executed on UI thread, invoked by the publishProgress() // from doInBackground() method // Overrider this handler to post interim updates to the UI thread. This handler receives the set of parameters // passed in publishProgress from within doInbackground. @Override protected void onProgressUpdate (Integer... values) { // Getting reference to the TextView tv_counter of the layout activity_main TextView tvCounter = (TextView) findViewById(R.id.tv_counter); // Updating the TextView tvCounter.setText( Integer.toString(values[0].intValue())); }
The final method of the AsyncTask is the onPostExecute(Result), which is invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter. In our coded example there is no result passed back from the doInBackground() method. Here we simple display DONE to the UI layout.
// A callback method executed on UI thread, invoked after the completion of the task // When doInbackground has completed, the return value from that method is passed into this event // handler. @Override protected void onPostExecute(Void result) { // Getting reference to the TextView tv_counter of the layout activity_main TextView tvCounter = (TextView) findViewById(R.id.tv_counter); tvCounter.setText("*DONE*"); } } } | https://www.cs.dartmouth.edu/~campbell/cs65/lecture20/lecture20.html | CC-MAIN-2018-39 | refinedweb | 1,190 | 55.74 |
I am trying to insert records to a database from jsp. The records are multiple line items returned from a Post action in a form. How do I arrange the records so that I can insert them properly? I can get one record to insert, but not more than one. Please show a code sample.
Created May 4, 2012
Ryan Breidenbach Since I don't know what your JSP page look like, I will simulate a similar form:
<FORM ACTION="post" .... > Line Item: <INPUT TYPE="text" NAME="lineItem"><BR> Line Item: <INPUT TYPE="text" NAME="lineItem"><BR> ... </FORM>This would be the form in the JSP that is submitting multiple line items. Now, you would have a servlet that processes this request, extacts the text from the form and inserts it into a database:
public class LineItemServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) { String lineItems[] = request.getParameterValues("lineItem"); for (int i = 0; i < lineItems.length; i++) { insertLineItem(lineItems[i]); } } private void insertLineItem(String lineItem) { /* * Here is where the data access code would be. You could access * the database from the servlet or use another class that handle data access. */ } }This is a very minimalistic approach to your problem, but is should work. Also, you don't have to name all the parameters the same, I just think it is easier for handling multiple parameters of the same type.
| http://www.jguru.com/faq/view.jsp?EID=227454 | CC-MAIN-2016-50 | refinedweb | 231 | 64.41 |
The
JFileChooser dialog class is one of the most useful classes that Swing provides. It allows users to choose either a single file or multiple files that match specified file filters. It provides Java programs with a platform-independent GUI component that does the same job as Internet Explorer under Microsoft Windows and Unix's File Manager.
Imagine the following scenario: your user wishes to open a specific file on a specific drive so that she can edit it using your text-editing program. How do you help her do this? Windows and Unix applications provide a file dialog box, allowing the user to select the file she wishes to see. Wouldn't it be nice if the same capability existed in Java? Fortunately, there is
JFileChooser, a platform-independent version of this file dialog box that provides this capability.
In this article, I'll show you how to use
JFileChooser effectively, as well as help you avoid some of its pitfalls. I'll show you how to set filters so that your users only see certain file types, how to set and handle the directories, and how to determine which files the user has selected.
A simple JFileChooser
Swing provides a free, platform-independent
JFileChooser
class. To use it, all you need to do is instantiate it (as you would with any other object) and show it to the user.
//for a default JFileChooser using the default directory JFileChooser fc = new JFileChooser(); fc.showOpenDialog(parentComponent) //where the 'parentComponent' is normally //a JFrame or a JDialog.
Since I have not specified the directory that the
JFileChooser should use, it will use a default. Since there is no concept of a current directory in Java,
JFileChooser defaults to using the
user.dir, which is defined in the system properties. The
JFileChooser has six constructors. Three of these are of particular interest to us:
JFileChooser(): Creates a
JFileChooserpointing to the user's home directory
JFileChooser(File currentDirectory): Creates a
JFileChooserusing the given
Fileas the path
JFileChooser(String currentDirectoryPath): Creates a
JFileChooserusing the given path
By using the last two constructors listed above, you can set the initial directory. The following examples demonstrate how to do this in a Windows environment:
//with the string representation of the path JFileChooser fc = new JFileChooser("C:\\temp\\"); fc.showOpenDialog(parentComponent)
//using a file object as the directory rather than a String File file = new File("C:\\temp\\"); JFileChooser fc = new JFileChooser(file); fc.showOpenDialog(parentComponent)
Each of the examples above creates a
JFileChooser
that displays the contents of the default or specified directory to the user. The filters (marked as such on the figure above) will default to All Files and *.*.
Handling the user's response
Displaying the
JFileChooser
is all well and good, but as of yet we have no way to obtain the user's response. As it stands, any choice the user makes will cause the
JFileChooser
dialog to disappear, without the program ever doing anything about the user's actions. Programs can determine which file the user selected in the following manner:
JFileChooser fc = new JFileChooser(); //the "this" in the below code is the JFrame that acts as the //parent to the JFileChooser dialog. int returnVal = fc.showOpenDialog(this); //declare the file object File selectedFile = null; //OR handle multiple files with // File[] selectedFiles; //this accounts for multiple selected files. //Query the JFileChooser to get the input from the user if(returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = fc.getSelectedFile(); // OR // selectedFiles = fc.getSelectedFiles(); //to handle multiple returns. }
The code fragment above allows the user to select a file, so that the underlying program can handle the selection in an appropriate manner (open it, delete it, copy it, and so forth). It's that simple, at least for a simple
JFileChooser
.
Tailoring the filters
Filters are a mechanism you can use to manipulate what the user can select, and, more importantly, manipulate what the user initially sees when first displaying
JFileChooser
. The last thing a user wants to do is scroll up and down a directory tree, hunting through every file in the system, looking for a specific file. For example, if you are writing an HTML editor, then the user will initially want to see only files with
.html
and
.htm
extensions. Later, when she wants to add a picture, she would only be interested in seeing image files (those with extensions like
.gif
,
.jpg
,
.tiff
, and so on). Therefore, you would want to filter the files so that only the image files are displayed to the user. To implement a file filter, you have to write a class that extends the
FileFilter
class, which is an abstract class, and implement the following methods:
boolean accept(java.io.File file) String getDescription()
The
accept
method is the engine of the
FileFilter
class. The
JFileChooser
passes a file to the
FileFilter
objects and asks the
FileFilter
to determine whether or not it should be displayed to the user. The
FileFilter
code must answer the following questions:
- If the file is actually a directory, then should this directory be displayed to the user?
- Does the file have the extension(s) which the user wants to see?
getDescription
is the method that is used to populate the description box of the file filters (as shown in the figure above). These two methods will then be used to tailor the
JFileChooser
. As an example, the
HTMLFilter
subclass below displays only HTML files:
import java.io.File; /** Class to filter files for .html and .htm only
@author Jon Sharpe */ public class HTMLFilter extends javax.swing.filechooser.FileFilter { /** This is the one of the methods that is declared in the abstract class */ public boolean accept(File f) { //if it is a directory -- we want to show it so return true. if (f.isDirectory()) return true; //get the extension of the file String extension = getExtension(f); //check to see if the extension is equal to "html" or "htm" if ((extension.equals("html")) || (extension.equals("htm"))) return true; //default -- fall through. False is return on all //occasions except: //a) the file is a directory //b) the file's extension is what we are looking for. return false; } /** Again, this is declared in the abstract class
The description of this filter */ public String getDescription() { return "HTML files"; } /** Method to get the extension of the file, in lowercase */ private String getExtension(File f) { String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) return s.substring(i+1).toLowerCase(); return ""; } }
Once you have created a filter, you can use it on files. This is handled internally by the
JFileChooser
dialog, and all you have to do is apply the filter to the
JFileChooser
class. There are two ways of applying the filters to the
JFileChooser
: by setting or adding them.
Setting filters
Setting the filter overrides
JFileChooser
's default action, which is *.*. Once you have set the filters, the default will become whatever you have set it to, rather than *.*.
//fc declared as above fc.setFileFilter(new HTMLFilter());
Setting a filter will remove any filters that have been added or previously set.
Adding filters
When a filter is added to
JFileChooser
, it is appended to the list of filters already stored internally. In my experience, the last file to be added or set is the one that is first displayed to the user.
//fc declared as above fc.addChoosableFileFilter(new HTMLFilter());
Fun and games
Swing has some problems and traps that can catch unwary programmers, just as other parts of the JDK and the Java class libraries do. Java 1.1 has a reputation for behaving unexpectedly; for example, it has inconsistent naming strategies, in which methods do not behave the way their names suggest. Most of these behavioral problems have been ironed out in Java 2, but there are still some pitfalls you'll want to avoid. The
JFileChooser
is no exception; it has a couple traps that are absolute beauties. There are also ways that some thought can make coding and handling the
JFileChooser
a lot easier.
The loading trap
One thing most people don't consider when they are creating, handling, and manipulating the
JFileChooser
is its performance on multiple platforms. I have an HTML tool that uses a
JFileChooser
dialog to let users select files. I initially had the
JFileChooser
create and populate itself when the Open command was activated. I developed and tested the code on a Windows 95 box, running JDK 1.3 beta, with four mapped drives (a floppy drive, two 1 GB hard drives, and my CD-ROM). It ran fine. I then moved the code over to a Windows NT box, running JDK 1.2, which has sixteen mapped drives, and it took nearly two minutes for the
JFileChooser
to appear. The reason: the Windows NT machine has nearly 200 GB of mapped drives, and the
JFileChooser
runs through all of that storage space in order to create its file map. Going through 200 GB takes time, especially when you're trying to do it over a slow network. I had to find a way to hide the process of populating the
JFileChooser
from the user. My solution to the problem was to first make the
JFileChooser fc
a class object. Therefore, I had to create and populate it only once (so long as I did not set it to null after I had finished). All I had to do was alter and reset the filters on it to display different file types. Next, once the GUI HTML tool had finished loading and just before the constructor terminated, I started a separate thread and allowed the
JFileChooser
to populate in the background. I also disabled the Open menu item until after the
JFileChooser
had finished loading. There are, of course, tradeoffs that I made here:
- On bad days, when the network is really slow, it can take two or more minutes before the
JFileChoosercan be used.
- You only get one
JFileChooserobject to work with. This isn't a major problem, but this object is always referenced, and it will always be populated, taking up memory and space.
- If you add a new file and don't refresh the filters, you run the chance that new files will be missed when you display the
JFileChooser.
The FileFilter trap
There are several problems with how the
JFileChooser
handles filters. These include:
- In Java 1.2, if you set a file filter, you will lose the default *.*. This has been fixed in Java 1.2.2 and later. If you don't want a *.* option for some reason, however, there is no way to suppress it in Java 1.2.2 and later.
- In Java 1.2, if you set a file filter, it will be the default choice in the filter list. However, in Java 1.2.2 and later, the last filter you added will be the default in the list.
I have noted these problems on Windows platforms, so it may be a Windows-specific problem, rather than one that occurs on all Java VMs.
FileFilters
Creating a file filter class can be somewhat of a pain, as the vast majority of the code is purely replicated from any other class that you use to filter files. So why not write a generic class that can handle any type of file extension and have any type of description associated with the files being filtered?
GenericFileFilter
, provided in the
section below, is such a class. You construct it in the following way:
String fileExts = {"html","htm"}; //construct it giving it an array of file //extensions and a description string GenericFileFilter html = new GenericFileFilter(fileExts, "HTML Files");
This is a lot simpler. You can then use the created file filter in the same way as any other file filter.
A few general issues
The following is a list of general issues that are worth noting when using a
JFileChooser
.
- Java does not have a notion of a current directory. The default for the system is the
user.dir, which is picked up from the system properties.
- When you are writing file filters, you only very rarely want to exclude the directories.
- Filter text belongs in resource bundles if you expect to localize your application.
- Load time can kill your application if it needs to pause for a few moments to load up the
JFileChooser.
- The filters on Java 1.2 and 1.2.2 (on Windows) behave differently, and not in the most logical ways. This might confuse the user.
- Even though
JFileChooserhas the method
getFileFilters, which returns an array of file filters, it does not have the methods
setFileFilters(FileFilter[] in)or
addChoosableFileFilters(FileFilter[] in). Again, this is somewhat illogical.
Conclusion
JFileChooser
is a simple and clean class that you can use to add an effective touch to your application. Because it is a Swing component, the actual look and feel will vary from platform to platform, leading users to believe that they are using a native tool rather than cross-platform Java.
JFileChooser
does have some features that make it illogical and tricky to program, as well as difficult for the user to understand. However, careful programming and a small amount of thought can bypass most of the problems.
Learn more about this topic
- The source code for
GenericFileFilter
- The online Sun tutorial for
JFileChooser | https://www.javaworld.com/article/2077588/learn-java/java-tip-85--fun-and-games-with-jfilechooser.html | CC-MAIN-2018-22 | refinedweb | 2,224 | 63.19 |
Opened 7 years ago
Closed 5 years ago
#1739 closed defect (fixed)
Language switch on wxGUI doesn't affect all strings
Description
Switch the language to any other (Settings > Pref > Appearance tab)
Open GRASS again
wxGUI is in the selected language, but error messages are not (try to find one).
Change History (7)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
comment:3 Changed 7 years ago by
I will test again on the Mac when I get back to town in a couple days. But as of a week or 2 ago, this did not work at all on the Mac for 6.4.3.
Michael
comment:4 Changed 7 years ago by
I found more examples where translated strings are ignored:
- Map Display buttons flags
- Dropdown list "Element list:" at Preferences -> Settings -> Appearance tab
comment:5 Changed 7 years ago by
I have completely changed the gettext usage in wxGUI.
As reported by mmetz and MilenaN, the translation was active only in the files where
gettext.install function was called. Adding
gettext.install function call to the file enabled translation for the particular file, although according to the documentation one and only one call of
gettext.install function should be enough (Python gettext localizing your application). The reason why it is not working is not known.
However,
gettext.install function is adding the underscore (
_("...")) function into the
__builtins__ module. This makes life of tools such as
pylint and
pep8 (and maybe also
doctest) harder and thus usage of
gettext.install function is not considered as a good practice by some most notably Django project, moreover there might by also some problems with unicode which are not clear to me (see this blog post).
Now I've implemented better different practice of using gettext which is supposed to be more general since it is also usable for Python modules (in the sense of libraries). The underscore function is no longer build-in (in global namespace) and must by defined (or imported) explicitly in every file.
Code to enable translation for the file and define undescore function:
import gettext _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
In the case when the translation is not available and exception is thrown (e.g., during compilation, maybe only with different locale). For this case I added the null translation underscore function (there is some way using gettext, but this should be enough). No error is reported in this case (I don't like it, but I don't know how to report it and not introduce some strange message during compilation).
The full code for enabling translation:
try: import gettext _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext except IOError: # using no translation silently def null_gettext(string): return string _ = null_gettext
It is possible to just import the underscore function and since the code is long the function is exposed by (
gui/wxpython/)
core.utils module and can be imported by others:
from core.utils import _
Some modules cannot use the import since they are imported by
core.utils. These modules have to use the larger code above. (This could be changed in the future by introducing the
core.translations module which needs to be on the were top of the import tree).
This was implemented in the r57219 and r57220 (first changesets contained bug, that's why committed in parts). These changesets (for trunk) fix the issue specified in the comment:4 by MilenaN. (Both changesets are hopefully easily revertable if necessary).
However, there is still issue with strings in
lib/python as specified in comment:2 by marisn. For GRASS 6 the string are no even generated as noted in comment:2. For GRASS 7 the strings are generated and I'm getting the translation. However,
grass.script modules are using
gettext.install which could be OK (but I thing it isn't) for GRASS Python modules but it is wrong when
grass.script and friends are used from wxGUI. So this should be probably changed too (very bad practice, against manual and this method did not work for wxGUI), but this means to change not only all the files. I'm not sure about GRASS Python modules and other libraries such as
temporal or
pygrass. However, the modules seems to work, so there is no pressure for the change.
comment:6 follow-up: 7 Changed.
comment:7 Changed.
No complains since then, so closing as fixed. Feel free open a new ticket if you encounter any other problems.
Related/unresolved:
If I understood correctly from non-helpful bug report, issue is with strings reported by Python parser preprocessor (or whatever it is).
Issue is twofold:
First part can be solved by (diff for 6.4 svn):
Still even after applying supplied patch, translated strings are ignored in module error dialogs. My guess - something with passing LANG to child processes. Somebody with better understanding of Python+parser magic should look into it.
Steps to reproduce issue: | https://trac.osgeo.org/grass/ticket/1739 | CC-MAIN-2020-05 | refinedweb | 842 | 63.39 |
(Batch) gradient descent algorithm
Gradient descent is an optimization algorithm that works by efficiently searching the parameter space, intercept($\theta_0$) and slope($\theta_1$) for linear regression, according to the following rule:\[\begin{aligned} \theta := \theta -\alpha \frac{\delta}{\delta \theta}J(\theta). \end{aligned} \]
Note that we used '$:=$' to denote an assign or an update.
The \(J(\theta)\) is known as the cost function and \(\alpha\) is the learning rate, a free parameter. In this tutorial, we're going to use a least squares cost function defined as following:\[\begin{aligned} J(\theta) = \frac{1}{2m}\sum_{i=1}^m (h_\theta(x^{(i)})-y^{(i)})^2, \end{aligned} \]
where \(m\) is the total number of training examples and $h_\theta(x^{(i)})$ is the hypothesis function defined like this:\[\begin{aligned} h_\theta(x^{(i)}) = \theta_0 + \theta_1 x^{(i)} \end{aligned} \]
where the super script $(i)$ is used to denote the $i^{th}$ sample (we'll save subscripts for the index to a feature when we deal with multi-features).
We need derivatives for both $\theta_0$ and $\theta_1$:\[\begin{aligned} \frac{\partial}{\partial \theta_0}J(\theta_0, \theta_1) = \frac{1}{m} \sum_{i=1}^m (h_\theta(x^{(i)})-y^{(i)}) \end{aligned} \] \[\begin{aligned} = \frac{1}{m} \sum_{i=1}^m (\theta_0 + \theta_1 x^{(i)}-y^{(i)}) \end{aligned} \] \[\begin{aligned} \frac{\partial}{\partial \theta_1}J(\theta_0, \theta_1) = \frac{1}{m} \sum_{i=1}^m (h_\theta(x^{(i)})-y^{(i)})x^{(i)} \end{aligned} \] \[\begin{aligned} = \frac{1}{m} \sum_{i=1}^m (\theta_0 + \theta_1 x^{(i)}-y^{(i)})x^{(i)} \end{aligned} \]
The following code runs until it converges or reaches iteration maximum. We get $\theta_0$ and $\theta_1$ as its output:
import numpy as np import random import sklearn from sklearn.datasets.samples_generator import make_regression import pylab from scipy import stats def gradient_descent(alpha, x, y, ep=0.0001, max_iter=10000): converged = False iter = 0 m = x.shape[0] # number of samples # initial theta t0 = np.random.random(x.shape[1]) t1 = np.random.random(x.shape[1]) # total error, J(theta) J = sum([(t0 + t1*x[i] - y[i])**2 for i in range(m)]) # Iterate Loop while not converged: # for each training sample, compute the gradient (d/d_theta j(theta)) grad0 = 1.0/m * sum([(t0 + t1*x[i] - y[i]) for i in range(m)]) grad1 = 1.0/m * sum([(t0 + t1*x[i] - y[i])*x[i] for i in range(m)]) # update the theta_temp temp0 = t0 - alpha * grad0 temp1 = t1 - alpha * grad1 # update theta t0 = temp0 t1 = temp1 # mean squared error e = sum( [ (t0 + t1*x[i] - y[i])**2 for i in range(m)] ) if abs(J-e) <= ep: print 'Converged, iterations: ', iter, '!!!' converged = True J = e # update error iter += 1 # update iter if iter == max_iter: print 'Max interactions exceeded!' converged = True return t0,t1 if __name__ == '__main__': x, y = make_regression(n_samples=100, n_features=1, n_informative=1, random_state=0, noise=35) print 'x.shape = %s y.shape = %s' %(x.shape, y.shape) alpha = 0.01 # learning rate ep = 0.01 # convergence criteria # call gredient decent, and get intercept(=theta0) and slope(=theta1) theta0, theta1 = gradient_descent(alpha, x, y, ep, max_iter=1000) print ('theta0 = %s theta1 = %s') %(theta0, theta1) # check with scipy linear regression slope, intercept, r_value, p_value, slope_std_error = stats.linregress(x[:,0], y) print ('intercept = %s slope = %s') %(intercept, slope) # plot for i in range(x.shape[0]): y_predict = theta0 + theta1*x pylab.plot(x,y,'o') pylab.plot(x,y_predict,'k-') pylab.show() print "Done!"
Output:
x.shape = (100, 1) y.shape = (100,) Converged, iterations: 641 !!! theta0 = [-2.81943944] theta1 = [ 43.1387759] intercept = -2.84963639461 slope = 43.2042438802
The regression line in the picture above confirms we got the right result from our Gradient Descent algorithm. Also, the sciPy's stats.linregress reassures (intercept and slope values) the correctness of our outcome (theta0 and theta1).
We need to be a little bit careful when we updates $\theta_0$ and $\theta_1$. First, we calculate the temporary $\theta_0$ and $\theta_1$ with old $\theta_0$ and $\theta_1$, and then we get new $\theta_0$ and $\theta_1$ from $temp0$ and $temp1$:\[\begin{aligned} temp0 := \theta_0 -\alpha \frac{\partial}{\partial \theta_0}J(\theta_0, \theta_1) \end{aligned} \] \[\begin{aligned} temp1 := \theta_1 -\alpha \frac{\partial}{\partial \theta_1}J(\theta_0, \theta_1) \end{aligned} \] \[\begin{aligned} \theta_0 := temp0 \end{aligned} \] \[\begin{aligned} \theta_1 := temp1. \end{aligned} \]
The following code is almost the same as the code we used in the previous section but simpler since it utilized numPy better. It runs until it reaches iteration maximum. We get $\theta_0$ and $\theta_1$ as its output:
import numpy as np import random from sklearn.datasets.samples_generator import make_regression import pylab from scipy import stats def gradient_descent_2(alpha, x, y, numIterations): m = x.shape[0] # number of samples theta = np.ones(2) x_transpose = x.transpose() for iter in range(0, numIterations): hypothesis = np.dot(x, theta) loss = hypothesis - y J = np.sum(loss ** 2) / (2 * m) # cost print "iter %s | J: %.3f" % (iter, J) gradient = np.dot(x_transpose, loss) / m theta = theta - alpha * gradient # update return theta if __name__ == '__main__': x, y = make_regression(n_samples=100, n_features=1, n_informative=1, random_state=0, noise=35) m, n = np.shape(x) x = np.c_[ np.ones(m), x] # insert column alpha = 0.01 # learning rate theta = gradient_descent_2(alpha, x, y, 1000) # plot for i in range(x.shape[1]): y_predict = theta[0] + theta[1]*x pylab.plot(x[:,1],y,'o') pylab.plot(x,y_predict,'k-') pylab.show() print "Done!"
Output:
iter 0 | J: 1604.873 iter 1 | J: 1586.636 iter 2 | J: 1568.768 iter 3 | J: 1551.261 ... iter 997 | J: 699.300 iter 998 | J: 699.300 iter 999 | J: 699.300 theta = [ -2.84837957 43.20234847]
We may also want to see how the batch gradient descent is used for the well known Iris dataset : Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient method | http://www.bogotobogo.com/python/python_numpy_batch_gradient_descent_algorithm.php | CC-MAIN-2017-34 | refinedweb | 988 | 58.69 |
I have the following API:
public interface MyApi { /** * Performs some stuff. * @throws MyException if condition C1 */ public void method() throws MyException; }
I am now performing the following modification in my API implementation
public class MyApiImpl { public void method() throws MyException { if (C1) { throw new MyException("c1 message"); } ... } }
is replaced by :
public class MyApiImpl { public void method() throws MyException { if (C1) { throw new MyException("c1 message"); } else if (c2) { throw new MyException("c2 message"); } ... } }
Do you consider this as an API breakage ?
Client’s code will still compile but method contract defined by the API javadoc is no more respected since MyExcepiton is thrown by a “new” condition.
If only my API jar file is updated, clients application will still work but depending on the way clients catch the exception the application behavior can change a lot.
What’s your point of view on that ?
Yes, you’re breaking the contract of the interface by throwing an exception when C1 doesn’t occur.
As a rule of thumb, the vaguer the interface contract, the easier it is not to break 🙂 If the interface isn’t defined in terms of an explicit C1, but in more general terms, that gives a lot more flexibility.
###
My point of view is that you should not change the contract defined by the API in the documentation. If you need new behavior you should either a.) create a new method that can be called by the client reflecting this new behavior or b.) discuss with the client the need for the change and make them aware of it.
This really can go both ways, it is between you and your clients as to what your approach will be.
###
It largely depends on what c2 is. Is it within the logical bounds on the pre-existing contract? If so, you’re satisfying the contract by throwing a MyException. If not then perhaps you need to throw a new type of exception.
I should point out that I’m not a huge fan of checked exceptions. Ultimately, forcing someone to deal with an exception doesn’t necessarily make their code any better or safer (in fact it can have the opposite effect as they can sloppily swallow spurious exceptions).
###
I’d say “no”, no API breakage, unless MyException is a RuntimeException. Then it is.
Anyway, I’d subclass MyException for condition C2
And both conditions C1 and C2 should be “exceptional” IMHO, I would not make an habit of throwing exceptions
###
It’s a breakage. Whether the API is enforced by language constructs or simply documented is irrelevant.
Whether this breakage causes a problem for client code is a different question. It may be that you are fixing a defect and need to cover case C2 in this way to fix it. From that respect client code developers may be happy that you’ve made this change (assuming they are not currently working around the defect in such a way which would break in the face of the change!)
###
I think the problem here is that you made part of your interface, implementation specific conditions. If the “C1” condition were only part of your implementation, then you could have simply created a new implementation that throws an exception on “C1” or “C2” without breaking the interface. | https://exceptionshub.com/java-api-break.html | CC-MAIN-2022-05 | refinedweb | 548 | 61.36 |
#include "sql/json_dom.h"
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include <cmath>
#include <functional>
#include <new>
#include "my_rapidjson_size_t.h"
#include <rapidjson/error/en.h>
#include <rapidjson/error/error.h>
#include <rapidjson/memorystream.h>
#include <rapidjson/reader.h>
#include "base64.h"
#include "decimal.h"
#include "json_binary.h"
#include "m_ctype.h"
#include "m_string.h"
#include "malloc_allocator.h"
#include "my_byteorder.h"
#include "my_compare.h"
#include "my_dbug.h"
#include "my_decimal.h"
#include "my_double2ulonglong.h"
#include "my_sys.h"
#include "my_time.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "sql/check_stack.h"
#include "sql/current_thd.h"
#include "sql/derror.h"
#include "sql/field.h"
#include "sql/json_path.h"
#include "sql/json_syntax_check.h"
#include "sql/psi_memory_key.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_sort.h"
#include "sql/sql_time.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql_string.h"
#include "template_utils.h"
Add a value to a vector if it isn't already there.
This is used for removing duplicate matches for daisy-chained ellipsis tokens in find_child_doms(). The problem with daisy-chained ellipses is that the candidate set may contain the same Json_dom object multiple times at different nesting levels after matching the first ellipsis. That is, the candidate set may contain a Json_dom and its parent, grandparent and so on. When matching the next ellipsis in the path, each value in the candidate set and all its children will be inspected, so the nested Json_dom will be seen multiple times, as its grandparent, parent and finally itself are inspected. We want it to appear only once in the result.
The same problem occurs if a possibly auto-wrapping array path leg comes after an ellipsis. If the candidate set contains both an array element and its parent array due to the ellipsis, the auto-wrapping path leg may match the array element twice, and we only want it once in the result.
Append a comma to separate elements in JSON arrays and objects.
Common implementation of move-assignment and copy-assignment for Json_wrapper.
If from is an rvalue, its contents are moved into to, otherwise the contents are copied over.
Map the JSON type used by the binary representation to the type used by Json_dom and Json_wrapper.
Note: Does not look into opaque values to determine if they represent decimal or date/time values. For that, look into the Value an retrive field_type.
Compare a decimal value to a double by converting the double to a decimal.
Compare a decimal value to a signed integer by converting the integer to a decimal.
Compare a decimal value to an unsigned integer by converting the integer to a decimal.
Compare a JSON double to a JSON signed integer.
Compare a JSON double to a JSON unsigned integer.
Compare a JSON signed integer to a JSON unsigned integer.
Compare the contents of two strings in a JSON value.
The strings could be either JSON string scalars encoded in utf8mb4, or binary strings from JSON opaque scalars. In either case they are compared byte by byte.
Perform quoting on a JSON string to make an external representation of it.
It wraps double quotes (text quotes) around the string (cptr) and also performs escaping according to the following table:
Common name C-style Original unescaped Transformed to escape UTF-8 bytes escape sequence notation in UTF-8 bytes --------------------------------------------------------------- quote \" %x22 %x5C %x22 backslash \\ %x5C %x5C %x5C backspace \b %x08 %x5C %x62 formfeed \f %x0C %x5C %x66 linefeed \n %x0A %x5C %x6E carriage-return \r %x0D %x5C %x72 tab \t %x09 %x5C %x74 unicode \uXXXX A hex number in the %x5C %x75 range of 00-1F, followed by except for the ones 4 hex digits handled above (backspace, formfeed, linefeed, carriage-return, and tab). ---------------------------------------------------------------
Escape a special character in a JSON string, as described in double_quote(), and append it to a buffer.
Find the child Json_dom objects identified by the given path.
The child doms are added to a vector.
See the header comment for Json_wrapper::seek() for a discussion of complexities involving path expressions with more than one ellipsis (**) token, or a combination of ellipsis and auto-wrapping path legs.
Get which helper function of seek_no_dup_elimination() should be used for this path leg.
Get string data as std::string from a json_binary::Value.
Push a warning/error about a problem encountered when coercing a JSON value to some other data type.
Check if a seek operation performed by find_child_doms() or Json_dom::seek() is done.
Create a DOM template for the provided json_binary::Value.
If the binary value represents a scalar, create a Json_dom object that represents the scalar and return a pointer to it.
If the binary value represents an object or an array, create an empty Json_object or Json_array object and return a pointer to it.
Compare two keys from a JSON object and determine whether or not the first key is less than the second key.
key1 is considered less than key2 if
a) key1 is shorter than key2, or if
b) key1 and key2 have the same length, but different contents, and the first byte that differs has a smaller value in key1 than in key2
Otherwise, key1 is not less than key2.
Make a sort key for a JSON numeric value from its string representation.
The input string could be either on scientific format (such as 1.234e2) or on plain format (such as 12.34).
The sort key will have the following parts:
1) One byte that is JSON_KEY_NUMBER_NEG, JSON_KEY_NUMBER_ZERO or JSON_KEY_NUMBER_POS if the number is positive, zero or negative, respectively.
2) Two bytes that represent the decimal exponent of the number (log10 of the number, truncated to an integer).
3) All the digits of the number, without leading zeros.
4) Padding to ensure that equal numbers sort equal even if they have a different number of trailing zeros.
If the number is zero, parts 2, 3 and 4 are skipped.
For negative numbers, the values in parts 2, 3 and 4 need to be inverted so that bigger negative numbers sort before smaller negative numbers.
Merge two doms.
The right dom is either subsumed into the left dom or the contents of the right dom are transferred to the left dom and the right dom is deleted. After calling this function, the caller should not reference the right dom again. It has been deleted.
Returns NULL if there is a memory allocation failure. In this case both doms are deleted.
scalars - If any of the documents that are being merged is a scalar, each scalar document is autowrapped as a single value array before merging.
arrays - When merging a left array with a right array, then the result is the left array concatenated with the right array. For instance, [ 1, 2 ] merged with [ 3, 4 ] is [ 1, 2, 3, 4 ].
array and object - When merging an array with an object, the object is autowrapped as an array and then the rule above is applied. So [ 1, 2 ] merged with { "a" : true } is [ 1, 2, { "a": true } ].
objects - When merging two objects, the two objects are concatenated into a single, larger object. So { "a" : "foo" } merged with { "b" : 5 } is { "a" : "foo", "b" : 5 }.
duplicates - When two objects are merged and they share a key, the values associated with the shared key are merged.
Helper function for wrapper_to_string() which adds a newline and indentation up to the specified level.
Does a search on this path, using Json_dom::seek() or Json_wrapper::seek(), need duplicate elimination?
Duplicate elimination is needed if the path contains multiple ellipses, or if it contains an auto-wrapping array path leg after an ellipses. See Json_wrapper::seek() for more details.
Populate the DOM representation of a JSON array with the elements found in a binary JSON array.
Populate the DOM representation of a JSON object with the key/value pairs found in a binary JSON object.
Populate the DOM representation of a JSON object or array with the elements found in a binary JSON object or array.
If the supplied value does not represent an object or an array, do nothing.
Pretty-print a string to an evolving buffer, double-quoting if requested.
Reserve space in a string buffer.
If reallocation is needed, increase the size of the buffer exponentially.
Helper function for seek_no_dup_elimination which handles jpl_array_cell path legs.
Helper function for seek_no_dup_elimination which handles jpl_array_cell_wildcard and jpl_array_range path legs.
Helper function for seek_no_dup_elimination which handles jpl_ellipsis path legs.
Helper function for seek_no_dup_elimination which handles the end of the path.
Helper function for seek_no_dup_elimination which handles jpl_member path legs.
Helper function for seek_no_dup_elimination which handles jpl_member_wildcard path legs.
Finds all of the JSON sub-documents which match the path expression.
Puts the matches on an evolving vector of results. This is a fast-track method for paths which don't need duplicate elimination due to multiple ellipses or the combination of ellipses and auto-wrapping. Those paths can take advantage of the efficient positioning logic of json_binary::Value.
Possibly append a single quote to a buffer.
Auto-wrap a dom in an array if it is not already an array.
Delete the dom if there is a memory allocation failure.
Helper function which does all the heavy lifting for Json_wrapper::to_string().
It processes the Json_wrapper recursively. The depth parameter keeps track of the current nesting level. When it reaches JSON_DOCUMENT_MAX_DEPTH (see json_syntax_check.cc for definition), it gives up in order to avoid running out of stack space.
The number of enumerators in the enum_json_type enum.
The following matrix tells how two JSON values should be compared based on their types.
If type_comparison[type_of_a][type_of_b] is -1, it means that a is smaller than b. If it is 1, it means that a is greater than b. If it is 0, it means it cannot be determined which value is the greater one just by looking at the types. | https://dev.mysql.com/doc/dev/mysql-server/latest/json__dom_8cc.html | CC-MAIN-2021-43 | refinedweb | 1,671 | 60.11 |
Publishing embedded resources in ASP.Net 2.0
I put up a post a while back about my issues with publishing embedded resources from an assembly with ASP.Net 2.0. Ramon wanted a sample, so here it is.
There are a couple of things to note about getting this to work:
- The resource must be marked as Build Action = Embedded Resource
- Line 18 in ResTest\ResTestLib\My Project\AssemblyInfo.vb must include the full namespace of the assembly, not just the filename of the embedded resource
- As above, Line 21 in ResTest\ResTestLib\ResTestControl.vb must also include the full namespace of the assemlby, not just the filename of the embedded resource
Written on October 11, 2005 | https://www.neovolve.com/2005/10/11/publishing-embedded-resources-in-asp-net-2-0/ | CC-MAIN-2020-05 | refinedweb | 118 | 61.87 |
Do you train for your upcoming coding interview? This question was asked by Google as reported in multiple occasions by programmers all around the world. Can you solve it optimally?
Let’s dive into the problem first.
Problem Formulation
Given an integer array or Python list
nums and an integer value
k.
Find and return the
k-th largest element in the array.
Constraints: You can assume that
k is a number between 1 and the length of the
nums list.
1 <= k <= nums.length
Therefore, it is implicitly ensured that the list
nums has at least one element and there always must be exactly one solution.
Examples
Let’s have a look at some examples to improve our understanding of this problem.
Example 1 Input: [1, 2, 3, 4, 5], k=2 Output: 4 Example 2 Input: [42, 1, 3, 2], k=1 Output: 42 Example 3 Input: [3], k=1 Output: 3 Example 4 Input: [3, 42, 30, 1, 32, 100, 44, 13, 28, 99, 100000], k=4 Output: 44
Video Solution
You can watch me explain this interview question in the following video:
Naive Solution: Sorting
The most straightforward way to return the k-th largest element from a list is as follows:
- Sort the list in descending order. The largest element is at position 0.
- Access the (k-1)-th element of the sorted list and return it. This is the k-th largest element.
Here’s the code that accomplishes that:
def find_k_largest_element(nums, k): sorted_nums = sorted(nums, reverse=True) return sorted_nums[k-1]
You use the
sorted() function to create a new sorted list. As the first argument, you pass the list to be sorted. As second argument, you pass reverse=True which ensures that the largest element appears at the first position, the second largest element at the second position, and so on.
Given the sorted list, you now need to access the k-th element from the list. As we use zero-based indexing in Python, the k-th largest element has index (k-1).
Let’s run this on our examples:
# Example 1 lst = [1, 2, 3, 4, 5] k = 2 print(find_k_largest_element(lst, k)) # 4 # Example 2 lst = [42, 1, 3, 2] k = 1 print(find_k_largest_element(lst, k)) # 42 # Example 3 lst = [3] k = 1 print(find_k_largest_element(lst, k)) # 3 # Example 4 lst = [3, 42, 30, 1, 32, 100, 44, 13, 28, 99, 100000] k = 4 print(find_k_largest_element(lst, k)) # 44
Yes, this passes all test!
Analysis: The code consists of two lines: sorting the list and accessing the k-th element from the sorted list. Accessing an element with a given index has constant runtime complexity O(1). The runtime of the algorithm, therefore, is dominated by the runtime for sorting a list with n elements. Without any further information about the list, we must assume that the worst-case runtime complexity of sorting is O(n log n), so it grows superlinearly with an increasing number of elements.
Discussion: Intuitively, we do a lot of unnecessary work when sorting the list given that we’re only interested in the k-th largest element. All smaller elements are of no interest to us. We observe that we do need to know the (k-1) larger elements, so that we can figure out the k-th largest. Is there a better way than O(n log n)?
Iteratively Removing the Maximum
Observation: Finding the largest element only has linear runtime complexity O(n): we need to traverse the list once and compare each element against the current maximum. If the current element is larger, we simply update our maximum. After traversing the whole list, we’ve determined the maximum with only n-1 comparisons.
- If k=1, this is already the solution and the runtime complexity is O(n) instead of O(n log n).
- If k>1, we can repeat the same procedure on the smaller list—each time removing the current maximum from the list.
The overall runtime complexity would be O(k*n) because we need to perform n comparisons to find one maximum, and repeat this k times.
The following code implements this exact algorithm:
def find_k_largest_element(nums, k): for i in range(k-1): nums.remove(max(nums)) return max(nums)
In each iteration i, we remove the maximum. We repeatedly remove the maximum (k-1) times as controlled by the
range() function. After the loop is terminated, the maximum in the list is the k-th largest element. This is what we return to the user.
Discussion: This algorithm has runtime complexity O(k*n) compared to the runtime complexity of the sorting method of O(n log n). So, if k<log(n), this is in fact the more efficient algorithm. However, for k>log(n), this algorithm would be worse!
Can we do better?
Hybrid Solution to Get Best of Both Worlds
In the previous discussion, we’ve observed that if k>log(n), we should use the algorithm based on sorting and if k<log(n), we should use the algorithm based on repeatedly removing the maximum. For k=log(n), it doesn’t really matter. Fortunately, we can use this simple check at the beginning of our code to determine the best algorithm to execute.
import math def find_k_largest_sort(nums, k): sorted_nums = sorted(nums, reverse=True) return sorted_nums[k-1] def find_k_largest_remove_max(nums, k): for i in range(k-1): nums.remove(max(nums)) return max(nums) def find_k_largest_element(nums, k): n = len(nums) if k > math.log(n, 2): return find_k_largest_sort(nums, k) else: return find_k_largest_remove_max(nums, k)
The code shows the function
find_k_largest_element that either executes the sorting-based algorithm if k > log(n) or the removal-based algorithm otherwise.
Discussion: By combining both algorithms this way, the overall runtime complexity drops to O(min(k, log(n)) * n) which is better than either O(n * log(n)) or O(n * k).
Can we do even better?
Best Solution with Sorted List of Top k Elements
The removal-based algorithm has the main problem that we need to perform the
min() computation on the whole list. This is partly redundant work. Let’s explore an alternative idea based on a sliding window that largely removes the overhead of computing the min repeatedly.
The idea of the following algorithm is to maintain a window of the k largest elements in sorted order. Initially, you fill the window with the first k elements from the list. Then, you add one element to the window at a time, but only if it is larger than the minimum from the window. The trick is that as the window of k elements is sorted, accessing the window has O(1) constant runtime complexity. Then you repeat this behavior (n-k) times.
Here’s an example run of the algorithm:
You start with the list
[5, 1, 3, 8, 7, 9, 2] and the sorted window
[1, 3, 5]. In each iteration, you check if the current element is larger than the minimum at position 0 of the sorted window. For elements 8, 7, and 9, this is indeed the case. In these instances, you perform a sorted insert operation to add the new element to the window after removing the previous minimum from the window. After one complete run, you’ll have the k largest elements in the window.
Here’s a runtime analysis of the algorithm that shows that the runtime is only O(n log k) which is the best we accomplished so far.
Let’s have a look at the code:
import bisect def find_k_largest_element(nums, k): window = sorted(nums[:k]) for element in nums[k:]: if element > window[0]: # Remove minimum from window window = window[1:] # Sorted insert of new element bisect.insort(window, element) return window[0]
The code uses the
bisect.insort() method to perform the sorted insert operation into the window. You should know how sorted insert actually works. However, in a coding interview, you can usually assume you have access to basic external functionality. Here’s a basic recap on the idea of sorted insert:
? Concept Sorted Insert: To insert an element into a sorted list, you peak the mid element in the list and check if it is larger or smaller than the element you want to insert. If it is larger, all elements on the right will also be larger and you can skip them. If the mid element is smaller, all elements on the left will be smaller as well and you can skip them. Then, you repeat the same halving the potential elements each time until you find the right position to insert the new element.
As sorted insert repeatedly halves the interval, it only takes O(log k) operations to insert a new element into a sorted list with k elements. This is the core idea of the whole algorithm so make sure you understand it!
This Google interview question is part of our upcoming Finxter Computer Science Academy course. Check it. | https://blog.finxter.com/find-the-k-th-largest-element-in-an-unsorted-array/ | CC-MAIN-2022-21 | refinedweb | 1,512 | 61.87 |
If you have ever wanted to learn how to program a computer, this is the tutorial for you. I walk you step-by-step through how to do anything with Python.
Everything you can do with Python will be covered. You can watch over my shoulder as I teach programming, based off of your requests. I asked you guys what you wanted and you said:
[adsense]
All The Code Associated with this Tutorial
#!/usr/bin/python3
import math, decimal
# Demonstrate how to work with numbers in Python
def varEx():
_legalVarName = 1
Another1 = 2
yet_another = 3
print(”’and, continue, except, global, lambda, pass, while, as, def, + \
False, if, None, raise, with, assert, del, finally, import, nonlocal, + \
return, yield, break, elif, for, in, not, True, class, else, from, + \
is, or, try ”’) # \ is the line continuation character
x, y, z = 1, 2, 3
print(x, y, z)
def boolEx():
# Boolean Variables (True or False)
a = True
print(type(a))
a = 5
print(type(a))
print(bool(a))
b = True
c = False
print(b and c)
print(b or c)
print(not b)
d = (1 > 2)
print(” It is {} that 1 is greater than 2″.format(d))
def intEx():
# There are integers, binary, octal, hexidecimals
# print(d)
x = 4
y = 2
print(“x + y = “, x+y)
print(“x – y = “, x-y)
print(“x * y = “, x*y)
print(“x / y = “, x+y)
print(“x % y = “, 5%2)
print(“x // y = “, 5//2)
print(“x ** y = “, x**y)
print(“\n”)
print(“{} + {} = {}”.format(x, y, x+y))
print(“{} – {} = {}”.format(x, y, x-y))
print(“{} * {} = {}”.format(x, y, x*y))
print(“{} / {} = {}”.format(x, y, x/y))
print(“{} % {} = {}”.format(5, 2, 5%2))
print(“{} // {} = {}”.format(5, 2, 5//2))
print(“{} ** {} = {}”.format(x, y, x**y))
print(“Binary format for 4”, bin(x))
print(“divmod(5,2) = “,divmod(5,2))
print(“4 converted into a float”, float(x))
print(“Hexidecimal format for 4”, hex(x))
print(“4 raised to the power of 2”, pow(x,y))
z = 100 / 3
print(“100 divided by 3 = “, z)
print(“z is of type “, type(z))
print(“100 / 3 rounded to 3 decimals “, round(z, 3))
print(“math.ceil(100/3) = “, math.ceil(z))
print(“math.floor(100/3) = “, math.floor(z))
def floatEx(x=1, y=2):
z = x / y
print(z)
print(type(z))
print(id(z))
z = 1.1234567891011
print(z)
decimalVar = decimal.Decimal(“1.123456789101112131415”)
print(decimalVar)
decimalVar2 = decimal.Decimal(“2.345678910”)
print(decimalVar + decimalVar2)
varEx()
boolEx()
intEx()
floatEx(5, 2)
Sorry, I couldn’t get more out today. Tomorrow I’ll provide at least 2 additional video’s for the Python Video series.
If you have any questions, leave them below.
Till Next Time
Think Tank
Is there a zip file with the code for the Python 3 tutorial?
Sorry, but I made that a long time ago and didn’t think about things like that. Sorry about that | http://www.newthinktank.com/2010/09/python-how-to-video-pt-1/ | CC-MAIN-2021-25 | refinedweb | 480 | 71.65 |
Part 2 of more to come 🙂
One of the features that is missing right now is a functionality to select the proper class. In Chrome or IE you can use the Developer Toolbar to inspect an element. In the UI Theme Designer this functionality is not present (yet?).
This blog will explain how to select the correct elements. First find out which CSS class you would like to change by selecting the Developer Toolbar (F12) in Chrome or IE. In my case I have selected the title (urPgHTTxtSmall).
If you search in the UI Theme Designer you will not find anything. Open Notepad++ (or any text editor that can search in files as well) and press CTRL+F, select Find in Files and search for urPgHTTxtSmall. Select as source two directories (download the applications from the server):
– com.sap.portal.design.portaldesigndataless
– com.sap.portal.design.urdesigndataless
I have placed the two applications in directory c:\nwds\sap less (see below):
There are 62 hits:
com.sap.portal.design.urdesigndataless\servlet_jsp\com.sap.portal.design.urdesigndataless\root\theming\UR\ls\baseTheme\ie6.less
IE6 is for IE, NN7 for chrome and so on. But the most important thing is that we can look at the definition:
.urPgHTTxtSmall {
width: @sapUrPgHTTxtWdth;
color: @sapUrPgHTTxtColor;
font-size: @sapUrPgHTTxtFSSmall;
@sapURPgHTtxtWdth is a LESS variable. In the UI Theme Designer go to your theme and select Expert mode. Search for sapURPgHTtxtWdth and there is the element!
Please note this is undocumented! Use it at your own risk!!!
/*
Any suggestions for another topic regarding UI Theme Designer is welcome 🙂
How to transport themes from one system to another. Hint: it doesn’t work, not at least in NW 731 SP09 patch 8 with UI Theme Designer 1.1.4. I have already involved SAP support but they haven’t provided a solution yet.
Hang on, posting it now 🙂 Link incoming….
How to… UI Theme Designer – Transportation
Noel
Is this used for UI5 app too? There is a Ui5 Theme Designer, are they the same?
Thanks
Sandip
The UI Theme Designer is also used for UI5 apps running inside the portal. If you create a theme, make sure it is based on SAP Gold Reflection. This theme is designed for UI5 applications.
The UI5 Theme Designer is the core application. UI Theme Designer in the portal is UI5 Theme Designer + portal integration, easily said.
Locating elements in UI5 is much easier than UR components. Also for UI5 applications the CSS tab should be available.
Thanks Noel
Are there plans to support Platinum & Blue Crystal themes too?
We have plans to use Platinum for our UI5 Apps, and then hook them with Portal. So will the UI5 App Elements inherit the Portal theme you mean? or, they will continue to use the theme defined in their namespace?
Sandip
Good question, I don’t know to be honest. Maybe Shani Limor knows more.
If I understand you right, you would like to use a non-portal theme (Platinum) and use it in the portal as well. I think every theme is inherited from a base theme (don’t know which one it is, could be SAP tradeshow). Adding portal elements to it is maybe unsupported.
What you can do is compare the definitions of the themes (Platinum and a standard portal theme like tradeshow plus). Maybe you can fool the UI Theme Designer 🙂
Hello Sandip, Noel,
The SAP_Platinum theme is not supported in the Portal and is also not supported by UR as a base for custom theme (please see note from UR: 1852400 – UI theme designer (main note) ).
Regarding SAP BlueCrystal, it is planned to be supported in the Portal (now in development) in 7.31 SP12.
Thanks,
Have a wonderful day,
Shani
Noel, Shani
Thanks for your replies.
One last question, if the Ui5 Apps running inside Portal – will the portal theme (lets say gold reflection) be forced upon the Ui5 apps if they are using a theme other than gold_reflection(e.g. platinum)?
We have plans to use Platinum for our Ui5 apps – so I just wanted to make sure the Portal theme will not effect the Ui5 apps.
Thanks
Sandip
Hello Sandip,
The Portal themes blue crystal and gold reflection will work with UI5 applications running inside the portal just as any other theme works with any other technology. Meaning that the Portal theme will be the theme for all applications running in the portal. It`s one theme for Portal ontegrated applications.
Have a wonderful day,
Shani
Hi Shani
Thanks for your reply. Appreciated..
Regards
Sandip
Shani Limor N. Hendrikx
I just came across a SAP NOte which says about how to prevent portal theme being enforced upon the UI5 applications
1895989 – UI5 iView stylesheet rendering issues
Hi Sandip,
This is a note published for UI5 based application integration to the portal before the implementation of the UI Theme Designer for UI5 applications.
Once the development will be done, your UI5 applications will render with the Portal theme.
Have a wonderful day,
Shani
Thanks Shani
I like these kind of tricks. Thanks for sharing.
You are welcome! Pleasure to share it with everyone.
Hi Noel,
We do not have UI Theme Designer for 7.4 sps 3. I think its in the later versions.
Any other way of doing this. I know of Theme Class Locator that was available in 7.3 or lower versions but it does not work in 7.4.
Can u guide me on this?
Thanks,
Deep Desai
Hello Deep Desai,
The UI Theme Designer for Portal is available starting from 7.30 SP10, 7.31 SP9 and 7.4 SP4.
Have a wonderful day,
Shani
Hi Noel,
We created a copy of the standard SAP Ajax framework theme and modifying it using the (old) theme designer.
We made allmost all the changes we wanted but we don’t allways have the same behaviour on each browser (Chrome, IE11, Firefox). I wondered what you suggest to resolve this?
Is there anyway to directly modify the CSS files adding some specific browser testing code?
Can the use of the new UI theme designer for this purpose?
Thanks for your help,
Good evening
Thomas
Hi Thomas,
First check if your portal version is compatible with the browsers you use. If it is not supported, you should wait till the browser is released.
With the old style editor I should not change the css files directly, since they will be overwritten every time.
With the new UI Theme Designer much more is possible. But it’s kinda strange that it works different in the browsers. The list of browsers/version you mention is that they support css 3. Older browsers (like IE7/8) use CSS2.1 so that might not work the same.
Please send some examples of what goes wrong. There are several solutions 😉
Hi Noël,
First of all thanks for your answer.
We’re working on SAP Portal 7.3 SP11. I’m checking the availability matrix but i’m getting lost on how to be sure what browser is supported. I can’t find a page showing the exact browser versions supported.
If we use the new UI Theme designer can we take over what we did with the old one? Or is there a kind of migration where we need to re-do the customizing of the theme?
About what is not working, here is an example, with horizontal menu in respectively: IE11, Chrome and Firefox.
Best regards,
Thomas
Hi Thomas,
In the PAM go to NW 7.3 > Technical Release information > Web browser platform.
Look at the Additional information as well.
Does the navigation work well with the standard sap_tradeshow theme? (you can use /irj/portal?theme=sap_tradeshow to find out).
Do you have custom navigation components?
For migrating the old css to the new UI theme designer : How to… UI Theme Designer – Migration
Please note you can go back also! So I suggest try to use the new UI Theme Designer.
cheers,
Noël
Hi Noel,
Thanks for the input. After some closer look we found the specific CSS parts for Internet Explorer that caused some troubles. So we changed them in the .LESS file.
Now we’re facing another problem when using the Web Page Composer or KM linked to the use of the New UI Theme. I found a note 2030755 – Solution for BI applications to render correctly with portal theme also in the old structure and KM document with WPC can’t be edited.
But on the version we’re are currently working (PORTAL BASIS 7.30) the release note for SP013 has not been provided yet.
As this is blocking for another project in the portal, we thought of temporarily deactivate the new UI Theme by deleting the LESS value for “Determine what will be the theme runtime provider” property and restart the portal.
I just want to be sure that this can be done. Could you confirm this?
Thanks a lot,
Thomas
Hi Thomas,
Sorry for the late reply. Yes, you can go back to the old theme editor. You don’t need to delete the Web Repository files, just delete the LESS value of “Determine what will be the theme runtime provider” and restart.
Cheers,
Noel
Hi Noel / Shani,
I am using new UI Theme Designer as part of 7.4 SP7 and using SAP_GOLDREFLECTION as base theme to customize. Once the Theme is copied and published (AJAX Framework), Some of the applications (UWL, Workset Maps) are loaded using Tradeshow Plus theme instead of Gold Reflection. In WRR i see no CSS Files generated under UR/ur/<theme>
Is this the normal behavior.
Thanks
Sumanth
Sounds familiar. All webdynpro Java applications do display the sap_tradeshow theme, right? Check out the patches for WD-RUNTIME and portal in general. This is a bug.
I think i have the latest patch of WD-RUNTIME for other issues we had. Not all Java applications are having this issue. Like User Administration is coming up with Gold reflection.
For Loading of Universal Worklist i notices Style sheets are pointing to ls/ls..css files of Tradeshow plus.
Where ever it is referred to UR related classes, CSS files are referenced to http://<….>/com.sap.portal.theming.webdav.themeswebdavlistener/UR/ur/sap_tradeshow_plus/sf3.css?ri…
Thanks
Sumanth
Please check oss messages related to UR versioning and WD Java. You cannot compare User Admin with a WD Java app (iview) unfortunately. We have the same issue at 730 SP10 and we are going to upgrade to SP12 with the latest patches. Keep you posted!
SAP doesn’t support the use of Gold Reflection together with the Ajax Framework, that is according to SAP support. <rant>One more combination that they don’t support. First Corbu, now even Gold Reflection can’t be used. It’s easy to label anything that doesn’t work “as not supported” rather than trying to make it work. Maybe I’ll try Blue Crystal next, I’m sure that won’t be supported either once I discover some problems with it.</rant>
Samuli
Thanks for raising these points. At this point, even I am not sure what is next from SAP. What theme is supported for Portal, Web Dynpro, UI5?? Is there any theme which will support all these 3?
Regards
Sandip
I don’t think so. I’m using my custom theme based on Gold Reflection, I worked around the restrictions meaning I didn’t change any CSS that would break something for portal. I guess we have to wait for SAP to enable standards mode for portal. Any update that you can share, Aviad Rivlin? Still SPS15? Even once portal supports standards mode, I’m sure that everything won’t be supported (e.g. HTMLB, JSPs, KM, …).
For standards mode FWP we already have the Fiori framework page available and we are still working on the AJAX framework page in standards mode.I agree with your comment Samuli Kaski, having a standard mode framework page does not mean that all the portal apps will be running in standards mode. But… we are working on having more and more UI technologies running in standards mode (e.g.: Web Dynpro,…). Ingo Deck can provide the full list of UI technologies running in standards mode.
Aviad
That’s good news Aviad. WD already runs in standards mode fortunately. Some old technology or non-SAP applications might run in Quirks mode. You can launch the application in a new browser window without the framework – or even with a quirks mode framework if that’s possible… Maybe it is a feature you can built in the framework, so here’s my proposal:
This is a very good discussion, but is built of two different topics which are not related to each other:
Thanks Shani. Will Blue Crystal work with all out of the box components, e.g. KM, portal admin, wiki, forums, etc?
Unfortunately I can`t say for other technologies except the Enterprise Portal.
Portal Admin will support the SAP Blue Crystal theme for all UI frameworks that can render with it. For example, if an editor\wizard in the Portal is written in HTMLB and HTMLB will not support SAP Blue Crystal, Portal will render the UI with a fallback theme.
Thanks, that’s the answer I was expecting, unfortunately. Will the fallback theme be changeable with the UI Theme Designer? There is a fallback theme even today but it can’t be changed with the UI Theme Designer (sap_standard or even sap_tradeshow_plus in later SPs).
The solution we are working on will allow to set the fallback theme for a custom theme through the UI Theme Designer for Portal.
That’s great news, Thanks Shani. I will start to implement a custom theme based on Blue Crystal.
Hi Noel, Samuli
I am using UI Theme designer in NetWeaver Portal. I changed the branding for Top level navigation using Expert tab, I would like to customizes the CSS for the Ui5 iviews created in the portal. But the CSS tab is not editable, I am unable to enter anything.
My EP version is 7.30 SP10
UI theme designer version is 1.1.4
Please suggest me on how to achieve it.
Thanks and Regards,
Prasanna S
Hi Prasanna,
I have written a blog about that too 🙂
How to… UI Theme Designer – Make use of the Custom CSS tab in the Portal!
Cheers,
Noël
Hi Noël,
I have gone through the document before posting the query. My problem is that the custom CSS tab is not editable to enter sample code to get the custom.less file under WRR.
Regards,
Prasanna
Noel,
I tried this using your example and it worked fine. However, when trying for others, the classes are not found, for instance. For Fiori Framework Page, the icon color, in developer tools you see the class as sapUshellTileBaseIcon. Using the method above, the class was not found, in the theme designer, I found the element as sapUshellTileIconColor. Is there a reason why your methodology in this blog did not find the class sapUShellTileBaseIcon?
Hi Roger,
It might be possible that your custom theme does not support the Fiori framework, which theme did you use as a default?
Also the two less files are quite old, it might be there are new less files as well for the new frameworkpages.
cheers,
Noel
Noel, thanks for your reply.
We learned a while ago to base everything on SAP_BLUECRYSTAL. I did find a com.sap.portal.desing.ui5designdataless.war it was pretty tiny though from a size perspective. I took a look in there but still not finding anything fiori.
In the portal you can use the WRR (Web Resource Repository). Open the themes folder and download it to your local disc. Now you have all the less files belonging to the custom themes.
In these files try to locate sapUShellTileBaseIcon or UShellTileBaseIcon, you might have luck then.
Another way to change the icon is to locate it in the WRR and replace the icon in your custom theme.
Last but not least, in the UI Theme Designer there is a CSS tab. You can define your own rule in it if you want.
.sapUShellTileBaseIcon {
background-color: yellow;
} | https://blogs.sap.com/2014/01/10/how-to-use-the-ui-theme-designer-part-2/ | CC-MAIN-2018-13 | refinedweb | 2,712 | 74.59 |
Using Stripe’s Python API
If you’re using the Full Python runtimes, you can choose not to use Anvil’s simplified APIs, and instead use the official Stripe Python API from your Server Modules.
To use Stripe’s Python API, you’ll need to do two things:
Configure your Stripe Secret Key in your Anvil app. Use the App Secrets service to store it, rather than leaving it in your source code!
Enter your Publishable Keys into Anvil’s Stripe configuration page.
The steps below show you how to do this in Anvil
Configuring your Stripe API keys
To use the official API, you will need to provide Anvil with your Secret Key and your Publishable Keys.
The steps below will walk you through how to access your keys and how to configure them inside Anvil.
Accessing your Stripe API Keys
First, navigate to your Stripe Dashboard
In the navigation pane on the left, click on ‘Developers’, then click on ‘API keys’:
You’ll see a list of ‘Standard Keys’ which includes both your Publishable Key and your Secret key:
You also have the option to view either your live keys or your test keys using the toggle:
Adding your publishable keys to Anvil
Select ‘Stripe’ from the App Browser, and enter your Test and Live publishable keys in the boxes provided:
Adding your secret key to Anvil
Use the App Secrets service to store your Secret key, and then add the key to your app.
For example, if you store your secret key using Anvil’s App Secrets service as ‘stripe_key’, add these lines to provide Stripe with your secret key:
import stripe stripe.api_key = anvil.secrets.get_secret('stripe_key')
Taking a payment
Once you have configured both your publishable and secret keys, you can use Stripe’s Python API.
To use the official API, you will still need to collect users’ card details and generate Stripe tokens. In your Form code, you can call
stripe.checkout.get_token() with the
raw=True parameter. This will generate a token that you can use with the Stripe Python API.
For example, to take a payment:
# Use Stripe Checkout to generate a raw token token, user_info = stripe.checkout.get_token( currency='GBP', amount=999, title='Payment for your Anvil', raw=True ) anvil.server.call('charge', token)
import stripe stripe.api_key = anvil.secrets.get_secret('stripe_key') @anvil.server.callable def charge(token): charge = stripe.Charge.create( currency='GBP', amount=999, description='Payment for your Anvil', source=token ) | https://anvil.works/docs/integrations/stripe/raw-api-tokens.html | CC-MAIN-2020-29 | refinedweb | 412 | 67.28 |
Opened 3 years ago
Last modified 5 months ago
#2878 new defect
Windows escaping seem to produce problems
Description
I am not sure for how long those paste's will be available:
- builder configuration --
- failed step output --
Error message:
'%VCENV_BAT%' is not recognized as an internal or external command, operable program or batch file.
Discussion on IRC starts at
BAT file that produces the error:
The problem seems to be
... ^&^& ...
The question is why & were escaped this way.
Change History (21)
comment:1 Changed 3 years ago by sa2ajj
comment:2 Changed 3 years ago by dustin
- Keywords windows added
- Milestone changed from undecided to 0.9.0
The pastes are gone already :(
comment:3 Changed 3 years ago by otterdam
If you run the command as a parameter to cmd.exe, then it becomes a parameter and the escaping behaviour is correct.
Try prefixing the list of command line arguments with ["cmd", "/c"] (buildbot-0.8.9/buildbot/steps/vstudio.py line 418). I use this in my configuration.
comment:4 Changed 3 years ago by sa2ajj
@otterdam, do you have the code you mentioned modified, or you use some external parameters?
I've been looking at this problem (unfortunately, no more information came my way) and it seems that Buildslave on Windows platform always runs commands using "cmd /c"...
comment:5 Changed 3 years ago by caktux
otterdam's solution works here(tm), seems "cmd", "/c" should be added to vstudio.py
comment:6 Changed 3 years ago by sa2ajj
comment:7 Changed 3 years ago by dustin
- Milestone changed from 0.9.0 to 0.9.+
comment:8 Changed 2 years ago by JustAMan
Can anybody express why buildbot doesn't simply use subprocess module for spawning stuff?..
comment:9 Changed 2 years ago by tardyp
buildbot is based on asynchrounous library called twisted. subprocess is synchronous, which means we could only spawn one process at a time. You can however use threads with twisted. If it happens to be proven more stable, I think a patch that go in that way for windows would be gladly accepted.
We are lacking good windows expertise contributions.
comment:10 Changed 2 years ago by JustAMan
That is completely untrue :) subprocess could spawn as much processes at a time as you need - just don't do .call() or .wait() unconditionally after subprocess.Popen().
Why I'm asking this is that subprocess handles quoting and stuff internally and is widely-tested given it's included in Python standard library, so IMHO it's much better to rely on this functionality rather than write some code that you cannot even test good enough since you lack Windows resources...
I see some more bugs that I think all could be resolved by switching to subprocess (at least on Windows).
P.S. Moving to Job Objects is a bad choice since there could be no nested Job Objects, and you cannot guarantee that a program you launch isn't using Job Objects inside.
comment:11 Changed 2 years ago by tardyp
just don't do .call() or .wait() unconditionally after subprocess.Popen().
JustAMan, I would advice you make some experiment on the buildslave code to convince your self that this is not as simple as you say.
- How would you watch for subprocess stdios, and stream the results in realtime to the master?
- How would you wait for the processes to finish?
The parallelism here is completely independant. The same slave runs arbitrary number of builder at the same time with arbitrary timing on sub process spawn and termination.
For the rest, I agree that subprocess is probably much more reliable on windows than twisted's process management
How can we reuse the windows workaround methods of subprocess inside twisted is the question
comment:12 Changed 2 years ago by JustAMan
I suggest we move Buildbot process spawning code to subprocess. Both issues (watching for stdio and waiting for finish) are almost easy.
We have SCons-based build system where I worked on refactoring how processes are spawned, and this system "tee's" process output to a separate file and to console without much problem. The same goes to waiting for process to finish or killing the whole tree.
I can talk to our system architect who's right now working on open-sourcing it if we can move this process handling code to a subpackage. Or maybe I can just copy-paste it to Buildbot as it's about 15K overall, and is regularly tested on Windows, Linux and MacOS (and now it works on FreeBSD as well).
If that won't suit Buildbot community I suggest we at least move to subprocess.list2cmdline() function instead of ugly manual quoting.
comment:13 Changed 2 years ago by sa2ajj
Any solution to the problem is very welcome.
15K as in "15K lines"?
If you think you could provide a PR, we could take it from there.
comment:14 Changed 2 years ago by JustAMan
15K is "15 Kilobytes" of code.
I'll talk to our open-sourcing guy then.
comment:15 Changed 2 years ago by JustAMan
I have a general "let's publish this code" approval, will work on that.
On a related note, does anyone have original "pastes" that could be used to reproduce the issue?
comment:16 Changed 17 months ago by shoelzer
This is still a problem in Buildbot 0.8.12. I worked around it by modifying the "win32_batch_quote" function in buildslave\runprocess.py. I made two changes:
- Added a special case so "&&" is not escaped.
- Allowed environment variable expansion by not changing "%" characters to "%%".
I'm not saying this is the right way to do it but it's working for me. Here is the complete function I'm using now:
def win32_batch_quote(cmd_list): def escape_arg(arg): if arg == '|': return arg if arg == '&&': return arg arg = quoteArguments([arg]) # escape shell special characters arg = re.sub(r'[@()^"<>&|]', r'^\g<0>', arg) return arg return ' '.join(map(escape_arg, cmd_list))
comment:17 Changed 16 months ago by dpb
Since I'm the one who implemented the current escaping logic, I think I need to weigh in.
Unfortunately, the pastes in the description are no longer available, so I don't know for sure, but I'm going to guess that the string %VCENV_BAT% was used as the first element of a list passed as the command to ShellCommand. When the command is a list, Buildbot runs the process in such a way that the program's argv are exactly the elements of the list. On Windows, that involves escaping all characters that are meaningful to the shell, including % and &.
This is nothing new. As far as I understand, on Unix-likes it has always been that way. On Windows, the escaping has been rather lax (only handling the pipe character) until I tightened it around 0.8.9. I did this to ensure consistency between Windows and non-Windows, and to solve issues like these (I had my own problem similar to that one).
To summarize, I don't think there is a problem here. If you want shell processing, you need to tell Buildbot to use the shell by passing the command as a single string. No escaping happens then.
comment:18 Changed 16 months ago by shoelzer
Whether dpb is right or wrong, all Visual C++ steps are broken as-is.
They all use a shell command with a list and expect %VCENV_BAT% to be expanded to a path. So either win32_batch_quote needs to change or the Visual C++ steps need an update to pass the command as a single string.
comment:19 Changed 16 months ago by dpb
Ah, now I get it. Yeah, that is a problem. I'll see if I can do anything about that.
It seems that it needs to be escaped when passed as a parameter, which does not seem to be our case. | http://trac.buildbot.net/ticket/2878 | CC-MAIN-2017-34 | refinedweb | 1,321 | 71.04 |
This document is also available in these non-normative formats: PDF version.
Copyright © 2010:
RIF is defined to use datatypes defined in the XML Schema Definition Language (XSD). As of this writing, the latest W3C Recommendation for XSD is version 1.0, with version 1.1 progressing toward Recommendation. RIF has been designed to take advantage of the new datatypes and clearer explanations available in XSD 1.1, but for now those advantages are being partially put on hold. Specifically, until XSD 1.1 becomes a W3C Recommendation, the elements of RIF which are based on it should be considered optional, as detailed in Datatypes and Builtins, section 2.3. Upon the publication of XSD 1.1 as a W3C Recommendation, those elements will cease to be optional and are to be considered required as otherwise specified.
We suggest that for now developers and users follow the XSD 1.1 Last Call Working Draft. Based on discussions between the Schema, RIF and OWL Working Groups, we do not expect any implementation changes will be necessary as XSD 1.1 advances to Recommendation..
The Rule Interchange Format (RIF) Working Group seeks public feedback on this First Public. No general mechanism for extensions has been detailed in the RIF specifications, however, although the RIF Framework for Logic Dialects (FLD) [RIF FLD] specifies how to create more expressive logic dialects.
The Resource Description Framework (RDF) [RDF] is a standard abstract way to represent data. The units of data in RDF are triples consisting of a subject, property (or predicate), and value (or object), which two ordered is possible for standard RIF by simply matching the RDF template and generating the corresponding XML. For extended RIF, the mapping is lossy, so the reverse mapping can only done if the translator has extra information.:
Editor's Note: In this current design, the mapping does not use rdf:type triples. This may change in the future. This is Issue 101.
For RIF syntactic extensions to be properly handled by this mapping, they must use different properties from any existing syntax, and those properties must be required wherever used.
For example, if one were adding a new type of formula, "Xor", which was usable wherever "Or" was usable, it could not be merely distinguished by having a different class element (extn:Xor instead of rif:Or); it would have to replace the rif:formula property inside the rif:Or element with something else, such as extn:xorFormulas. Additionally, where rif:Or allows zero or more rif:formula property elements to occur, the extn:xorFormulas property would have to be defined to occur exactly once. Since the Xor operation needs multiple values, the ordered="yes" mechanism would be used to allow them..
Editor's Note: In this current design, the mapping does not use rdf:type triples. This may change in the future. This is Issue 101.
For another example of a specification of a mapping to RDF graphs, which may lend insight into how to use this specification, see OWL 2 Mapping to RDF Graphs [OWL2 Mapping]. like other property elements, singleton.
Editor's Note: If Issue 101 is resolved to allow the use of class information, this table could potentially be simplified or folded into Table 2. Perhaps the type attribute could map to a rif:symbolspace property, and any character data after the last child could map to the value of a rif:text property. is to a new focus node and a set of triples which depend on each of the children of the class element. The exact dependency is detailed in this section.
Each child of the class element being mapped (except as noted above) is a property element.:
Editor's Note: The names of the RDF properties in the resulting graph (the values of prop in Table 3) are still under discussion and may change in the future. This is Issue 102.
Because the above mapping function Tr is not injective (one-to-one), the inverse mapping is not a function, but provides many outputs for each input. Intuitively, Tr loses information, such as the order in which property elements occurred in the RIF XML document, so properly reconstructing a RIF XML document requires additional information.
The reverse mapping function XTr is therefore the inverse of Tr constrained to only produce schema-valid RIF XML documents:
XTr(focus-node, triples, XML-Schema, XML-Root-Element) → rif-xml-tree
Editor's Note: Additional details will be provided in future versions of this document. In particular, how perfect will roundtripping be? Exactly what information is lost?
This document is the product of the Rules Interchange Format (RIF) Working Group (see below) whose members deserve recognition for their time and commitment. The editor extends special thanks to Dave Reynolds and Axel Polleres for their insightful review comments.
The regular attendees at meetings of the Rule Interchange Format (RIF) Working Group at the time of the publication were: Adrian Paschke (Freie Universitaet Berlin), Axel Polleres (DERI), Changhai Ke (IBM), Chris Welty (IBM), Christian de Sainte Marie (IBM), Dave Reynolds (HP), Gary Hallmark (ORACLE), Harold Boley (NRC), Hassan Aït-Kaci (IBM), Jos de Bruijn (FUB), Leora Morgenstern (IBM), Michael Kifer (Stony Brook), Mike Dean (BBN), Sandro Hawke (W3C/MIT), and Stella Mitchell (IBM).
Here is Example 8 from BLD converted via the RIF-in-RDF mapping to Turtle:
@prefix : <> . <> :payload <>; :directives ( ). <> :meta [ :object [ :constName "pd" ]; :slots ( [ :slotkey [ :constIRI "" ]; :slotvalue [ :constIRI "" ] ] [ :slotkey [ :constIRI "" ]; :slotvalue [ :constName "2008-04-04"^^<> ] ] ) ]; :parts ( [ :formula [ :if [ :allTrue ( [ :args ( [ :varname "item" ] ); :predicate [ :constIRI "" ] ] [ :args ( [ :varname "item" ] [ :varname "deliverydate" ] [ :constIRI "John" ] ); :predicate [ :constIRI "" ] ] [ :args ( [ :varname "item" ] [ :varname "scheduledate" ] ); :predicate [ :constIRI "" ] ] [ :left [ :varname "diffduration" ]; :right [ :content [ :args ( [ :varname "deliverydate" ] [ :varname "scheduledate" ] ); :function [ :constIRI "" ] ] ] ] [ :left [ :varname "diffdays" ]; :right [ :content [ :args ( [:varname "diffduration" ] ); :function [ :constIRI "" ] ] ] ] [ :content [ :args ( [ :varname "diffdays" ] [ :constName 10 ] ); :predicate [ :constIRI "" ] ] ] ) ]; :then [ :args ( [ :constIRI "John" ] [ :varname "item" ] ); :predicate [ :constIRI "" ] ] ]; :univars ( [ :varname "item" ] [ :varname "deliverydate" ] [ :varname "scheduledate" ] [ :varname "diffduration" ] [ :varname "diffdays" ] ) ] [ :formula [ :if [ :args ( [ :varname "item" ] ); :predicate [ :constIRI "" ] ]; :then [ :args ( [ :constIRI "Fred" ] [ :varname "item" ] ); :predicate [ :constIRI "" ] ] ]; :univars ( [ :varname "item" ] ) ] ) .
Editor's Note: To be provided in a future version. This transform may installed, linked from the RIF namespace for automatic use by GRDDL processors [GRDDL]. | http://www.w3.org/TR/2010/WD-rif-in-rdf-20100622/ | CC-MAIN-2017-30 | refinedweb | 1,028 | 51.89 |
The GY-302 from CJMCU is an I2C board that allows you to measure the amount of light using the BH1750 photodetector. We will use the measured brightness to construct an ambient lighting quality indicator based on European Standard EN 12464-1. It is very easy to integrate the sensor GY-302 in an Arduino project or ESP8266 using the library developed by Christopher Laws. It is available on this GitHub page. The GY-302 costs less than one euro.
Add the BH1750 library to the Arduino IDE
Download the ZIP archive of the library from GitHub without decompressing it.
From the Arduino IDE, go to the menu and then Add the .ZIP library
Circuit
The GY-302 module communicates via the I2C bus with the Arduino or ESP8266. The wiring is very simple.
On an Arduino, connect the SDA pin to pin A4 and SCL on pin A5. On the ESP8266 Wemos d1 mini, SDA is in D2 and SCL in D1. For other ESP8266 boards, read this article.
It is possible to manually assign the I2C bus pins using the Wire.h library. At the beginning of the program, the library is declared
#include <Wire.h>
Then in the setup ()
Wire.begin (SDA pin, SCL pin);
Here, all I2C devices are diverted to the new pins.
How to measure the quality of lighting?
In Europe, EN 12464-1 (summary in English and French) defines the minimum lighting levels according to the occupied workplace.
Source: LUX Lighting Review No. 228 May / June 2004 available online.
In a dwelling, there is no specific standard (to my knowledge). Keria, a lighting specialist, has published some common light intensities on his site. Here are excerpts of the recommendations for some rooms of the house (or to obtain a certain atmosphere: intimate, convivial, game, work).
Source :
On the basis of these different data, I constructed a 5-level indicator (too low, low, ideal, high, too high). You can adjust the values according to your habits and needs.
#define _TOOLOW 25 #define _LOW 50 #define _HIGH 500 #define _TOOHIGH 750 #define LEVEL_TOOLOW "Too low" #define LEVEL_LOW "Low" #define LEVEL_OPTIMAL "Ideal" #define LEVEL_HIGH "High" #define LEVEL_TOOHIGH "Too high"
How to use the BH1750 library
The BH1750 library is used very similar to the BME280 library (or BMP180). At the beginning of the program, the library is called and the lightMeter object is initialized by indicating the address of the BH1750 on the I2C bus. By default the BH1750 is located at address 0x23. If you have a conflict with another component, you can assign the address 0x5C by feeding the addr pin to 3.3V.
#include <BH1750.h> BH1750 lightMeter (0x23);
The library supports the 6 modes of operation of the sensor. The sensor can measure continuous brightness
- BH1750_CONTINUOUS_LOW_RES_MODE: Fast measurement (16ms) at low resolution (4 lux of precision)
- BH1750_CONTINUOUS_HIGH_RES_MODE (default mode): High resolution (1 lux accuracy). The measurement time is 120ms
- BH1750_CONTINUOUS_HIGH_RES_MODE_2: Very high resolution (0.5 lux accuracy). Measurement time 120ms
These three other modes allow to realize a single measurement (One_Time) and then to put the sensor in energy saving. Accuracy and measurement time are identical.
- BH1750_ONE_TIME_LOW_RES_MODE
- BH1750_ONE_TIME_HIGH_RES_MODE
- BH1750_ONE_TIME_HIGH_RES_MODE_2
In the setup, the lightMeter object is started by using the function begin (uint8_t mode) by passing it as parameter the measurement mode. The configure (uint8_t mode) function is (called by begin) is also exposed.
void setup(){ lightMeter.begin(BH1750_CONTINUOUS_HIGH_RES_MODE); }
The readLightLevel method reads the light intensity measured by the BH1750 at any time. The function returns the measurement directly to Lux.
uint16_t lux = lightMeter.readLightLevel();
Arduino Code compatible ESP8266
Here is the complete code of the application you just need to upload. It works either on Arduino, ESP8266 or ESP32.
</co/* Mesurer la qualité d'éclairage de votre habitation à l'aide d'un capteur GY-302 (BH1750) Measure the lighting quality of your home with a GY-30 (BH1750) sensor Code basé sur la librairie Arduino de Christopher Laws disponible sur GitHub Based on the Arduino library of Christopher Laws abailable on GitHub Connection: VCC -> 5V (3V3 on Arduino Due, Zero, MKR1000, etc) GND -> GND SCL -> SCL (A5 on Arduino Uno, Leonardo, etc or 21 on Mega and Due) SDA -> SDA (A4 on Arduino Uno, Leonardo, etc or 20 on Mega and Due) ADD -> GND or VCC (see below) ADD pin uses to set sensor I2C address. If it has voltage greater or equal to 0.7VCC voltage (as example, you've connected it to VCC) - sensor address will be 0x5C. In other case (if ADD voltage less than 0.7 * VCC) - sensor address will be 0x23 (by default). - */ #include <Wire.h> #include <BH1750.h> /* * Niveau d'éclairage définit à partir de la norme EN 12464-1 * Lighting level defined from the standard EN 12464-1 * */ #define _TOOLOW 25 #define _LOW 50 #define _HIGH 500 #define _TOOHIGH 750 #define LEVEL_TOOLOW "Trop bas" // Too low #define LEVEL_LOW "Bas" // Low #define LEVEL_OPTIMAL "Idéal" // Ideal #define LEVEL_HIGH "Elevé" // High #define LEVEL_TOOHIGH "Trop élevé" // Too High uint16_t lux = 250; int luxLevel = 3; String luxMessage = LEVEL_OPTIMAL; /*. */ BH1750 lightMeter(0x23); void setup(){ Serial.begin(115200); /* Each mode, has three different precisions: - Low Resolution Mode - (4 lx precision, 16ms measurment time) - High Resolution Mode - (1 lx precision, 120ms measurment time) - High Resolution Mode 2 - (0.5 lx precision, 120ms measurment time) Full mode list: */ lightMeter.begin(BH1750_CONTINUOUS_HIGH_RES_MODE); Serial.println(F("BH1750 Test")); } void loop() { lux = lightMeter.readLightLevel(); if ( lux <= _TOOLOW ) { luxLevel = 1; luxMessage = LEVEL_TOOLOW; } else if ( lux > _TOOLOW && lux <= _LOW ) { luxLevel = 2; luxMessage = LEVEL_LOW; } else if ( lux > _LOW && lux <= _HIGH ) { luxLevel = 3; luxMessage = LEVEL_OPTIMAL; } else if ( lux > _HIGH && lux < _TOOHIGH ) { luxLevel = 4; luxMessage = LEVEL_HIGH; } else { luxLevel = 5; luxMessage = LEVEL_TOOHIGH; } Serial.print("Light: "); Serial.print(lux); Serial.print(" lx, level: "); Serial.print(luxLevel); Serial.print(" , quality: "); Serial.println(luxMessage); delay(1000); }
Here. One more brick finished for our station is monitoring the air quality (and well being).
- | https://diyprojects.io/bh1750-gy-302-measure-lighting-quality-home-arduino-esp8266-esp32/?amp | CC-MAIN-2022-40 | refinedweb | 978 | 55.54 |
Download presentation
Presentation is loading. Please wait.
Published bySara Heath Modified over 3 years ago
1
Chapter 8 Testing a class
2
This chapter discusses n Testing in general. n Testing a single class. n Test plans. n Building a test system.
3
Testing n Testing is an activity whose goal is to determine if the implementation is correct. n A successful test is one that reveals some previously undiscovered error.
4
Testing Phases n Test activities are determined and test data selected. n The test is conducted and test results are compared with expected results.
5
Test design n Begins with an analysis of: u The functional specifications of the system. u The ways in which the system will be used (referred to as use cases). n Testing based on these considerations is referred to as black box testing.
6
Black Box testing n The test designer ignores the internal structure of the implementation in developing the test. n The expected external behavior of the system drives the selection of test activities and data. n The system is treated as a black box whose behavior can be observed, but whose internal structure cannot.
7
Test case n Test cases are defined by: u A statement of case objectives. u The data set for the case. u The expected results.
8
Equivalency groups n Test cases are chosen from each equivalency group. n Particular attention is paid to data that lie on group boundaries.
9
Test plan n A test plan is a document that describes the test cases giving the purpose of each case, the data values to be used, and the expected results. n Test design should be carried out concurrently with system development. n Developing and refining test cases based on the implementation of the system is referred to as white box testing. n A test plan can be based on class specifications only.
10
Test system n Test systems allow us to interact with the object we want to test. n The test system will let us create the object to be tested and then act as a client of the object.
11
Testing Counter n Class specifications: public class Counter A simple integer counter. public Counter () Create a new Counter initialized to 0. public int count () The current count. ensure: this.count() >= 0 public void reset () Reset this Counter to 0. public void increment () Increment the count by 1. public void decrement () Decrement the count by 1. If the count is 0, it is not decremented.
12
Possible system Enter number denoting action to perform: Increment..............1 Decrement..............2 Reset..................3 Create a new Counter...4 Exit...................5 Enter choice. 1 The current count is: 1 Enter number denoting action to perform: Increment..............1 Decrement..............2 Reset..................3 Create a new Counter...4 Exit...................5 Enter choice. 1 The current count is: 2...
13
Building a test system n The test system will be composed of two objects: u A Counter to be tested. u A test driver to invoke the Counters methods. n The test driver prompts the user with a menu, gets input from the user, and provides output in the form of the count.
14
CounterTUI n TUI -> Textual User Interface.
15
Basic input/output n Basic I/O consists of reading from standard input (keyboard) and writing to standard output (monitor).
16
Basic input/output (cont.) n We will use methods provided by the authors (OOJ.basicIO.BasicFileWriter, OOJ.basicIO.BasicFileReader). public BasicFileWriter () Create a BasicFileWriter attached to standard output. public void displayLine (String line) Write the specified line to standard output. public BasicFileReader () Create a BasicFileReader attached to standard input. public void readInt() Reads a new int from standard input. public int lastInt() Returns the int read by readInt(). public void readline () Read rest of line from standard input.
17
CounterTUI specifications public class CounterTUI A text-based test driver for the class Counter. public CounterTUI () Create a new test driver with a Counter to test. public void start () Conduct the test.
18
CounterTUI implementation public class CounterTUI { public CounterTUI () { input = new OOJ.basicIO.BasicFileReader(); output = new OOJ.basicIO.BasicFileWriter(); counter = new Counter(); … } … private OOJ.basicIO.BasicFileReader input; private OOJ.basicIO.BasicFileWriter output; private Counter counter; }
19
CounterTUI implementation (cont.) n If we look at what happens when the test is conducted, we see that the following sequence of actions are repeated over and over: u Display menu to the user and prompt the user for input. u Get the users input. u Perform requested action. u Display results.
20
CounterTUI implementation (cont.) n We define an instance variable to hold the users choice. private int choice; // the users most // recent choice n The local methods we will create are specified as follows. private void displayMenuPrompt () Display the menu to the user. private void getChoice () Get the users choice. private void executeChoice () Perform the action indicated by this.choice, and display the results to the user.
21
While loop n A while loop continues to perform an action as long as a condition is true. The while statement is composed of a condition (a boolean expression) and another statement, the body. n syntax: while ( condition ) body
25
Implementation n main method: the top-level method that initiates execution of a system. n Although the main method is defined in a class, it is really outside the object-oriented paradigm. n Its only purpose should be to create the top level objects and get the system started.
26
Implementation (cont.) /** * A test system for the class Counter. */ public class CounterTest { /** * Create the user interface, start * the system. */ public static void main (String[] argv) { CounterTUI theInterface = new CounterTUI(); theInterface.start(); }
27
Test plan action expected comment increment 1 increment from initial state increment 2 sequence of increments increment 3 increment 4 decrement 3 sequence of decrements decrement 2 increment 3 increment follows decrement reset 0 increment 1 increment follows reset decrement 0 decrement 0 decrement 0 count reset 0 decrement 0 decrement follows reset create 0 initial state decrement 0 decrement from initial state
28
Weve covered n The process of testing. n Test systems. n Text-based user interface. n read-process-write loop. n while loops. n main method.
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/245069/ | CC-MAIN-2017-17 | refinedweb | 1,045 | 59.8 |
and 1 contributors
NAME
App::Tel::Passwd - Methods for managing App::Tel::Passwd:: modules
load_module
my $name = App::Tel::Passwd::load_module($password_module, $file, $passwd);
Loads the module for the specified password store type. Returns the module's namespace.
input_password
my $password = input_password($prompt);
Prompts the user for a password then disables local echo on STDIN, reads a line and returns it.
keyring
my $password = keyring($user, $domain, $group);
Reads a password from a keyring using Passwd::Keyring::Auto if it's available. If the password isn't found the user is prompted to enter a password, then we try to store it in the keyring.
load_from_profile
my $pass = load_from_profile($profile);
Given an App::Tel profile, see if it contains entries for Passwd modules. If it does attempt to load them and return the password associated.
I'm not too happy with the flexibility of this, but I think it will get the job done for right now. | http://web-stage.metacpan.org/pod/App::Tel::Passwd | CC-MAIN-2020-34 | refinedweb | 157 | 53.81 |
MySQL Shell 8.0 (part of MySQL 8.0)
MySQL Shell provides commands which enable you to modify the
execution environment of the code editor, for example to configure
the active programming language or a MySQL Server connection. The
following table lists the commands that are available regardless
of the currently selected language. As commands need to be
available independent of the execution mode,
they start with an escape sequence, the
\
character.
The
\help command can be used with or without
a parameter. When used without a parameter a general help
message is printed including information about the available
MySQL Shell commands, global objects and main help categories.
When used with a parameter, the parameter is used to search the available help based on the mode which the MySQL Shell is currently running in. The parameter can be a word, a command, an API function, or part of an SQL statement. The following categories exist:
AdminAPI - details the
dba global object and the AdminAPI,
which enables you to work with InnoDB Cluster and
InnoDB ReplicaSet.
X DevAPI - details the
mysqlx module as well as the capabilities
of the X DevAPI, which enable you to work with MySQL as a
Document Store
Shell Commands - provides details about
the available built-in MySQL Shell commands.
ShellAPI - contains information about the
shell and
util global
objects, as well as the
mysql module that
enables executing SQL on MySQL Servers.
SQL Syntax - entry point to retrieve
syntax help on SQL statements.
To search for help on a topic, for example an API function, use
the function name as a
pattern. You
can use the wildcard characters
? to match
any single character and
* to match multiple
characters in a search. The wildcard characters can be used one
or more times in the pattern. The following namespaces can also
be used when searching for help:
dba for AdminAPI
mysqlx for X DevAPI
mysql for ShellAPI for classic MySQL protocol
shell for other ShellAPI classes:
Shell,
Sys,
Options
commands for MySQL Shell commands
cmdline for the
mysqlsh command interface
For example to search for help on a topic, issue
and:
pattern
use
x devapi to search for help
on the X DevAPI
use
\c to search for help on the
MySQL Shell
\connect command
use
Cluster or
dba.Cluster to search for help on
the AdminAPI
dba.Cluster() operation
use
Table or
mysqlx.Table to search for help
on the X DevAPI
Table class
when MySQL Shell is running in JavaScript mode, use
isView,
Table.isView or
mysqlx.Table.isView to search for
help on the
isView function of the
Table object
when MySQL Shell is running in Python mode, use
is_view,
Table.is_view or
mysqlx.Table.is_view to search
for help on the
isView function of the
Table object
when MySQL Shell is running in SQL mode, if a global
session to a MySQL server exists SQL help is displayed. For
an overview use
sql syntax as the
search pattern.
Depending on the search pattern provided, one or more results could be found. If only one help topic contains the search pattern in its title, that help topic is displayed. If multiple topic titles match the pattern but one is an exact match, that help topic is displayed, followed by a list of the other topics with pattern matches in their titles. If no exact match is identified, a list of topics with pattern matches in their titles is displayed. If a list of topics is returned, you can select a topic to view from the list by entering the command again with an extended search pattern that matches the title of the relevant topic.
The
\connect command is used to connect to a
MySQL Server. See Section 4.3, “MySQL Shell Connections”.
For example:
\connect root@localhost:3306
If a password is required you are prompted for it.
Use the
--mysqlx (
--mx)
option to create a session using the X Protocol to connect to
MySQL server instance. For example:
\connect --mysqlx root@localhost:33060
Use the
--mysql (
--mc)
option to create a ClassicSession, enabling you to use
classic MySQL protocol to issue SQL directly on a server. For
example:
\connect --mysql root@localhost:3306
The use of a single dash with the short form options (that is,
-mx and
-mc) is deprecated
from version 8.0.13 of MySQL Shell.
The
\reconnect command is specified without
any parameters or options.
\disconnect command, available from
MySQL Shell 8.0.22, is also specified without any parameters or
options. The command disconnects MySQL Shell's global session
(the session represented by the
session
global object) from the currently connected MySQL server
instance, so that you can close the connection but still
continue to use MySQL Shell.
\status command displays information
about the current global connection. This includes information
about the server connected to, the character set in use, uptime,
and so on.
The
\source command or its alias
\. can be used in MySQL Shell's interactive
mode to execute code from a script file at a given path. For
example:
\source /tmp/mydata.sql
You can execute either SQL, JavaScript or Python code. The code in the file is executed using the active language, so to process SQL code the MySQL Shell must be in SQL mode.
As the code is executed using the active language, executing a script in a different language than the currently selected execution mode language could lead to unexpected results. mode, to execute a further script from within the file.
So with MySQL Shell in SQL mode, you could now execute the
script in the
/tmp/mydata.sql file from
either interactive mode or batch mode using any of these three
commands:
source /tmp/mydata.sql; source /tmp/mydata.sql \. /tmp/mydata.sql
The command
\source /tmp/mydata.sql is also
valid, but in interactive mode only.
In interactive mode, the
\source,
\. or
source command
itself is added to the MySQL Shell history, but the contents of
the executed script file are not added to the history.
The
\use command enables you to choose which
schema is active, for example:
\use
schema_name
The
\use command requires a global
development session to be active. The
\use
command sets the current schema to the specified
schema_name and updates the
db variable to the object that represents the
selected schema.
The
\history command lists the commands you
have issued previously in MySQL Shell. Issuing
\history shows history entries in the order
that they were issued with their history entry number, which can
be used with the
\history delete
command.
entry_number
The
\history command provides the following
options:
Use
\history save to save the history
manually.
Use
\history delete entrynumber to delete
the individual history entry with the given number.
Use
\history delete
to delete history entries within the range of the given
entry numbers. If
firstnumber-
lastnumber
goes past the last found history entry number, history
entries are deleted up to and including the last entry.
lastnumber
Use
\history delete
to delete the
history entries from
number-
up to
and including the last entry.
number
Use
\history delete
- to delete the
specified number of history entries starting with the last
entry and working back. For example,
number
\history
delete -10 deletes the last 10 history entries.
Use
\history clear to delete the entire
history.
Note that by default the history is not saved between sessions,
so when you exit MySQL Shell the history of what you issued
during the current session is lost. If you want to keep the
history across sessions, enable the MySQL Shell
history.autoSave option. For more
information, see
Section 5.5, “Code History”.
When you have disabled the autocomplete name cache feature, use
the
\rehash command to manually update the
cache. For example, after you load a new schema by issuing the
\use
command, issue
schema
\rehash to update the
autocomplete name cache. After this autocomplete is aware of the
names used in the database, and you can autocomplete text such
as table names and so on. See
Section 5.3, “Code Autocompletion”.
The
\option command enables you to query and
change MySQL Shellconfiguration options in all modes. You can
use the
\option command to list the
configuration options that have been set and show how their
value was last changed. You can also use it to set and unset
options, either for the session, or persistently in the
MySQL Shell configuration file. For instructions and a list of
the configuration options, see
Section 10.4, “Configuring MySQL Shell Options”.
You can configure MySQL Shell to use an external pager to read long onscreen output, such as the online help or the results of SQL queries. See Section 4.6, “Using a Pager”.
The
\show command runs the named report,
which can be either a built-in MySQL Shell report or a
user-defined report that has been registered with MySQL Shell.
You can specify the standard options for the command, and any
options or additional arguments that the report supports. The
\watch command runs a report in the same way
as the
\show command, but then refreshes the
results at regular intervals until you cancel the command using
Ctrl + C. For instructions, see
Section 7.1.5, “Running MySQL Shell Reports”.
The
\edit (
\e) command
opens a command in the default system editor for editing, then
presents the edited command in MySQL Shell for execution. The
command can also be invoked using the key combination
Ctrl-X Ctrl-E. For details, see
Section 5.4, “Editing Code”.
The
\system (
\!) command
runs the operating system command that you specify as an
argument to the command, then displays the output from the
command in MySQL Shell. MySQL Shell returns an error if it was
unable to execute the command. The output from the command is
returned as given by the operating system, and is not processed
by MySQL Shell's JSON wrapping function or by any external
pager tool that you have specified to display output. | https://docs.oracle.com/cd/E17952_01/mysql-shell-8.0-en/mysql-shell-commands.html | CC-MAIN-2021-04 | refinedweb | 1,665 | 63.49 |
This is somewhat similar to and
The patch in 11624 resolved the issue except in instances where we are accessing files within nested DFS namespaces. In these circumstances the same symptoms as in 11195 are seen.
To reproduce create two DFS namespaces:-
domain.com\namespace1
domain.com\namespace2
Create a folder target inside namespace1 which points to namespace2:-
domain.com\namespace1\Target -> domain.com\namespace2
Then open and close files using domain.com\namespace1\Target
As with 11195 running...
lsof | grep microsoft
...will show multiple connections labelled "microsoft-ds (ESTABLISHED)" to the target server even after the files have been closed. The connections will only be closed once the parent process is terminated.
Accessing multiple files in this way can quickly lead to the file server returning nt_status_too_many_opened_files
Hmmm. Can you can get debug logs to show exactly *when* the extra connections are being made ? That would help me track down the circumstances causing this.
Or indeed, a wireshark trace might also do the trick. I need to determine why when going to the same server name we're not re-using the existing connections in the DFS connection cache.
Sure, no problem.
I tried running:-
smbclient //domain/dfs -W DOMAIN.COM -U username -d10 -l/tmp --option=gensec:gse_krb5=no
...and a /tmp/log.smbclient is created but never written.
I'll try to get Wireshark running tomorrow.
Created attachment 14912 [details]
Debug output from smbclient
OK, I set debug to 10 and tee-d the output. Hope that's OK?
I've attached the log file. As you'll see all I was doing was navigating the folder structure and dir-ing. By the end of this test:-
lsof | grep microsoft-ds | grep smbclient -c
...was showing 30.
I also spotted that in the log there are entries like:-
dos_clean_name [\DFS\Information for Staff\Information for Staff\Information for Students]
unix_clean_name [\DFS\Information for Staff\Information for Staff\Information for Students]
...but the actual path is:-
\DFS\Information for Staff\Information for Students
So it seems to be doubling part of the path up somewhere. Not sure if this is just a display issue but I've also found a problem with renaming files in this type of nested namespace environment where libsmbclient returns that it can't find the file. Could this be related?
At a brief glance it looks like it's not finding the existing cached connections, so it's opening a new connection for every operation.
Even with SMB2 we should be finding existing connections tagged with remote_host name, look at the cli_cm_find(referring_cli, server, share) code in cli_cm_open().
Are you able to rebuild the code ? If so, I might send you a patch adding extra debugs that will show what remote names we're caching and examining why the cached connection lookup isn't working.
Sure. Fire it over when you're ready and I'll build and post back more logs.
Any thoughts on the incorrect paths in the logs?
Created attachment 14916 [details]
Extra debug patch.
Can you try building with this and giving me the level 10 output. Should give me more data on the problems.
Thanks !
Jeremy.
OK, I applied the patch and built with no issues but I don't see any extra output. I'm doing this against the latest CentOS 7 srpm. I guess that's the issue?
You need to run with debug level 10. The extra calls are DBG_DEBUG (log level 10) values. If you're running with debug level 10 but don't see the new calls that at least is showing the SMB2 calls aren't going through the DFS connection manager (which is strange).
So as above?
smbclient //domain/dfs -W DOMAIN.COM -U username -d10 --option=gensec:gse_krb5=no
If so then definitely not seeing any of the additional output. I'm just building from the latest source from samba.org to check if that makes a difference.
OK, just in case it's something strange to do with DBG_DEBUG(), change these calls to d_printf() to have the debug data come out in the normal output stream and re-test. If you still don't see them, then there's a problem that SMB2 just isn't going through the DFS connection caching layer.
Created attachment 14917 [details]
Debug output from smbclient with patch
Rebuilt it from latest and it looks like the additional output is there.
See attached.
OK, this looks like the core of the error:
cli_resolve_path: Calling cli_dfs_get_referral on dfs_path \2012FS\DFS\Information for Staff
signed SMB2 message
cli_resolve_path: Calling cli_cm_find on server domain.com share Information for Staff
cli_cm_find: Looking for connection to server domain.com share Information for Staff
cli_cm_find: List entry server 2012FS share DFS
cli_cm_find: List entry server 2012FS share IPC$
The server / share name pair it should be looking for inside the DFS connection caching code is incorrect.
It seems to be looking for a share called "Information for Staff".
Looks like cli_dfs_get_referral() is working correctly, but then this code:
for (count = 0; count < num_refs; count++) {
if (!split_dfs_path(dfs_refs, refs[count].dfspath,
&dfs_refs[count].server,
&dfs_refs[count].share,
&dfs_refs[count].extrapath)) {
TALLOC_FREE(dfs_refs);
return NT_STATUS_NOT_FOUND;
}
ccli = cli_cm_find(rootcli, dfs_refs[count].server,
dfs_refs[count].share);
if (ccli != NULL) {
extrapath = dfs_refs[count].extrapath;
*targetcli = ccli;
break;
}
}
specifically the split_dfs_path() code is messing up. Extra patch
to follow to discover what is being passed into this function and
what it is doing.
Created attachment 14920 [details]
Extra debug - v2.
Updated patch to give debug info inside split_dfs_path().
Created attachment 14921 [details]
Debug output from smbclient with patch v2
Rebuilt and output attached. I followed the same route through the folder structure as before.
OK, here is the problem:
cli_resolve_path: Calling cli_dfs_get_referral on dfs_path
\2012FS\DFS\Information for Staff
The return from the referral lookup is returning a bogus DFS path of:
signed SMB2 message
split_dfs_path: split_dfs_path: |\domain.com\Information for Staff|
split_dfs_path: server: |domain.com|
split_dfs_path: share: |Information for Staff|
split_dfs_path: extrapath: ||
\domain.com\Information for Staff
Given that - the code is trying to parse it into 'server' \ 'share'
and gives the wrong result.
How are you creating these DFS links ? Are they on a Samba server ?
I will now look into adding debugs into cli_dfs_get_referral() to see what might be doing this. We're making progress (slowly :-).
Created attachment 14922 [details]
Extra debug - v3
OK, here is another version that adds dump_data() calls to the SMB2 request to get the DFS referral. This is essentially a poor-mans wireshark trace (you could also just upload the wireshark traces :-) but will allow me to examine what the request/response data is for the DFS referral lookup.
OK, just building now.
To answer your question about how this is all setup, it's a little out-of-the-ordinary (I hadn't ever come across one like this before) but apparently Microsoft allow it.
There are three separate domain-based DFS namespaces
domain.com\DFS
domain.com\Information for Students
domain.com\Information for Staff
From here, there are folder targets like so:-
domain.com\DFS\Information for Staff -> domain.com\Information for Staff
domain.com\DFS\Information for Students -> domain.com\Information for Students
And then, within the Information for Staff namespace there's one for Information for Students:-
domain.com\Information for Staff\Information for Students -> domain.com\Information for Students
So you effectively end up with:-
domain.com\DFS\Information for Staff\Information for Students
...where "Information for Staff" and "Information for Students" are folder targets to different namespaces. These namespaces are nested within one another.
Again, this isn't something I've seen before but Microsoft do seem to suggest that namespaces can be nested in this way.
I'll post the output back as soon as I have it.
OK, this is starting to look like a strange setup we haven't come across before and the code isn't coping well with - not a generic "DFS is broken with SMB2" bug.
I still want to know what the problem is, but this might take a little longer to fix as we'll need to be able to create a regression test case that duplicates the problem so we can test the fix.
Created attachment 14925 [details]
Debug output from smbclient with patch v3
Yes, I agree. I had to check the docs to confirm that it was actually possible to configure things this way but I've replicated the setup on my network just to be sure.
Latest output attached.
Created attachment 14926 [details]
Debug output from smbclient with patch v3 corrected
Apologies, one of the namespace names is wrong in the previous attachment. Corrected in this one. | https://bugzilla.samba.org/show_bug.cgi?id=13824 | CC-MAIN-2020-40 | refinedweb | 1,448 | 58.18 |
28 February 2012 11:23 [Source: ICIS news]
LEVERKUSEN, Germany (ICIS)--Bayer MaterialScience performed below expectations in the fourth quarter and in the whole of 2011, German chemical producer Bayer's CEO said on Tuesday.
Marijn Dekkers reported that Bayer MaterialScience, Bayer's business with high-performance plastics, saw earnings fall because raw material cost increases could not be passed on to customers in the second half of the year.
Higher operating costs were also incurred, including those for commissioning a toluene di-isocyanate (TDI) plant in ?xml:namespace>
“The MaterialScience business unfortunately performed below expectations in 2011,” said Dekkers.
“Although sales rose by 8% [on a currency-adjusted basis] compared with 2010, to €10.8bn, EBITDA [earnings before interest, tax, depreciation and amortisation] before special items was down by nearly 14% to €1.17bn. As a result, the underlying EBITDA margin for 2011 receded by a substantial 2.6 percentage points,” he added.
Within the MaterialScience segment, sales from its business unit with raw material for foams (polyurethanes) in 2011 improved by 9.5% year on year, high-tech plastics (polycarbonates) improved by 5.6% year on year, and raw material coatings, adhesives and specialities were up by 4.5%. Sales in the segment's industrial operations business achieved year-on-year sales growth of 22%.
Dekkers said that although it was a positive factor that sales had increased, the company scarcely achieved any volume increases.
He added that the segment had also felt the negative effects of the economic uncertainty in the fourth quarter.
In the fourth quarter, sales at the MaterialScience business grew by 0.5% to €2.60bn, while EBITDA fell by 49.5% to €150m ($200m).
Earlier on Tuesday, Bayer reported that it swung to an overall fourth-quarter net profit of €397m, from a net loss of €145m in the same period a year earlier, and posted a 2% year-on-year rise in sales to €9.19bn
EBITDA decreased by 6.3% to €1.42bn compared with the same period in 2010 because of a decline in earnings from the MaterialScience segment, said Bayer.
“Overall business development in the fourth quarter showed a mixed picture,” said company CFO Werner Baumann.
EBITDA for the fourth quarter at Bayer’s Healthcare and CropScience businesses improved by 13% and 2.9% respectively.
The company’s net profit in 2011 grew by 89.9% year on year to €2.47bn, while sales rose by 4.1% to €36.5bn, it said. EBITDA at its Healthcare segment in 2011 grew by 9.4% to €4.50bn, and its CropScience unit earnings surged to €1.22bn, from €767m in 2010, Baumann said.
The group’s total EBITDA in 2011 grew by 10.1% year on year to €6.92bn, | http://www.icis.com/Articles/2012/02/28/9536352/MaterialScience-performance-below-expectations-Bayer.html | CC-MAIN-2014-10 | refinedweb | 460 | 67.76 |
Latent Variable Implementation¶
The
gp.Latent class is a direct implementation of a GP. It is called
“Latent” because the underlying function values are treated as latent
variables. It has a
prior method, and a
conditional method.
Given a mean and covariance function, the function \(f(x)\) is
modeled as,
.prior¶
With some data set of finite size, the
prior method places a
multivariate normal prior distribution on the vector of function values,
\(\mathbf{f}\),
where the vector \(\mathbf{m}\) and the matrix \(\mathbf{K}_{xx}\) are the mean vector and covariance matrix evaluated over the inputs \(x\). Some sample code is,
import numpy as np import pymc3 as pm # A one dimensional column vector of inputs. X = np.linspace(0, 1, 10)[:,None] with pm.Model() as latent_gp_model: # Specify the covariance function. cov_func = pm.gp.cov.ExpQuad(1, ls=0.1) # Specify the GP. The default mean function is `Zero`. gp = pm.gp.Latent(cov_func=cov_func) # Place a GP prior over the function f. f = gp.prior("f", X=X)
By default, PyMC3 reparameterizes the prior on
f under the hood by
rotating it with the Cholesky factor of its covariance matrix. This
helps to reduce covariances in the posterior of the transformed random
variable,
v. The reparameterized model is,
For more information about this reparameterization, see the section on
drawing values from a multivariate
distribution.
This reparameterization can be disabled by setting the optional flag in
the
prior method,
reparameterize = False. The default is
True.
.conditional¶
The conditional method implements the predictive distribution for function values that were not part of the original data set. This distribution is,
Using the same
gp object we defined above, we can construct a random
variable with this distribution by,
# vector of new X points we want to predict the function at X_star = np.linspace(0, 2, 100)[:, None] with latent_gp_model: f_star = gp.conditional("f_star", X_star)
Example 1: Regression with Student-T distributed noise¶
The following is an example showing how to specify a simple model with a
GP prior using the
gp.Latent class. So we can verify that the
inference we perform is correct, the data set is made using a draw from
a GP.
In [1]:
import sys import pymc3 as pm import theano.tensor as tt import numpy as np import matplotlib.pyplot as plt %matplotlib inline
In [2]:
# set the seed np.random.seed(1) n = 100 # The number of data points X = np.linspace(0, 10, n)[:, None] # The inputs to the GP, they must be arranged as a column vector # T distributed noise # The standard deviation of the noise is `sigma`, and the degrees of freedom is `nu` σ_true = 2.0 ν_true = 3.0 y = f_true + σ_true * np.random.standard_t(ν_true, size=n) ## Plot the data and the unobserved latent function fig = plt.figure(figsize=(12,5)); ax = fig.gca() ax.plot(X, f_true, "dodgerblue", lw=3, label="True f"); ax.plot(X, y, 'ok', ms=3, label="Data"); ax.set_xlabel("X"); ax.set_ylabel("y"); plt.legend();
The data above shows the observations, marked with black dots, of the unknown function \(f(x)\) that has been corrupted by noise. The true function is in blue.
Coding the model in PyMC3¶
Here’s the model in PyMC3. We use a \(\text{Gamma}(2, 1)\) prior over the lengthscale parameter, and weakly informative \(\text{HalfCauchy}(5)\) priors over the covariance function scale, and noise scale. A \(\text{Gamma}(2, 0.1)\) prior is assigned to the degrees of freedom parameter of the noise. Finally, a GP prior is placed on the unknown function. For more information on choosing priors in Gaussian process models, check out some of recommendations by the Stan folks.
In [3]:
with pm.Model() as model: ℓ = pm.Gamma("ℓ", alpha=2, beta=1) η = pm.HalfCauchy("η", beta=5) cov = η**2 * pm.gp.cov.Matern52(1, ℓ) gp = pm.gp.Latent(cov_func=cov) f = gp.prior("f", X=X) σ = pm.HalfCauchy("σ", beta=5) ν = pm.Gamma("ν", alpha=2, beta=0.1) y_ = pm.StudentT("y", mu=f, lam=1.0/σ, nu=ν, observed=y) trace = pm.sample(1000)
Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... 100%|██████████| 1500/1500 [04:02<00:00, 7.41it/s]
Results¶
Below are the posteriors of the covariance function hyperparameters. The red lines show the true values that were used to draw the function from the GP.
In [4]:
pm.traceplot(trace, lines={"η": η_true, "σ": σ_true, "ℓ": ℓ_true, "ν": ν_true}, varnames=["η", "σ", "ℓ", "ν"]);
In [5]:
# plot the results fig = plt.figure(figsize=(12,5)); ax = fig.gca() # plot the samples from the gp posterior with samples and shading from pymc3.gp.util import plot_gp_dist plot_gp_dist(ax, trace["f"], X); # plot the data and the true latent function plt.plot(X, f_true, "dodgerblue", lw=3, label="True f"); plt.plot(X, y, 'ok', ms=3, alpha=0.5, label="Observed data"); # axis labels and title plt.xlabel("X"); plt.ylabel("True f(x)"); plt.title("Posterior distribution over $f(x)$ at the observed values"); plt.legend();
As you can see by the red shading, the posterior of the GP prior over the function does a great job of representing both the fit, and the uncertainty caused by the additive noise. The result also doesn’t over fit due to outliers from the Student-T noise model.
Using
.conditional¶
Next, we extend the model by adding the conditional distribution so we
can predict at new \(x\) locations. Lets see how the extrapolation
looks out to higher \(x\). To do this, we extend our
model with
the
conditional distribution of the GP. Then, we can sample from it
using the
trace and the
sample_posterior_predictive function.
This is similar to how Stan uses its
generated quantities {...}
blocks. We could have included
gp.conditional in the model before
we did the NUTS sampling, but it is more efficient to separate these
steps.
In [6]:
# 200 new values from x=0 to x=15 n_new = 200 X_new = np.linspace(0, 15, n_new)[:,None] # add the GP conditional to the model, given the new X values with model: f_pred = gp.conditional("f_pred", X_new) # Sample from the GP conditional distribution with model: pred_samples = pm.sample_posterior_predictive(trace, vars=[f_pred], samples=1000)
100%|██████████| 1000/1000 [00:18<00:00, 50.64it/s]
In [7]:
# plot the results fig = plt.figure(figsize=(12,5)); ax = fig.gca() plot_gp_dist(ax, pred_samples["f_pred"], X_new); plt.plot(X, f_true, "dodgerblue", lw=3, label="True f"); plt.plot(X, y, 'ok', ms=3, alpha=0.5, label="Observed data"); plt.xlabel("X"); plt.ylabel("True f(x)"); plt.title("Conditional distribution of f_*, given f"); plt.legend();
Example 2: Classification¶
First we use a GP to generate some data that follows a Bernoulli distribution, where \(p\), the probability of a one instead of a zero is a function of \(x\).
In [8]:
np.random.seed(1) # number of data points n = 200 # x locations x = np.linspace(0, 1.5, n) # true covariance ℓ_true = 0.1 η_true = 1.0 cov_func = η_true**2 * pm.gp.cov.ExpQuad(1, ℓ_true) K = cov_func(x[:,None]).eval() # zero mean function mean = np.zeros(n) # sample from the gp prior f_true = np.random.multivariate_normal(mean, K + 1e-6 * np.eye(n), 1).flatten() # link function def invlogit(x, eps=sys.float_info.epsilon): return (1.0 + 2.0 * eps) / (1.0 + np.exp(-x)) + eps y = pm.Bernoulli.dist(p=invlogit(f_true)).random()
In [9]:
fig = plt.figure(figsize=(12,5)); ax = fig.gca() ax.plot(x, invlogit(f_true), 'dodgerblue', lw=3, label="True rate"); ax.plot(x, y + np.random.randn(n)*0.01, 'ko', ms=3, label="Observed data"); ax.set_xlabel("X"); ax.set_ylabel("y"); plt.legend();
In [10]:
with pm.Model() as model: # covariance function ℓ = pm.Gamma("ℓ", alpha=2, beta=2) # informative, positive normal prior on the period η = pm.HalfNormal("η", sd=5) cov = η**2 * pm.gp.cov.ExpQuad(1, ℓ) gp = pm.gp.Latent(cov_func=cov) # make gp prior f = gp.prior("f", X=x[:,None]) # logit link and Bernoulli likelihood p = pm.Deterministic("p", pm.math.invlogit(f)) y_ = pm.Bernoulli("y", p=p, observed=y) trace = pm.sample(1000)
Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... 100%|██████████| 1500/1500 [06:34<00:00, 8.11it/s]/Users/colin/projects/pymc3/pymc3/step_methods/hmc/nuts.py:451: UserWarning: The acceptance probability in chain 0 does not match the target. It is 0.696329285313, but should be close to 0.8. Try to increase the number of tuning steps. % (self._chain_id, mean_accept, target_accept))
In [11]:
pm.traceplot(trace, lines={"ℓ": ℓ_true, "η": η_true});
In [12]:
n_pred = 200 X_new = np.linspace(0, 2.0, n_pred)[:,None] with model: f_pred = gp.conditional("f_pred", X_new) with model: pred_samples = pm.sample_posterior_predictive(trace, vars=[f_pred], samples=1000)
100%|██████████| 1000/1000 [00:11<00:00, 90.75it/s]
In [13]:
# plot the results fig = plt.figure(figsize=(12,5)); ax = fig.gca() # plot the samples from the gp posterior with samples and shading plot_gp_dist(ax, invlogit(trace["f"]), x); # plot the data (with some jitter) and the true latent function plt.plot(x, invlogit(f_true), "dodgerblue", lw=3, label="True f"); plt.plot(x, y + np.random.randn(y.shape[0])*0.01, 'ok', ms=3, alpha=0.5, label="Observed data"); # axis labels and title plt.xlabel("X"); plt.ylabel("True f(x)"); plt.title("Posterior distribution over $f(x)$ at the observed values"); plt.legend();
| https://docs.pymc.io/notebooks/GP-Latent.html | CC-MAIN-2018-47 | refinedweb | 1,583 | 54.08 |
Java recursion and inheritance - java
I have two classes like below:
public class Animal {
public void askForLocation() {
System.out.println("In animal");
System.out.println("Street?");
Scanner inFromConsole = new Scanner(System.in);
String street = inFromConsole.nextLine();
if (street.equals(""))
this.askForLocation();
else
System.out.println("Street: " + street);
}
}
}
public class Dog extends Animal {
#Override
public void askForLocation() {
Scanner inFromConsole = new Scanner(System.in);
System.out.println("In dog");
String city;
super.askForLocation();
System.out.println("Back in dog");
System.out.println("City?");
city = inFromConsole.nextLine();
System.out.println("city: " + city);
}
}
Then I run the following code:
public class TestAnimals {
public static void main(String[] args) {
System.out.println("----");
Dog doggy = new Dog();
doggy.askForLocation();
}
}
When I give an empty string as an argument for street the first time I get the following output:
1 In dog
2 In animal
3 Street?
4
5 In dog
6 In animal
7 Street?
8 Main Street
9 Street: Main Street
10 Back in dog
11 City?
12 NY
13 city: NY
14 Back in dog
15 City?
16 NY
17 city: NY
It's two things that I don't understand:
In line 5 of the output the call to askForLocation is a call to askForLocation in the class Dog and not in the class Animal.
Why is this? I want it to call askForLocation in the class Animal, so I was expecting not to see line 5 at all.
Line 14-17 in the output. I can't understand why the code executes tt all. I was expecting it to end at line 13.
Would be really nice if someone could explain this.
I can get around the problem by renaming the method askForLocation() in the class dog to for example askForLocation2(), but I want to know how it works.
Answer to question 1 : "this" refers to the current object being executed. In your case current object being executed is "Dog". Since Java uses dynamic binding for resolving overriding methods, so this.askForLocation(), will invoke the method of Dog class.
Answer to question 2 : you can understand this by creating a stack trace.
main(1) ->
Dog,askForLocation(2)->
Animal,askForLocation(3) ->
Dog,askForLocation(4)->
Animal,askForLocation(5)
After completing 5th one, control will go back to 4 one, will complete the remaining statements(statements after super.askForLocation(); ), call to 3rd one is already completed, then control will go back to 2 one executing the remaining statements(statements after super.askForLocation(); ), finally control will come back to main() where program will finish execution.
What you are seeing with the askForLocation method is called 'dynamic binding'. When you call a (non-private) instance method, then Java resolves the class of the instance at runtime, in this case Dog, and will always look for this method in that class first. Only if it doesn't find it there, it "goes up the inheritence ladder" (from point of view of your code), in this case to class Animal. But as you have overriden the method in class Dog, it will always execute the overriden version of the method from the Dog class, no matter from what class you call it. Note that this in class Animal refers to the instance in context, which is still a Dog.
I guess you could just put your code in the Animal class in a loop instead of doing recursive calls to the method. But there may be a better way to do it, my answer is mainly about explaining to you why your program behaves as it does.
On start of execution from here doggy.askForLocation(); you got Dog class function callled-
public void askForLocation() {
Scanner inFromConsole = new Scanner(System.in);
System.out.println("In dog");
String city;
super.askForLocation();
System.out.println("Back in dog");
System.out.println("City?");
city = inFromConsole.nextLine();
System.out.println("city: " + city);
}
Now when it came to super.askForLocation() it went to Animal class and from there you entered nothing so it called this.askForLocatioon(). Now this refers to the current object which is doggy of Dog class so again Dog's class function -askForLocation() called on line 5 . Now in animal class you enter the street and control passes back to the Dog class function and you run the rest of the code.
After this, the control passes to the first instance of askForLocation() function in the stack that could not complete because u called this.askForLocation().
And thats why you get the code repeated 14-17.
The subsequent function calls get stacked up in the stack.
A simple workaround could be like this:
public class Animal {
public void askForLocation() {
System.out.println("In animal");
System.out.println("Street?");
Scanner inFromConsole = new Scanner(System.in);
String street = inFromConsole.nextLine();
while (street.equals("")) {
System.out.println("Street?");
street = inFromConsole.nextLine();
}
else
System.out.println("Street: " + street);
}
}
}
There could be better workarounds too.
The recursive call in Animal#askForLocation calls askForLocation on this. It doesn't call Animal#askForLocation. It calls this.askForLocation, whatever that is. If this is a Dog, it calls Dog#askForLocation, because that's what would happen in any other code, whether its in another method in Animal, or outside these classes entirely. Imagine, e.g. doing Animal foo; if (bar) foo = this else foo = ...; foo.askForLocation();. You need to be specific that you want to call the code written in the Animal class. The easiest way is:
public class Animal {
private void askForLocationLoop() {
// ...
}
public void askForLocation() {
askForLocationLoop();
}
}
public class Dog extends Anumal {
#Override
public void askForLocation() {
// ...
}
}
private methods entirely bypass virtual dispatch; any recursive call in askForLocationLoop will always go back to it, even if a subclass declares another method with the same name, because it's a private method.
For your output, I'll show you the call stack for each line:
1: Dog#askForLocation
2-4: Dog#askForLocation > Animal#askForLocation
5: Dog#askForLocation > Animal#askForLocation > Dog#askForLocation
6-9: Dog#askForLocation > Animal#askForLocation > Dog#askForLocation > Animal#askForLocation
10-13: Dog#askForLocation > Animal#askForLocation > Dog#askForLocation
14-17: Dog#askForLocation.
There are two Dog#askForLocations in the stack. When the second one returns, the Animal#askForLocation above it also returns, so between 13 and 14 we go up two methods.
Now, for "fun"
// given f : (A -> B) -> (A -> B), calculate g : A -> B
// such that f(g) = g, making g the fixed point of f,
// and then call g on an A
static <A, B> B fix(Function<Function<A, B>, Function<A, B>> f, A a) {
return f.apply(a2 -> fix(f, a2)).apply(a);
}
public class Animal
public void askForLocation() {
Function<Function<Void, Void>, Function<Void, Void>> step = continu -> ign -> {
System.out.println("In animal");
System.out.println("Street?");
String street = new Scanner(System.in).nextLine();
if(street.equals(""))
return continu.apply(null);
else
System.out.println("Street: " + street);
return null;
};
fix(step, null);
// we write step in terms of open recursion; it gets an argument
// continu that it can call to "recurse" and fix feeds step to itself.
// that is; fix lets you write recursion indirectly.
}
}
Now you don't have to explicitly write a private method (but the compiler will end up doing so anyway by lifting the lambda).
Or you may just use a do-while loop:
public class Animal
public void askForLocation() {
String street;
do {
System.out.println("In animal");
System.out.println("Street?");
street = new Scanner(System.in).nextLine();
} while(street.equals(""));
System.out.println("Street: " + street);
}
}
Related
The relation between the declared type and created type
I have an question about the following code (Is this call dynamic binding?). I feel confused about 3 point. First, what is the mean of the variable pq? Does pd still be the data type of P or be the Q? Second, when I invoke the pq.m(pp) method, why the result become Q::P but not P::Q? Finally, what is this mean ((P) qq).m(qq);? I hope somebody could solve my problem. The result of the following code will be P::Q, Q::P, Q::Q, R::P, Q::P, Q::Q, Q::Q class Test { public static void main(String[] args) { P pp = new P(); Q qq = new Q(); R rr = new R(); P pq = qq; pp.m(qq); pq.m(pp); pq.m(qq); rr.m(pp); qq.m(pq); qq.m(qq); ((P) qq).m(qq); } } class P { public void m(P p){System.out.println("P::P"); } public void m(Q p){System.out.println("P::Q"); } public void m(R c){System.out.println("P::R"); } } class Q extends P { public void m(P p){System.out.println("Q::P"); } public void m(Q p){System.out.println("Q::Q"); } public void m(R c){System.out.println("Q::R"); } } class R extends Q { public void m(P p){System.out.println("R::P"); } public void m(Q p){System.out.println("R::Q"); } public void m(R c){System.out.println("R::R"); } }
P pq = qq; means that pq is known to the rest of the program as a type P. But as the creator, you know it's really of type Q. So this means that when you call pq.m(), it's really calling the implementation from class Q. It's called overriding a method. So when you call pq.m(pp), you are really calling: public void m(P p){System.out.println("Q::P"); because that is the method from class Q. If Q did not have a m(P) method, then it would automatically call the superclass method, the one from P. ((P) qq).m(qq); is the same as doing: P pqq = (P)qq; // pqq is known as P type, but it's instance is still the original Q type pqq.m(qq); // Again, since pqq is truly an instance of Q, it calls Q.m(Q) You should really read about inheritance. This is a bigger subject than can be explained here. All this being said, your example doesn't illustrate its power well. But for example, if class Q had an extra method, public void sayHello();, then Q q = new Q(); P p = new Q(); q.sayHello(); // This would be legal p.sayHello(); // This would be illegal because the compiler knows p as a declared instance of P, even though you know it's truly a Q. ((Q)p).sayHello(); // This would be legal because you told the compiler to look at p as an instance of Q. It's called a cast. I hope this all helps. Be sure to go read up on object orientation.
Starting, I think you mean pq, not pd. Since Q extends P, Q is also a P type. It's like saying that an apple is a fruit. So you take the apple (Q) and says: It's a fruit (P). When you call the pq methods, they will call the methods from the Q class, since pq is still a Q object. In the last part, when you do ((P) qq).m(qq);, is the same as doing the following: P p = (P) qq; q.m(qq); So as said above, the code will still call the method from the Q class, printing "Q::Q"
Dynamic binding, and therefore polymorphism, only works for the object to the left of the dot in a method call (o.m(x) -- only for o). The arguments types are resolved statically, at compile time. Take a more well-known situation: class A { public boolean equals(A other) { System.out.println("A.equals called"); return true; } } A a1 = new A(), a2 = new A(); Object o = a1; o.equals(a1); // doesn't print anything a1.equals(o); // doesn't print anything a1.equals(a2); // prints "A.equals called" The point here is that class A doesn't override Object.equals(Object), but instead just adds another overloaded method A.equals(A) -- and that one gets called only when the argument is of a declared type A.
Java - Method declared but cannot reference it
I am kind of new to Java, although I've programmed in other procedural langauages for 25 years. So, I'm trying to teach myself Java. Trying to write some silly program consisting of two files: a Class called "Customer", and a main program called "Silly4". I'm pretending to implement a credit card system for a bank type company (even though the majority of my experience was in defense contracting). I figure this would be a good teaching example for me. Trying to build a credit card data structure called "Customer" such that (for the time being) it can accomodate 1000 customers. In the main program "Silly4", I instantiate this Customer class as "cust2", and then from there I attempt to work with "cust2". I try to retrieve customer number 5's (j=5) credit card balance. So far, so good. Then from there I attempt to declare in the class Customer another method (for future use) which I arbitrarily call "bal44", and then I attempt to reference it in the main program Silly4 as " ball44(5541);". So I compile class Customer, then compile program Silly4, and I'm getting a compile error "java:52: error: cannot find symbol" for the reference to method "bal44(5541)" in main program "Silly4". I'm confused. I've declared and successfully compiled the class Customer with "bal44" in there, but Java is telling me it can't find it. I'm confused. Please excuse all the extraneous println's, I use them to see how the program is moving along. Here is class Customer: // Data Structure for credit card database public class Customer { private String name; private int accountNo; private double balance; private boolean Overdue; // Getters, setters, constructor... public void setName( String new_name ) { name = new_name; } public void setAccount( int new_account ) { accountNo = new_account; } public void setBalance( double new_bal ) { System.out.println( " Start proc setBalance "); balance = new_bal; System.out.println( " Finish proc setBalance "); } public double getBalance() { System.out.println( " Start proc getBalance "); System.out.println( " proc getBalance , balance= " + balance + " end print"); return balance; // how to specify which element of array[1000] ? balance I want ? // System.out.println( " Finish proc getBalance "); } // Add new customer to credit card system // (note - index in array Customer[i] is worry of main program // public void addCustomer( String name2, int account2, double bal2 ) { name = name2; accountNo = account2; balance = bal2; } public void bal44 ( int account3 ) { accountNo = account3; } // Constructor Customer () { name = "John Smith"; accountNo = 1005; balance = 125.43; Overdue = false; } // see page 1032 Liang for definition complex Object and get-Procs for it } Here is main program/class Silly4: class Silly4 { // Program for credit card database public static void main(String[] args) { double bal2, bal3; int i; // loop counter int j; bal2 = 151.47; bal3 = 5.0; // just initialize // And then you can create an array of it: System.out.println("** Program Silly4 Running **"); Customer[] cust2 = new Customer[1000]; System.out.println("** Array cust2 instantiated **"); for(i=0; i<=999; ++i) { cust2[i] = new Customer(); } System.out.println("** Array2 cust2 Obj initialized **"); // try to code this eventually - cust2.balance = 151.47 ; // j = 5; // customer no. 5 cust2[j].setBalance( bal2 ); bal3 = cust2[j].getBalance() ; System.out.println("** Balance Customer " + j + " is " + bal3); // Add a new customer // comment out - addCustomer( "Steve Jones", 5541, 1.0 ); bal44( 5541 ); // test out declaring new method "bal44" System.out.println("** End of Silly4 **"); } }
You basically answered yourself in the first sentence of your query. Java is not a purely procedural language, it's an object-oriented language. That means that when you declare methods, they are not just scoped functions. A method declared in a class is not similar to a function declared in an included file in C. It's something that can be only called from the scope of an object of the enclosing class. In other words, you don't have a function named bal44. You have a method bal44 of class Customer, which means that you need to ask an object fo class Customer to execute it for you, similar to how you call setBalance(). EDIT: As another comment mentions, what might be confusing you more is that whenever you use a method name without qualifiers, Java treats it as a shortcut of asking this (the current object) to execute the method, so technically, method(args) is a shortcut for this.method(args). Therefore, whenever you are within the scope of a single class, a class's methods will behave almost as traditional functions.
When you call bal44( 5541 ); Without any object, Java assumes it as a "this" object and searches for that method in Silly4 not in Customer class. Call that method from Silly4 like you are calling other method of customer class. e.g. cust2[j]. bal44( 5541 ); or something like that. Read more about "this" here P.S. A bonus point to note here is that static method's like main method do not have this reference available to them. So, technically here it is searching for a class-level(static) method in Silly4 rather than instance method. :)
See, here is the problem : You are using the bal44(5541), but you made that method non static, meaning you need to make an object of your class (Customer) and then say for example Customer customer = new Customer() customer.bal(5541); If you want to call that method without making an object of its class, simply put the keyword "static" in the method's header. public static void bal44(int num) Further explanation : Since you are from a procedural language, recall the main difference is the usage of objects. An object is something that has several traits, or attributes, and actions or behaviors. For example a car, its attributes are its color, speed, etc. and its main action/behavior is drive. Attributes are variables, and Behaviors/Actions are methods. e.g. car.drive(); car.setColor("red"); I hope that helped? If you don't understand you can PM me or respond here and I'll explain in further detail
logical error in this java code, how do i resolve this error?
public class DogOwner extends Dog { public static void main(String[] args){ Dog dog1 = new Dog (); Dog dog2 = new Dog(); Dog dog3 = new Dog(); dog1.setLegs(4); dog1.setTail(true); dog3.setFur(" furry fur"); System.out.println("this dog has"+ dog1.GetLeg()+"legs"); System.out.println("does this dog have a tail?"+ dog2.Gettail()); System.out.println("this dog has"+ dog3.GetFur()); } } } }enter code here enter code here public class Dog { /** variables**/ int Legs; boolean tail; String Fur; /** returns the Legs variable (getter) **/ public int GetLeg(){ return Legs; } /** stores method variable Llgs within variable legs (setter) **/ public void setLegs(int legs){ this.Legs=legs; } /** returns the tail variable (getter) **/ public boolean Gettail(){ return tail; } /** stores method variable tail within variable tail (setter) **/ public void setTail(boolean tail){ this.tail=tail; } /**because the void does not work with String data type, the type String * replaces void to make this code work (Hovercraft Full Of Eels, 2013) * Hovercraft Full Of Eels.2013.why is this code not working in Java?. * accessed from:. * stockoverflow.com. [accessed: 14/12/2013]**/ public String GetFur(){ return Fur; } /**stores for the method variable within the parameter variable Fur **/ public void setFur(String fur){ this.Fur=fur; } } the output that i wanted was: this dog has 4 legs, Does this dog have a tail? True, this dog has furry fur the text true should not be text and it should execute what the boolean value is, in this case it should execute true without the use of quoatation mark (hope this makes sense). im a beginner at Java and I can't seem to understand fully on how to code in java (or any programming language) using books. I require assistance from someone to fully understand coding. Also please explain how this code was resolved so I can understand the problem and how to resolve these types of problem in the future (hopefully). thanks in advance.
You can't just put the object in the output string and expect it to know what you mean. when you add a regular object to a string, it calls its toString() method, which you haven't defined and defaults to what looks like a bunch of grable... Instead, you need to do something like System.out.println("this dog has"+ dog1.getLegs() +"legs"); and likewise on the others.
You don't seem to be calling the methods, just inserting the objects into the strings - this won't work in a sensible manner most of the time. Try calling the 'get' methods you've implemented. "this dog has " + dog1.GetLegs() + " legs"; "does this dog have a tail? " + dog2.GetTail(); "this dog has " + dog3.GetFur() + " fur";
On the lines where you print the information you print the object instead of one of the properties for it. Change the first System.out.println to: System.out.println("this dog has"+ dog1.GetLeg() +"legs"); I think you will figure out how to change the other rows :)
Head First Java example explanation needed
Hi! I'm reading Head First Java and i can't understand the behaviour of the following code: public class Dog { String name;; } } public void bark() { System.out.println(name + " says Ruff!"); } The output produced by this code is the following: null says Ruff! last dog name is Bart Fred says Ruff! Marge says Ruff! Bart says Ruff! I have a very hard time understanding this, IMO the code should run to somekind of infinite loop. From what i understand (and i've previously programmed in python): When the class is acticated, the main method gets called, and then inside the main method, two more classes of the same type are created. (Now here comes the incomprehensible part -->) When the new class is created, inside it's main method, 2 more classes are created and so on .. How can it be that it produces the output shown above, when it creates an infinte number of classes, so the code should actually never finish running. Thank you!
The code you've posted just instantiates a total of 3 instances of the Dog class. The myDogs array has 3 elements, so the while loop is guaranteed to terminate. What's not clear? The main method is called only when executing the program. Your program could have been written like this (more clear for a Java beginner, I think): class Dog { String name; public void bark() { System.out.println(name + " says Ruff!"); } } public class MyDogTest {; } } } If you put the two classes (Dog and MyDogTest) inside the same .java file, please note that only MyDogTest should be declared as public, otherwise the program won't compile.
You're misunderstanding the main() method. Java calls the main() method when you start executing a program. Instantiating a class does not run the main() method; it will just run the class's constructor.
Instantiating a class will call the constructor of the class. You didn't define one, so your constructor is actually one without parameters and without body, like this: public Dog () { } Of course, this constructor will never cause an infinite loop. The main method is the one called when starting your program and thus called exactly once.
Notice the static keyword in the main() method declaration. It means that the method is always accessible, unrelated to a specific class instance. (Since you come from Python world, you are welcome to read a bit about the field modifiers). You can in a way observe it as "an external" method (meaning you can always access it externally and execute it with Dog.main(your string args)), that is not "aware" of the class existence. Also notice that multiple classes that you use can have main method, in which case you should decide which one is the really the main one, by declaring it in the manifest file, but this is a bit advanced topic, that is left for your further research. And of course, as the others already explained, main method is a specific method that the JVM runs once, in the moment you execute your program.
Recursive java method, get mother, grand mother, great grand mother and so on
I have a list Dogs in a text file with the following format: id:fatherid:motherid:born:owner:breed ex: 3:2:1:2000:Scotty:Peter:dachs I then populate an array list with objects of dog. I Need a method that returns all the mothers for a dog with a given id. I already have methods for: getMother, getDog, getChildren, getParents, existDog. getDog and getMother returns a Dog, getChildren and getParents returns a String. Now i need a method that gives me the mother, grand mother, great grand mother and so on. I do not know how to make this method. This code gives me the mother and grand mother of a dog: public String getMotherTree(int id) { String output = ""; if (existDog(id)) { Dog mother = GetMother(id); output += mother.toString(); int morId = mother.getId(); Dog grandMother= GetMother(motherId); output += grandMother.toString; return output; } output = "The dog with that id do not exist!"; return output; } I think that what i need is a recursive method, but i do not know how to do this.
Basically, you'd create a method that calls itself with another parameter unless some condition is met. In your case, you might use getMotherTree() (or some adjusted method): public String getMotherTree(int id) { String output = ""; if (existDog(id)) { Dog mother = GetMother(id); output += mother.toString(); int morId = mother.getId(); return output + ", " + getMotherTree(morId); //recursion } //return an empty string if the dog doesn't exist //this basically ends the recursion return output; } As BalusC pointed out recursion is not necessary here, so please view that as a learning exercise only.
You don't need recursion for this: you could replace your IF with a WHILE, and after adding the mother to the String, replace id with the id of the mother. (If you still want a message if the dog doesn't exist, just check if output is blank or not before returning.) Note that you have a logic problem (which what I just described doesn't solve): just because a dog exists doesn't mean it has a mother (or your loop/recursion would never end!), so calls to any method of this missing mother should fail.
It can be done recursively (which is computationally expensive but perhaps simpler code to understand) or can be done iteratively. Here's an iterative solution: public String getMotherTree(int id) { if (!existDog(id)) { return "The dog with that id do not exist!"; } StringBuilder output = new StringBuilder(); for (Dog mother = GetMother(id); mother != null; mother = mother.getMother()) { if (output.length() > 0) { output.append(", "); } output.append(mother.toString()); } return output.toString(); } This assumes that aDog.getMother() returns null if aDog has no mother in the data base. | https://java.develop-bugs.com/article/10000312/Java+recursion+and+inheritance | CC-MAIN-2021-21 | refinedweb | 4,472 | 65.83 |
# The first viewer issue, or the difficulties of converting WebRTC video streams to HLS

George shut his laptop and rubbed his sleep-deprived red eyes. "Customers continue to complain about stream freezing; the new fix package did not help at all! What do I do with this (censored) HLS?" he said.
The browser is not only hypertext, but also a streamer
------------------------------------------------------
Browsers have had players for a long time, but the story is different with the video encoder and streaming. Now, in almost any browser of the latest version, we can find modules for encoding, streaming, decoding, and playback. These functions are available through the JavaScript API, and the implementation is called Web Real Time Communications or WebRTC. This library built into browsers can do quite a lot: capture video from a built-in, virtual or USB camera, compress it with H.264, VP8, and VP9 codecs, and send it to the network via SRTP protocol; i.e., it functions as a software streamer video encoder. As a result, we see a browser that has something similar to ffmpeg or gstreamer, compresses video well, streams on RTP, and plays video streams.
WebRTC gives us the freedom to implement a variety of streaming cases in JavaScript:
* stream from the browser to the server for recording and subsequent distribution
* distribute peer-to-peer streams
* play another user’s stream and send one’s own (video chat)
* convert other protocols by the server, for example RTMP, RTSP, etc., and play them in the browser as WebRTC
Refined flow control scripts may look like this:
```
//Launching broadcast from browser to server
session.createStream({name:”mystream”}).publish();
//Playing broadcast by the browser
session.createStream({name:”mystream”}).play();
```
HLS works where WebRTC does not work
------------------------------------
WebRTC runs in the latest versions of browsers, however, there are the following two factors: 1) Not all users update their browsers in a timely manner and may well use Chrome’s old version for three years. 2) Updates and new browsers, WebView, as well as other clients and instant messengers helping users to surf the Internet are released almost once a week. Needless to say, not all of them have WebRTC support, and if they do, it can be limited. See how things are now:

Everyone's favorite devices by Apple can be a headache. They have begun to support WebRTC only recently and at times, their behavior compared to webkit browsers may seem surprising. Where WebRTC does not work or works not very well, HLS works fine. In this regard, compatibility is required, and something like a converter that allows us to convert WebRTC to HLS and play it on almost any device.
HLS was not originally conceived for real-time streams. Indeed, how can we stream real-time video via HTTP? The task of HLS is to cut the video into pieces and deliver them to the player smoothly, without rushing, by downloading them one by one. A HLS player expects a strictly formed and smooth video stream. Here we have a conflict, since WebRTC, on the contrary, can afford to lose packets due to real-time requirements and low latency and have a floating FPS/GOP and a variable bit rate — be the exact opposite of HLS in terms of predictability and regularity of the stream.
An obvious approach — WebRTC depacketization (SRTP) and subsequent [conversion to HLS](https://flashphoner.com/live-broadcasting-of-a-webrtc-stream-to-hls/) may not work in a native Apple HLS player or work with freezing, which is a form unsuitable for production. The native player means a player that is used in Apple iOS Safari, Mac OS Safari, and Apple TV.
Therefore, if you notice the HLS freezing in the native player, maybe this is the case, and the source of the stream is WebRTC or another dynamic stream with uneven markup. In addition, in the implementation of the native Apple players, there is behavior that can only be understood empirically. For example, the server should start sending HLS segments immediately after the m3u8 playlist is returned. A 1-second delay may result in freezing. If the bitstream configuration changed in the process (which is fairly common during WebRTC streaming), there will also be freezing.
Fighting freezing in native players
-----------------------------------
Thus, WebRTC depacketization and HLS packetization generally do not work. In the [Web Call Server (WCS)](https://flashphoner.com/) streaming video server, we solve the problem in two ways, and we offer the third as an alternative:
1) Transcoding.
This is the most reliable way to align a WebRTC stream to HLS requirements, set the desired GOP, FPS, etc. However, in some cases, transcoding is not a good solution; for example, transcoding 4k streams
of VR video is indeed a bad idea. Such weighty streams are very expensive to transcode in terms of CPU time or GPU resources.

2) Adapting and aligning WebRTC flow on the go to match HLS requirements.
These are special parsers that analyze H.264 bitstream and adjust it to match the features/bugs of Apple’s native HLS players. Admittedly, non-native players like video.js and hls.js are more tolerant of streams
with a dynamic bitrate and FPS running on WebRTC and do not slow down where the reference implementation of Apple HLS essentially results in freezing.

3) Using RTMP as the stream source instead of WebRTC.
Despite the fact that Flash player is already obsolete, the RTMP protocol is actively used for streaming; take OBS Studio, for example. We must acknowledge that RTMP encoders produce generally more even
streams than WebRTC and therefore practically do not cause freezing in HLS, i.e. RTMP>HLS conversion looks much more suitable in terms of freezing, including in native HLS players. Therefore, if streaming is
done using the desktop and OBS, then it is better to use it for conversion to HLS. If the source is the Chrome browser, then RTMP cannot be used without installing plugins, and only WebRTC works in this case.

All three methods described above have been tested and work, so you can choose based on the task.
WebRTC to HLS on CDN
--------------------
There are some undesirables you're going to run into in a distributed system when there are several WebRTC stream delivery servers between the WebRTC stream source and the HLS player, namely [CDN](https://flashphoner.com/cdn-for-low-latency-webrtc-streaming/), in our case, based on a WCS server. It looks like this: There is Origin — a server that accepts WebRTC stream, and there is Edge — servers that distribute this stream including via HLS. There can be many servers, which enables horizontal scaling of the system. For example, 1000 HLS servers can be connected to one Origin server; in this case, system capacity scales 1000 times.

The problem has already been highlighter above; it usually arises in native players: iOS Safari, Mac OS Safari, and Apple TV. By native we mean a player that works with a direct indication of the playlist url in
the tag, for example . As soon as the player requested a playlist – and this action is actually the first step in playing the HLS stream – the server must immediately, without
delay, begin to send out HLS video segments. If the server does not start to send segments immediately, the player will decide that it has been cheated and stop playing. This behavior is typical of Apple’s native HLS players, but we can’t just tell users “please do not use iPhone Mac и Apple TV to play HLS streams.”
So, when you try to play a HLS stream on the Edge server, the server should immediately start returning segments, but how is it supposed do it if it doesn’t have a stream? Indeed, when you try to play it, there
is no stream on this server. CDN logic works on the principle of Lazy Loading – it won’t load the stream to the server until someone requests this stream on this server. There is a problem of the first connected
user; the first one who requested the HLS stream from the Edge server and had the imprudence to do this from the default Apple player will get freezing for the reason that it will take some time to order this stream
from the Origin server, get it on Edge, and begin HLS slicing. Even if it takes three seconds, this will not help. It will freeze.

Here we have two possible solutions: one is OK, and the other is less so. One could abandon the Lazy Loading approach in the CDN and send traffic to all nodes, regardless of whether there have viewers or not. A solution, possibly suitable for those who are not limited in traffic and computing resources. Origin will send traffic to all Edge servers, as a result of which, all servers and the network between them will be constantly loaded. Perhaps this scheme would be suitable only for some specific solutions with a small number of incoming flows. When replicating a large number of streams, such a scheme will be clearly
inefficient in terms of resources. And if you recall that we are only solving the “problem of the first connected user from the native browser,” then it becomes clear that it is not worth it.

The second option is more elegant, but it is also merely an end-around. We give the first connected user a video picture, but this is still not the stream that they want to see – this is a preloader. Since we must give them something already and do it immediately, but we don’t have the source stream (it is still being ordered and delivered from Origin), we decide to ask the client to wait a bit and show them a video of the
preloader with moving animation. The user waits a few seconds while the preloader spins, and when the real stream finally comes, the user starts getting the real stream. As a result, the first user will see the
preloader, and those who connect after that will finally see the regular HLS stream coming from the CDN operating on the principle of Lazy Loading. Thus, the engineering problem has been solved.
But not yet fully solved
------------------------
It would seem that everything works well. The CDN is functioning, the HLS streams are loaded from the Edge servers, and the issue of the first connected user is solved. And here is another pitfall – we give the
preloader in a fixed aspect ratio of 16:9, while streams of any formats can enter the CDN: 16:9, 4:3, 2:1 (VR video). And this is a problem, because if you send a preloader in 16:9 format to the player, and the ordered stream is 4:3, then the native player will once again face freezing.
Therefore, a new task arises – you need to know with what aspect ratio the stream enters the CDN and give the same ratio to the preloader. A feature of WebRTC streams is the preservation of aspect ratio when
changing resolution and transcoding — if the browser decides to lower the resolution, it lowers it in the same ratio. If the server decides to transcode the stream, it maintains the aspect ratio in the same proportion. Therefore, it makes sense that if we want to show the preloader for HLS, we show it in the same aspect ratio in which the stream enters.

The CDN works as follows: when traffic enters the Origin server, it informs other servers on the network, including Edge servers, about the new stream. The problem is that at this point, the resolution of the
source stream may not yet be known. The resolution is carried by H.264 bitstream configs along with the key frame. Therefore, the Edge server may receive information about a stream, but will not know about its
resolution and aspect ratio, which will not allow it to correctly generate the preloader. In this regard, it is necessary to signal the presence of the stream in the CDN only if there is a key frame – this is guaranteed to give the Edge server size information and allow the correct preloader to be generated to prevent “first connected viewer issue.”

Summary
-------
Converting WebRTC to HLS generally results in freezing when played in default Apple players. The problem is solved by analyzing and adjusting the H.264 bitstream to Apple's HLS requirements, either by ranscoding,
or migrating to the RTMP protocol and encoder as a stream source. In a distributed network with Lazy Loading of streams, there is the problem of the first connected viewer, which is solved using the preloader and determining the resolution on the Origin server side – the entry point of the stream in the CDN.
Links
-----
[Web Call Server](https://flashphoner.com/) – WebRTC server
[CDN for low latency WebRTC streaming](https://flashphoner.com/cdn-for-low-latency-webrtc-streaming/) — WCS based CDN
[Playing WebRTC and RTMP video streams via HLS](https://flashphoner.com/live-broadcasting-of-a-webrtc-stream-to-hls/) — Server functions for converting streams from various sources to HLS | https://habr.com/ru/post/481668/ | null | null | 2,297 | 59.64 |
This article describes some first steps in loading, analyzing, and visualizing imagery data in EarthAI Notebook. We will first generate a new query that will be used in a simple example to demonstrate the types of raster-based DataFrame analyses that can be carried out in EarthAI.
First log into your account with an EarthAI Notebook open. In the first cell we’ll run an import statement for the necessary libraries and modules.
from earthai.init import *
As a refresher there will be a * in the brackets beside the cell as the import is executing. When it is finished there will be a number in the brackets along with dialog related to a SparkSession being created.
In this example we will generate a query using the EarthAI Catalog API. This process was covered in detail in a separate article. If you want to know what data collections are available you can in a new cell run:
earth_ondemand.collections()
We are going to carry out a normalized difference vegetation index (NDVI) calculation over the Yellowstone National Park region. NDVI is a calculated quantity derived from the red and rear-infrared (NIR) radiation bands measured by remote sensing platforms. NDVI provides an index for classifying land cover with a focus on vegetation. In this case, we’ll be using data from the MODIS spectroradiometer onboard the Terra and Aqua satellites. There are multiple MODIS collections available. For our analysis we’ll use the MCD43A4 product; note from the "id" column in the collections DataFrame above that this product's collection identification is "mcd43a4".
In a new code cell run the following and, by convention, assign the query result to the variable name catalog.
catalog = earth_ondemand.read_catalog(
geo='POINT(-110.0 44.5)',
start_datetime='2018-07-01',
end_datetime='2018-08-31',
collections='mcd43a4',
)
The catalog is a DataFrame with a shape of (62, 40). That is there are 62 rows and 40 columns. You can run
catalog.columns to see a list of the columns which are the attributes of the data. Included in these attributes are the radiation bands that we will use to calculate NDVI and need to access. The rows represent images acquired by MODIS, or scenes. Scenes are raster data with a specific spatial extent, date-time, and coordinate reference system (CRS). You can check the CRS of the catalog by running
catalog.crs. MODIS images the planet once every day, so the 62 rows represent daily images of our region over the two month period of the query. The format of catalog is then a collection of 62 scenes and the 40 attributes for each.
For the NDVI analysis we only need to read in the red and NIR bands. They have the non-intuitive names of ‘B01’ and ‘B02’, but those can be renamed for clarity when they are selected as we’ll do below.
We are going to read these bands in as a Spark DataFrame. The differences and pros/cons between Spark DataFrames and GeoDataFrames will be covered in a later article. In this example we choose to load the raster data into a Spark DataFrame in order to demonstrate geospatial operations using the
rasterframes module.
The code below takes the rows of MODIS scenes from catalog and loads the imagery data into a Spark DataFrame called bandsNDVI. We select only the "B01" (red) and "B02" (NIR) columns, which avoids reading in bands that we do not intend to use. We want to rename the columns to something a bit more descriptive. This is accomplished by the
withColumnRenamed method that is chained onto the original
spark.read.raster function. Method chaining can be thought of as a “do this then that” process from left to right. In this case the columns of interest are read and then each is renamed. If you’ve not seen it before, the backslash at the end of each line signifies that the code continues onto the next line.
bandsNDVI = spark.read.raster(catalog, catalog_col_names=['B01', 'B02'],)\
.withColumnRenamed('B01', 'red') \
.withColumnRenamed('B02', 'nir')
You can run
type(bandsNDVI) and see it is now a Spark DataFrame, and running
bandsNDVI.columns shows the renamed columns.
At a base level these procedures have all dealt with MODIS imagery, but we’ve yet to see any imagery visually. We can run the
select method on bandsNDVI to return visual representations of the "red" and "NIR" bands. We’ll also select the "id" and "datetime" columns, and return the extent and crs using the functions
rf_extent() and
rf_crs(). We’ll also give them aliases for clarity in the output. Running this cell may take a few seconds, and returns the top five rows of the selection.
bandsNDVI.select(
'red',
'nir',
'datetime',
'id',
rf_extent('red').alias('extent'),
rf_crs('red').alias('crs')
)
After running the cell you should see a DataFrame now with images. Double clicking the images enlarges them a bit. These images are false color representations of the red and NIR bands. More specifically each of these images represent tiles contained within a scene. In this case the scene is from July 7, 2018 as evidenced that they all have the same datetime, id, and crs. What differs for each is the extent. You are seeing how a scene is represented as a group of smaller tiles.
Now we will use the tile data from the red and NIR scenes to calculate the NDVI. NDVI is the ratio of (NIR - red) to (NIR + red) and ranges from -1.0 to 1.0. This calculation will take place in every cell or pixel in the tiles. The resulting NDVI is itself a tile of raster data. EarthAI has a built-in function
rf_normalized_difference() that performs the calculations with the two bands as input parameters. The code below calculates this and appends it to the bandsNDVI DataFrame.
bandsNDVI = bandsNDVI.withColumn('ndvi', rf_normalized_difference('nir', 'red'))
You can check to see that NDVI is appended to the DataFrame by again running:
bandsNDVI.columns
and see that it is listed at the end. You can also visualize the newly created NDVI tiles by running:
bandsNDVI.select(
'ndvi',
'datetime',
'id',
rf_extent('red').alias('extent'),
rf_crs('red').alias('crs')
)
Finally, we’ll look at how NDVI changed over the course of the time period we used for the original query.
First, we’ll import libraries needed for this. One quick note is that all of the needed libraries can be imported in the first cell of the notebook. They do not need to be imported as needed throughout the notebook.
import pyspark.sql.functions as F
import matplotlib.pyplot as plt
%matplotlib inline
The last statement ensures that plots appear in the notebook and not in a separate window.
The timeseries for change detection can be generated in any number of ways, but here we will calculate weekly averages of NDVI over the two months of the period. We’ll first group the data by year (which in this case is all in a single year so trivial) and then group it by week of the year. Finally, we’ll compute the mean each week and label it as “mean_ndvi”. This may take some time to complete after running.
time_series = bandsNDVI.groupBy(F.year('datetime').alias('year'),
F.weekofyear('datetime').alias('week')) \
.agg(rf_agg_mean('ndvi').alias('mean_ndvi'))
ts_pd = time_series.toPandas()
Let’s unpack this a bit before proceeding. The above code is applying two functions to the bandsNDVI DataFrame. First, it is grouping the data by year and week by unpacking the "datetime" attribute using a PySpark function that is designed to parse datetime strings. Next we are calculating the means of the NDVI values and aggregating those. Finally, we’re converting the time_series Spark DataFrame to a Pandas DataFrame to make plotting easier. If you wish you can check the type of ts_pd to confirm the conversion.
Below is the code to plot our new weekly averages of NDVI. Much of the code may be hard to follow if you have not used Matplotlib before. This is fine; at this point it is more to show you that we calculated mean NDVI from imagery and can display it. Data visualization in Python is a rich and extensive topic. The Matplotlib module that we’ve used here is quite verbose, but gives you a great deal of control over the graphics. There are numerous other libraries that abstract this verbosity away, allow for dynamic graphics, dashboard development, and web deployment. A future article will survey the options for geospatial data visualization.
ts_pd.sort_values([‘week’], inplace=True)
plt.figure(figsize=(10,8))
plt.plot(ts_pd.week, ts_pd.mean_ndvi, ‘g*-’, )
plt.ylabel(‘NDVI’)
plt.xlabel(‘Week of 2018’)
plt.title(‘Yellowstone NDVI’)
The resulting plot shows an overall decreasing trend in average NDVI over the time period. This represents a de-greening of the land which could be a result of drought, wildfire, forest mortality, slowing of seasonal photosynthetic activity or other reasons. The take home points in this article are that raster imagery was queried and loaded, used to calculate NDVI, and this was visualized as a time series to detect changes across the scenes.
Please sign in to leave a comment. | https://docs.astraea.earth/hc/en-us/articles/360043451792-Visualizing-an-NDVI-Time-Series-Using-the-EarthAI-Catalog-API-and-RasterFrames | CC-MAIN-2021-25 | refinedweb | 1,530 | 64.81 |
I've been having some difficulty with MatPlotLib's finance charting. Seems like their candlestick charts work best with daily data and I am having a hard time making them work with intraday (every 5 minutes, between 9:30 and 4pm) data.
I have pasted sample data in pastebin, top is what I get from the database, bottom is tupled with the date formated into an ordinal float for use in matplotlib.
Link to sample data
When I draw my charts there are huge gaps in it, the axes suck, the zoom is equally horrible.
Can anyone guide me through making a nice readable graph out of this data? My ultimate goal is to get a chart that looks remotely like this: The data points can be in various increments from 5minutes to 30 minutes.
Edit:
If I understand well, one of your major concern is the gaps between the daily data. To get rid of them, one method is to artificially 'evenly space' your data (but of course you will loose any temporal indication intra-day).
Anyways, doing this way, you will be able to obtain a chart that looks like the one you have proposed as an example.
The commented code and the resulting graph are below.
import numpy as np import matplotlib.pyplot as plt import datetime from matplotlib.finance import candlestick from matplotlib.dates import num2date # data in a text file, 5 columns: time, opening, close, high, low # note that I'm using the time you formated into an ordinal float data = np.loadtxt('finance-data.txt', delimiter=',') # determine number of days and create a list of those days ndays = np.unique(np.trunc(data[:,0]), return_index=True) xdays = [] for n in np.arange(len(ndays[0])): xdays.append(datetime.date.isoformat(num2date(data[ndays[1],0][n]))) # creation of new data by replacing the time array with equally spaced values. # this will allow to remove the gap between the days, when plotting the data data2 = np.hstack([np.arange(data[:,0].size)[:, np.newaxis], data[:,1:]]) # plot the data fig = plt.figure(figsize=(10, 5)) ax = fig.add_axes([0.1, 0.2, 0.85, 0.7]) # customization of the axis ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.tick_params(axis='both', direction='out', width=2, length=8, labelsize=12, pad=8) ax.spines['left'].set_linewidth(2) ax.spines['bottom'].set_linewidth(2) # set the ticks of the x axis only when starting a new day ax.set_xticks(data2[ndays[1],0]) ax.set_xticklabels(xdays, rotation=45, horizontalalignment='right') ax.set_ylabel('Quote ($)', size=20) ax.set_ylim([177, 196]) candlestick(ax, data2, width=0.5, colorup='g', colordown='r') plt.show() | https://codedump.io/share/adaVKgTmjBhr/1/intraday-candlestick-charts-using-matplotlib | CC-MAIN-2017-26 | refinedweb | 454 | 58.18 |
Trouble compiling files with identical filenames
Hey there,
I am currently working on a project which contains some duplicate class names. To prevent them from clashing I am using namespaces. Then I can use those classes the following way
#include "core/audio.hpp" // Audio class #include "core/database/dbaudio.hpp" // db::Audio class
Now I really dislike the fact of needing the extra
db-prefix for the database class. I tried changing the class name to just
audio.hppbut that raised an error while compiling with MSVC.
Then I googled around and found the qmake config values
object_parallel_to_source(and its older brother
object_with_source). When compiling the project using
CONFIG += object_parallel_to_sourceI get the compiler error
LNK1181: File "release/src/main.obj" cannot be opened..
Is there any way to fix that and use multiple files with the same name inside my Qt project? Does it perhaps have something to do with the fact, that I am compiling into a
bindir inside my repository?
Putting aside the fact that using same file names for different files (and classes!) is very confusing - and thus makes code maintenance harder.
Do you use proper header guards in your header files? Ifdefs or pragma or both?
Yes, I am using proper include guards. What would a good way of naming those classes? I am using
Audiomostly as a data class and
db::Audioas an "interface" for the database. I used to call it
DbAudiobut then I had lots of classes prefixed
Dband decided to put them all into a namespace.
The current main problem is keeping the class names as easy as possible without name clashing :(
If it is an interface, it can be called AudioInterface. Or as some people do: IAudio.
If it holds data, it could be AudioData, or in more webby style: AudioTransferObject.
OK if you are using header guards, then indeed the issue is likely to come from putting the object files in single directory. Two possible workarounds:
- move one of the headers to a separate .pri file - not sure if that causes build layout to change, but it is the easiest to check
- separate part of your project into a subproject (qmake's
TEMPLATE = subdirs), possibly as a library, and then include with your main app
But shouldn't
object_parallel_to_sourcework right out of the box? From what I understand it's supposed to mimic the project directory structure when compiling and should thereby eliminate duplicate
.obj-files in the same directory. The problem is the almost instant error mentioned in the first post.
@jsmolka said in Trouble compiling files with indentical filenames:
But shouldn't object_parallel_to_source work right out of the box?
No idea - if this option exists, it is not documented in qmake manual.
- SGaist Lifetime Qt Champion last edited by
Hi,
What version of Qt are you using to build your project ?
@SGaist I am using the current version (5.11.2) and the up-to-date QtCreator. I am building my project with
object_parallel_to_sourceenabled and it only works when I disable shadow build. I would love to use the feature in combination with shadow build.
- aha_1980 Qt Champions 2018 last edited by
(Personal opinion): Identical filenames in a project lead to problems sooner or later.
Instead of working around the problem, you should just avoid these different classes with same name. @sierdzio already gave examples how structure things better.
Even if you get it running now, it may break anytime, leading to addional time to fix these things. Better invest that time into development.
Regards
@aha_1980 You probably right. I am still learning C++ and I am currently trying to figure out the best way to organize my source files. Currently project structure looks something like this:
src/
├── namespace1/
│ ├── namespace1_base.cpp
│ ├── namespace1_derived1.cpp
│ └── namespace1_derived2.cpp
├── namespace2/
│ ├── namespace2_base.cpp
│ ├── namespace2_derived3.cpp
│ └── namespace2_derived4.cpp
├── other.cpp
└── files.cpp
I usually use a
Baseclass which implements functionality the classes inside the namespace need. It just seems odd not to call the source file
base.cppbecause I can't use duplicate files names.
- kshegunov Qt Champions 2017 last edited by
@jsmolka said in Trouble compiling files with identical filenames:
Is there any way to fix that and use multiple files with the same name inside my Qt project? Does it perhaps have something to do with the fact, that I am compiling into a bin dir inside my repository?
Not with shadow building, no. When you generate a bunch of object files in the same directory, the object is named after the source file. So the identically named source's object file will overwrite the previous one (in order of building); it may even happen only partially if you're building on multiple cores.
It's a known pitfall and you should name your files better as people have already suggested. | https://forum.qt.io/topic/96445/trouble-compiling-files-with-identical-filenames/11 | CC-MAIN-2019-51 | refinedweb | 799 | 65.62 |
InLink tag : To provide links to important words in the contents.
Hi , this is a very simple but yet useful tag to provide links to important words in the content given in between the starting and end inLink tag.
Taking an Example of contents :-
“No One Killed Jessica is a 2011 Hindi film starring Vidya Balan and Rani Mukherjee , produced by UTV Spotboy and directed by Raj Kumar Gupta, who had earlier directed the acclaimed film Aamir (2008). Vidya Balan plays the character of Jessica’s elder sister, Sabrina Lal, Rani is set to play a reporter.[7] . The director clarified that the title and the script are actually inspired by a headline carried out by The Times of India (epaper link) in 2006, when the accused in the infamous murder case were acquitted by the lower courts.The film, No One Killed Jessica is based on the true story of Jessica Lal, a Delhi-based model, who was shot in 1999 at a New Delhi restaurant by Manish Bhardwaj, alias Manu, the son of an influential Haryana politician.In February 2006, the court acquitted. It received positive reviews from critics.[12]No One Killed Jessica opened quite well and got positive feedback from audience.No One Killed Jessica received a number of positive reviews. Nikhat Kazmi of the Times of India gave the movie four stars out of five stating. ”
Output after passing the contents between inLink tag :–
This tag takes celebrity list and movie list as input and then just replaces each celebrity name or movie name with its link which takes to the corresponding celebrity page or movie page.
Now the code for the inLink tag is as follows :-
[java]
def inLink = {attrs, body ->
List<Celebrity> celebrities = attrs[‘celebrities’]
List<Movie> movies = attrs[‘movies’]
String bodyText = body()
String currentCelebrity
String currentMovie
celebrities.each {currentSelect ->
currentCelebrity = currentSelect.name
bodyText = bodyText.replaceAll(currentCelebrity, (hys.celebrityPageLink(id: currentSelect.id,title:currentCelebrity ) {currentCelebrity}).toString())
}
movies.each {currentSelect ->
currentMovie = currentSelect.name
bodyText = bodyText.replaceAll(currentMovie, (hys.moviePageLink(id: currentSelect.id,title:currentMovie) {currentMovie}).toString())
}
out << bodyText
}
[/java]
Here ,two more tags :- celebrityPageLink tag and moviePageLink tag are used which are defined under the namespace “hys” .These two tags are very similar ,one links its given content i.e. celebrity name to its corresponding celebrity page and the one links its given content i.e. movie name to its corresponding movie page. Lets see the code for one of these tags for sake of avoiding confusion regarding these.
Taking celebrityPageLink tag which takes celebrity id,title and class as input. Its code is as follows :-
[java]
def celebrityPageLink = {attrs, body ->
def celebrity = Celebrity.read(attrs.id)
out << g.link(controller: ‘celebrity’, action: ‘show’, params: [name: celebrityName]) {body()}
}
[/java]
Now lets see how to use this tag on gsp page :-
[html] <hys:inLink${movie.description}</hys:inLink> [/html]
ok……now lets see how much its useful for grails users.
Regards,
Shweta Gupta
Intelligrape
Hello! I just wish to give you a big thumbs up for your excellent information you have got right here on this post. I will be returning to your web site for more soon.
I having Two Different Domanis
Eg:CoreFolder[ProductItem-Domain] & ProductionFolder[PatternShop].
I pass these two domains params in Single list action in ProductItem Controller
like: [ProductItem.list(),PatternShop.list()]
Then I need to display Two domain params in single list page after vales are entered either any of one domain values.
will u help me? | https://www.tothenew.com/blog/inlink-tag-to-provide-links-to-important-words-in-the-contents/ | CC-MAIN-2021-25 | refinedweb | 578 | 55.84 |
curves in computer graphics applications. This tool allows you to create a big spline made of several 3rd-degree Bezier segments, in a way that is similar to the Bezier tool in Inkscape. A general Bezier curve of any degree can be created with Draft BezCurve.
The Draft BezCurve and the Draft CubicBezCurve tools use control points to define the position and curvature of the spline;
Properties
Data
View
Scripting
See also: Draft API and FreeCAD Scripting Basics.
See Draft BezCurve for the general information. A cubic Bezier is created by passing the option
degree=3 to
makeBezCurve().
For each cubic Bezier segment four points must be used, of which the two extreme points indicate where the spline passes through, and the two intermediate points are control points.
- If only 3 points are given, it creates a quadratic Bezier instead, with only one control point.
- If only 2 points are given, it creates a linear Bezier, that is, a straight line.
- If 5 points are given, the first 4 create a cubic Bezier segment; the 4th and the 5th points are used to create a straight line.
- If 6 points are given, the first 4 create a cubic Bezier segment; the 4th and the other two points are used to create a quadratic Bezier segment.
- If 7 points are given, the first 4 create a cubic Bezier segment; the 4th and the other three points are used to create a second cubic Bezier segment.
- In general, the last point in a group of four is shared with the following three points maximum to create another Bezier segment.
- To have smooth curves, with no straight segments, the number of points should be
3n + 1or
3n, where
nis the number of segments, for
n >= 1.
Example:
import FreeCAD as App import Draft p1 = App.Vector(-3500, 0, 0) p2 = App.Vector(-3000, 2000, 0) p3 = App.Vector(-1100, 2000, 0) p4 = App.Vector(0, 0, 0) p5 = App.Vector(1500, -2000, 0) p6 = App.Vector(3000, -1500, 0) p7 = App.Vector(5000, 0, 0) p8 = App.Vector(6000, 1500, 0) rot = App.Rotation() c1 = Draft.makeCircle(100, placement=App.Placement(p1, rot), face=False) c1.Label = "B1_E1" c2 = Draft.makeCircle(50, placement=App.Placement(p2, rot), face=True) c2.Label = "B1_c1" c3 = Draft.makeCircle(50, placement=App.Placement(p3, rot), face=True) c3.Label = "B1_c2" c4 = Draft.makeCircle(100, placement=App.Placement(p4, rot), face=False) c4.Label = "B1_E2" c5 = Draft.makeCircle(50, placement=App.Placement(p5, rot), face=True) c5.Label = "B2_c3" c6 = Draft.makeCircle(50, placement=App.Placement(p6, rot), face=True) c6.Label = "B2_c4" c7 = Draft.makeCircle(100, placement=App.Placement(p7, rot), face=False) c7.Label = "B2_E3" c8 = Draft.makeCircle(50, placement=App.Placement(p8, rot), face=True) c8.Label = "B3_c5" App.ActiveDocument.recompute() B1 = Draft.makeBezCurve([p1, p2], degree=3) B1.Label = "B_lin" B1.ViewObject.DrawStyle = "Dashed" B2 = Draft.makeBezCurve([p1, p2, p3], degree=3) B2.Label = "B_quad" B2.ViewObject.DrawStyle = "Dotted" B3 = Draft.makeBezCurve([p1, p2, p3, p4], degree=3) B3.Label = "B_cub" B3.ViewObject.LineWidth = 4 B4 = Draft.makeBezCurve([p1, p2, p3, p4, p5], degree=3) B4.Label = "B_cub+lin" B4.ViewObject.DrawStyle = "Dashed" B5 = Draft.makeBezCurve([p1, p2, p3, p4, p5, p6], degree=3) B5.Label = "B_cub+quad" B5.ViewObject.DrawStyle = "Dotted" B6 = Draft.makeBezCurve([p1, p2, p3, p4, p5, p6, p7], degree=3) B6.Label = "B_cub+cub" B6.ViewObject.LineWidth = 2 B7 = Draft.makeBezCurve([p1, p2, p3, p4, p5, p6, p7, p8], degree=3) B7.Label = "B_cub+cub+lin" B7.ViewObject.DrawStyle = "Dashed" | https://wiki.freecadweb.org/index.php?title=Draft_CubicBezCurve&oldid=509030&curid=148535 | CC-MAIN-2020-45 | refinedweb | 590 | 63.76 |
.
Having taken an article each to look at the two biggest enhancements in Python 3.5, this article covers a collection of the smaller additions to the langauge.
This release adds a new operator
@ for matrix multiplication. None of the modules in the Python standard library actually implement this operator, at least in this release, so it’s primarily for third party modules to use. First and foremost among these is NumPy, a popular library for scientific and applied mathematics within Python. One of its primary purposes is to add support for multidimensional matrices, so this operator suits it well.
To see how this works I whipped up my own simple
Matrix class. This isn’t production quality and has very little error checking, it’s just for illustrative purposes. The key point to notice here is that it implements the
__matmul__() method to support the
@ operator. Similar to other infix operators, there’s also an
__rmatmul__() method for reversed operation in cases where only the right-hand operand supports the method, and
__imatmul__() to override how
x @= y is handled. I didn’t bother to define these since in this case the automatic fallback options are sufficient.
Below you can see an example of it being used:
>>> m1 = Matrix([[1], [2], [3]]) >>> m2 = Matrix([[4, 5, 6]]) >>> m1[2, 0] 3 >>> m2[0, 1] 5 >>> print(m1 @ m2) [[4, 5, 6] [8, 10, 12] [12, 15, 18]] >>> >>> print(m1 @ Matrix.create_empty(1, 4, initial=2)) [[2, 2, 2, 2] [4, 4, 4, 4] [6, 6, 6, 6]] >>> >>> m1 @ Matrix.create_empty(2, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/andy/misc-files/blog/py35/matrix.py", line 30, in __matmul__ raise IndexError("Row/col count mismatch") IndexError: Row/col count mismatch
Handy to be aware of this operator, but unless you’re using NumPy or you’re implementing your own matrix class, it’s probably something of an obscure curiosity.
There have been some improvements to the way that iterables can be unpacked when calling functions and at other times. To recap, for a long time Python has had the ability to capture variable argument lists passed into functions, whether specified positionally or by keyword. Conversely, it’s also been able to unpack a sequence or mapping into position or keyword arguments when calling the function.
>>> def func(*args, **kwargs): ... print("Args: " + repr(args)) ... print("Keyword args: " + repr(kwargs)) ... >>> func("one", 2, three="four", five=6) Args: ('one', 2) Keyword args: {'five': 6, 'three': 'four'} >>> >>> def func2(arg1, arg2, arg3, arg4, arg5): ... print(arg1, arg2, arg3, arg4, arg5) ... >>> func2(*("a", "b", "c"), **{"arg4": "D", "arg5": "E"}) a b c D E
As per PEP 448 this release expands these facilities to address some limitations of the current approach. One of the main issues is if you are collecting parameters from multiple places, you’re forced to collapse them all into a temporary structure (typically
list or
dict) and pass that into the function in question. This is not difficult, but it makes for somewhat cumbersome code.
As of Python 35, however, it’s possible to specify these operators multiple times each and the results are merged for the actual function call:
>>> func(1, 2, *[3, 4], *[5, 6, 7], ... **{"eight": 9, "ten": 11}, **{"twelve": 12}) Args: (1, 2, 3, 4, 5, 6, 7) Keyword args: {'eight': 9, 'ten': 11, 'twelve': 12}
It’s still the case that positional arguments must precede keyword ones, and
*-arguments must precede
**-arguments. Also, I note with interest that it’s actually an error to specify the same keyword parameter twice, raising a
TypeError, as opposed to the second instance silently replacing the first:
>>> func(**{"arg": 1}, **{"arg": 2}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: func() got multiple values for keyword argument 'arg'
Perhaps more usefully, this syntax has also been extended to be usable within the construction of literals for
tuple,
list,
set and
dict:
>>> [*range(3), *range(10, 5, -2)] [0, 1, 2, 10, 8, 6] >>> config = {"rundir": "/tmp", "threads": 5, "log_level": "INFO"} >>> {**config, "log_level": "DEBUG", "user": "andy"} {'threads': 5, 'rundir': '/tmp', 'log_level': 'DEBUG', 'user': 'andy'} >>> {*config.keys(), "user"} {'threads', 'rundir', 'user', 'log_level'}
As a further aside, you’ll notice that unlike in the function call case, it’s fine to have repeated keys in the
dict constructor (e.g.
"log_level" occurs twice above). This is useful as it means you can perform an “upsert” where you either replace or add an entry in the new copy of the
dict that’s created.
This may be a small feature, but I can think of a number of places in code where it will be quite convenient to have such a concise expression of intent.
There are a couple of improvements to interactions with the operating system, one related to a faster way to iterate over directory listings and the other more graceful handling of interrupted system calls.
os.scandir()¶
There’s a new function
os.scandir() which is roughly an improved version of
os.listdir() which includes some file attribute information. This can significantly improve performance over performing separate calls to things like
os.is_dir() or
os.state() for each entry. The
os.walk() implementation has been updated to take advantage of
scandir(), which makes it 3-5x faster on POSIX systems and 7-20x faster on Windows.
As an example of the improvements in time, see the following snippet which shows code to count the number of subdirectories whose name doesn’t begin with a dot.
>>> timeit.timeit('sum(1 for i in os.scandir("/Users/apearce16")' ' if i.is_dir() and not i.name.startswith("."))', setup='import os', number=100000) 9.061285664036404 >>> timeit.timeit('sum(1 for i in os.listdir("/Users/apearce16")' ' if os.path.isdir("/Users/apearce16/" + i)' ' and not i.startswith("."))', setup='import os', number=100000) 31.92237657099031
Another handy feature in this release is automatic retry of
EINTR error results. This occurs when a system call is interrupted, typically by a signal arriving in the process — the system call returns an error with
errno set to
EINTR. It’s worth noting that this behaviour depends on the system call — for example,
write() calls which have already written some partial data won’t return an error, but instead indicate success and return the number of bytes that were actually written1.
In Python 3.4 and earlier, this error code triggered an
InterruptedError exception which the application had to handle appropriately. This can be quite annoying, particularly if you’re making these calls in quite a few different places. But if you don’t do it them your application is at risk of randomly suffering all kinds of odd bugs. To make things more complicated, many libraries don’t handle this error for you, so it can propogate out of almost anywhere to bite you.
The good news for Python programmers is that as of Python 3.5 they won’t generally need to worry about this thanks to the improvements proposed in PEP 475. The wrappers around the standard library will now catch the
EINTR case, check if any pending signal handlers need calling, and then retry the operation behind the scenes. This means that
InterruptedError should not occur anywhere any more and any code to handle it may be removed.
This applies to almost all library calls, so I’m not going to enumerate them all here. Notable exceptions are
os.close() and
os.dup2() due to the indeterminate state of the file descriptor under Linux if these functions return
EINTR — these calls will now simply ignore
EINTR instead of retrying.
Many people reading this will probably be aware of the
StopIteration exception. Whilst we rarely deal with it explicitly, it’s used implicitly any time we use a generator — when
__next__() is called on an iterator it’s expected to either return the next item, or raise
StopIteration to indicate the iterator is exhausted.
As with any other exception, however, it’s possible that it can be raised unexpectedly, perhaps due to a bug in your code, or perhaps even a bug in another library outside your control. If this happens within the implementation of a generator, if the
StopIteration exception isn’t caught then it’ll propogate out to the looping code which will interpret it as an end of the iterator. This silent swallowing of erroneously raised exceptions can make all sorts of bugs particularly difficult to track down, as opposed to the normal behaviour of getting an immediate interruption with a helpful backtrace to help you figure out what the issue is.
As a result of these issues, a change has been introduced which prevents a
StopIteration that’s raised within a generator from propogating outside it, instead turning it into a
RuntimeError. The original
StopIteration is still included as a chained exception for debugging.
This change is not backwards-compatible, because there are some potential valid uses of the behaviour around
StopIteration. Take the code below, for example — whilst I wouldn’t suggest this is a great implementation, it’s certainly not safe to rule out that people have written this sort of thing.
>>> def spacer(it, value): ... while True: ... yield next(it) ... yield value ... >>> list(spacer(iter(range(5)), 999)) [0, 999, 1, 999, 2, 999, 3, 999, 4, 999]
As a result, to activate this new behaviour you need to
from __future__ import generator_stop. You can see the difference in behaviour below:
>>> from __future__ import generator_stop >>> >>> def spacer(it, value): ... while True: ... yield next(it) ... yield value ... >>> list(spacer(iter(range(5)), 999)) Traceback (most recent call last): File "<stdin>", line 3, in spacer StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: generator raised StopIteration
This behaviour will likely become default in some future release, so it’s worth updating any code that breaks. I suspect there’s not a huge amount of code that will be impacted, but if you want to check your code then be aware that if you do raise a
StopIteration in a generator without the
from __future__ import then it’ll raise a
PendingDeprecationWarning if you have that warning enabled.
If you want some more detailed discussion of the motivation for this change, PEP 479 has some great discussion.
There are some changes in 3.5 to the way that C extension modules are initialised to bring them more closely in line with the way standard Python modules are loaded. I’ll need to go into a certain level of detail to explain what this change is doing, but I’ll do my best to keep it moving along as I know not everyone deals with extension modules. You can always check out PEP 489 for more details.
As a reminder, loading a standard Python module proceeds in five stages since Python 3.42:
sys.modules. If found, this module is used and the import process is complete.
ModuleSpecwhich has some metainformation about the module and the loader to actually load it.
create_module()on the loader to create a new module object3. You can think of this as conceptually equivalent to the
__new__()method of a class.
sys.modulesunder the fully-qualified name. Doing this before the next step avoids an infinite loop if the module indirectly causes itself to be re-imported.
exec_module()method of the loader to actually load the code itself. This is conceptually similar to the
__init__()method of a class. If it raises an exception then the module is removed from
sys.modulesagain.
By comparison, extension modues have had a monolithic loading process prior to Python 3.5. The module exports an initialisation function named
PyInit_modulename(), where
modulname must match the filename. This is executed by the import machinery and expected to provide a fully initialised module object, combining steps 2 and 4 above into one call. Also, extension modules are not added to
sys.modules at present.
To put this into more concrete terms, extension modules typically provide a static definition of a
PyModuleDef structure which defines the details for the module such as the methods it provides and the docstring. This is passed into
PyModule_Create() at the start of the initialisation function to create the module object. This is followed by any module-specific initialisation required and finally the module object is returned.
This process is still supported in Python 3.5, to avoid breaking all the existing extension modules, but modules can also now request multi-phase initialisation by just returning the
PyModuleDef objec itself without yet creating the module object. It must be passed through
PyModuleDef_Init() to ensure it’s a properly initialised Python object, however.
The remaining stages of initialisation are then performed according to callbacks provided by the module. These are specified in the
PyModuleDef structure using the
m_slots pointer, which is a pointer to a NULL-terminated array of
PyModuleDef_Slot structures4. Each
PyModuleDef_Slot has an integer ID to specify the type of slot and a
void* value which is currently always interpreter as a function pointer.
In this release there are two valid values for the slot ID:
Py_mod_create
create_module()object of the loader. It’s passed the
ModuleSpecinstance and the
PyModuleDefas returned from the initialisation function. If you don’t need a custom module object then just omit this, and the import machinery calls
PyModule_New()to construct a standard module object.
Py_mod_exec
exec_module()method of the loader. This is invoked after the module was added to
sys.modulesand it’s passed the module object that was created, and typically adds classes and constants to the module. Multiple slots of this type can be specified, and they’ll be executed in sequence, in the order that they appear in the array.
So that’s about the shape of it. I have a feeling a lot of people will just stick to the single initialisation approach because a lot of C extension modules are essentially just Python bindings around libraries in other languages, and these probably have little use for custom module objects. But it’s good to know the flexibility is there if you need it.
As usual there are some smaller language changes that I wanted to give a shout out to, but not discuss in detail.
%Formatting for
bytes
%operator can now also be used with
bytesand compatible values to construct a
bytesvalue directly. Typically arguments will be either numeric of
bytesthemselves —
strarguments can be used with the
%aformat specifier, but this passes them through
repr()so it’s probably not what you want.
math.isclose()and
cmath.is_close()for testing approximate equality between two numeric values. There are two tolerances that can be specified, a relative tolerance and an absolute one — if the gap betwen the values is smaller than either tolerance then the function returns
True, otherwise
False. The relative tolerance is expressed as a percentage which is applied to the larger of the two values to derive another absolute tolerance. See PEP 485 for more details.
.pyofiles
.pycfiles normally and
.pyofiles for optimized code (if
-Oor
-OOwere specified). However, since the same extension is used for both levels of optimisation it’s not easy to tell which was used, and code may end up using a mixture of optimisation levels. In this release the
.pyoextension is removed entirely and
.pycis used in all cases. Instead of differing in the extension, a new tag is added indicating the optimisation level, which means the interpreter can select the correct optimisation level in all cases. For a source file
lib.py, the unoptimised bytecote will be in
lib.cpython-35.pyc, and the optimised versions will be in
lib.cpython-35.opt-1.pycand
lib.cpython-35.opt-2.pyc. PEP 488 has more.
zipappmodule
__main__.pyfile and then just passing this package directory as an argument to
python -m zipapp. This gives you a
.pyzfile which can be executed directly by the interpreter as could a standard script.
Nothing too earth-shattering in this collection, I’d say, and quite a few of these items are a little niche. The argument unpacking improvements will certainly be useful for writing concise code in particular cases, although I do wonder how useful that is for people who’ll want to make full use of the type-hinting system — I can imagine all of those varargs-style constructions make accurate type-hinting a little tricky. The creation of
os.scandir(), and consequent improvements to
os.walk() performance, are certainly very welcome. It’s not uncommon to want to trawl a large directory structure for some reason or other, and these heavily IO-bound cases can be pretty slow, hence any improvement is welcome.
The next article in the series will likely be the last one looking at changes in 3.5, and it’ll be looking at all the remaining standard library improvements.
Which, incidentally, is why you must always check the result of calling the
write() system call and handle the case of a partial write gracefully, typically by immediately calling
write() again with the remaining data. The knock-on effect of this is that if you’re using asynchronous IO then you never want to discard your pending output until
write() returns, because you never know in advance how much of it you’ll need to retry in the case of a failed or partial write. ↩
Prior to Python 3.4 the process was similar except that the finder would return a loader directly instead of the
ModuleSpec object, and the loader provided a
load_module() method instead of
exec_module(). The difference between the two methods is that
load_module() had to perform more of the boilerplate that the import machine does itself as of Python 3.4, which makes
exec_module() methods simpler to implement correctly. ↩
In Python 3.5 strictly speaking
create_module() is optional and Python falls back on just calling the
types.ModuleType() constsructor if it’s not specified. However, it’s mandatory in Python 3.6 so I thought it best to delegate this detail to a footnote. ↩
Despite the addition of the
m_slots member, binary compatibility with previous releases was helpfully maintained by renaming the unused
m_reload member — since both are pointers then both have the same size and hence the memory layout of the structure as a whole is unchanged. ↩
This is the 10th of the 15 articles that currently make up the “Python 2to3” series. | https://www.andy-pearce.com/blog/posts/2021/May/python-2to3-whats-new-in-35-part-3-other-additions/ | CC-MAIN-2021-49 | refinedweb | 3,087 | 53.21 |
How relevant is optimization? You judge
I want to walk through an example. If you're interested, read the post called "how relevant is optimization" for background. I started a new topic because I think this example is interesting in its own right.
I'm using pseudo code that is somewhat like C++, I hope it doesn't need explanation, but feel free to ask.
Let's say I want to compute the mean and standard deviation of fields across many records. Assume all fields are float. Let's further assume that this can't be done in advance for some reason, but has to be done online.
I'll start with the simplest, ugliest way to do that: A static, two dimensional array; One index is the record number and the other is the field number. It would be something like:
float data[n_records][n_fields]
for x in field:
. sum[x] = 0
. sumsqr[x] = 0
for x in field:
. for y in record:
. item = data[y][x]
. sum[x] += item
. sumsqr[x] += item*item
for x in field:
. mean[x] = sum[x] / n_fields
. stddev[x] = sumsqr[x] / n_fields - (mean[x]*mean[x])
Now, believe it or not, if the number of fields is large, or, if we need to swap to disk for some reason, then exchanging the order of the "for" loops for x and y can change the running time by two or three orders of magnitude. If the array storage order is C like, then an internal field loop will be perfectly cache coherent and predicted by any working set algorithm, whereas an external field loop (as written above) will be not have horrible cache coherence, and won't be predicted as easily. (If the number of fields is a multiple of the cache line size, and the cache is 2-way or 4-way associative, the cache will be completely ineffective).
"Well, exchange the loop order then" I hear you say. Fair enough; that's a luxury all Fortran programmers and early C programmers had. But now I'll evolve the example and make it conform to standard "structured programming" practice:
struct record { float field[n_fields] }
record data[n_records]
. (snipped)
for x in field:
. for each record y:
. sum[field] += y.field[x]
. sumsqr[field] += y.field[x]
. (snipped)
It's still possible to reorder the loops, but it's not as natural now. All our routines process complete "records", so the program structure would probably favor iterating by record rather than by field. Let's go further, and enumerate the fields by name, and make this object oriented...
struct record { float field_1, field_2, ... field_n }
class field_selector {
. int i;
. field_selector(index) { i = index }
. operator get(record r) { return r->field_#i }
}
float mean_stddev(field_selector sel, record rec[]) {
. sum = sumsqr = 0
. for r in rec:
. item = sel->get(r)
. sum += item
. sumsqr += item*item
. return sum/len(rec), sumsqr/len(rec) - (sum/len(rec))**2
}
do_all() {
for i in field:
. collect mean_stddev(field_selector(i), data)
}
It's object oriented, so it must be better, right? It actually does do things we couldn't do before, such as "virtual" columns; If I wanted to calculate the mean and deviation of, say, field1*field2, all I'd have to do is write a new field selector that returns that in response to get().
Hmmpf. Now it's not so simple to change the iteration order. In fact, if "rec" is abstract (we don't use it directly - only through "get"), it's impossible - and because we made it abstract in the first place (A probable OO design decision), Joey does the hall already wrote 200,000 lines that rely on it being abstract.
Badness doesn't end there, though - if the records are allocated independently (as they usually are in OO programs), then the cache use will be effectively unused and unpredictable.
Most OO people I know solve things closer to the "OO" way I gave above. That's fine, but don't delude yourself that it is optimizable to the first case because in practice it isn't.
Also, consider - how would you even detect that the program runs orders of magnitude slower than it could, and that it's because of memory access patterns?
"But that's only for number crunching stuff". Well, newsflash: *everything* a computer does is number crunching. Yep, you wrap it in 250 layers of abstraction, and try to forget about it, but every bottleneck is a number crunching bottleneck because everything eventually reduces to computing numbers and moving them around.
Whenever I design a solution, I measure the complexity of teh problem by counting the byte moving and number crunching that (eventually) has to be done to solve it. For a proposed solution, I do a rough estimate of the byte moving / number crunching that it will do; If it takes more than 10 times as much as really needed, I seek to improve or replace it. If I can't give a rough estimate of the byte moving / number crunching that a solution requires, then I seek to simplify it.
It works wonders - it keeps the solution simple, and the performance predictable. Being able to count byte moves also means you're not overabstracting to the point that you can't exchange loop indices.
And I would like, again, to point you to the wonder that is K [ ]. It's a language that's entirely interpreted (no JIT or anything), in which the natural way to write programs makes them faster by an order of magnitude, and shorter by two. The magic is selecting the right primitives, and the right memory layout. Yep, it's unlike anything else you've used (unless you've used APL / J), but it does deliver everything it promises.
Another example - you've got your class hierarchy all neatly developed, and now you need a few thousand objects (out of a few million) in memory for producing a report. Unfortunately, you can't fit the whole million in memory for some reason, so you resort to a database. You could have, in fact, used memory mapped files and not have to deal with any persistence issues (which often take 1000 times as much CPU as your processing). But because objects require proper construction, and have pointers to one another, you can't just mmap/MapViewOfFile and forget about it. You'll have to find some clever trick like caching computations on the database, moving them to batch processes etc. But if you used pointerless structs in advance, you could have; And it's possible that the code wouldn't have looked much different.
To sum up - my point is that you have to plan in advance where to leave a place for optimization, or there's a chance you won't have where to optimize.
Thank you for your time :)
Ori Berger
Monday, July 28, 2003
Maybe it's just me, but your "object oriented" solution seems backwards. I'd think you would have a class representing a record, which contains all the fields. If you set it up like this you can get the same performance characteristics of having the record as the outer loop
That said, I do understand what you're saying and it is an important point. Algorithmic/structural changes are by far the most significant things in optimizations. The real question is: When do you do this optimization? The problem with your suggestion that everything is studied and done in an "optimal" manner to begin with (which I'm not sure is even possible in general, since you can't necessarily figure out the optimal way to do something without the framework of the rest of the program), you waste a lot of time optimizing code that has no business being optimized. Take your example. What if I had a small enough data set that the whole thing fit in cache? Then your optimization means nothing. Or what if the only time you do that calculation, you also do some reading from disk, so the time spent on the operation is completely dominated by waiting for the IO. In that case, this optimization is completely unnoticable to the user.
The point is, if you attempt to optimize too early, two bad things happen: 1) You spend a lot of time optimizing things that shouldn't be optimized. 2) You (potentially) make your code harder to work with. Almost all abstractions come at a cost of performance. However, the gain from these abstractions often far exceeds the cost. If you try to optimize too early, you will do away with the many benefits of abstraction in search for some performance which is very likely to not matter at all in the final product
You are absolutely right that your design can back you into a corner performance-wise, and it *is* a good idea to think about that through the entire process. You should absolutely take into consideration access patterns of your data when designing data structures. We do this all the time. Nobody claims you should be totally ignorant of performance while designing your program (ie, few people would suggest to use a list instead of a map on anything larger than a few elements).
Mike McNertney
Monday, July 28, 2003
I have a set of business rules, which have a 25% chance of needing optimization at some point.
Implementing them in code module "A" in a logical, well-thought-out manner would take four weeks.
Implementing them in code module "B" in a logical, well-thought-out manner ensuring room for future optimizations would take eight weeks.
Refactoring "A" to optimize it would take four weeks.
Refactoring "B" to optimize it would take one week.
Doing "A" results in a delivery time of four weeks, and a 50% chance of needing four weeks additional work later. Doing "B" results in a delivery time of eight weeks, and a 50% chance of needing two weeks additional work later.
Now you could do the actual analysis and figure out what the real lengths of time and probabilities are, weighing them and determining the best path. Or you can start work.
My personal opinion - you can worry, or you can do. People who do get things done. People who worry produce five-volume specifications of over-designed code while the people who do have code in production.
Yeah, sometimes you get bitten. But I think you get bitten no matter which direction you go, so it's better to get bitten when you have code in testing than when you're still designing well after the delivery date. ;-)
Philo
Philo
Monday, July 28, 2003
Oops. Those 50's should be 25's. I never said you don't need testing. ;-)
Philo
"The problem with your suggestion that everything is studied and done in an "optimal" manner to begin with ..."
That's not what I wanted to say; I summed up by saying "my point is that you have to plan in advance where to leave a place for optimization, or there's a chance you won't have where to optimize."
Which I'll restate: DO NOT OPTIMIZE CODE UNTIL YOU'VE GOT SOMETHING WORKING. However, *DO* optimize structure and architecture so that you will be able to optimize should the need arise.
About "studied" - a carpenter should be able to give a rough estimate, within a factor of 10, of the amount of wood needed for a project. I believe same goes for a programmer, both about no. of lines of code and about no. of CPU cycles. It's not a matter of "study", it's part of the trade.
And I'll try to clarify what I was aiming at (and, upon rereading 30 minutes later, see I didn't express well enough): That all too often, thinking about performance in advance would lead you to a solution that is of comparable effort, but can be improved at a later stage, whereas the "natural" solution can't, and may not offer anything in return (it may, but it does not necessarily).
About the OO being backwards - that depends on what you expect to change more, and what you have control over. Your "forward" is the natural SmallTalk / Python solution - if you need a new virtual field, you just add it to Object (or the most common ancestor), and use it from there.
However, this doesn't work well as well for C++ / Java. If you want to add a virtual field to existing objects, you'll have to change the base class (often not possible), or create a new class that supports the virtual field, and an object of that new class for every object of the original class (possibly holding just a pointer to the original, but still, you'd have to construct it if you follow the language spec). On the other hand, if you use an adapter object like I did, it can "adapt" any class to the required functionality (providing fields, real or virtual), and if used properly this results in much less object creation / destruction and much less code than subclassing. But YMMV. In my experience, adapters work better than simple inheritence (this is also the approach taken by the STL; However, I do not consider the STL A good example of adapter use).
One of the problems of OO is that it lacks a good definition, so one's forward is another backward. [ ] sums it up nicely.
Ori Berger
Monday, July 28, 2003
Philo - Totally agree.
You've done the analysis, and took the efficient (business wise) choice. I'm all for it.
But what usually happens is that plan B is never even considered (you know. "We'll look at it later if there's a problem"). And it often turns out that Plan B is the same length as Plan A, only using somewhat different principles, but optimizing plan A will take 4 times as much or won't be possible.
P.S: Everything I say about running time, I apply to coding time and no. of lines as well. Which is compatible with how you look at it.
Know thy alternatives, and pick wisely, according to case. Don't discard performance estimations and alternatives, just as you don't discard schedule estimations and alternatives or complexity estimations and alternatives.
> a carpenter should be able to give a rough
> estimate, within a factor of 10, of the amount
> of wood needed for a project.
I hope you mean 10% not a factor of ten (x10) or do I misunderstand the factor of ten?
Sanger B
Tuesday, July 29, 2003
Ori - sure you can. Can't you coerce objects of type list-of-records to array-of-records? The fact that languages like Java let you declare multidimensional arrays, suggests that such optimizations are common. I'd treat this as a similar problem to caching.
Tayssir John Gabbour
Tuesday, July 29, 2003
Ah I understand what you're saying now Ori. I pretty much agree with you. You should definitely think about different possibilities for doing the same thing, and whether any would be drastically faster for the same (or similar) effort. Drawing the line between that and doing premature optimization can be a bit hard at times, though
Mike McNertney
Tuesday, July 29, 2003
" I hope you mean 10% not a factor of ten (x10) or do I misunderstand the factor of ten? "
Well, for a carpenter it better be closer to 10% than 900%, but I did mean a factor of 10 for software. With todays caches, instruction sets and compilers, I don't think that it's possible to make a precise estimate.
"Can't you coerce objects of type list-of-records to array-of-records?"
In C++, you can't. You can write a templace function that accepts either, but if you have a non-template function you want to use, then coercion is effectively constructing the container anew; This will always take O(n), even if the routine you use only requires O(log n) or O(1) processing.
"Drawing the line between that and doing premature optimization can be a bit hard at times, though"
Couldn't agree more.
I'm being a bit extreme on the performance side in an attempt to balance the common view that performance doesn't matter. Whenever you're doing something nontrivial, it DOES.
Ori Berger
Tuesday, July 29, 2003
Recent Topics
Fog Creek Home | http://discuss.fogcreek.com/joelonsoftware2/default.asp?cmd=show&ixPost=59949&ixReplies=9 | CC-MAIN-2017-13 | refinedweb | 2,756 | 69.92 |
On 24/01/18 13:59, Vivek Das Mohapatra wrote: > Apologies for the exegesis: It seems to me that the copy of libc in the > private namespace has somehow managed to scribble on the linked list > pointed to by __stack_user, overwriting a key address. > > Is my analysis correct? Is there something I could or should have done to > avoid this? > > A while ago ( > I suggested a dlmopen flag RTLD_UNIQUE or similar which would cause the > existing mapping of the target library in the main namespace/link-map to be > re-used instead of creating a new one: I believe this would prevent this > problem (and others detailed in that message) from occurring - any thoughts? i don't know what you are doing, but it's hard to imagine that two libcs (or libpthreads) would work in the same process: if they can run code on the same thread they cannot both control the tcb (and will clobber each other's global state through that). same for signal handlers (for internal signals) or brk syscall, or stdio buffering, etc. the libc has to deal with process global/thread local state that must be controlled by the same code consistently otherwise bad things happen. | https://sourceware.org/pipermail/libc-help/2018-January/004430.html | CC-MAIN-2022-21 | refinedweb | 202 | 60.58 |
- NAME
- SYNOPSIS
- DESCRIPTION
- EXAMPLES
- TODO
- BUGS
- AUTHOR
- ACKNOWLEDGMENTS
- LICENSE
- SEE ALSO
NAME
Log::Procmail - Perl extension for reading procmail logfiles.
SYNOPSIS
use Log::Procmail; my $log = new Log::Procmail 'procmail.log'; # loop on every abstract while(my $rec = $log->next) { # do something with $rec->folder, $rec->size, etc. }
DESCRIPTION
Log::Procmail
Log::Procmail reads procmail(1) logfiles and returns the abstracts one by one.
- $log = Log::Procmail->new( @files );
Constructor for the procmail log reader. Returns a reference to a Log::Procmail object.
The constructor accepts a list of file as parameter. This allows you to read records from several files in a row:
$log = Log::Procmail->new( "$ENV{HOME}/.procmail/log.2", "$ENV{HOME}/.procmail/log.1", "$ENV{HOME}/.procmail/log", );
When $log reaches the end of the file "log", it doesn't close the file. So, after procmail processes some incoming mail, the next call to next() will return the new records.
- $rec = $log->next
Return a Log::Procmail::Abstract object that represent an entry in the log file. Return undef if there is no record left in the file.
When the Log::Procmail object reaches the end of a file, and this file is not the last of the stack, it closes the current file and opens the next one.
When it reaches the end of the last file, the file is not closed. Next time the record method is called, it will check again in case new abstracts were appended.
Procmail(1) log look like the following:
From karen644552@btinternet.com Fri Feb 8 20:37:24 2002 Subject: Stock Market Volatility Beating You Up? (18@2) Folder: /var/spool/mail/book 2840
Some informational messages can be put by procmail(1) in the log file. If the
errorsattribute is true, these lines are returned one at a time.
With errors enabled, you have to check that next() actually returns a Log::Procmail::Abstract object. Here is an example:
$log->errors(1); # fetch data while ( $rec = $log->next ) { # if it's an error line if ( !ref $rec ) { # this is not a log, but an informational message # do something with it next; } # normal log processing }
- $log->push( $file [, $file2 ...] );
Push one or more files on top of the list of log files to examine. When Log::Procmail runs out of abstracts to return (i.e. it reaches the end of the file), it transparently opens the next file (if there is one) and keeps returning new abstracts.
- $log->errors( [bool] );
Set or get the error flag. If set, when the next() method will return the string found in the log file, instead of ignoring it. Be careful: it is a simple string, not a Log::Procmail::Abstract object.
Default is to return no error.
- $fh = $log->fh()
Returns the currently opened filehandle, from which the next call to
next()will try to read a record.
- $select = $log->select()
Return a IO::Select object that watches the currently opened filehandle.
You are not supposed to use
add()or
remove()on the returned IO::Select object.
Additional warning for
MSWin32,
NetWare,
dos,
VMS,
riscosand
beos: on those systems,
select()returns
undef. (Check ext/IO/t/io_sel.t in the Perl sources for details. Hint: look for the message 4-arg select is only valid on sockets.)
Log::Procmail::Abstract
Log::Procmail::Abstract is a class that hold the abstract information. Since the abstract hold From, Date, Subject, Folder and Size information, all this can be accessed and modified through the from(), date(), subject(), folder() and size() methods.
Log::Procmail::next() returns a Log::Procmail::Abstract object.
- Log::Procmail::Abstract accessors
The Log::Procmail::Abstract object accessors are named from(), date(), subject(), folder() and size(). They return the relevant information when called without argument, and set it to their first argument otherwise.
# count mail received per folder while( $rec = $log->next ) { $folder{ $rec->folder }++ }
The source() accessor returns the name of the log file or the string representation of the handle, if a filehandle was given.
- $rec->ymd()
Return the date in the form
yyyymmmddhhmmsswhere each field is what you think it is.
;-)This method is read-only.
EXAMPLES
Here is an example procmail biff-like script, courtesy of Ian Langworth:
#/usr/bin/perl -w use strict; use Log::Procmail; use constant LOGFILE => "$ENV{HOME}/procmail.log"; use constant VALID_FOLDERS => [qw( agent inbox perl systems )]; my $format = "\%8s: \%-30.30s / %s\n"; my $log = Log::Procmail->new( LOGFILE ); $log->errors(1); while ( $log->select->can_read ) { my $rec = $log->next; # error? warn "$rec\n", next unless ref $rec; # ignore mailboxes we don't care about next unless grep { $_ eq $rec->folder } @{ VALID_FOLDERS() }; # print data printf $format, From => $rec->from; printf $format, Subject => $rec->subject, $rec->folder; }
TODO
The Log::Procmail object should be able to read from STDIN.
BUGS
Sometimes procmail(1) logs are mixed up. When this happens, I've chosen to accept them the way mailstat(1) does: they are discarded unless they have a
Folderline.
If you use Log::Procmail and the select() method to follow a live logfile as in the above example, please not that Log::Procmail will not detect when the file is rotated.
Please report all bugs through the rt.cpan.org interface:
AUTHOR
Philippe "BooK" Bruhat <book@cpan.org>.
ACKNOWLEDGMENTS
Thanks to Briac "Oeufmayo" Pilpré and David "Sniper" Rigaudiere for early comments on irc. Thanks to Olivier "rs" Poitrey for giving me his huge procmail log file (51 Mb spanning over a two-year period) and for probably being the first user of this module. Many thanks to Michael Schwern for insisting so much on the importance of tests and documentation.
Many thanks to "Les Mongueurs de Perl" for making cvs.mongueurs.net available for Log::Procmail and many other projects.
LICENSE
This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see)
SEE ALSO
perl(1), procmail(1). | https://metacpan.org/pod/Log::Procmail::Abstract | CC-MAIN-2016-44 | refinedweb | 988 | 65.01 |
NAME
RDS - Reliable Datagram Sockets
SYNOPSIS
#include <sys/socket.h> #include <netinet/in.h>
DESCRIPTION
This is an implementation of the RDS socket API. It provides reliable, in-order datagram delivery between sockets over a variety of transports. Currently, RDS can be transported over Infiniband, and loopback. RDS over TCP is disabled, but will be re-enabled in the near future. RDS uses standard AF_INET addresses as described in ip(7) to identify end points. Socket Creation RDS is still in development and as such does not have a reserved protocol family constant. Applications must read the string representation of the protocol family value from the pf_rds sysctl parameter file described below. rds_socket = socket(pf_rds, SOCK_SEQPACKET, 0); Socket Options RDS sockets support a number of socket options through the setsockopt(2) and getsockopt(2) calls. The following generic options (with socket level SOL_SOCKET) are of specific importance: SO_RCVBUF Specifies the size of the receive buffer. See section on "Congestion Control" below. SO_SNDBUF Specifies the size of the send buffer. See "Message Transmission" below. SO_SNDTIMEO Specifies the send timeout when trying to enqueue a message on a socket with a full queue in blocking mode.. Binding A new RDS socket has no local address when it is first returned from socket(2). It must be bound to a local address by calling bind(2) before any messages can be sent or received. This will also attach the socket to a specific transport, based on the type of interface the local address is attached to. From that point on, the socket can only reach destinations which are available through this transport.. Connecting The default mode of operation for RDS is to use unconnected socket, and specify a destination address as an argument to sendmsg. However, RDS allows sockets to be connected to a remote end point using connect(2). If a socket is connected, calling sendmsg without specifying a destination address will use the previously given remote address. Congestion Control RDS does not have explicit congestion control like common streaming protocols such as TCP. However, sockets have two queue limits associated with them; the send queue size and the receive queue size. Messages are accounted based on the number of bytes of payload.. Blocking Behavior The sendmsg(2) and recvmsg(2) calls can block in a variety of situations. Whether a call blocks or returns with an error depends on the non-blocking setting of the file descriptor and the MSG_DONTWAIT message flag. If the file descriptor is set to blocking mode (which is the default), and the MSG_DONTWAIT flag is not given, the call will block. In addition, the SO_SNDTIMEO and SO_RCVTIMEO socket options can be used to specify a timeout (in seconds) after which the call will abort waiting, and return an error. The default timeout is 0, which tells RDS to block indefinitely. Message Transmission Messages may be sent using sendmsg(2) once the RDS socket is bound. Message length cannot exceed 4 gigabytes as the wire protocol uses an unsigned 32 bit integer to express the message length.. Message Receipt Messages may be received with recvmsg(2) on an RDS socket once it is bound to a source address. RDS will return messages in-order, i.e. messages from the same sender will arrive in the same order in which they were be sent.. Control Messages RDS uses control messages (a.k.a. ancillary data) through the msg_control and msg_controllen fields in sendmsg(2) and recvmsg(2). Control messages generated by RDS have a cmsg_level value of sol_rds. Most control messages are related to the zerocopy interface added in RDS version 3, and are described in rds-rdma(7). The only exception is the RDS_CMSG_CONG_UPDATE message, which is described in the following section. Polling RDS supports the poll(2) interface in a limited fashion. POLLIN is returned when there is a message (either a proper RDS message, or a control message) waiting in the socket's receive queue. POLLOUT is always returned while there is room on the socket's send queue.)) Canceling Messages An application can cancel (flush) messages from the send queue using the RDS_CANCEL_SENT_TO socket option with setsockopt(2). This call takes an optional sockaddr_in address structure as argument. If given, only messages to the destination specified by this address are discarded. If no address is given, all pending messages are discarded. Note that this affects messages that have not yet been transmitted as well as messages that have been transmitted, but for which no acknowledgment from the remote host has been received yet. Reliability If sendmsg(2) succeeds, RDS guarantees that the message will be visible to recvmsg(2) on a socket bound to the destination address as long as that destination socket remains open..
SYSCTL VALUES
These parameteres may only be accessed through their files in /proc/sys/net/rds. Access through sysctl(2) is not supported. pf_rds This file contains the string representation of the protocol family constant passed to socket(2) to create a new RDS socket. sol_rds This file contains the string representation of the socket level parameter that is passed to getsockopt(2) and setsockopt(2) to manipulate RDS socket options. max_unacked_bytes and max_unacked_packets These parameters are used to tune the generation of acknowledgements. By default, the system receiving RDS messages does not send back explicit acknowledgements unless it transmits a message of its own (in which case the ACK is piggybacked onto the outgoing message), or when the sending system requests an ACK. However, the sender needs to see an ACK from time to time so that it can purge old messages from the send queue. The unacked bytes and packet counters are used to keep track of how much data has been sent without requesting an ACK. The default is to request an acknowledgement every 16 packets, or every 16 MB, whichever comes first. reconnect_delay_min_ms and reconnect_delay_max_ms RDS uses host-to-host connections to transport RDS messages (both for the TCP and the Infiniband transport). If this connection breaks, RDS will try to re-establish the connection. Because this reconnect may be triggered by both hosts at the same time and fail, RDS uses a random backoff before attempting a reconnect. These two parameters specify the minimum and maximum delay in milliseconds. The default values are 1 and 1000, respectively.
SEE ALSO
rds-rdma(7), socket(2), bind(2), sendmsg(2), recvmsg(2), getsockopt(2), setsockopt(2). RDS(7) | http://manpages.ubuntu.com/manpages/precise/man7/rds.7.html | CC-MAIN-2014-15 | refinedweb | 1,072 | 55.24 |
NAME
VOP_LINK - create a new name for a file
SYNOPSIS
#include <sys/param.h> #include <sys/vnode.h> int VOP_LINK(struct vnode *dvp, struct vnode *vp, struct componentname *cnp);
DESCRIPTION.
LOCKS
VOP_LINK() expects the directory and file vnodes to be locked on entry and will leave the vnodes locked on return.
RETURN VALUES
Zero is returned if the file was linked successfully, otherwise an error is returned.
ERRORS
[EMLINK] The file has too many links. [EPERM] The file is immutable. [EXDEV] A hard link is not possible between different file systems.
SEE ALSO
vn_lock(9), vnode(9)
AUTHORS
This manual page was originally written by Doug Rabson. | http://manpages.ubuntu.com/manpages/lucid/en/man9/VOP_LINK.9freebsd.html | CC-MAIN-2015-11 | refinedweb | 107 | 68.67 |
Is there anything special about unit/test? We all have unit testing libraries; they are important, but I'm leaving out lots of important things that don't distinguish one language from the other.
Re: modification of base classes. I imagine modification of Object could be necessary at times. This is the flip side of Python's magic methods -- where you can build defaults and other rules into the function that then optionally calls magic methods, in Ruby (presumably?) you would create an implementation in Object that gets specialized as necessary. That's certainly the norm in Smalltalk, though I think there are some serious reason's to be concerned by how that effects the larger process and the many users of Object. From the opposite end CLOS handles the same thing with generic functions, with substantially better decoupling; in Python people are pushing in that direction with adaptation and generic functions, though that kind of development is not the form.
Along these lines, the experimental Javascript 2.0 spec adds namespaces to methods, mitigating the issues of adding methods to other classes. An interesting way to address the problem.
Disclaimer: Read this post with the knowledge that I really only know enough about Ruby to be dangerous.
Hmm, no I don't think there's anything particularly standout about test/unit. I just really REALLY like unit testing and I think I didn't understand what you meant about notable libraries.
Oh, actually, now that I think about it, optparse is pretty sweet and I've never really seen anything like it other languages I've used (though I'm not really up on Python, so it may have something similar) RDoc here:
Back to Object mods: Well, you know, it's not too hard to do change localization in Object with the alias method. Like:alias :meth, :old_meth def meth ... end
and then when you're done with being a clever bugger:alias :old_meth, :meth and Bob's your Uncle, back to normal.
Not sure what you're talking about with CLOS and adaptation and generic functions or JavaScript 2.0 as I'm not up on that (in fact, I'm probablly not in a position to be talking about language features at all as it's certainly not my specialty).
I don't think popping Object open and changing it around is the flip side of Python Magic Methods though. Read the following section with the knowledge that I am no Ruby expert and know only of Python from mythical tales of its courage in battle:
From what I've used of Ruby, it would seem that the actual flip side of Python "magic methods" is just using some standard method names, like "to_s" or "each" that behave like they should for the Object they're inside of. I think the "magic" is typically accomplished with mixins, Enumerable being the example used in the Pickaxe where you define "each" to get a bunch of the iterators and "<=>" if you want the rest (I think defining "<=>" and including Enum also gives you Comparable, but you might need to add it explicitly) and then if you want a special version of one of the methods the mixin adds, you just go ahead and change it.
I'm gonna shut up now because if I keep talking, I'm probablly going to misrepresent something and start a flamewar.
Oh, actually, now that I think about it, optparse is pretty sweet and I've never really seen anything like it other languages I've used (though I'm not really up on Python, so it may have something similar). -- need I say more? optparse existed in Python under name of Optik since 2001: and given apparent similarities in API, I even doubt whether Ruby one is clone of Python one... | http://www.ianbicking.org/ruby-python-power-comment-13.html | CC-MAIN-2018-05 | refinedweb | 640 | 64.64 |
Introduction:
In this article I will explain how to read or write connection strings in web.config file using asp.net.
In this article I will explain how to read or write connection strings in web.config file using asp.net.
Description:
In Previous article I explained clearly about Encrypt or Decrypt connection strings in web.config file using asp.net. Now I will explain how to write connection strings in web.config file and how to read connection strings from web.config file using asp.net.
In Previous article I explained clearly about Encrypt or Decrypt connection strings in web.config file using asp.net. Now I will explain how to write connection strings in web.config file and how to read connection strings
Example of declaring connectionStrings in web.config file like this
This namespace is used to get configuration section details from web.config file.
After add namespaces write the following code in code behind
C# code
VB.NET
Here we stored our database connection string in web.config file it was not secured if we want to encrypt the connection string in web.config file check this post encrypt or decrypt connection string in web.config file.
25 comments :
how can I connect multi Dababase server using this connection string?
hello
i have MS access 2007 connection string
I use asp.net 2010 express adition
I right below code in my website
IN Recent_artical.aspx.cs file
String strCon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
OleDbConnection con = new OleDbConnection(strCon);
con.Open();
which code right in Web.config file
Please urgent answer in my gmail id
hetalmodi43@gmail.com
hi suresh its been very interesting by reading ur articles....
can u plz give me the clear difference of app settings and connection strings which one is better to use?
r they both same if not how they differ?
can u plz explain on this
SPECIAL REQUEST CAN YOU GUIDE ME HOW TO CONNECT THE DATABASE IN ASP.NET WITH ORACLE
fhghjgjhgjhjhoikjahgdfsdgfbbbbb
very helpful code
thank you
pls tell if i want to use multiple connection string one for access and one for sql ..how can i achieve this
Nice article, your article are very help full........Thanks to you from bottom of my heart
hi sir iam veerendra u r regular follower sir pls
help me i want remote database connection through
C# windows Applications
Very Nice article Sir.I really wants to thank you for such a nice explanation.
can you say how many types of connection string available with asp.net and sql server combine...
Your code is very useful to beginner also.
nice example for understanding. thank you
nice article brother it has helping me a lot!thanx bro
how to write namespaces in web config with that use we can't write namespaces for every page
I need a help for Locking the User Account in Asp.Net Can u Guide Please
Thanks a lot for help people like me
how we find the connection strings path
hello sir i hosting my website but is see the error 500 - Internal server error.
using web.config file please help me
I use asp.net 2005 and database SQL server management studio 2005 but the problem is when I run my web application through virtual directory its display an error
"Cannot open database "website1" requested by the login. The login failed.Login failed for user 'server name'."
Somebody suggest me for this problem
Inspro Calendar Report
Your code is very useful
Thank You
Note: Only a member of this blog may post a comment. | https://www.aspdotnet-suresh.com/2011/11/write-connection-strings-in-webconfig.html | CC-MAIN-2021-31 | refinedweb | 598 | 58.89 |
requestAnimationFrame not fired during scroll in Chrome
Parallax on Chrome (mac) out of a sudden started to cause performance issues. This used to work smoothly, as for example Firefox is still doing.
It seems like the requestAnimationFrame stops being called during scroll. What could be the reason for this?
I am using requestAnimationFrame, transform3d, will-change. See the site on its temporarily location:
See also questions close to this topic
- Assign some of fields from another array based on id and get final output based on value type?
arr1 = [ { id : 1, name : 'book1', description: 'some text' }, { id : 2, name : 'book2', description: 'some text' }, { id : 3, name : 'book3', description: 'some text' } ] arr2 = [ { id : 1, name : 'book1', type : 'thriller', publisher : 'some x', }, { id : 2, name : 'book2', type : 'action', publisher : 'some x', }, { id : 3, name : 'book3', type : 'thriller', publisher : 'some y', } ]
I want to assign fields 'type' and 'publisher' to arr1 based on id value and in parallel i want the array based on type.
The required output is
arr3 = { 'thriller': [ { id: 1, name: 'book1', type: 'thriller', publisher: 'some x' }, { id: 3, name: 'book3', type: 'thriller', publisher: 'some y' } ], 'action': [ { id: 2, name: 'book2', type: 'action', publisher: 'some x' }] }
Performance is key issue. I can achieve above one using 2 functions but I want to achieve it in single function.
Edit1:- In arr1 along with above fields I am getting some other fields from database(mongodb). For simplicity I have included what ever is necessery.
Currently I am achieving this with below 2 functions
Function 1:-
let result = arr1.map((e) => { for(let element of arr2){ if(e.id === element.id) { e['type'] = element.type e['publisher'] = element.publisher } } return e })
Function 2:-
function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); } let output = groupBy(result, 'type');
What I want is combine both functionalities and perform it in single function call.
- Outer query/Limiting results dramatically slows down the whole query
I have a query that returns about 800-900 rows and takes about 1-2s to execute. Unfortunately, this query is inside another select query, which limits results to 1000. This 'limiting' query slows down whole execution dramatically, like 10 times or so.
SELECT * FROM ( SELECT x.id FROM tableX x WHERE --some conditions...) WHERE ROWNUM <= 1000;
SQL developer shows the same plan for both inner and whole query (except whole query has to do
COUNT filter predicates rownum <= 1000. Costs are exactly the same.
EDIT: even when I remove the where clause
WHERE ROWNUM <= 1000;it still takes about 20s to execute.. So it looks like the outer query changes the execution plan.
- Faster way of finding all indices of specific string in an array
Below code is used to find all indices of a string that might occur only once in an array but the code isn't very fast. Does somebody know a faster and more efficient way to find unique strings in an array?
using System; using System.Collections.Generic; using System.Linq; public static class EM { // Extension method, using Linq to find indices. public static int[] FindAllIndicesOf<T>(this IEnumerable<T> values, T val) { return values.Select((b,i) => Equals(b, val) ? i : -1).Where(i => i != -1).ToArray(); } } public class Program { public static string FindFirstUniqueName(string[] names) { var results = new List<string>(); for (var i = 0; i < names.Length; i++) { var matchedIndices = names.FindAllIndicesOf(names[i]); if (matchedIndices.Length == 1) { results.Add(names[matchedIndices[0]]); break; } } return results.Count > 0 ? results[0] : null; } public static void Main(string[] args) { Console.WriteLine("Found: " + FindFirstUniqueName(new[] { "James", "Bill", "Helen", "Bill", "Helen", "Giles", "James", } )); } }
- [Sharing]Anyone have/found super eye catching animation idea or component on HTML5?
This discussion only for sharing, if anyone found/have an opensource library for create cool animation me first, this library are very awesome :
happy sharing..
- HTML element not detected in external .js file
My HTML code:
<div class="container"> <div class="question-card"> <h1 id="question1">This is the question</h1> </div> <div class="answer-choices"> <div class="row1"> <span class="choice1" id="one" onclick="choice1()">One</span> <span class="choice2" onclick="choice2()">Two</span> </div> <div class="row2"> <span class="choice3" onclick="choice3()">Three</span> <span class="choice4" onclick="choice4()">Four</span> </div> </div> <button id="btn" onclick="next()">Next</button>
My js code:
function clickNextText(){ document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed" } //This is working fine var str element = document.getElementById('btn'); if (element != null) { str = element.value; } else { str = null; } console.log(str) //This is however returning null.
I don't understand what is wrong here. Moreover every element with an id after the div with class answer-choices isn't detected. While the script code when placed in .html itself works fine.
- How can I create an inset curved background that works with a background gradient and overlapping transparent shapes?
I have been trying to create a section of a webpage that looks like the image below with just CSS. I can not figure out how to create the curves the top and bottom of the background and keep intact the transparent overlays. The section above and below (partially shown) also use transparent backgrounds. So, you see the different shades the circles have.
-.
- Completing a game section with parallax view
When the player completes a level or a section in a game with parallax view, how can the time of completion actually differ if the parallax scroll speed is constant? If the scroll speed is constant then the average speed of the vehicle will also be constant and the time of completing a section will be the same.
Example Moon Patrol
When the player completes a section, how can the time be different different sections (sections with the same length) if the scrolling speed is constant? Isn't the only way of getting a good fast completion time that the scrolling speed actually increases when the player increases the speed of the vehicle?
The background is that I am working on an Android mini game with a parallax view, you can find it on code review if you track my questions there.
The actual code that updates the scroll is the following
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.util.Log; public class MoonBackground { boolean hasRock = true; public MoonBackground(Context context, int screenWidth, int screenHeight, String bitmapName, int sY, int eY, float s) { // Make a resource id out of the string of the file name int resID = context.getResources().getIdentifier(bitmapName, "drawable", context.getPackageName()); int resID2 = context.getResources().getIdentifier("grass2", "drawable", context.getPackageName()); // Load the bitmap using the id bitmap1 = BitmapFactory.decodeResource(context.getResources(), resID); bitmap2 = BitmapFactory.decodeResource(context.getResources(), resID2); //1, screenWidth, (endY - startY) , true); bitmap2 = Bitmap.createScaledBitmap(bitmap2,); bitmapReversed2 = Bitmap.createBitmap(bitmap2, 0, 0, width, height, matrix, true); } Bitmap bitmap, bitmap1, bitmap2; Bitmap bitmapReversed, bitmapReversed2; int width; int height; boolean reversedFirst; float speed; int xClip; int startY; int endY; static char checkpoint = 'A'; public void update(long fps) { // Move the clipping position and reverse if necessary xClip -= speed / fps; if (xClip >= width) { xClip = 0; reversedFirst = !reversedFirst; } else if (xClip <= 0) { xClip = width; reversedFirst = !reversedFirst; } } }
Therefore I wonder if I should increase the scroll speed when the vehicle accelerates or reaches the far right of the screen?
- How to make Layers revealing parallax
I need to make sections on my website reveal on scroll with scrolling parallax. But unlike usual parallax where only background image remain fixed and rest of the content comes on scroll, I want the content of previous and next div to remain their in background and gets revealed. Here is the reference:
While searching I got a link showing same effect:
$(window).scroll(function() { $("section div").each(function() { $(this).css('margin-top', $(window).scrollTop() - $(this).parent().position().top); console.log(); }); });
But this example is little shaky and jerky on mozilla/safari browser. Can this fiddle get repaired to avoid jerks/shakes?
- window.requestAnimationFrame - need more explanation
I'm working on a tile game, in html5 using canvas, to learn about html5, and reached point when animations should be added. However
window.requestAnimationFrame
seems way too confusing. I got the basic idea, that its sync to browser, runs in a loop of itself, but no clue how to proceed from there.
but that's just one loop. How can i restart it on click? How can i trigger different animations?
here is what i have in mind:
fade tiles in on load -> idle loop -> fade certain tiles out on user interaction. -> back to idle loop.
how is syntax of that would look like?
- Leaflet - CanvasLayer: how to get animated features to move correctly when dragging the map?
Trying to add a Canvas layer on top of a Bing TileLayer using the extensions below. In addition to that, I would like to animate the canvas drawing using
RequestAnimationFrame. The issue is that it seems that when dragging, the point moves more than what it should (see video). However, at the end of the moving, it comes back to the right place.
I tried different methods, either inheriting CanvasLayer and overriding render() or setting a delegate, always same result.
Here is the relevant part of the code:
// layer creation (TypeScript) this.mapCanvasLayer = new L.CanvasLayer(); this.mapCanvasLayer.delegate(this).addTo(map); // L.canvasLayer() // .delegate(this) // -- if we do not inherit from L.CanvasLayer we can setup a delegate to receive events from L.CanvasLayer // .addTo(map); // drawing and animation (TypeScript) public onDrawLayer(info) { // quick test, this just draws a red dot that blinks this.info = info; var data = [[0,0]]; var ctx = info.canvas.getContext('2d'); ctx.clearRect(0, 0, info.canvas.width, info.canvas.height); ctx.fillStyle = "rgba(255,0,0," + this.i/10 + ")"; for (var i = 0; i < data.length; i++) { var d = data[i]; if (info.bounds.contains([d[0], d[1]])) { var dot = info.layer._map.latLngToContainerPoint([d[0], d[1]]); ctx.beginPath(); ctx.arc(dot.x, dot.y, 3, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); } } }; public animate() { // make the point blink if (this.up) { this.i++; if (this.i >= 10) this.up = false; } else { this.i--; if (this.i <= 1) this.up = true; } // animate: this.mapCanvasLayer.drawLayer(); window.requestAnimationFrame(this.animate.bind(this)); }
Extensions tried:
- gLayers.Leaflet // example is this one
- Leaflet.CanvasLayer
Not tried yet:
I have the feeling it is due either to the dragging event or the coordinates translations (
latLngToContainerPoint) not being properly handled, but have no idea why. In the samples available for the Leaflet.CanvasLayer dragging an animated map seems to work fine. Any idea what is wrong with this code? Thank you for your help!
Edit
See comments: replaced the call as below:
// var dot = info.layer._map.latLngToContainerPoint([d[0], d[1]]); var dot = info.layer._map.latLngToLayerPoint([d[0], d[1]]);
Now, the point moves correctly. However, when I release the button, it now shifts to a position relative to the container, i.e. same distance of window borders, but wrong coordinates (wrong location on map).
If I now do this:
public onDrawLayer(info) { this.info = info; var ctx = info.canvas.getContext('2d'); ctx.clearRect(0, 0, info.canvas.width, info.canvas.height); const fillStyleLayer = "rgba(255,0,0,1)"; // red: layer const fillStyleContainer = "rgba(0,0,255,1)"; // blue: container var layerPoint = info.layer._map.latLngToLayerPoint([0,0]); var containerPoint = info.layer._map.latLngToContainerPoint([0,0]); // this.dot = (this.dragging) // ? info.layer._map.latLngToLayerPoint([0,0]); // : info.layer._map.latLngToContainerPoint([0,0]); ctx.fillStyle = fillStyleLayer; ctx.beginPath(); ctx.arc(layerPoint.x, layerPoint.y, 3, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); ctx.fillStyle = fillStyleContainer; ctx.beginPath(); ctx.arc(containerPoint.x, containerPoint.y, 3, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); }; public animate() { this.mapCanvasLayer.drawLayer(); window.requestAnimationFrame(this.animate.bind(this)); }
Layer point (red) moves correctly when panning but then shifts to wrong location. Container point (blue) moves too much when panning but then shifts back to correct location... :(
- Why are my setInterval and setTimeout Animations behaving unexpectedly when switching windows
This is a two part question -
I'm trying to build a continuous infinite loop animation with plain javascript with
setIntervaland
setTimeoutmethods with applying css properties. When i switch browser tabs and return to this after a while my animations seem to behave very unexpectedly. Why does this happen??
After reading online I understand that
requestAnimationFrameis recommended way to do animations using javascript. In my case i'm using JS to trigger transform and scale properties in css with a
transitionproperty. Even if i were to use
requestAnimationFramewith a ease or bezier function lets say, how would I take care of the
setTimeoutfunctionality? Where after animating between first and second cards to repeat the animation from second to third..
The link to codepen is pasted above. Thanks in advance! | http://quabr.com/46685763/requestanimationframe-not-fired-during-scroll-in-chrome | CC-MAIN-2018-30 | refinedweb | 2,152 | 51.04 |
How to Use the HTML5 Full-Screen API
Update: This article is now outdated. Please see the updated version, How to Use the HTML5 Full-Screen API (Again).
Flash could emulate the OS and trick users into handing over passwords, credit card details, etc.
At the time of writing, the HTML5 full-screen API has been implemented in Firefox, Chrome and Safari. Mozilla provide good cross-browser details but it’s worth noting that the specifications and implementation details are likely to change.
Unlike pressing F11 to make your browser go full-screen, the API sets a single element full-screen. It’s intended for images, videos and games using the canvas element. Once an element goes full-screen, a message appears temporarily to inform the user that they can press ESC at any time to return to windowed mode.
The main properties, methods and styles are:
element.requestFullScreen()
Makes an individual element full-screen, e.g. document.getElementById(“myvideo”).requestFullScreen().
document.cancelFullScreen()
Exits full-screen mode and returns to the document view.
document.fullScreen
Returns true if the browser is in full-screen mode.
:full-screen
A CSS pseudo-class which applies to an element when it’s in full-screen mode.
Vexing Vendor Prefixes
Don’t bother trying to use these API names. You’ll require vendor prefixes for BOTH the CSS and JavaScript properties:
There’s no support in Internet Explorer or Opera yet, but I would suggest you use the ‘ms’ and ‘o’ prefixes for future proofing.
I’ve developed a function in the demonstration page which handles the prefix shenanigans for you:
var pfx = ["webkit", "moz", "ms", "o", ""]; function RunPrefixMethod(obj, method) { var p = 0, m, t; while (p < pfx.length && !obj[m]) { m = method; if (pfx[p] == "") { m = m.substr(0,1).toLowerCase() + m.substr(1); } m = pfx[p] + m; t = typeof obj[m]; if (t != "undefined") { pfx = [pfx[p]]; return (t == "function" ? obj[m]() : obj[m]); } p++; } }
We can then make any element viewable full screen by attaching a handler function which determines whether it’s in full-screen mode already and acts accordingly:
var e = document.getElementById("fullscreen"); e.onclick = function() { if (RunPrefixMethod(document, "FullScreen") || RunPrefixMethod(document, "IsFullScreen")) { RunPrefixMethod(document, "CancelFullScreen"); } else { RunPrefixMethod(e, "RequestFullScreen"); } }
The CSS
Once the browser enters full-screen mode you’ll almost certainly want to modify the styles for the element and it’s children. For example, if your element normally has a width of 500px, you’ll want to change that to 100% so it uses the space available, e.g.
#myelement { width: 500px; } #myelement:full-screen { width: 100%; } #myelement:full-screen img { width: 100%; }
However, you cannot use a list of vendor prefixed selectors:
/* THIS DOES NOT WORK */ #myelement:-webkit-full-screen, #myelement:-moz-full-screen, #myelement:-ms-full-screen, #myelement:-o-full-screen, #myelement:full-screen { width: 100%; }
For some bizarre reason, you must repeat the styles in their own blocks or they won’t be applied:
/* this works */ #myelement:-webkit-full-screen { width: 100% } #myelement:-moz-full-screen { width: 100% } #myelement:-ms-full-screen { width: 100% } #myelement:-o-full-screen { width: 100% } #myelement:full-screen { width: 100% }
Weird.
View the demonstration page in Firefox, Chrome or Safari…
The technique works well. The only issue I’ve discovered concerns Safari on a two-monitor desktop — it insists on using the first monitor for full-screen mode even if the browser is running on the second screen?
While it’s possibly a little early to use full-screen mode, games developers and video producers should keep an eye on progress.?
- Luke Madhanga
- Steve
- Muhamad Abdul Hay
- Francesco
- Jason
- Luis Alberto Hernandez
- Nick Ciske
- Nick Ciske
- Brockdin Barr
- Craig Rogers
- Berra
- Berra
- Mike
- manoj
- Francesco
- Anthony Goodley
- Sindre Sorhus
- jno manh
- noypiscripter
- Kurt Kemple
- Ovi | http://www.sitepoint.com/html5-full-screen-api/ | CC-MAIN-2014-15 | refinedweb | 629 | 51.38 |
I’m not a very good SAP web developer, or am I too good a SAP web developer? Before you accuse me of either false modesty or bragging, I’m not talking about my programming skills. No, I’m talking about my sensory abilities. As with my Enjoy the silence, my sight is still perfect despite my age. I can still read a license plate from across the parking lot if there’s any market for that – which younger colleagues aren’t able to.
I have always had good eye sight which had as a consequence that I almost served as a sniper during my military service. Luckily I didn’t. I barely touched the arms, which were sometimes more than double the age of the conscripts, apart from the daily cleaning routine. I was rather clumsy with them, meaning the weapons. The only two times that I actually had to shoot with live ammo ended up being two sessions of self mutilation, and not even being a sniper for 1 second, since I didn’t hit much other than myself.
Good sight
is sometimes a good thing in the computing world, but it can also be a burden too. My screen resolution is set to 1280 x 1024, 96 DPI on a 17 screen, but that seems to be rather unreadable for a lot of people. They prefer 120 DPI on a 19 screen. As a web developer this can be rather annoying. One needs to put so much information into the very limited available space. The user even prefers not to scroll within a screen either so that development sometimes becomes almost an impossible task. And just when I think that it’ll all fit, I find that the user has set an extra task bar on his browser. The intention of this web log is/was (I’ll come to that later) to alter things in such a way that the visibility of the site is set to the max, without compromising the content itself. But how can one achieve this?
Max headroom
Let’s take the SDN site as an example. I’m sure that the SDN site developers have these problems too. It is a fact that a lot of info is available on one screen at the SDN site, which sometimes works out badly due to the small font type used. The first thing that catches the eye is the site header. It’s an eye catcher because it is big and just the size of it means that there’s less place for the rest of the info.
So what if we move the header somewhat higher in order to gain space, in other words let’s make the SDN header the background for the toolbars of your browser. It’s relatively easy to do.
For MIE, you need to:
make a bmp file with the desired image.
start regedit and navigate to HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerToolbar. Needless to say that you need to make a backup first and that it’s not for the faint-hearted.
Make a new entry called BackBitmap, and put the value c:windowssdn.bmp in.
Save everything.
Guess what you see when you (re)start MIE.
I discovered that File Explorer gets the same skin, although you should officially make a BackBitmapShell entry
Less radical changes are needed when you want to alter Firefox:
locate your profile folder
create or edit the userChrome.css file with the following /*
* Do not remove the @namespace line -- it's required for correct functioning
*/
@namespace url(""); /* set default namespace to XUL */ /* Use a background image for the toolbars */
toolbox, menubar, .tabbrowser-tabs {
background-image: url("sdn.gif") !important;
background-color: none !important; }
That’s easily done, isn’t it. But when you (re)start Firefox, you see a problem. The image is repeated within the different toolbars. The only remedy for this is to create an image without any logos.
I guess that SAP wouldn’t be too happy if no logo appeared. However there is a solution to that that the SDN admins can do for their part. Just install a SDN icon as favicon.ico on the web server’s root. That icon will appear in both the location bar and bookmarks and thus have an excellent promotional aspect.
Furthermore you can replace the Firefox window icon by your own, in this case the SDN icon. All you need to do is to rename the icon to main-window.ico and place the icon in the chromeiconsdefault directory.
That’s all for phase 1 of the revamping. Wait a second you’ll say, what about the links within the header. No problem, just put them as bookmarks in the bookmark toolbar.
Nothing in the hand, nothing in the pockets
The next step is to hide the header Copperfield wise. That’s easy done with Platypus, see my earlier web log for further info. The result script looks like this:
// ==UserScript==
// @name Platypus-
// @namespace Platypus
// @include
function do_platypus_script() {
platypus_do_function(window, 'smart_remove',document.getElementById('header'),'null');
}; // Ends do_platypus_script
window.addEventListener("load", function() { do_platypus_script() }, false);//.user.js
If you want to give your Firefox an even more SDN look you can define the colours of the browsing tabs too. It’s just a matter of adding the following lines in the earlier mentioned userChrome.css
/* Change color of active tab */
tab{ -moz-appearance: none !important; }
tab[selected="true"] {
background-color: rgb(181,203,231) !important;
color: black !important; }
/* Change color of normal tabs */
tab:not([selected="true"]) {
background-color: rgb(152, 180, 216);
color: gray !important; }
The end result will look something like this.
Unfortunately this kind of feature doesn’t exist for MIE. Trixie can be tried for this, but due to differences between Firefox and Internet Explorer, not all Greasemonkey scripts can be executed within MIE. So you need to try things out to see whether it works or not.
Conclusion
As you can see, there are plenty of things you can do in order to make things more visible/readable as an end user. Please make sure that you don’t infringe any copyrights when doing this with a site. The SDN examples, and the files in the zip, are for educational purposes only. As a SAP web developer you have to make sure that your site is viewable/readable by as many people as possible without losing any information. The nec plus ultra is of course your site being WAI compliant.
Ich bin der Eddy in Tirol
This PS is to wish you all a well deserved holiday. This year I’m heading for Tirol, with a stop over in Legoland Germany.
Funny to see how marital status and the breeding instinct have influenced holiday destinations.
- When I was single I did things like making movies in Hawaii and the Bahama’s, touring in the mountains of Northern Pakistan by jeep and doing a whole tour of West Cuba by bike.
- When I was engaged we did a tour of southern Turkey by jeep.
- When I got married the tours were limited to the province of Québec and Finland, all by car.
- Since having kids we’ve always remained in the same hotel with the kids interests and physical limitations in mind. My view of the world is now limited to an 800 km radius from Brussels. The business trip to Bangalore 5 years ago being the only exception to this.
Having said this, I’ll try to take some time to reflect on the past, present and future of the things I do/did. I’ve done my stint for certain things. See you back (maybe) in August, what, what, hey, hey?
Cheers
Dom
dj | https://blogs.sap.com/2005/07/14/always-read-the-small-print/ | CC-MAIN-2017-51 | refinedweb | 1,286 | 73.58 |
On Nov 21, 2007 12:42 AM, <fx.robin@laposte.net> wrote:
> I tried yesterday on Windows XP SP2 with JDK 1.5 (I needed to add stax-api.jar and stax.jar)
and it still does not work : "Malformed URL c"
> Where can I found a document which tells what are the dependencies ? So that I could
import the right libraries.
Java 6 comes with a STaX implementation, Java 5 does not (which is why
DdlUtils provides the stax-api.jar as well as a jar of Woodstox which
is a STaX implementation).
You can find all libraries required to run DdlUtils in the lib folder
in the binary package that you can download from DdlUtils' website.
> I'll try on Linux in the next days.
> I'll put in in JIRA if the bug disapered on Linux.
This could be related to the commons-digester change that was
mentioned on the list recently. Please try the commons-digester jar
that comes with the binary package and see whether the error goes
away.
Tom | http://mail-archives.apache.org/mod_mbox/db-ddlutils-user/200711.mbox/%3C224f32340711252012g498ad6ddwc348c6d7052cf777@mail.gmail.com%3E | CC-MAIN-2019-22 | refinedweb | 175 | 75.81 |
See Also edit
- Escaping special characters
- Commands to escape special characters in arguments to glob, [match], regexp, and subst.
- Tcl Syntax
- EIAS
- Tcl Minimal Escaping Style
- Advocates using braces and quotes only when necessary.
- Tcl_Merge
- eval
- Frequently-Made Mistakes
- Is white space significant in Tcl
- Covers much of the material pertinent to "Quoting hell".
- Move any widget
- Contains an over-quoted script and a fixed version.
- string map
- The go-to command for help generating properly-quoted Tcl code
- Toplevel Watermark
- Contains an over-quoted script and a fixed version.
- Quoting Hell
- You know you're a sinner when...
- Quoting Heaven!
- Can't have one without the other.
- Quoting and function arguments
- A pre-8.6 explanation of a few gotchas.
- README.programmer
, by Brent Welch, 1993
- When and how to use [list] to avoid quoting hell. Predates {*}.
Description editIn a Tcl script, most characters represent their literal value. A handful of characters, $, [, {, \, and white space, have syntactic meaning, but can be quoted so that they lose that meaning and represent their literal value instead. One of the key distinctions between quoting in Tcl vs. in other languages is that while in other languages quoting may indicate a special type of value such as a string, that's not its function in Tcl where values are already strings. Quoting is just another escape mechanism to allow special characters to appear as literal characters in a value.
At the C level editWhen composing an individual command to be evaluated from inside C code, use Tcl_Merge, which composes a list from argv. The result can then be passed to Tcl_Eval. Tcl_VarEval does not take pains to compose a list from its arguments, but simply concatenates them together. If its arguments happen to not be lists, the results could be unexpected. APN This advice is really applicable only when you have the command in the form of argv to begin with. Normally, at the C level arguments already exist as an array or list of Tcl_Obj structures and you should use Tcl_EvalObj* variants to evaluate commands, not Tcl_Eval or Tcl_VarEval.
When Quoting is not Needed at All editQuoting is only necessary when there is a need to change the default interpretation of some character. For simple values, it can be avoided entirely:
puts Hello
set greeting Hello puts $greetingSo far, so good. No quotes quotes necessary.Command names are also just literal values. The only thing that makes them special is their position at the beginning of a line:
set cmd puts set greeting Hello $cmd $greetingIn the following example, variables are stacked against each other:
set prefix antidis set root establishment set suffix arianism set entry $prefix$root$suffix$prefix$root$suffix contains no literal whitespace, and $ carries its normal syntactic meaning, so no grouping is needed.The following is an example of both variable subtitution and [command substitution], with no grouping required:
set digits 245 puts 01[string replace $digits 1 1 34]67output:
01234567Since all characters in the script carried their normal syntactic meaning, no quoting was required. Note, however, that [ started a new command evaluation state where the whitespace served its normal purpose of delimiting words.When a word includes literal whitespace, use {}
set greeting {Good morning} puts $greetingVariable substitution and command substitution are not performed within {}, so when those features are needed, " can be used instead of {}:
set name Bob proc daystage {return Morning} set greeting "Good [daystage], $name." puts $greetingoutput:
Good Morning, Bob.
Composing a Script for Evaluation edituplevel is used in the following examples, but the same principles hold for any command leading to double substitution.The best approach to this is probably just to avoid it by converting the script into a proc and then composing a single command to invoke that proc. Besides sidestepping the need to compose a script, this also has the advantage that proc's are byte-compiled for better performance.
proc reputation_cb {msg msg2} { puts $msg puts $msg2 set time [clock seconds] puts [list {The time is now} [clock format $time]] set ::done 1 } proc reputation {} { set msg {an idle and false imposition} set msg2 {got without merit} uplevel #0 [list reputation_cb $msg $msg2] } reputationOne way to get the benefits of a proc without actually creating another proc is to use apply:
proc reputation {} { set msg {an idle and false imposition} set msg2 {got without merit} set script { puts $msg puts $msg2 set time [clock seconds] puts [list {The time is now} [clock format $time]] } uplevel #0 [list apply [list {msg msg2} $script [namespace current]] $msg $msg2] } reputationIf you really want to compose a script for evaluation, read on.When composing more than a single command (a script), the key is to make sure when substituting in values, each value is a well-formed list. There are various ways to do this.One way to do this is to create a template, and then substitute in any desired values, making sure that the values are well-formed lists:
proc reputation {} { set msg {an idle and false imposition} set msg2 {got without merit} set script { puts ${msg} puts ${msg2} set time [clock seconds] puts "The time is now [clock format $time]" } set script [string map [list \${msg} [list $msg] \${msg2} [list $msg2]] $script] uplevel #0 $script } reputationTo avoid ambiguity when doing the replacement, the placeholders should be constructed with both a beginning and ending delimiter. Some people use @, but in the previous example, something that looked like a normal Tcl variable was used. If $msg and $msg2 had been used instead of ${msg} and ${msg2}, a subtle error would have occured as $msg2 would have become {an idle and false imposition}2 in the script.Another way is to puts each substitution into a list command, but the drawback is the need to quote every other special character, which can then often lead to all kinds of confusion as the code becomes less readable and newbie Tcl programmers start piling on the backquotes to try to get things to "work":
proc reputation {} { set msg {an idle and false imposition} set msg2 {got without merit} set script " puts [list $msg] puts [list $msg2] set time \[clock seconds] puts \"The time is now \[clock format \$time]\" " uplevel #0 $script } reputation
Composing a Command for Evaluation editdouble evaluation comes into play here. There are various ways to get Tcl to interpret a value as a script and evaluate it. eval is one of those ways. When using variable substitution to manipulate a value which will then be evaluated as a Tcl script, use list to keep the script well-formed:
proc reputation {} { set msg {an idle and false imposition} after 1000 [list puts $msg] after 2000 "puts [list $msg]" }$msg is local to the procedure, so after 1000 {puts $msg} would not have worked because puts $msg will be evaluated later.set cmd "puts $msg" would have failed in this case, because $msg would have been expanded, and the script would have literally been puts an idle and false imposition, which is obviously too many arguments for puts.[list puts $msg] is potentially better because puts [list $msg] can have worse performance due to internal list-string conversion.
Passing $args to Another Command editIn the following script, $args are any additional options to button, e.g., -fg blue
#! /bin/env tclsh package require Tk proc mybutton { parent name label args} { if {$parent eq {.}} { set myname $parent$name } else { set myname $parent.$name } button $myname -text $label -command [list puts stdout $label] {*}$args pack append $parent $myname {left fill} } mybutton . hello whadda -bg aquamarine{*}$args is the right way to do it, but prior to Tcl 8.5, it was necessary to use eval:
eval {button $myname -text $label -command [list puts stdout $label]} $argsAlternatively, explicitly combine the lists first rather than relying on eval to concatenate its arguments:
set cmd [concat {button $myname -text $label -command [list puts stdout $label]} $args] eval $cmd
Misc editAMG: Tcl
-
- This post mis-characterizes most of the aspects of Tcl that it attempts to describe. In particular, the comment about seven consecutive backslashes is a strong hint that Ian didn’t grasp the elegance of Tcl quoting. This happens when people come to Tcl steeped in other language traditions, and attempt to apply those traditions to to Tcl, which is a different sort of creature. With all due respect to Ian, each of the criticisms in this article indicate that he just didn’t stick with Tcl long enough, or perhaps look into it deeply enough to resolve his misunderstandings of the language. More info at [1].
To Do edit
- fold Quoting Heaven! into this page | http://wiki.tcl.tk/37332 | CC-MAIN-2017-51 | refinedweb | 1,438 | 55.07 |
Hunter is a flexible code tracing toolkit.
Project description
Hunter is a flexible code tracing toolkit, not for measuring coverage, but for debugging, logging, inspection and other nefarious purposes. It has a simple Python API, a convenient terminal API and a CLI tool to attach to processes.
- Free software: BSD 2-Clause License
Installation
pip install hunter
Documentation
Overview
Basic use involves passing various filters to the trace option. An example:
import hunter hunter.trace(module='posixpath', action=hunter.CallPrinter) => _get_sep(path='a') /usr/lib/python3.6/posixpath.py:42 line if isinstance(path, bytes): /usr/lib/python3.6/posixpath.py:45 line return '/' /usr/lib/python3.6/posixpath.py:45 return <= _get_sep: '/' <= join: 'a/b' 'a/b'
In a terminal it would look like:
Actions
Output format can be controlled with “actions”. There’s an alternative CodePrinter action that doesn’t handle nesting (it was the default action until Hunter 2.0).
If filters match then action will be run. Example:
import hunter hunter.trace(module='posixpath', action=hunter.CodePrinter) import os os.path.join('a', 'b')
That would result in:
>>> os.path.join('a', 'b') /usr/lib/python3.6/posixpath.py:75 call def join(a, *p): /usr/lib/python3.6/posixpath.py:80 line a = os.fspath(a) /usr/lib/python3.6/posixpath.py:81 line sep = _get_sep(a) /usr/lib/python3.6/posixpath.py:41 call def _get_sep(path): /usr/lib/python3.6/posixpath.py:42 line if isinstance(path, bytes): /usr/lib/python3.6/posixpath.py:45 line return '/' /usr/lib/python3.6/posixpath.py:45 return return '/' ... return value: '/' return path ... return value: 'a/b' 'a/b'
- or in a terminal:
Another useful action is the VarsPrinter:
import hunter # note that this kind of invocation will also use the default `CallPrinter` action hunter.trace(hunter.Q(module='posixpath', action=hunter.VarsPrinter('path'))) [path => 'a'] /usr/lib/python3.6/posixpath.py:41 call => _get_sep(path='a') /usr/lib/python3.6/posixpath.py:42 line [path => 'a'] /usr/lib/python3.6/posixpath.py:42 line if isinstance(path, bytes): /usr/lib/python3.6/posixpath.py:45 line [path => 'a'] /usr/lib/python3.6/posixpath.py:45 line return '/' /usr/lib/python3.6/posixpath.py:45 return [path => 'a'] /usr/lib/python3.6/posixpath.py:45 return <= _get_sep: '/' /usr/lib/python3.6/posixpath.py:82 line path = a /usr/lib/python3.6/posixpath.py:83 line [path => 'a'] /usr/lib/python3.6/posixpath.py:83 line try: /usr/lib/python3.6/posixpath.py:84 line [path => 'a'] /usr/lib/python3.6/posixpath.py:84 line if not p: /usr/lib/python3.6/posixpath.py:86 line [path => 'a'] /usr/lib/python3.6/posixpath.py:86 line for b in map(os.fspath, p): /usr/lib/python3.6/posixpath.py:87 line [path => 'a'] /usr/lib/python3.6/posixpath.py:87 line if b.startswith(sep): /usr/lib/python3.6/posixpath.py:89 line [path => 'a'] /usr/lib/python3.6/posixpath.py:89 line elif not path or path.endswith(sep): /usr/lib/python3.6/posixpath.py:92 line [path => 'a'] /usr/lib/python3.6/posixpath.py:92 line path += sep + b /usr/lib/python3.6/posixpath.py:86 line [path => 'a/b'] /usr/lib/python3.6/posixpath.py:86 line for b in map(os.fspath, p): /usr/lib/python3.6/posixpath.py:96 line [path => 'a/b'] /usr/lib/python3.6/posixpath.py:96 line return path /usr/lib/python3.6/posixpath.py:96 return [path => 'a/b'] /usr/lib/python3.6/posixpath.py:96 return <= join: 'a/b' 'a/b'
In a terminal it would look like:
You can give it a tree-like configuration where you can optionally configure specific actions for parts of the tree (like dumping variables or a pdb set_trace):
from hunter import trace, Q, Debugger from pdb import Pdb trace( # drop into a Pdb session if ``foo.bar()`` is called Q(module="foo", function="bar", kind="call", action=Debugger(klass=Pdb)) | # or Q( # show code that contains "mumbo.jumbo" on the current line lambda event: event.locals.get("mumbo") == "jumbo", # and it's not in Python's stdlib stdlib=False, # and it contains "mumbo" on the current line source__contains="mumbo" ) ) import foo foo.func()
With a foo.py like this:
def bar(): execution_will_get_stopped # cause we get a Pdb session here def func(): mumbo = 1 mumbo = "jumbo" print("not shown in trace") print(mumbo) mumbo = 2 print(mumbo) # not shown in trace bar()
We get:
>>> foo.func() not shown in trace /home/ionel/osp/python-hunter/foo.py:8 line print(mumbo) jumbo /home/ionel/osp/python-hunter/foo.py:9 line mumbo = 2 2 /home/ionel/osp/python-hunter/foo.py:1 call def bar(): > /home/ionel/osp/python-hunter/foo.py(2)bar() -> execution_will_get_stopped # cause we get a Pdb session here (Pdb)
In a terminal it would look like:
Tracing processes
In similar fashion to strace Hunter can trace other processes, eg:
hunter-trace --gdb -p 123
If you wanna play it safe (no messy GDB) then add this in your code:
from hunter import remote remote.install()
Then you can do:
hunter-trace -p 123
See docs on the remote feature.
Note: Windows ain’t supported.
Environment variable activation
For your convenience environment variable activation is available. Just run your app like this:
PYTHONHUNTER="module='os.path'" python yourapp.py
On Windows you’d do something like:
set PYTHONHUNTER=module='os.path' python yourapp.py
The activation works with a clever .pth file that checks for that env var presence and before your app runs does something like this:
from hunter import * trace(<whatever-you-had-in-the-PYTHONHUNTER-env-var>)
Note that Hunter is activated even if the env var is empty, eg: PYTHONHUNTER="".
Environment variable configuration
Sometimes you always use the same options (like stdlib=False or force_colors=True). To save typing you can set something like this in your environment:
PYTHONHUNTERCONFIG="stdlib=False,force_colors=True"
This is the same as PYTHONHUNTER="stdlib=False,action=CallPrinter(force_colors=True)".
Notes:
Setting PYTHONHUNTERCONFIG alone doesn’t activate hunter.
All the options for the builtin actions are supported.
Although using predicates is supported it can be problematic. Example of setup that won’t trace anything:
PYTHONHUNTERCONFIG="Q(module_startswith='django')" PYTHONHUNTER="Q(module_startswith='celery')"
which is the equivalent of:
PYTHONHUNTER="Q(module_startswith='django'),Q(module_startswith='celery')"
which is the equivalent of:
PYTHONHUNTER="Q(module_startswith='django')&Q(module_startswith='celery')"
Filtering DSL
Hunter supports a flexible query DSL, see the introduction.
Development
To run the all tests run:
tox
Design notes
Hunter doesn’t do everything. As a design goal of this library some things are made intentionally austere and verbose (to avoid complexity, confusion and inconsistency). This has few consequences:
- There are Operators but there’s no negation operator. Instead you’re expected to negate a Query object, eg: ~Q(module='re').
- There are no specialized operators or filters - all filters behave exactly the same. For example:
- No filter for packages. You’re expected to filter by module with an operator.
- No filter for arguments, return values or variables. You’re expected to write your own filter function and deal with the problems of poking into objects.
- Layering is minimal. There’s are some helpers that do some argument processing and conversions to save you some typing but that’s about it.
- The library doesn’t try to hide the mechanics of tracing in Python - it’s 1:1 regarding what Python sends to a trace function if you’d be using sys.settrace.
- Doesn’t have any storage. You are expected to redirect output to a file.
You should look at it like it’s a tool to help you understand and debug big applications, or a framework ridding you of the boring parts of settrace, not something that helps you learn Python.
Why not Smiley?
There’s some obvious overlap with smiley but there are few fundamental differences:
Complexity. Smiley is simply over-engineered:
- It uses IPC and a SQL database.
- It has a webserver. Lots of dependencies.
- It uses threads. Side-effects and subtle bugs are introduced in your code.
- It records everything. Tries to dump any variable. Often fails and stops working.
Why do you need all that just to debug some stuff in a terminal? Simply put, it’s a nice idea but the design choices work against you when you’re already neck-deep into debugging your own code. In my experience Smiley has been very buggy and unreliable. Your mileage may vary of course.
Tracing long running code. This will make Smiley record lots of data, making it unusable.
Now because Smiley records everything, you’d think it’s better suited for short programs. But alas, if your program runs quickly then it’s pointless to record the execution. You can just run it again.
It seems there’s only one situation where it’s reasonable to use Smiley: tracing io-bound apps remotely. Those apps don’t execute lots of code, they just wait on network so Smiley’s storage won’t blow out of proportion and tracing overhead might be acceptable.
Use-cases. It seems to me Smiley’s purpose is not really debugging code, but more of a “non interactive monitoring” tool.
In contrast, Hunter is very simple:
Few dependencies.
Low overhead (tracing/filtering code has an optional Cython extension).
No storage. This simplifies lots of things.
The only cost is that you might need to run the code multiple times to get the filtering/actions right. This means Hunter is not really suited for “post-mortem” debugging. If you can’t reproduce the problem anymore then Hunter won’t be of much help.
Why not pytrace?
Pytrace is another tracer tool. It seems quite similar to Smiley - it uses a sqlite database for the events, threads and IPC, thus it’s reasonable to expect the same kind of problems.
Why not PySnooper or snoop?
snoop is a refined version of PySnooper. Both are more suited to tracing small programs or functions as the output is more verbose and less suited to the needs of tracing a big application where Hunter provides more flexible setup, filtering capabilities, speed and brevity.
Why not coverage?
For purposes of debugging coverage is a great tool but only as far as “debugging by looking at what code is (not) run”. Checking branch coverage is good but it will only get you as far.
From the other perspective, you’d be wondering if you could use Hunter to measure coverage-like things. You could do it but for that purpose Hunter is very “rough”: it has no builtin storage. You’d have to implement your own storage. You can do it but it wouldn’t give you any advantage over making your own tracer if you don’t need to “pre-filter” whatever you’re recording.
In other words, filtering events is the main selling point of Hunter - it’s fast (cython implementation) and the query API is flexible enough.
Projects using Hunter
Noteworthy usages or Hunter (submit a PR with your project if you built a tool that relies on hunter):
- Crunch-io/diagnose - a runtime instrumentation library.
- talwrii/huntrace - an alternative cli (similar to ltrace).
- anki-code/xunter - a profiling tool made specifically for the xonsh shell.
More projects using it at
Changelog
3.3.8 (2021-06-23)
- Fixed CI problem that publishes same type of wheels two times.
3.3.7 (2021-06-23)
- Fixed a bug with how stdlib is detected on Windows (at least).
3.3.6 (2021-06-23)
- Fixed regression from 3.3.4: stdlib filter was broken.
- Improved the pth file (PYTHONHUNTER environment variable activation) to use a clean eval environment. No bogus variables like line (from the site.py machinery) will be available anymore.
- Fixed a bug in VarsSnooper that would make it fail in rare situation where a double return event is emitted.
3.3.5 (2021-06-11)
- Added support for Python 3.10.
- Added support for time objects and the fold option in safe_repr.
- 3.3.4 was skipped cause I messed up the CI.
3.3.3 (2021-05-04)
Fixed tracer still being active for other threads after it was stopped.
Python unfortunately only allows removing the trace function for the current thread - now hunter.tracer.Tracer will uninstall itself if it’s marked as stopped.
This fixes bogus errors that appear when using ipdb with the hunter.actions.Debugger action while thread support is enabled (the default).
3.3.2 (2021-03-25)
- Changed CI to build Python 3.9 wheels. Python 3.5 no longer tested and wheels no longer built to keep things simple.
- Documentation improvements.
3.3.1 (2020-10-24)
- Fixed CI/test issues that prevented all of 21 wheels being published.
3.3.0 (2020-10-23)
- Fixed handling so that hunter.event.Event.module is always the "?" string instead of None. Previously it was None when tracing particularly broken code and broke various predicates.
- Similarly hunter.event.Event.filename is now "?" if there’s no filename available.
- Building on the previous changes the actions have simpler code for displaying missing module/filenames.
- Changed hunter.actions.CallPrinter so that trace events for builtin functions are displayed differently. These events appear when using profile mode (eg: trace(profile=True)).
- Fixed failure that could occur if hunter.event.Event.module is an unicode string. Now it’s always a regular string. Only applies to Python 2.
- Fixed argument display when tracing functions with tuple arguments. Closes #88. Only applies to Python 2.
- Improved error reporting when internal failures occur. Now some details about the triggering event are logged.
3.2.2 (2020-09-04)
- Fixed oversight over what value is in hunter.event.Event.builtin. Now it’s always a boolean, and can be used consistently in filters (eg: builtin=True,function='getattr').
3.2.1 (2020-08-18)
- Added support for regex, date and datetime in safe_repr.
- Fixed call argument display when positional and keyword arguments are used in hunter.actions.CallPrinter.
3.2.0 (2020-08-16)
- Implemented the hunter.actions.StackPrinter action.
- Implemented the hunter.predicates.Backlog predicate. Contributed by Dan Ailenei in #81.
- Improved contributing section in docs a bit. Contributed by Tom Schraitle in #85.
- Improved filtering performance by avoiding a lot of unnecessary PyObject_GetAttr calls in the Cython implementation of hunter.predicates.Backlog.
- Implemented the hunter.actions.ErrorSnooper action.
- Added support for profiling mode (eg: trace(profile=True)). This mode will use setprofile instead of settrace.
- Added ARM64 wheels and CI.
- Added hunter.event.Event.instruction and hunter.event.Event.builtin (usable in profile mode).
- Added more cookbook entries.
3.1.3 (2020-02-02)
- Improved again the stdlib check to handle certain paths better.
3.1.2 (2019-01-19)
- Really fixed the <frozen importlib.something stdlib check.
3.1.1 (2019-01-19)
- Marked all the <frozen importlib.something files as part of stdlib.
3.1.0 (2019-01-19)
- Added hunter.actions.ErrorSnooper - an action that detects silenced exceptions.
- Added hunter.load_config and fixed issues with configuration being loaded too late from the PYTHONHUNTERCONFIG environment variable.
- Changed hunter.From helper to automatically move depth and calls filters to the predicate (so they filter after hunter.predicates.From activates).
- Changed hunter.predicates.From to pass a copy of event to the predicate. The copy will have the depth and calls attributes adjusted to the point where hunter.predicates.From activated.
- Fixed a bunch of inconsistencies and bugs when using & and | operators with predicates.
- Fixed a bunch of broken fields on detached events <hunter.event.Event.detach> (hunter.event.Event.function_object and hunter.event.Event.arg).
- Improved docstrings in various and added a configuration doc section.
- Improved testing (more coverage).
3.0.5 (2019-12-06)
- Really fixed safe_repr so it doesn’t cause side-effects (now isinstance/issubclass are avoided - they can cause side-effects in code that abuses descriptors in special attributes/methods).
3.0.4 (2019-10-26)
- Really fixed stream setup in actions (using force_colors without any stream was broken). See: hunter.actions.ColorStreamAction.
- Fixed __repr__ for the hunter.predicates.From predicate to include watermark.
- Added binary wheels for Python 3.8.
3.0.3 (2019-10-13)
- Fixed safe_repr on pypy so it’s safer on method objects. See: hunter.actions.ColorStreamAction.
3.0.2 (2019-10-10)
- Fixed setting stream from PYTHONHUNTERCONFIG environment variable. See: hunter.actions.ColorStreamAction.
- Fixed a couple minor documentation issues.
3.0.1 (2019-06-17)
- Fixed issue with coloring missing source message (coloring leaked into next line).
3.0.0 (2019-06-17)
The package now uses setuptools-scm for development builds (available at). As a consequence installing the sdist will download setuptools-scm.
Recompiled cython modules with latest Cython. Hunter can be installed without any Cython, as before.
Refactored some of the cython modules to have more typing information and not use deprecated property syntax.
Replaced unsafe_repr option with repr_func. Now you can use your custom repr function in the builtin actions. BACKWARDS INCOMPATIBLE
Fixed buggy filename handling when using Hunter in ipython/jupyter. Source code should be properly displayed now.
Removed globals option from VarsPrinter action. Globals are now always looked up. BACKWARDS INCOMPATIBLE
Added support for locals in VarsPrinter action. Now you can do VarsPrinter('len(foobar)').
Always pass module_globals dict to linecache methods. Source code from PEP-302 loaders is now printed properly. Contributed by Mikhail Borisov in #65.
Various code cleanup, style and docstring fixing.
Added hunter.From helper to allow passing in filters directly as keyword arguments.
Added hunter.event.Event.detach for storing events without leaks or side-effects (due to prolonged references to Frame objects, local or global variables).
Refactored the internals of actions for easier subclassing.
Added the hunter.actions.ColorStreamAction.filename_prefix, hunter.actions.ColorStreamAction.output, hunter.actions.ColorStreamAction.pid_prefix, hunter.actions.ColorStreamAction.thread_prefix, hunter.actions.ColorStreamAction.try_repr and hunter.actions.ColorStreamAction.try_source methods to the hunter.actions.ColorStreamAction baseclass.
Added hunter.actions.VarsSnooper - a PySnooper-inspired variant of hunter.actions.VarsPrinter. It will record and show variable changes, with the risk of leaking or using too much memory of course :)
Fixed tracers to log error and automatically stop if there’s an internal failure. Previously error may have been silently dropped in some situations.
2.2.1 (2019-01-19)
- Fixed a link in changelog.
- Fixed some issues in the Travis configuration.
2.2.0 (2019-01-19)
- Added hunter.predicates.From predicate for tracing from a specific point. It stop after returning back to the same call depth with a configurable offset.
- Fixed PYTHONHUNTERCONFIG not working in some situations (config values were resolved at the wrong time).
- Made tests in CI test the wheel that will eventually be published to PyPI (tox-wheel).
- Made event.stdlib more reliable: pkg_resources is considered part of stdlib and few more paths will be considered as stdlib.
- Dumbed down the get_peercred check that is done when attaching with hunter-trace CLI (via hunter.remote.install()). It will be slightly insecure but will work on OSX.
- Added OSX in the Travis test grid.
2.1.0 (2018-11-17)
- Made threading_support on by default but output automatic (also, now 1 or 0 allowed).
- Added pid_alignment and force_pid action options to show a pid prefix.
- Fixed some bugs around __eq__ in various classes.
- Dropped Python 3.3 support.
- Dropped dependency on fields.
- Actions now repr using a simplified implementation that tries to avoid calling __repr__ on user classes in order to avoid creating side-effects while tracing.
- Added support for the PYTHONHUNTERCONFIG environment variable (stores defaults and doesn’t activate hunter).
2.0.2 (2017-11-24)
- Fixed indentation in hunter.actions.CallPrinter action (shouldn’t deindent on exception).
- Fixed option filtering in Cython Query implementation (filtering on tracer was allowed by mistake).
- Various fixes to docstrings and docs.
2.0.1 (2017-09-09)
- Now Py_AddPendingCall is used instead of acquiring the GIL (when using GDB).
2.0.0 (2017-09-02)
- Added the hunter.event.Event.count and hunter.event.Event.calls attributes.
- Added the lt/lte/gt/gte lookups.
- Added convenience aliases for startswith (sw), endswith (ew), contains (has) and regex (rx).
- Added a convenience hunter.wrap decorator to start tracing around a function.
- Added support for remote tracing (with two backends: manhole and GDB) via the hunter-trace bin. Note: Windows is NOT SUPPORTED.
- Changed the default action to hunter.actions.CallPrinter. You’ll need to use action=CodePrinter if you want the old output.
1.4.1 (2016-09-24)
- Fix support for getting sources for Cython module (it was broken on Windows and Python3.5+).
1.4.0 (2016-09-24)
1.3.0 (2016-04-14)
- Added hunter.event.Event.thread.
- Added hunter.event.Event.threadid and hunter.event.Event.threadname (available for filtering with hunter.Q).
- Added hunter.event.Event.threading_support argument to hunter.trace. It makes new threads be traced and changes action output to include thread name.
- Added support for using pdb++ in the hunter.actions.Debugger action.
- Added support for using manhole via a new hunter.actions.Manhole action.
- Made the hunter.event.Event.handler a public but readonly property.
1.2.2 (2016-01-28)
- Fix broken import. Require fields>=4.0.
- Simplify a string check in Cython code.
1.2.1 (2016-01-27)
- Fix “KeyError: ‘normal’” bug in hunter.actions.CallPrinter. Create the NO_COLORS dict from the COLOR dicts. Some keys were missing.
1.2.0 (2016-01-24)
- Fixed printouts of objects that return very large string in __repr__(). Trimmed to 512. Configurable in actions with the repr_limit option.
- Improved validation of hunter.actions.VarsPrinter’s initializer.
- Added a hunter.actions.CallPrinter action.
1.1.0 (2016-01-21)
- Implemented a destructor (__dealloc__) for the Cython tracer.
- Improved the restoring of the previous tracer in the Cython tracer (use PyEval_SetTrace) directly.
- Removed tracer as an allowed filtering argument in hunter.Query.
- Add basic validation (must be callable) for positional arguments and actions passed into hunter.Q. Closes #23.
- Fixed stdlib checks (wasn’t very reliable). Closes #24.
1.0.2 (2016-01-05)
- Fixed missing import in setup.py.
1.0.1 (2015-12-24)
- Fix a compile issue with the MSVC compiler (seems it don’t like the inline option on the fast_When_call).
1.0.0 (2015-12-24)
Implemented fast tracer and query objects in Cython. MAY BE BACKWARDS INCOMPATIBLE
To force using the old pure-python implementation set the PUREPYTHONHUNTER environment variable to non-empty value.
Added filtering operators: contains, startswith, endswith and in. Examples:
- Q(module_startswith='foo' will match events from foo, foo.bar and foobar.
- Q(module_startswith=['foo', 'bar'] will match events from foo, foo.bar, foobar, bar, bar.foo and baroo .
- Q(module_endswith='bar' will match events from foo.bar and foobar.
- Q(module_contains='ip' will match events from lipsum.
- Q(module_in=['foo', 'bar'] will match events from foo and bar.
- Q(module_regex=r"(re|sre.*)\b") will match events from ``re, re.foobar, srefoobar but not from repr.
Removed the merge option. Now when you call hunter.trace(...) multiple times only the last one is active. BACKWARDS INCOMPATIBLE
Remove the previous_tracer handling. Now when you call hunter.trace(...) the previous tracer (whatever was in sys.gettrace()) is disabled and restored when hunter.stop() is called. BACKWARDS INCOMPATIBLE
Fixed CodePrinter to show module name if it fails to get any sources.
0.6.0 (2015-10-10)
- Added a clear_env_var option on the tracer (disables tracing in subprocess).
- Added force_colors option on hunter.actions.VarsPrinter and hunter.actions.CodePrinter.
- Allowed setting the stream to a file name (option on hunter.actions.VarsPrinter and hunter.actions.CodePrinter).
- Bumped up the filename alignment to 40 cols.
- If not merging then self is not kept as a previous tracer anymore. Closes #16.
- Fixed handling in VarsPrinter: properly print eval errors and don’t try to show anything if there’s an AttributeError. Closes #18.
- Added a stdlib boolean flag (for filtering purposes). Closes #15.
- Fixed broken frames that have “None” for filename or module (so they can still be treated as strings).
- Corrected output files in the install_lib command so that pip can uninstall the pth file. This only works when it’s installed with pip (sadly, setup.py install/develop and pip install -e will still leave pth garbage on pip uninstall hunter).
0.5.1 (2015-04-15)
- Fixed hunter.event.Event.globals to actually be the dict of global vars (it was just the locals).
0.5.0 (2015-04-06)
- Fixed hunter.And and hunter.Or “single argument unwrapping”.
- Implemented predicate compression. Example: Or(Or(a, b), c) is converted to Or(a, b, c).
- Renamed hunter.event.Event.source to hunter.event.Event.fullsource.
- Added hunter.event.Event.source that doesn’t do any fancy sourcecode tokenization.
- Fixed hunter.event.Event.fullsource return value for situations where the tokenizer would fail.
- Made the print function available in the PYTHONHUNTER env var payload.
- Added a __repr__ for hunter.event.Event.
0.4.0 (2015-03-29)
- Disabled colors for Jython. Contributed by Claudiu Popa in #12.
- Test suite fixes for Windows. Contributed by Claudiu Popa in #11.
- Added an introduction section in the docs.
- Implemented a prettier fallback for when no sources are available for that frame.
- Implemented fixups in cases where you use action classes as a predicates.
0.3.1 (2015-03-29)
- Forgot to merge some commits …
0.3.0 (2015-03-29)
0.2.1 (2015-03-28)
- Added missing color entry for exception events.
- Added hunter.event.Event.line property. It returns the source code for the line being run.
0.2.0 (2015-03-27)
- Added color support (and colorama as dependency).
- Added support for expressions in hunter.actions.VarsPrinter.
- Breaking changes:
- Renamed F to hunter.Q. And hunter.Q is now just a convenience wrapper for hunter.predicates.Query.
- Renamed the PYTHON_HUNTER env variable to PYTHONHUNTER.
- Changed hunter.predicates.When to take positional arguments.
- Changed output to show 2 path components (still not configurable).
- Changed hunter.actions.VarsPrinter to take positional arguments for the names.
- Improved error reporting for env variable activation (PYTHONHUNTER).
- Fixed env var activator (the .pth file) installation with setup.py install (the “egg installs”) and setup.py develop/pip install -e (the “egg links”).
0.1.0 (2015-03-22)
- First release on PyPI.
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/hunter/ | CC-MAIN-2021-31 | refinedweb | 4,432 | 53.47 |
t_sndrel(3) t_sndrel(3)
NAME [Toc] [Back]
t_sndrel() - initiate an orderly release
SYNOPSIS [Toc] [Back]
#include <xti.h> /* for X/OPEN Transport Interface - XTI */
/* or */
#include <tiuser.h> /* for Transport Layer Interface - TLI */
int t_sndrel (fd);
int fd;
DESCRIPTION [Toc] [Back]
The t_sndrel() function is used in connection-oriented mode to
initiate an orderly release at a transport endpoint specified by fd,
which is a file descriptor previously returned by the t_open()
function.
After this orderly release is indicated, the transport user should not
try to send more data through that transport endpoint. An attempt to
send more data to a released transport endpoint may block
continuously. However, the transport user may continue to receive
data over the connection until an orderly release indication is
received. This function is an optional service of the transport
provider and is only supported if the transport provider returned
service type T_COTS_ORD on t_open() or t_getinfo().
Thread-Safeness [Toc] [Back]
The t_sndrel().
Note [Toc] [Back]
HP OSI XTI does not support t_sndrel(). identifier does not refer to a
transport endpoint.
[TFLOW] Asynchronous mode is indicated because O_NONBLOCK
was set, but the transport provider cannot accept
a release because of flow-control restrictions.
[TLOOK] An asynchronous event has occurred on this
transport endpoint and requires immediate
Hewlett-Packard Company - 1 - HP-UX 11i Version 2: August 2003
t_sndrel(3) t_sndrel(3)
attention.
[TNOTSUPPORT] This function is not supported by the underlying
transport provider.
[TSYSERR] A system error has occurred during execution of
this function.
[TPROTO] (XTI only) This error indicates that a
communication problem has been detected between
XTI and the transport provider for which there is
no other suitable XTI (t_errno).
SEE ALSO [Toc] [Back]
t_getinfo(3), t_open(3), t_rcvrel(3).
STANDARDS CONFORMANCE [Toc] [Back]
t_sndrel(): SVID2, XPG3, XPG4
Hewlett-Packard Company - 2 - HP-UX 11i Version 2: August 2003 | http://nixdoc.net/man-pages/HP-UX/man3/t_sndrel.3.html | CC-MAIN-2019-47 | refinedweb | 306 | 54.22 |
0
i have this program...the color program..but i have a problem on converting a string to character. anybody can help me..thanks..
below is the java code
import javax.swing.JOptionPane; public class ab{ public static void main(String[]args){ String a; a=JOptionPane.showInputDialog("Enter color: "); // I need to convert the variable a from string to character since condition below //deals with a character..a is declared as a character since jOptionpane above // accepts string.Or, do i lack some necessary header files in order to convert a //string to character...thanks if ((a=='r')||(a=='R')) JOptionPane.showMessageDialog(null,"RED"); else if((a=='r')||(a=='B')) JOptionPane.showMessageDialog(null,"Blue"); else JOptionPane.showMessageDialog(null,"Invalid Input"); } }
Edited by Nick Evan: Fixed formatting | https://www.daniweb.com/programming/software-development/threads/300859/how-do-i-convert-a-string-to-character | CC-MAIN-2017-47 | refinedweb | 126 | 55.4 |
"Ming Poon" <mingp@corel.ca> writes: >. In fact, this is the way that it is already done. There is a single file, boxes.c, that contains most of the UI; that is the main file that I've had to write a new version of as I write the FB setup code. I plan to move the remaining bits of UI into that file as I continue my work on the FB install over the coming weeks.. Excellent plan. I highly approve.. My personal to-do list for the install includes the following: * Selectable language. * It would be nice to have exhaustive documentation and explanation available at install time, on diskette or CD. * How about an `expert install' floppy that omits dinstall but has nicer command-line tools? * RAID install. * Auto-install via prewritten options on diskette or NFS or whatever. ({Jump,Kick}Start-like). * Partition-Magic or FIPS or whatever (on another disk?). Vincent Renardias <vincent@ldsol.com> shared some suggestions for the partitioning tool with me tonight that I hope he won't mind my passing on: a "cfdisk with the ability to shrink FAT partitions" (ie: cfdisk + fsresize) would be cool. I'm not too much in favour of a Disk Druid like interface since most people actually find it confusing. The problem being most beginners don't have the concept of mountpoints, and mixing partitions and mountpoints in the same screen just confuse them. If there are several disks, I don't know if their partitions should be presented in the same screen layout or not. In my experience, many people also try weird partition size (like trying to install the whole system on a 32MB partition). The partitioning tool should(may?) also: 1/ whine (ok, ask confirmation) for things that really look weird (ie: swap partition 10 times bigger than the actual RAM, '/' partition smaller than 32 MB, etc...) 2/ record the available space somewhere, and use it to warn if the selected packages won't fix on the HD _before_ trying to install. (the Red Hat installer doesn't get it right either) 3/ Offer to mount the DOS/NTFS/whatever-not-Linux-but-recognized=20 partitions in the Linux namespace (even Slackware has been doing this for ages) | https://lists.debian.org/debian-boot/1999/03/msg00377.html | CC-MAIN-2015-18 | refinedweb | 375 | 63.09 |
18 October 2013 17:45 [Source: ICIS news]
LONDON (ICIS)--Spot prices in the European methyl ethyl ketone (MEK) market rose sharply amid tighter supply because of production problems at Sasol, pushing prices to their highest level in more than a year, market sources said on Friday.
The average price this week, at €1,375/tonne ($1,858/tonne) matches the price on 5 October 2012 (see graph at foot of story).
Sources also said ExxonMobil had production problems at its MEK plant in Fawley in the ?xml:namespace>
A Sasol spokesman said on Friday: “There were technical issues, but they have been resolved and we are working to restore stock levels.” The spokesman did not give any further detail. The plant in
“There was some kind of panic in the market. Some suppliers told us they’re sold out. It would be interesting to know how long this will go on,” a distributor said.
Some traders said they expect prices to fall in the next few weeks as producers restock to normal levels.
This is the fourth straight week of price increases in the MEK market. The rise, however, is purely due to limited supply and does not reflect any improvement in demand, which is still affected by uncertainties in the macroeconomic environment.
Spot prices as high as €1,600/tonne and as low as €1,250/tonne were heard but neither extreme were widely reflected elsewhere in the market.
The technical problems at Sasol come just a month after the company its force majeure | http://www.icis.com/Articles/2013/10/18/9716639/europe-mek-prices-jump-to-12-month-high-on-plant-problems.html | CC-MAIN-2014-52 | refinedweb | 256 | 69.31 |
View Complete"
I have a sharepoint site (2007) with two subsites . while I am trying to edit list items in subsite its giving me Access denied error even though I have the Site collection Admin Rights.
Please help .?
There are supposed fixes for this but I cannot get a decent reply so i am posting a new thread. I am getting the same error as what was in this thread.
I want to run the script but cannot without getting an error.
Can I get step by step of how to run this script? Save the code into what? Run from what? On server or workstation?
I am a sharepoint admin, not a developer so I'm a bit clueless when it comes to code language...
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;
namespace CA_TestingHotfix
{
class Program
{
static void Main(string[] args)
{
FixField(args);
}
static void FixField(string[] args)
{
Okay, I have a WF that works on NEW created Items only, But, if the item gets Rejected and then the Creator goes back into the Request/list Item and fixes what he has wrong, it changes the Status back to Pending, which is fine, but it doens't go through
the process again treating it like a New Request, kicking off the WF for NEWLY created items.
What do I do??
Trying to figure it out. Any help would be greatly appreciated..
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/40963-accessing-checkbox-list-from-with-edit-item.aspx | CC-MAIN-2016-44 | refinedweb | 255 | 75.4 |
68..
Here is another example of the ATSread opcode. It uses the file ATSread-2.csd.
Example 69. Example 2 of the ATSread ReadOnePartial iPartial = p4 p3 = giDur ktime line 0, giDur, giDur prints "Resynthesizing partial number %d.\n", iPartial kFq,kAmp ATSread ktime, gSfile, iPartial kAmp port kAmp, .1 ;smooth amplitudes - still not satisfactoring aOut poscil kAmp, kFq, giSine aOut linen aOut, 0, p3, .01 ;anti-click outs aOut*10, aOut*10 ;start next instr: normal speed, three loops, pause between loops one second event_i "i", "MasterRand", giDur+3, 1, 1, 3, 2 endin instr MasterRand ;random selections of 10 partials per second, overlapping iSpeed = p4 ;speed of reading / playing iNumLoops = p5 ;number of loops iPause = p6 ;length of pause between loops prints "Resynthesizing random partials.\n" p3 = (giDur/iSpeed+iPause) * iNumLoops ;start next instr: half speed, three loops, three seonds pause between loops event_i "i", "MasterArp", p3+3, 1, .5, 3, 3 ;loop over duration plus pause loop: timout 0, giDur/iSpeed+iPause, play reinit loop play: gkTime line 0, giDur/iSpeed, giDur ;start time from 0 in each loop kTrig metro 10 ;10 new partials per second ;call subinstrument if trigger and no pause if kTrig == 1 && gkTime < giDur then kPart random 1, giNumParts+.999 event "i", "PlayRand", 0, 1, int(kPart) endif endin instr MasterArp ;argeggio-like reading and playing of partials iSpeed = p4 ;speed of reading / playing iNumLoops = p5 ;number of loops iPause = p6 ;length of pause between loops prints "Arpeggiating partials.\n" p3 = (giDur/iSpeed+iPause) * iNumLoops loop: timout 0, giDur/iSpeed+iPause, play reinit loop play: gkTime line 0, giDur/iSpeed, giDur kArp linseg 1, (giDur/iSpeed)/2, giNumParts, (giDur/iSpeed)/2, 1 ;arp up and down kTrig metro 10 ;10 new partials per second if kTrig == 1 && gkTime < giDur then event "i", "PlayArp", 0, 5, int(kArp) endif ;exit csound when finished event_i "i", "End", p3+5, 1 endin instr PlayRand iPartial = p4 kFq,kAmp ATSread gkTime, gSfile, iPartial kamp port kAmp, .15 ;smooth amplitudes aOut poscil kAmp, kFq, giSine aOut linen aOut, .01, p3, .01 outs aOut, aOut endin instr PlayArp kCount init 1 ;k-cycle iPartial = p4 kFq,kAmp ATSread gkTime, gSfile, iPartial if kCount == 1 then ;get freq from first k-cycle kModFq = kFq ;avoid to go with 0 Hz as this blocks the mode filter if kModFq == 0 then turnoff endif endif iVol random -42, -12 ;db iOffset random .01, .1 ;no too regularily ... aImp mpulse ampdb(iVol), p3, iOffset iQ random 500, 5000 aOut mode aImp, kModFq, iQ aOut linen aOut, 0, p3, p3/3 outs aOut, aOut kCount = 2 endin instr End exitnow endin </CsInstruments> <CsScore> i "ReadOnePartial" 0 1 10 e 999 </CsScore> </CsoundSynthesizer>
ATSreadnz, ATSinfo, ATSbufread, ATScross, ATSinterpread, ATSpartialtap, ATSadd, ATSaddnz, ATSsinnoi | http://www.csounds.com/manual/html/ATSread.html | CC-MAIN-2016-30 | refinedweb | 458 | 57.84 |
.NET From a Markup Perspective
Don writes that XML in its entirety had become more complex than COM ever was.
I disagree with this statement on its face.
I agree that there is a huge family of specifications surrounding XML, but each specification is just built upon the XML foundation. If the intent of the post intends to point out that XML eclipses COM for complexity by sheer volume of implementations, then consider the lack of a standards body for COM implementations. If there were such a thing, maybe it can be represented by opening a new Visual Basic 6 project on a default installation of Windows XP and going to the Add References tab.
Reading between the lines, I think Don is saying that there is a core of XML technologies, his "kernel" list, that XML developers need to know, and that "kernel" is somehow more comprehensive than COM's. I don't think comprehensiveness necessarily equates to complexity. However, the W3C has never been known to make the specs overly readable with a clear understanding of their target audience.
XML is just data. XML at its own core is just XML 1.0, which lays out the base rules for the representation of a document. The surrounding specs for XML, including SOAP, XML namespaces, and XML Schemas, just makes XML more functional. They are further implementations of XML. If you know the basics of XML, the rest is just learning the individual specification that you are adopting.
You can absolutely use XML without XML Schemas or SOAP, considering the number of DTD validations still performed daily. XML Schemas and namespaces are a great addition to the XML landscape, but they are just further implementations of a core concept. The only real requirement for XML is that you support the well-formedness rules for XML 1.0.
I agree more with Dare's evaluation of the "Core XML Technologies That Matter". Dare points out Don Smith's interpretation of XML's complexity, which sums up my view even more closely. Just drop XSLT from the mix, and the core that you really have to understand to work with in XML is:
The comment thread on Dare's post indicates that only Part 2 should be considered, but Part 0 serves as a road map to parts 1 and 2 and provides a topical overview that is enough for 80% to get by... the other 20% will consider both Parts 1 and 2.
To boil it down even further, you really don't need to know XML 1.0 in depth, just like you don't need to know HTML in depth. You just need to know the basics enough to work with a DOM model. | http://blogs.msdn.com/kaevans/archive/2003/06/24/9222.aspx | crawl-002 | refinedweb | 456 | 69.62 |
> From: Juliusz Chroboczek <address@hidden> > TL> So, sealing is a kind of advisory lock and you can use it to model > TL> releases. > That appears to be what I'm looking for. Thanks a lot. (And thanks > to Dustin for the link.) > Before I switch to arch, I'm trying to work out the branching model to > use. I'm thinking of the following. > All development happens on foo--devel--0.7. When 0.7.0 is released, > it is tagged as foo--release--0.7.0. Bug fixes to the 0.7 branch > continue on foo--devel--0.7, with later tags foo--release--0.7.1 and > so on. There are never any commits on the foo--release branch. > When a new unstable branch is created, it is tagged as > foo--devel--0.8. Development happens on this new branch, and bug > fixes to the stable branch can go to foo--devel--0.7. > I guess what I'm trying to achieve is something equivalent to cvs > symbolic tags, which I'm used to. If you see better ways of doing > that, I'm all ears. Nope -- that's exactly (but not exclusively) right. You can use a "tags only" branch as a symbolic tag --- the variety of tag that you explicitly move. Unlike CVS, the history of the tag is preserved. One variation, if your releases include multiple projects, is to make a top-level directory containing config files --- and use tags of that top-level dir to mark your releases. Some people will tell you (not incorrectly) that you can also blow off tags entirely and use nothing but config files --- personally, I like tags just to give releases a fixed name in the arch namespace. >. For that and other reasons you'll want to setup a revision library and figure out how you want it configured (greedy?, sparse?). The `tla delta' command can give you a changeset. The changeset is saved as output by default but, with --diffs, you'll just see a display of its contents. > > (And of course the ability to do cvs export, but that's already in the > wiki.) Strangely enough, we have only commands that produce output _close_ to that but not exactly what you are looking for. It would be an easy change to add to src/tla/libarch/changeset-report.c to give a format along those lines and propogate it to various commands as an option. It would obviously be a very good thing to do and I'll happilly accept good patches along those lines. -t | http://lists.gnu.org/archive/html/gnu-arch-users/2004-04/msg00023.html | CC-MAIN-2016-30 | refinedweb | 430 | 75.3 |
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.
How to mimic autofill when importing via external script?
Update: I resolved this issue by setting the values during the import. So there is no urgency. However, I would like to know if I am doing this right.
I am importing leads using a python script. The import itself works great but the fields that get auto filled when I create a lead using the web client remain blank for the leads imported from the script. How do I mimic the auto fill action when importing using an external script. an excerpt from the script is pasted here. The lead shows up correctly in the web client. Just that the other values which get auto filled in the web client are blank. (the code works... it may give errors because it has been heavily redacted.)
import openerplib import csv def import_leads(csvfile): partner_model = connection.get_model('res.partner') lead_model = connection.get_model('crm.lead') user_model = connection.get_model('res.users') with open(csvfile, "rb") as csvfile: records = csv.reader(csvfile, delimiter=',') next(records) for record in records: print(record[0]) # crmid fields are created in various models ids = lead_model.search([('crmid', '=', record[0])]) if len(ids) > 0: continue ids = partner_model.search([('crmid', '=', record[2])]) if len(ids) is 0: print("partner not found: " + record[2]) continue partner_id = ids[0] from_user = record[19] ids = user_model.search([('login', '=', from_user)]) from_user_id = ids[0] lead = { 'crmid': record[0], 'partner_id': partner_id, 'user_id': from_user_id, 'crmid': record[0], 'name': record[4] } lead_id = lead_model.create(lead) # i think i have do something here like browse() or refresh() or something. hostname = "localhost" database = "test1" login = "admin" password = "admin" connection = openerplib.get_connection(hostname=hostname, database=database, login=login, password=password) import_leads("./Leads.csv")
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-mimic-autofill-when-importing-via-external-script-33875 | CC-MAIN-2017-30 | refinedweb | 335 | 52.26 |
So, What Is This Boo language Anyway?
So, What Is This Boo language Anyway?
Join the DZone community and get the full member experience.Join For Free
This article is taken from Building Domain Specific Languages in Boo from Manning Publications. It introduces the Boo language and demonstrates its syntax. For the table of contents, the Author Forum, and other resources, go to.
It is being reproduced here by permission from Manning Publications.
Manning early access books and ebooks are sold exclusively through Manning. Visit the book's page for more information.
MEAP Began: February 2008
Softbound print: November 2009 (est.) | 400 pages
ISBN: 1933988606
Use code "dzone30" to get 30% off any version of this book.
Boo is an object oriented, statically typed language for the common language runtime with a Python inspired syntax and a focus on language and compiler extensibility.
Boo is an Open Source project, released under the BSD license. This means that you are free to take, modify and use the language and its products in any way you want, without any limitation(1), including for commercial use.
Rodrigo B. de Oliveira started the project in early 2004. Since then, it has grown significantly in popularity and features. The project is active and is continually evolving. At the time of the writing, the released version of Boo is 0.8.2.
Note, however, that Boo seems to be following the trend of many open source projects in that it is not really rushing toward 1.0 release. Boo has been stable for a number of years, and I have been using it for production for the last two years.
Production, in this case, means systems that move money around with my neck on the line. I have a high degree of trust in Boo, and it has not failed me yet.
Now that we have spoken a bit about the history and some of the background, we will quickly move forward to talk about the language itself.
Getting Boo
You can download the binary distribution of Boo from the Boo website:
You can execute booish in order to get a command interpreter that will allow you to experiment with Boo directly. It makes it very convenient when you want to quickly try out some ideas, or verify an assumption.
Probably the first question that needs to be answered is why Boo?
What makes Boo unique?
Boo is a CLR based language, this means that when we use Boo we benefit from the rich library, JIT optimizations and plenty of good tools. Leaving aside the ability to extend the compiler, Boo has the following to offer:
Syntactic sugar for common programming patterns - List, hash and array literals, object initialization, string formatting and regular expression matching are all first class concepts in Boo, with direct support for all of them in a natural manner.
Automatic Variable Declaration and Automatic Type Inference(2) – the compiler takes care of things for you, instead of having to type the same thing over and over and over again. Some would say that this is bad, for them I would reply that they should try it first. From my experience, it works. Take a look at listing 1:
Listing 1 – Exploring Boo’s type inferencing explicitly specify the type, such as in listing 2:
Listing 2 - Boo is statically typed, this code will cause compiler error
val as string = random() # will error about type mismatch
Automatic type casting – don’t make me explicitly say it, figure it out for me. I’ll have unit tests to check to cover me. The following example shows what automatic casting means:
obj as object
obj = "some string"
str as string = obj # will automatically cast obj to string in listing 3 and what we can do with it.
Listing 3 – Using IQuackFu to get better syntax for working with XML
person = XmlObject(xmlDocument) print person.FirstName print person.LastName
What we just did was resolve, at runtime, that we were asked to get the value of a property called “FirstName”, and then a property named “LastName”.
These features take care of some rough spots in many cases, and they can be very useful when we are building our own languages on top of Boo. But first, you have to understand the syntax a bit…
Boo Basic Syntax
I am going to assume that just printing the BNF(3) of the language will be… an unpopular decision. What we will do instead is write a few sample programs, just enough to let you have a feeling for the language.
Significant whitespace vs. Whitespace agnostic
If you have done any work with Python, you are probably aware that one of the major gripes against the language is the significant whitespace issue. Python use the indention of the code to define control blocks. This means that you don’t need curly braces or explicit block ending like end (Ruby), End If (VB.NET), etc.
The code looks like this:if lives == 0: print "Game over!" game.Finish() else: lives-- print "${lives} more lives"
As I mentioned already, this is a major point of contention with Python. Since Boo uses the same convention, the same issue has been raised against it as well. However, after spending several years working with it, I can say that it has been my experience that it very rarely caused any issues.
Saying that it very rarely causes issues is not the same as saying that it never causes issues, however.
When I wrote Brail, a templating language using Boo, the whitespace issue was a major issue. I wanted to use the usual HTML formatting, but that really messed up the formatting that boo required.
Luckily for us, Boo comes with Whitespace Agnostic mode, which we can utilize by flipping a compiler switch. The same code we have above would then turn to:if lives == 0: print "Game over!" game.Finish() else: lives-- print "${lives} more lives"
end
The only difference that you will note is the “end” at the end of the statement. This is because now Boo will use the structure of the code to figure out where control blocks begin and end. Usually, this means that a block starts when a statement ends with a colon (“:”) and ends with a statement of the “end” keyword.
When writing DSLs, I tend to use the significant whitespace mode, and only go to the whitespace agnostic mode when I find that it causes issues.
The first sample program is, of course, Hello World. To make it a bit more interesting, we will use WinForms for it. Listing 4 has the details.
Listing 4 – Hello World using WinForms
import System.Windows.Forms
f = Form(Text: "Hello, boo!")
btn = Button(Text: "Click Me!", Dock: DockStyle.Fill)
btn.Click += do(sender, e): f.Close()
f.Controls.Add(btn)
Application.Run(f)
First, we import the System.Windows.Forms namespace. This is similar to the using statement in C#, but in Boo this also instructs the compiler to load the System.Windows.Forms assembly if the namespace could not be found in the loaded assemblies.
Then we create a Form and a Button. Note that Boo’s support property initialization at construction (C# 3.0 supports a similar notion, of object initializers).
We register to the button Click event, add the button to the form, and then start the application with the form as the main form.
Not bad for a hello world application. Note that you can type the source in listing 4 directly into booish, in order to experiment with the language.
Now, let us try to make something just a tad bit more complicated, shall we?
Tip, but it is a secret
When you are not sure how to do something in Boo, try doing it like you would with C# (with the obvious syntax changes), in most cases, it would work. It may not be the best way to do something, however.
Keep this a secret, I may get thrown out of the Boo Associated Hackers (BAH!) community if that would happen, and where I would be without my BAH membership?
Listing 5 is an HTTP server that allows you to download files from a directory.
Listing 5 – An HTTP server in Boo()
We have a tiny amount of argument validation, and then we setup an HttpListener and start replying to requests. I’ll admit that this is not the most interesting bit of code that I have ever seen, but it does manage to touch on quite a lot of different topics.
For anyone proficient in .NET, what we are doing should be very familiar. The language may be a bit different, but the concepts, the objects and methods that we call are all from the Base Class Library.
This familiarity is very welcome. We don't need to learn everything from scratch.
Tip – That annoying semi colon
One of the more annoying things when moving between languages is the semi colon. When I am moving between C# and VB.NET code, I keep putting semicolons at the end of VB.NET statements, and forgetting to end my C# code with proper semicolons.
Boo’s has optional semicolons, so you can put them or not, as you wish. This makes dropping into the language for a while a far smoother experience, since you don’t have to unlearn ingrained habits.
And one last sample program before we get back to talking about Domain Specific Languages. Listing 6 is a simple implementation of GREP.
Listing 6 – A simple GREP implementation
import System
import System.IO
import System.Text.RegularExpressions
# get all files matching a specific pattern from a directory
# and all its sub directories
# note: string* is a shorthand to IEnumerable<string>
def GetFiles(dir as string, pattern as string) as string*:
# get all sub directories
folders = Directory.GetDirectories(dir)
# for each sub directory, recurse into that directory
# and yield all the files that were returned
for folder in folders:
for file in GetFiles(folder, pattern):
yield file
# yield all the files that match the given pattern
for file in Directory.GetFiles(dir, pattern):
yield file
# argument validation
if argv.Length != 2:
print "Usage: grep [pattern] [regex]"
filePattern = argv[0]
textPattern = Regex(argv[1])
# get all the files matching the pattern in the current directory
for file in GetFiles(Environment.CurrentDirectory, filePattern):
# for each file, read all the lines
using sr = StreamReader(file):
while line = sr.ReadLine():
# if the line match the given pattern, print it
if textPattern.IsMatch(line):
print file, ":", line
A few points on interest in listing 6, GetFiles returns a generic type, IEnumerable of string (T* is Boo’s way of specific generic enumerables), it also uses yield to return results in a streaming fashion, the while loop will repeat until line will return a null reference (which is considered to be false in Boo).
We have gone over the major benefits of Boo as a language and its basic syntax. I hope that this gave you some feel about the Boo language.
(1) Well, if you are interested in creating a new language called Ba, you probably would want to make it clear where the project ancestry came from.
(2) C# 3.0 has introduced the var keyword, which allows the C# compiler to do much the same for local variables. Boo supports this for just about everything (fields, properties, methods, local variables, etc).
(3) Backus Naur Form – a formal way to specify the syntax of a computer language.save
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/so-what-boo-language-anyway | CC-MAIN-2020-05 | refinedweb | 1,940 | 62.98 |
There may be up to three ways to specify type style.
As a tuple whose first element is the font family, followed by a size in points, optionally followed by a string containing one or more of the style modifiers bold, italic, underline and overstrike.
You can create a "font object" by importing the tkFont module and using its Font class constructor −
import tkFont font = tkFont.Font ( option, ... )
Here is the list of options −
family − The font family name as a string.
size − The font height as an integer in points. To get a font n pixels high, use -n.
weight − "bold" for boldface, "normal" for regular weight.
slant − "italic" for italic, "roman" for unslanted.
underline − 1 for underlined text, 0 for normal.
overstrike − 1 for overstruck text, 0 for normal.
helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")
If you are running under the X Window System, you can use any of the X font names.
For example, the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*" is the author's favorite fixed-width font for onscreen use. Use the xfontsel program to help you select pleasing fonts.
187 Lectures 17.5 hours
55 Lectures 8 hours
136 Lectures 11 hours
75 Lectures 13 hours
Eduonix Learning Solutions
70 Lectures 8.5 hours
63 Lectures 6 hours | https://www.tutorialspoint.com/python/tk_fonts.htm | CC-MAIN-2022-21 | refinedweb | 217 | 67.15 |
Syncfusion Dashboards. Cloud-based. The only BI solution you need for your business.
Syncfusion Essential XlsIO is a .NET Excel library used to create, read, and edit Excel documents. Using this library, you can start creating an Excel document in C# and VB.NET.
Microsoft DataGridView control is a new control which has numerous features than DataGrid control like sorting, etc. This article explains how the data can be exported from DataGridView to Excel with its column header and cell formatting using XlsIO.
Note: Difference between DataGrid and DataGridView can be found here.
Include the following namespace to create new DataGridView object.
Include the following namespace for XlsIO.
After the initialization set valid data sources to the DataGridView’s DataSource property. Here the DataTable object has been used for the DataSource property.
Note: GetDataTable() method returns DataTable of applicable data to import.
Use the following code snippet to create new Excel workbook object.
Use the ImportDataGridView() method to export the data from DataGridView to Excel worksheet with its column header and cell formatting.
The following C#/ VB.NET complete code snippet shows how to export data from DataGridView to Excel using XlsIO.
A complete working DataGridView to Excel sample can be downloaded here.
We recommend you to walkthrough the documentation for importing data from other grid controls, other data objects and exporting operations available with XlsIO for various data objects (DataTable, Business Objects, etc).
An online sample link to import from DataGrid can be found here.. | https://www.syncfusion.com/kb/9078/how-to-export-datagridview-to-excel | CC-MAIN-2018-39 | refinedweb | 246 | 50.12 |
>
Note: question and answer were updated due to the relevance of the topic.
We wanted to publish our Unity application in the Windows Store ("Metro" apps for Windows 8) and faced a big problem, as some important classes/methods are absent in this platform, resulting in errors when building in Unity as a Windows Store App (WSA). Some examples are the File and Directory classes in the System.IO namespace, which allowed us to store the user files for our app in the directory given by Unity: Application.persistentDataPath.
System.IO
Application.persistentDataPath
Our research showed that Windows Store Apps (WSA) should use the Windows.Storage namespace and use async calls to handle filesystem access. This is due to the fact that WSA apps have restricted access to the filesystem, and thus the old classes and methods - which take a full path to the file/directory in question - are forbidden. Apps now should store their data in a folder that is reserved to them.
Windows.Storage
However, Unity does not recognize the namespace Windows.Storage (or even Windows, for that matter). How are Unity developers handling this problem?
Windows
Answer by CanisLupus
·
Dec 03, 2013 at 02:38 PM
Note: This answer was updated after we gained experience with issues for Windows Store Apps. Consequently, old comments in the question/answer might not make sense for new readers. ;)
WSA apps have a different API for file access, when compared with most other platforms. Like I mentioned in the question, each app has mostly only access to a local folder reserved for it (which thankfully includes the folder given by Application.persistentDataPath), and the API is async, and thus not supposed to block the application when files are being accessed. Unfortunately for us all as Unity developers, this seems to be the only way to get IO working in WSA, and the API is quite different to using System.IO classes.
First of all, Unity compiles code differently when building for the various platforms. When you simply select "Windows Store Apps" (WSA) as the active platform in Unity's "Build Settings" window (not creating a build yet!) you're still compiling scripts "as normal" in the Editor. This uses the Mono compiler, which is what Unity uses for most platforms. It means that, before actually being asked to build the application for WSA, Unity has no idea that many classes/methods might not exist in these apps, and also does not recognize classes which only exist there (as is the case with the Windows.Storage namespace), so everything seems to work as in the other platforms.
For actually building a WSA app, Unity uses a .NET compiler in your system (not Mono anymore), from a Windows Development Kit that you probably downloaded. This results in errors that you didn't have before. In our case, we had a few errors with deprecated types (Hashtable, ArrayList, etc) and many errors with filesystem access (classes File, Directory, and our usage of full file paths related to BinaryReader, BinaryWriter, StreamReader, etc). The deprecated types are easy to solve, as there are clear generic substitutes (Dictionary, List, etc); the latter... not so much, as we are supposed to use the Windows.Storage namespace, which is full of async calls and totally different method calls.
Unity has a list of defines / preprocessor directives that you can use for dynamic compilation of script portions depending on the platform you're building for. When you change the active platform to WSA (not building), Unity activates the UNITY_METRO directive, but I don't find this one particularly useful. When you finally press "Build" for WSA, and Unity uses the .NET compiler, you have access to the NETFX_CORE directive. It's only active when actually creating a build with the true .NET compiler, so you should wrap your WSA-only code with it, like so:
UNITY_METRO
NETFX_CORE
#if !NETFX_CORE
// code active when building for platforms other than WSA
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/UserData");
#else
// code active when building for WSA
/* <insert here some WSA-compatible code to create a directory> */
#endif
This compiles the "#if !NETFX_CORE" body when NOT building for WSA, with the usual method calls. Likewise, it compiles the "else" body in WSA builds, so any code put there will be able to access the Windows.Storage namespace. You might also need some of these "#if NETFX_CORE" when including libraries at the top of your script, so you might have, among others:
#if NETFX_CORE
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
#endif
To solve our problem, we went to the trouble of learning the new API, creating a small library of methods implemented with the WSA API (just the ones we required) and filling our code with platform dependent compilation. It was hard but we got there. It was similar to what can be seen here (not my repository or my team's!) and, more specifically, here. Also check their Whitepaper (.pdf) links in the project description, as they might be useful.
Later on, I actually further developed our code, so now there's an asset for cross platform IO in the Unity Asset Store (shameless self-promotion! ;p). It's called UnifiedIO, and contains quite a few common IO methods for handling files and directories in the same way for all platforms. Internally, it does platform dependent compilation like described here, allowing different implementations to be called depending on the platform.
Answer by AshwaniKumar
·
Mar 02, 2015 at 05:33 PM
I have written a post on how to handle some of the file operations seamlessly on multiple environments. Have a.
Virtual keyboard in Windows Store Apps (Metro) via the TouchScreenKeyboard class
0
Answers
WSA System.IO.Directory Error Referenced from Assembly-UnityScript at System.Void ScreenshotMovie::Start()
1
Answer
[Winrt] Hashtable & Arraylist compilation error
1
Answer
Game not Working in Windows 8 but works in Windows 8.1
0
Answers
XDocument in windows store apps usage.
2
Answers | https://answers.unity.com/questions/579641/handling-the-lack-of-systemio-classes-in-windows-8.html | CC-MAIN-2019-30 | refinedweb | 998 | 54.52 |
The Adaptive Communication Environment (ACE) is a high-performance, open
source, object-oriented framework and
C++ class
library that simplifies the development of network applications. The ACE toolkit
is a combination of an operating system layer and a collection of
C++ facades that encapsulate the network API. This
article shows how to design high-performance, concurrent, object-oriented networking
applications using ACE threads. For a complete description of ACE, including how to
download and install the toolkit, see Resources.
ACE classes for creating and managing threads
The following classes are involved in spawning and managing multiple threads within a process:
ACE_Thread_Manager: This is the main class responsible for creation, management, and synchronization of threads. Every operating system has its own subtleties in handling threads: This wrapper class makes these vagaries opaque to the application developer.
ACE_Sched_Params: You use this class to manage the scheduling priority of individual threads, which is defined as part of the ace/Sched_Params.h header in the ACE source distribution. Scheduling policies vary and could be round robin or first come, first served.
ACE_TSS: Using global variables in a multithreaded application is a synchronization issue. The
ACE_TSSclass provides the thread-specific storage pattern, providing an abstraction of data that is logically global to the program but is in reality private to every thread. The
ACE_TSSclass provides the
operator()method, which in turn provides the thread-specific data.
Understanding the thread manager class
Native operating system threading APIs are not portable: Both syntactic and semantic
differences exist. For example, UNIX®
pthread_create()
and Windows®
CreateThread() methods create a
thread, but with syntactic differences. The
ACE_Thread_Manager
class comes with the following capabilities:
- It can spawn one or more threads, each running its own designated function.
- It can manage related threads as a cohesive collection, known as a thread group.
- It manages the scheduling priority of individual threads.
- It allows for synchronization between threads.
- It may alter thread attributes such as stack size.
The salient methods of the
ACE_Thread_Manager class are
described in Table 1.
Table 1. ACE_Thread_Manager class methods
Usage variants of the ACE_Thread_Manager class
You can use the
ACE_Thread_Manager class as a
singleton or make multiple instantiations of the class. For the singleton,
you use a call to the
instance method for
access. In situations where you need to manage multiple thread groups,
it is useful to have different thread-manager classes, each controlling its
own set of threads.
Look at the example in Listing 1, which creates a thread.
Listing 1. Creating a thread using the ACE_Thread_Manager class
#include "ace/Thread_Manager.h" #include <iostream> void thread_start(void* arg) { std::cout << "Running thread..\n"; } int ACE_TMAIN (int argc, ACE_TCHAR* argv[]) { ACE_Thread_Manager::instance()->spawn((ACE_THR_FUNC)thread_start); return 0; }
Listing 2 shows the prototype for the
spawn() method, sourced from
ace/Thread_Manager.h.
Listing 2. The ACE_Thread_Manager::spawn method prototype
int spawn (ACE_THR_FUNC func, void *arg = 0, long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, ACE_thread_t *t_id = 0, ACE_hthread_t *t_handle = 0, long priority = ACE_DEFAULT_THREAD_PRIORITY, int grp_id = -1, void *stack = 0, size_t stack_size = ACE_DEFAULT_THREAD_STACKSIZE, const char** thr_name = 0);
The sheer number of arguments needed to make just a basic thread might appear overwhelming to the first-time user, so let's take a closer look at the individual arguments and why they are needed:
ACE_THR_FUNC func: This function is called upon when the thread is spawned.
void* arg: An argument to the function called upon when the thread is spawned,
void*implies that the user is free to pass in any application-specific data type or even coalesce multiple arguments to a single data using a structure.
long flags: Several properties of the spawned thread are set using the
flagsvariable. The individual attributes are
bitwiseor
-ed. Table 2 shows some of the attributes.
ACE_thread_t *t_id: Use this function to access the ID of the created thread. Every thread has a unique ID.
long priority: This is the priority at which the threads are spawned.
int grp_id: If provided, this argument indicates whether the spawned thread is to be part of some existing thread group. Otherwise, if
-1is passed as the argument, a new thread group is created, and the spawned thread is added to the same.
void* stack: This is the pointer to the preallocated stack area. If
0is provided as the argument, the operating system is requested to provide for the stack area of the spawned thread.
size_t stack_size: This argument indicates the size of the thread stack in bytes. If
0is provided as the argument for
stack pointer (item 7), the operating system is requested for a stack area with size
stack_size.
const char** thr_name: This argument is relevant only in platforms like VxWorks that have an ability to name threads. It is ignored for most purposes on UNIX systems.
Table 2. Thread properties and their description
Listing 3 provides an example that creates multiple threads
using the
spawn_n method of the thread manager
class.
Listing 3. Creating multiple threads using the ACE_Thread_Manager class
#include "ace/Thread_Manager.h" #include <iostream> void print (void* args) { int id = ACE_Thread_Manager::instance()->thr_self(); std::cout << "Thread Id: " << id << std::endl; } int ACE_TMAIN (int argc, ACE_TCHAR* argv[]) { ACE_Thread_Manager::instance()->spawn_n( 4, (ACE_THR_FUNC) print, 0, THR_JOINABLE | THR_NEW_LWP); ACE_Thread_Manager::instance()->wait(); return 0; }
Alternative thread-creation mechanism in ACE
This section discusses an alternate thread-creation/management scheme from
ACE, one that does not need the explicit level of fine-grained control of the
thread manager. By default, every process is created with a single thread that
starts and ends with the
main function. Any extra
threads need explicit creation. An alternative way of creating threads is to
create a sub-class of the predefined
ACE_Task_Base
class, then override the
svc() method. The new
thread starts in the
svc() method and ends when
the
svc() method returns. Before explaining further,
take a look into the source shown in Listing 4.
Listing 4. Creating a thread using ACE_Task_Base::svc
#include “ace/Task.h” class Thread_1 : public ACE_Task_Base { public: virtual int svc( ) { std::cout << “In child’s thread\n”; return 0; } }; int main ( ) { Thread_1 th1; th1.activate(THR_NEW_LWP|THR_JOINABLE); th1.wait(); return 0; }
The application-specific behavior of the thread is coded inside the
svc() method. To execute the thread, the
activate() method (declared and defined as part of
the
ACE_Task_Base class) is called upon. When the
thread is activated, the
main() function waits for the
child thread to complete execution. This is what the
wait()
method strives to achieve: The main thread is blocked until
Thread_1 is complete. This wait is a needed feature;
otherwise, the main thread would have scheduled the child thread and made an exit.
The
C run time, on seeing the main thread exiting,
would have destroyed all the child threads; as such, the child thread would probably
never have been scheduled or executed.
Understanding ACE_Task_Base class in more detail
Here's a somewhat detailed look into a few of the methods in
ACE_Task_Base.
Listing 5 shows the
activate()
method prototype.
Listing 5. The ACE_Task_Base::activate method prototype
virtual int activate (long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, int n_threads = 1, int force_active = 0, long priority = ACE_DEFAULT_THREAD_PRIORITY, int grp_id = -1, ACE_Task_Base *task = 0, ACE_hthread_t thread_handles[ ] = 0, void *stack[ ] = 0, size_t stack_size[ ] = 0, ACE_thread_t thread_ids[ ] = 0, const char* thr_name[ ] = 0);
You can use the
activate() method to create one or
more threads of control, each of which calls the same
svc() method, and all running at the same priority
with the same group ID. Here's a brief description of some of the input
arguments:
long flags: Refer to Table 2.
int n_threads: Create the number of threads specified by
n_threads.
int force_active: If this flag is True and there are existing threads spawned by the task, then all the newly spawned threads would share the group ID of the previously spawned threads and ignore the value as passed to the
activate()method.
long priority: This argument assigns a priority to the thread or collection of threads. Scheduling priority values are operating system specific, and it's a safe bet to stick to the default value of
ACE_DEFAULT_THREAD_PRIORITY.
ACE_hthread_t thread_handles: If
thread_handles != 0, then after the spawning of the n threads, this array will be assigned the individual thread handles.
void* stack: If specified, this argument indicates an array of pointers to the base of the stacks for the individual threads.
size_t stack_size: If specified, this argument indicates an array of integers denoting the size of the individual thread stacks.
ACE_thread_t thread_ids: If
thread_ids != 0, it is assumed to be an array that will hold the IDs of the n newly spawned threads.
Listing 6 shows a couple of other useful routines in the
ACE_Task_Base class.
Listing 6. Miscellaneous routines from ACE_Task_Base
// Block the main thread until all threads of this task are completed virtual int wait (void); // Suspend a task virtual int suspend (void); // Resume a suspended task. virtual int resume (void); // Gets the no. of active threads within the task size_t thread_count (void) const; // Returns the id of the last thread whose exit caused the thread count // of this task to 0. A zero return status implies that the result is // unknown. Maybe no threads are scheduled. ACE_thread_t last_thread (void) const;
In order to create a thread in a suspended state (as opposed to a suspension
explicitly using the
suspend() method call), you
need to pass the
THR_SUSPENDED flag to the
activate() method. You can resume the thread
by calling the
resume() method, as shown in
Listing 7.
Listing 7. Suspension and resumption of threads
Thread_1 th1; th1.activate(THR_NEW_LWP|THR_JOINABLE|THR_SUSPENDED); …// code in the main thread th1.resume(); …// code continues in main thread
A second look into thread flags
Two kinds of threads are possible: kernel-level threads and user-level threads. If the
activate() method is called without any argument,
the default is to create a kernel-level thread. Kernel-level threads interact directly
with the operating system and are scheduled by the kernel-level scheduler. In
contrast, user-level threads operate within the process scope and are "assigned"
kernel-level threads on an as-needed basis to complete some task. The flag
THR_NEW_LWP, which is the default argument to the
activate() method, always ensures that the new thread
created is a kernel-level thread.
Thread hooks
ACE provides a global thread startup hook that allows the user to perform
any kind of operation that is globally applicable to all threads. To create
a startup hook, you need to create a subclass of the predefined class
ACE_Thread_Hook and provide the definition for
the
start() method. The
start() method accepts two arguments: a pointer
to a user-defined function and a
void*, which is
passed to this user-defined function. In order to register the hook, you need to
call the static method
ACE_Thread_Hook::thread_hook,
as shown in Listing 8.
Listing 8. Using global thread hooks
#include "ace/Task.h" #include "ace/Thread_Hook.h" #include <iostream> class globalHook : public ACE_Thread_Hook { public: virtual ACE_THR_FUNC_RETURN start (ACE_THR_FUNC func, void* arg) { std::cout << "In created thread\n"; (*func)(arg); } }; class Thread_1 : public ACE_Task_Base { public: virtual int svc( ) { std::cout << "In child's thread\n"; return 0; } }; int ACE_TMAIN (int argc, ACE_TCHAR* argv[]) { globalHook g; ACE_Thread_Hook::thread_hook(&g); Thread_1 th1; th1.activate(); th1.wait(); return 0; }
Note that the
ACE_THR_FUNC pointer that is
automatically passed to the startup hook is the same function that would
have been called when the
activate() method
of the thread is executed. The outputs from the above code are the messages:
In created thread In child’s thread
Conclusion
This article took a first look at the creation and management of threads using the ACE framework. The ACE framework has several other useful features, such as mutexes, guard blocks for synchronization, shared memory, and network services. See Resources for details.
Resources
Learn
- Building and Install ACE: Learn how to build and install the ACE library.
- ACE support: Get commercial support for the ACE library.
- AIX and UNIX: Visit the developerWorks AIX and UNIX zone provides a wealth of information relating to all aspects of AIX systems administration and expanding your UNIX skills.
- New to AIX and UNIX? Visit the New to AIX and UNIX page to learn more.
- Technology bookstore: Browse for books on this and other technical topics.
Get products and technologies
- ACE framework: Download the ACE library framework.
Discuss
- developerWorks blogs:. | http://www.ibm.com/developerworks/aix/library/au-ace/index.html?ca=dgr-lnxw16ACEthreadsdth-a&S_TACT=105AGX59&S_CMP=grlnxw16 | CC-MAIN-2014-35 | refinedweb | 2,048 | 52.9 |
On Monday 09 June 2008, Carl Love wrote:
>
> This is a reworked patch, version 3, to fix the SPU profile
> sample data collection.
>
> Currently, the SPU escape sequences and program counter data is being
> added directly into the kernel buffer without holding the buffer_mutex
> lock. This patch changes how the data is stored. A new function,
> oprofile_add_value, is added into the oprofile driver to allow adding
> generic data to the per cpu buffers. This enables adding series of data
> to a specified cpu_buffer. The function is used to add SPU data
> into a cpu buffer. The patch also adds the needed code to move the
> special sequence to the kernel buffer. There are restrictions on
> the use of the oprofile_add_value() function to ensure data is
> properly inserted to the specified CPU buffer.
>
> Finally, this patch backs out the changes previously added to the
> oprofile generic code for handling the architecture specific
> ops.sync_start and ops.sync_stop that allowed the architecture
> to skip the per CPU buffer creation.
>
> Signed-off-by: Carl Love <carll@...>
Thanks for your new post, addressing my previous complaints.
Unfortunately, I'm still uncomfortable with a number of details
about how the data is passed around, and there are a few style
issues that should be easier to address.
> - if (num_samples == 0) {
> + if (unlikely(!spu_prof_running)) {
> + spin_unlock_irqrestore(&sample_array_lock,
> + sample_array_lock_flags);
> + goto stop;
> + }
> +
> + if (unlikely(num_samples == 0)) {
> spin_unlock_irqrestore(&sample_array_lock,
> sample_array_lock_flags);
> continue;
I think you should not use 'unlikely' here, because that optimizes only
very specific cases, and often at the expense of code size and readability.
If you really want to optimize the spu_prof_running, how about doing
it outside of the loop?
Similarly, it probably makes sense to hold the lock around the loop.
Note that you must never have a global variable for 'flags' used
in a spinlock, as that will get clobbered if you have lock contention,
leading to a CPU running with interrupts disabled accidentally.
It's better to never use spin_lock_irq or spin_lock, respectively,
since you usually know whether interrupts are enabled or not
anyway!
> @@ -214,8 +218,26 @@ int start_spu_profiling(unsigned int cyc
>
> void stop_spu_profiling(void)
> {
> + int cpu;
> +
> spu_prof_running = 0;
> hrtimer_cancel(&timer);
> +
> + /* insure everyone sees spu_prof_running
> + * changed to 0.
> + */
> + smp_wmb();
I think you'd also need have a 'smp_rb' on the reader side to
make this visible, but it's easier to just use an atomic_t
variable instead, or to hold sample_array_lock when changing
it, since you already hold that on the reader side.
> -static DEFINE_SPINLOCK(buffer_lock);
> +static DEFINE_SPINLOCK(add_value_lock);
> static DEFINE_SPINLOCK(cache_lock);
> static int num_spu_nodes;
> int spu_prof_num_nodes;
> -int last_guard_val[MAX_NUMNODES * 8];
> +int last_guard_val[MAX_NUMNODES * SPUS_PER_NODE];
> +static int spu_ctx_sw_seen[MAX_NUMNODES * SPUS_PER_NODE];
> +
> +/* an array for mapping spu numbers to an index in an array */
> +static int spu_num_to_index[MAX_NUMNODES * SPUS_PER_NODE];
> +static int max_spu_num_to_index=0;
> +static DEFINE_SPINLOCK(spu_index_map_lock);
Your three locks are rather confusing. Please try to consolidate them
into fewer spinlocks and/or document for each lock exactly what
data structures it protects, and how it nests with the other locks
(e.g. "lock order: spu_index_map_lock can not be held around other locks")
and whether you need to disable interrupts and bottom half processing
while holding them.
>
> -static struct cached_info *spu_info[MAX_NUMNODES * 8];
> +static struct cached_info *spu_info[MAX_NUMNODES * SPUS_PER_NODE];
> +
> +struct list_cpu_nums {
> + struct list_cpu_nums *next;
> + int cpu_num;
> +};
> +
> +struct spu_cpu_map_struct {
> + int cpu_num;
> + int spu_num;
> +};
> +
> +struct spu_cpu_map_struct spu_cpu_map[MAX_NUMNODES * SPUS_PER_NODE];
> +
> +struct list_cpu_nums *active_cpu_nums_list;
> +struct list_cpu_nums *next_cpu;
Here, you are putting more symbols into the global namespace, which is
not acceptable. E.g. 'next_cpu' should either be static, or be called
something like spu_task_sync_next_cpu.
Ideally, put them into a function context, or get rid of the globals
altogether.
> +static int max_entries_spu_cpu_map=0;
By convention, we do not preinitialize global variables to zero.
> +
> +/* In general, don't know what the SPU number range will be.
> + * Create an array to define what SPU number is mapped to each
> + * index in an array. Want to be able to have multiple calls
> + * lookup an index simultaneously. Only hold a lock when adding
> + * a new entry.
> + */
> +static int add_spu_index(int spu_num) {
> + int i, tmp;
> + int flags;
> +
> + spin_lock_irqsave(&spu_index_map_lock, flags);
> +
> + /* Need to double check that entry didn't get added
> + * since the call to get_spu_index() didn't find it.
> + */
> + for (i=0; i<max_spu_num_to_index; i++)
> + if (spu_num_to_index[i] == spu_num) {
> + tmp = i;
> + goto out;
> + }
> +
> + /* create map for spu num */
> +
> + tmp = max_spu_num_to_index;
> + spu_num_to_index[max_spu_num_to_index] = spu_num;
> + max_spu_num_to_index++;
> +
> +out: spin_unlock_irqrestore(&spu_index_map_lock, flags);
> +
> + return tmp;
> +}
> +
> +static int get_spu_index(int spu_num) {
> + int i, tmp;
> +
> + /* check if spu map has been created */
> + for (i=0; i<max_spu_num_to_index; i++)
> + if (spu_num_to_index[i] == spu_num) {
> + tmp = i;
> + goto out;
> + }
> +
> + tmp = add_spu_index(spu_num);
> +
> +out: return tmp;
> +}
> +
> +static int valid_spu_num(int spu_num) {
> + int i;
> +
> + /* check if spu map has been created */
> + for (i=0; i<max_spu_num_to_index; i++)
> + if (spu_num_to_index[i] == spu_num)
> + return 1;
> +
> + /* The spu number has not been seen*/
> + return 0;
> +}
> +
> +static int initialize_active_cpu_nums(void) {
> + int cpu;
> + struct list_cpu_nums *tmp;
> +
> + /* initialize the circular list */
> +
> + active_cpu_nums_list = NULL;
> +
> + for_each_online_cpu(cpu) {
> + if (!(tmp = kzalloc(sizeof(struct list_cpu_nums),
> + GFP_KERNEL)))
> + return -ENOMEM;
> +
> + tmp->cpu_num = cpu;
> +
> + if (!active_cpu_nums_list) {
> + active_cpu_nums_list = tmp;
> + tmp->next = tmp;
> +
> + } else {
> + tmp->next = active_cpu_nums_list->next;
> + active_cpu_nums_list->next = tmp;
> + }
> + }
> + next_cpu = active_cpu_nums_list;
> + return 0;
> +}
This function does not clean up after itself when getting an ENOMEM.
> +
> +static int get_cpu_buf(int spu_num) {
> + int i;
> +
> +
> + for (i=0; i< max_entries_spu_cpu_map; i++)
> + if (spu_cpu_map[i].spu_num == spu_num)
> + return spu_cpu_map[i].cpu_num;
> +
> + /* no mapping found, create mapping using the next
> + * cpu in the circular list of cpu numbers.
> + */
> + spu_cpu_map[max_entries_spu_cpu_map].spu_num = spu_num;
> + spu_cpu_map[max_entries_spu_cpu_map].cpu_num = next_cpu->cpu_num;
> +
> + next_cpu = next_cpu->next;
> +
> + return spu_cpu_map[max_entries_spu_cpu_map++].cpu_num;
> +}
>
The whole logic you are adding here (and the functions above)
looks overly complicated. I realize now that this may be my
fault because I told you not to rely on the relation between
SPU numbers and CPU numbers, but I'm still not sure if this
is even a correct approach.
Your code guarantees that all samples from a physical SPU always
end up in the same CPUs buffer. However, when an SPU context
gets moved by the scheduler from one SPU to another, how do you
maintain the consistency between the old and the new samples?
Also, this approach fundamentally does not handle CPU hotplug,
though that is probably something that was broken in this code
before.
Having to do so much work just to be able to use the per-cpu
buffers indicates that it may not be such a good idea after all.
> @@ -161,27 +293,28 @@ out:
> */
> static int release_cached_info(int spu_index)
> {
> - int index, end;
> + int index, end, spu_num;
>
> if (spu_index == RELEASE_ALL) {
> - end = num_spu_nodes;
> + end = max_spu_num_to_index;
> index = 0;
> } else {
> - if (spu_index >= num_spu_nodes) {
> + if (!valid_spu_num(spu_index)) {
> printk(KERN_ERR "SPU_PROF: "
> "%s, line %d: "
> "Invalid index %d into spu info cache\n",
> __FUNCTION__, __LINE__, spu_index);
> goto out;
> }
> - end = spu_index + 1;
> - index = spu_index;
> + index = get_spu_index(spu_index);
> + end = index + 1;
> }
> for (; index < end; index++) {
> - if (spu_info[index]) {
> - kref_put(&spu_info[index]->cache_ref,
> + spu_num = spu_num_to_index[index];
> + if (spu_info[spu_num]) {
> + kref_put(&spu_info[spu_num]->cache_ref,
> destroy_cached_info);
> - spu_info[index] = NULL;
> + spu_info[spu_num] = NULL;
> }
> }
>
> @@ -289,6 +422,8 @@ static int process_context_switch(struct
> int retval;
> unsigned int offset = 0;
> unsigned long spu_cookie = 0, app_dcookie;
> + unsigned long values[NUM_SPU_CNTXT_SW];
> + int cpu_buf;
>
> retval = prepare_cached_spu_info(spu, objectId);
> if (retval)
> @@ -303,17 +438,31 @@ static int process_context_switch(struct
> goto(spu_cookie);
> - add_event_entry(offset);
> - spin_unlock_irqrestore(&buffer_lock, flags);
> + /* Record context info in event buffer. Note, there are more
> + * SPUs then CPUs. Map the SPU events/data for a given SPU to
> + * the same CPU buffer. Need to ensure the cntxt switch data and
> + * samples stay in order.
> + */
> +
> + spin_lock_irqsave(&add_value_lock, flags);
> + cpu_buf = get_cpu_buf(spu->number);
> +
> + values[0] = ESCAPE_CODE;
> + values[1] = SPU_CTX_SWITCH_CODE;
> + values[2] = spu->number;
> + values[3] = spu->pid;
> + values[4] = spu->tgid;
> + values[5] = app_dcookie;
> + values[6] = spu_cookie;
> + values[7] = offset;
> + oprofile_add_value(values, cpu_buf, NUM_SPU_CNTXT_SW);
> +
> + /* Set flag to indicate SPU PC data can now be written out. If
> + * the SPU program counter data is seen before an SPU context
> + * record is seen, the postprocessing will fail.
> + */
> + spu_ctx_sw_seen[get_spu_index(spu->number)] = 1;
> + spin_unlock_irqrestore(&add_value_lock, flags);
> smp_wmb(); /* insure spu event buffer updates are written */
> /* don't want entries intermingled... */
The spin_unlock obviously contain an implicit barrier, otherwise
it would not be much good as a lock, so you can remove the smp_wmb()
here.
> out:
> @@ -363,38 +512,51 @@;
> + int flags;
> + int unsigned long values[NUM_SPU_SYNC_START];
>
> spu_prof_num_nodes = number_of_online_nodes();
> - num_spu_nodes = spu_prof_num_nodes * 8;
> + num_spu_nodes = spu_prof_num_nodes * SPUS_PER_NODE;
>
> - spin_lock_irqsave(&buffer_lock, flags);
> - add_event_entry(ESCAPE_CODE);
> - add_event_entry(SPU_PROFILING_CODE);
> - add_event_entry(num_spu_nodes);
> - spin_unlock_irqrestore(&buffer_lock, flags);
> + ret = initialize_active_cpu_nums();
> + if (ret)
> + goto out;
> +
> + /* The SPU_PROFILING_CODE escape sequence must proceed
> + * the SPU context switch info.
> + *
> + * SPU profiling and PPU profiling are not supported
> + * at the same time. SPU Profilining does not support
> + * call graphs, hence just need lock to prevent mulitple
> + * calls to oprofile_add_value().
> + */
> + values[0] = ESCAPE_CODE;
> + values[1] = SPU_PROFILING_CODE;
> + values[2] =(unsigned long int) num_spu_nodes;
> +
> + spin_lock_irqsave(&add_value_lock, flags);
> + for_each_online_cpu(cpu)
> + oprofile_add_value(values, cpu, NUM_SPU_SYNC_START);
> + spin_unlock_irqrestore(&add_value_lock, flags);
>
> /* Register for SPU events */
> register_ret = spu_switch_event_register(&spu_active);
> if (register_ret) {
> - ret = SYNC_START_ERROR;
> + ret = -1;
> goto out;
> }
>
> - for (k = 0; k < (MAX_NUMNODES * 8); k++)
> + for (k = 0; k < (MAX_NUMNODES * SPUS_PER_NODE); k++) {
> last_guard_val[k] = 0;
> + spu_ctx_sw_seen[k] = 0;
> + }
Why do you need the spu_ctx_sw_seen here? Shouldn't
spu_switch_event_register() cause a switch event in every context
anyway? You call that just a few lines earlier.
> );
Please change the prototype of the unregister function instead
then, you are the only caller anyway.
> @@ -40,6 +40,7 @@ static cpumask_t marked_cpus = CPU_MASK_
> static DEFINE_SPINLOCK(task_mortuary);
> static void process_task_mortuary(void);
>
> +extern int work_enabled; // carll added for debug
This obviously needs to be removed again.
>
> /* Take ownership of the task struct and place it on the
> * list for processing. Only after two full buffer syncs
> @@ -521,6 +522,46 @@ void sync_buffer(int cpu)
> } else if (s->event == CPU_TRACE_BEGIN) {
> state = sb_bt_start;
> add_trace_begin();
> + } else if (s->event == VALUE_HEADER_ID) {
> + /* The next event entry contains the number
> + * values in the sequence to add.
> + */
> + int index, j, num;
> +
> + if ((available - i) < 2)
> + /* The next entry which contains the
> + * number of entries in the sequence
> + * has not been written to the
> + * buffer yet.
> + */
> + break;
> +
> + /* Get the number in the sequence without
> + * changing the state of the buffer.
> + */
> + index = cpu_buf->tail_pos + 1;
> + if (!(index < cpu_buf->buffer_size))
> + index = 0;
> +
> + num = cpu_buf->buffer[index].eip;
> +
> + if ((available - i) < (num+1))
> + /* The entire sequence has not been
> + * written to the buffer yet.
> + */
> + break;
> +
> + if (work_enabled == 0) {
> + printk("work_enabled is zero\n");
> + }
> + for (j = 0; j < num; j++) {
> + increment_tail(cpu_buf);
> + i++;
> +
> + s = &cpu_buf->buffer[cpu_buf->tail_pos];
> + add_event_entry(s->event);
> + }
> +
> } else {
> struct mm_struct * oldmm = mm;
This is a substantial amount of code that you are adding to the existing
function, please move this out into a separate function, for better
readability.
> @@ -32,7 +32,9 @@ struct oprofile_cpu_buffer cpu_buffer[NR
> static void wq_sync_buffer(struct work_struct *work);
>
> #define DEFAULT_TIMER_EXPIRE (HZ / 10)
> -static int work_enabled;
> +//carll changed static int work_enabled;
> +extern int work_enabled;
> +int work_enabled;
please revert.
> Index: Cell_kernel_5_15_2008-new/drivers/oprofile/cpu_buffer.h
> ===================================================================
> --- Cell_kernel_5_15_2008-new.orig/drivers/oprofile/cpu_buffer.h
> +++ Cell_kernel_5_15_2008-new/drivers/oprofile/cpu_buffer.h
> @@ -54,5 +54,6 @@ void cpu_buffer_reset(struct oprofile_cp
> /* transient events for the CPU buffer -> event buffer */
> #define CPU_IS_KERNEL 1
> #define CPU_TRACE_BEGIN 2
> +#define VALUE_HEADER_ID 3
'VALUE_HEADER_ID' does not describe well enough to me what this
is doing. Maybe some other identifier if you can think of one?
> @@ -106,6 +97,22 @@ void oprofile_add_sample(struct pt_regs
> void oprofile_add_ext_sample(unsigned long pc, struct pt_regs * const regs,
> unsigned long event, int is_kernel);
>
> +/*
> + * Add a sequence of values to the per CPU buffer. An array of values is
> + * added to the specified cpu buffer with no additional processing. The assumption
> + * is any processing of the value will be done in the postprocessor. This
> + * function should only be used for special architecture specific data.
> + * Currently only used by the CELL processor.
> + *
> + * REQUIREMENT: the user of the function must ensure that only one call at
> + * a time is made to this function. Additionally, it must ensure that
> + * no calls are made to the following routines: oprofile_begin_trace(),
> + * oprofile_add_ext_sample(), oprofile_add_pc(), oprofile_add_trace().
> + *
> + * This function does not perform a backtrace.
> + */
> +void oprofile_add_value(unsigned long *values, int cpu, int num);
> +
> /* Use this instead when the PC value is not from the regs. Doesn't
> * backtrace. */
> void oprofile_add_pc(unsigned long pc, int is_kernel, unsigned long event);
>
These are pretty strict requirements. How do you ensure that these are
all true? What if the user is running timer based profiling on the CPU
at the same time as event profiling on the SPU?
Maybe someone else with an oprofile background can comment on whether the
interface is acceptable as is.
Arnd <><
Hi everybody.
I am profiling an MP3 decoding on an ARM9-based processor, and using kernel
2.6.20
When I set --no-vmlinux I have a reasonable number of samples (14/15 k) in 2
minutes of test.
When specifying the vmlinux image it can't get more than 600 samples in the
same time.
It seems like it looses some samples.
Where could the problem be?
I set the kernel_range manually in opcontrol (sh script), since the
environment in which I run it uses busybox which does not implement
completely some functionalities, could the problem lie in this?
Here I paste the 2 different results i get from the 2 tests.
(cm is a kernel module)
/host # opreport
CPU: CPU with timer interrupt, speed 0 MHz (estimated)
Profiling through timer interrupt
TIMER:0|
samples| %|
------------------
12854 90.4765 no-vmlinux
635 4.4696 mp3decoder
TIMER:0|
samples| %|
------------------
516 81.2598 no-vmlinux
77 12.1260 mp3decoder
26 4.0945 libpthread-2.5.so
16 2.5197 libc-2.5.so
446 3.1393 aplay
TIMER:0|
samples| %|
------------------
279 62.5561 libasound.so.2.0.0
155 34.7534 no-vmlinux
10 2.2422 libc-2.5.so
2 0.4484 aplay
266 1.8723 busybox
TIMER:0|
samples| %|
------------------
214 80.4511 no-vmlinux
22 8.2707 ld-2.5.so
15 5.6391 libc-2.5.so
14 5.2632 busybox
1 0.3759 libcrypt-2.5.so
4 0.0282 ophelp
TIMER:0|
samples| %|
------------------
3 75.0000 no-vmlinux
1 25.0000 ld-2.5.so
2 0.0141 busybox
TIMER:0|
samples| %|
------------------
1 50.0000 no-vmlinux
1 50.0000 ld-2.5.so
/host # opreport
CPU: CPU with timer interrupt, speed 0 MHz (estimated)
Profiling through timer interrupt
TIMER:0|
samples| %|
------------------
288 52.9412 aplay
TIMER:0|
samples| %|
------------------
281 97.5694 libasound.so.2.0.0
5 1.7361 libc-2.5.so
1 0.3472 aplay
1 0.3472 ld-2.5.so
182 33.4559 mp3decoder
TIMER:0|
samples| %|
------------------
74 40.6593 mp3decoder
62 34.0659 cm
31 17.0330 libpthread-2.5.so
14 7.6923 libc-2.5.so
1 0.5495 ld-2.5.so
55 10.1103 busybox
TIMER:0|
samples| %|
------------------
20 36.3636 ld-2.5.so
18 32.7273 libc-2.5.so
16 29.0909 busybox
1 1.8182 libm-2.5.so
19 3.4926 cm
Thanks a lot.
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/oprofile/mailman/oprofile-list/?viewmonth=200806&viewday=10 | CC-MAIN-2016-44 | refinedweb | 2,493 | 55.95 |
Hi Paul, On 16 August 2010 09:32, Paul Smith wrote: > Are you saying that MinGW defines a MAXPATHLEN that is shorter than the > real maximum path length on Windows, and that the max path length on > Windows is really 1024 not 259? So, this change is a workaround for a > MinGW system header bug? No, I didn't explain things well. MAX_PATH on windows should be 259. > Or, are you saying that make is using this value incorrectly, and that > instead of MAXPATHLEN it should be using something else? Looking at the make source, in particular dir.c, it has (in find_directory()): char tem[MAXPATHLEN], *tstart, *tend; and when running the attached Makefile with make via GDB, make craped out in the find_directory function. So based on my findings explained below, I suspected that MAXPATHLEN was expected to be greater than 259. >? My debugging process was somewhat convoluted. Upon discovering that the original make-3.82 binary I produced for MinGW caused an exception with the attached Makefile, I re-compiled the binary and did not strip it (which how I found out about the failure in find_directory()). Unfortunately doing further debugging with GDB was problematic due to the optimization (-O2). I recompiled again without optimization and did not experience the exception. Being far from a GDB expert, I was at a loss as to how to use GDB to debug this issue further (i.e. with the Optimization enabled). However, I've seen this type of behaviour before with pointers addressing memory they shouldn't be. I was made aware on the MinGW-Users list that when compiled with the build_w32.bat file, the gnumake.exe produced did not generate the exception. Doing a comparison between config.h.W32 and the generated config.h (via running configure in MSYS), I noticed there were several differences. Executing a trial-and-error approach, I found that the exception occurred if 'HAS_SYS_PARAM_H' was defined. Looking at MinGW's sys/param.h I saw that MAXPATHLEN was defined as follows: #define MAXPATHLEN PATH_MAX where PATH_MAX is defined as 259. Looking at make.h I saw: #ifndef MAXPATHLEN # define MAXPATHLEN 1024 #endif Given the behaviour I was experiencing (the exception) and seeing the discrepancy in MAXPATHLEN, I made the minor change: #ifdef __MINGW32__ # undef MAXPATHLEN #endif #ifndef MAXPATHLEN # define MAXPATHLEN 1024 #endif Under the assumption that make was expecting MAXPATHLEN to be 1024 (vs. 259). When I recompiled with this change, I could no longer re-create the exception. Please let me know if there is anything more I can do to help. Chris -- Chris Sutcliffe
Makefile
Description: Binary data | http://lists.gnu.org/archive/html/make-w32/2010-08/msg00006.html | CC-MAIN-2014-10 | refinedweb | 437 | 57.47 |
In this blog we will understand how Multi threading works in JAVA and why is it so Important to understand?
What is Multithreading?
Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilisation of CPU. Multi-threaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java.
Advantages of multithread:
- The users are not blocked because threads are independent, and we can perform multiple operations at times
- As such the threads are independent, the other threads won’t get affected if one thread meets an exception.
- Program structure simplification. Threads can be used to simplify the structure of complex applications, such as server-class and multimedia applications. Simple routines can be written for each activity, making complex programs easier to design and code, and more adaptive to a wide variation in user demands.
- Improved server responsiveness. Large or complex requests or slow clients don’t block other requests for service. The overall throughput of the server is much greater.
Life cycle of a Thread
-.
- Dead/Terminated – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.
We can create threads in java by extending the
java.lang.Thread class or by implementing the
java.lang.Runnable interface. Both the implementation overrides the
run() method to do so. Both the implementations can be used according to the use case of the class.
Creating Thread Using Thread Class
@Component public class MultiThreadingExample extends Thread{ private final static Logger log = LoggerFactory.getLogger(MultiThreadingExample.class); @Override public void run() { log.info("This class extends Thread class for multithreading"); } }.
Checkout our other blogs on java and java on Knoldus blogs. | https://blog.knoldus.com/multithreading-in-java/ | CC-MAIN-2021-31 | refinedweb | 291 | 50.84 |
On Jul 7, 2005, at 10:26 AM, Jonathan Blocksom wrote: > Hi, I've got a SOAPPublisher class with some published methods and > I was hoping to access the HTTP request object from within. > Anybody know how to do this? Unfortunately it doesn't look like it. If you look at the SOAPPublisher.render method, it looks up the callable and then calls it (indirecting through maybeDeferred). The only place the request is available is in the local namespace of render. So, you could: 1) override render, stuff the request somewhere (like self), then get it out in your method; you should only do this if threads are in no way involved. If there aren't any threads then it would be safe. Just be sure to get it out immediately and pass around what you got out (for example, don't return a deferred then look in self in a callback) 2) use some horrible callframe hack to extract the request from the caller's frame. This would have the advantage of being threadsafe, but you aren't using threads anyway -- right? Itamar is the guy to talk to about SOAP and XMLRPC, but I guess he doesn't read this list. If you want to have a cleaner way of doing this in the future, you should probably talk to him about it, either on IRC or through email or something. Donovan | http://twistedmatrix.com/pipermail/twisted-web/2005-July/001665.html | CC-MAIN-2013-48 | refinedweb | 234 | 77.77 |
Project 2: Command Line Shell (v 1.3)
Starter repository on GitHub:
The outermost layer of the operating system is called the shell. In Unix-based systems, the shell is generally a command line interface. Most Linux distributions ship with
bash as the default (there are several others:
csh,
ksh,
sh,
tcsh,
zsh). In this project, we’ll be implementing a shell of our own – see, I told you that you’d come to love command line interfaces in this class!
You will need to come up with a name for your shell first. The only requirement is that the name ends in ‘sh’, which is tradition in the computing world. In the following examples, my shell is named
crash (Cool Really Awesome Shell) because of its tendency to crash.
The Basics
Upon startup, your shell will print its prompt and wait for user input. Your shell should be able to run commands in both the current directory and those in the PATH environment variable. Use
execvp to do this. To run a command in the current directory, you’ll need to prefix it with
./ as usual. If a command isn’t found, print an error message:
╭─[🙂]─[1]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ ./hello Hello world! ╭─[🙂]─[2]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ ls /usr bin include lib local sbin share src ╭─[🙂]─[3]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ echo hello there! hello there! ╭─[🙂]─[4]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ ./blah crash: no such file or directory: ./blah ╭─[🤮]─[5]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ cd /this/does/not/exist chdir: no such file or directory: /this/does/not/exist ╭─[🤮]─[6]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼
Prompt
The shell prompt displays some helpful information. At a minimum, you must include:
- Command number (starting from 1)
- User name and host name:
(username)@(hostname)followed by
:
- The current working directory
- Process exit status
In the example above, these are separated by dashes and brackets to make it a little easier to read. The process exit status is shown as an emoji: a smiling face for success (exit code
0) and a sick face for failure (any nonzero exit code or failure to execute the child process). For this assignment, you are allowed to invent your own prompt format as long as it has the elements listed above. You can use colors, unicode characters, etc. if you’d like. For instance, some shells highlight the next command in red text after a nonzero exit code.
You will format the current working directory as follows: if the CWD is the user’s home directory, then the entire path is replaced with
~. Subdirectories under the home directory are prefixed with
~; if I am in
/home/mmalensek/test, the prompt will show
~/test. Here’s a test to make sure you’ve handled
~ correctly:
╭─[🙂]─[6]─[mmalensek@glitter-sparkle:~] ╰─╼ whoami mmalensek ╭─[🙂]─[7]─[mmalensek@glitter-sparkle:~] ╰─╼ cd P2-malensek # Create a directory with our full home directory in its path: # **Must use the username outputted above from whoami)** ╭─[🙂]─[8]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ mkdir -p /tmp/home/mmalensek/test ╭─[🙂]─[9]─[mmalensek@glitter-sparkle:~/P2-malensek] ╰─╼ cd /tmp/home/mmalensek/test # Note that the FULL path is shown here (no ~): ╭─[🙂]─[10]─[mmalensek@glitter-sparkle:/tmp/home/mmalensek/test] ╰─╼ pwd /tmp/home/mmalensek/test
Scripting
Your shell must support scripting mode to run the test cases. Scripting mode reads commands from standard input and executes them without showing the prompt.
cat <<EOM | ./crash ls / echo "hi" exit EOM # Which outputs (note how the prompt is not displayed): bin boot dev etc home lib lost+found mnt opt proc root run sbin srv sys tmp usr var hi # Another option (assuming commands.txt contains shell commands): ./crash < commands.txt (commands are executed line by line)
You should check and make sure you can run a large script with your shell. Note that the script should not have to end in
exit.
To support scripting mode, you will need to determine whether stdin is connected to a terminal or not. If it’s not, then disable the prompt and proceed as usual. Here’s some sample code that does this with
isatty:
#include <stdio.h> #include <unistd.h> int main(void) { if (isatty(STDIN_FILENO)) { printf("stdin is a TTY; entering interactive mode\n"); } else { printf("data piped in on stdin; entering script mode\n"); } return 0; }
Since the
readline library we’re using for the shell UI is intended for interactive use, you will need to switch to a traditional input reading function such as
getline when operating in scripting mode.
When implementing scripting mode, you will likely need to close
stdin on the child process if your call to
exec() fails. This prevents infinite loops.
Built-In Commands
Most shells have built-in commands, including
cd and
exit. Your shell must support:
cdto change the CWD.
cdwithout arguments should return to the user’s home directory.
#will be ignored by the shell
history, which prints the last 100 commands entered with their command numbers
!(history execution): entering
!39will re-run command number 39, and
!!re-runs the last command that was entered.
!lsre-runs the last command that starts with ‘ls.’ Note that command numbers are NOT the same as the array positions; e.g., you may have 100 history elements, with command numbers 600 – 699.
jobsto list currently-running background jobs.
exitto exit the shell.
Signal Handling
Your shell should gracefully handle the user pressing Ctrl+C:
╭─[🙂]─[11]─[mmalensek@glitter-sparkle:~] ╰─╼ hi there oh wait nevermind sleep 100 ^C ╭─[🤮]─[12]─[mmalensek@glitter-sparkle:~] ╰─╼ sleep 5
The most important aspect of this is making sure
^C doesn’t terminate your shell. To make the output look like the example above, in your signal handler you can (1) print a newline character, (2) print the prompt only if no command is currently executing, and (3)
fflush(stdout).
History
Here’s a demonstration of the
history command:
╭─[🙂]─[142]─[mmalensek@glitter-sparkle:~] ╰─╼ history 43 ls -l 43 top 44 echo "hi" # This prints out 'hi' ... (commands removed for brevity) ... 140 ls /bin 141 gcc -g crash.c 142 history
In this demo, the user has entered 142 commands. Only the last 100 are kept, so the list starts at command 43. If the user enters a blank command, it should not be shown in the history or increment the command counter.
Redirection
Your shell must support file output redirection and pipe redirection:
# Create/overwrite 'my_file.txt' and redirect the output of echo there: ╭─[🙂]─[14]─[mmalensek@glitter-sparkle:~] ╰─╼ echo "hello world!" > my_file.txt # Pipe redirection: ╭─[🙂]─[15]─[mmalensek@glitter-sparkle:~] ╰─╼ cat other_file.txt | sort (contents shown) ╭─[🙂]─[16]─[mmalensek@glitter-sparkle:~] ╰─╼ seq 100000 | wc -l 10000 ╭─[🙂]─[17]─[mmalensek@glitter-sparkle:~] ╰─╼ cat /etc/passwd | sort > sorted_pwd.txt (contents shown)
Use
pipe and
dup2 to achieve this. Your implementation should support arbitrary numbers of pipes, but you only need to support one file redirection per command line (i.e., a
> in the middle of a pipeline is not something you need to consider).
Background Jobs
If a command ends in
&, then it should run in the background. In other words, don’t wait for the command to finish before prompting for the next command. If you enter
jobs, your shell should print out a list of currently-running backgrounded processes (use the original command line as it was entered, including the
& character). The status of background jobs is not shown in the prompt.
To implement this, you will need:
- A signal handler for
SIGCHLD. This signal is sent to a process any time one of its children exit.
- A non-blocking call to
waitpidin your signal handler. Pass in
pid = -1and
options = WNOHANG.
The difference between a background job and a regular job is simply whether or not a blocking call to
waitpid() is performed. If you do a standard
waitpid() with
options = 0, then the job will run in the foreground and the shell won’t prompt for a new command until the child finishes (the usual case). Otherwise, the process will run and the shell will prompt for the next command without waiting.
Each background process should be stored in a job array, with a maximum of 10 background jobs. NOTE: your shell prompt output may print in the wrong place when using background jobs. This is completely normal.
Incremental History Search
When the user presses the ‘up’ arrow key on the keyboard, display the most recent history entry. If the user continues to press ‘up’, they should be able to scroll through each history entry in reverse chronological order. Pressing ‘down’ navigates back toward the most recently-entered command in the history, ending back at the start (a blank line).
If the user enters a string prefix, e.g., ‘ec’ before pressing the ‘up’ arrow, only show history entries that begin with ‘ec.’ For instance, these might include various invocations of the ‘echo’ command. The ‘down’ key works similarly in this case. If the user edits any of the displayed history entries, start the process over again – in other words, if one of the history entries was
echo hello and the user changes the command line to read
echo helloworld then the history search is reset and pressing up will begin searching for ‘echo helloworld’ as the prefix instead.
You can use the
rl_line_buffer variable to determine what the user has entered – this is a global variable defined in the readline library.
Tab Completion
When the user presses the tab key, autocomplete their command. Search in this order:
- Each executable entry in the user’s
$PATH
- The built-in commands your shell supports
- Local files in the current working directory
Luckily the
readline library we’re using provides support for local files as a fallback mechanism.
Hints
Here’s some hints to guide your implementation:
execvpwill use the PATH environment variable (already set up by your default shell) to find executable programs. You don’t need to worry about setting up the PATH yourself.
getlogin,
gethostname, and
getpwuidfunctions for constructing your prompt.
- Don’t use
getwdto determine the CWD – it is deprecated on Linux. Use
getcwdinstead.
- For the
cdcommand, use the
chdirsyscall.
- To replace the user home directory with
~, the
strstrfunction may be useful. Some creative manipulation of character arrays and pointer arithmetic can save you some work.
Testing Your Code
Check your code against the provided test cases. You should make sure your code runs on your Arch Linux VM. We’ll have interactive grading for projects, where you will demonstrate program functionality and walk through your logic.
Submission: submit via GitHub by checking in your code before the project deadline.
Grading
- 25 pts - Rubric coming soon!
- 5 pts - Code review:
- Prompt, UI, and general interactive functionality. We’ll run your shell to test this with a few commands.
- Code quality and stylistic consistency
- Functions, structs, etc. must have documentation in Doxygen format (similar to Javadoc). Describe inputs, outputs, and the purpose of each function. NOTE: this is included in the test cases, but we will also look through your documentation.
- No dead, leftover, or unnecessary code.
- You must include a README.md file that describes your program, how it works, how to build it, and any other relevant details. You’ll be happy you did this later if/when your revisit the codebase. Here is an example README.md file.
Restrictions: you may use any standard C library functionality. Other than
readline, external libraries are not allowed unless permission is granted in advance (including the GNU
history library). Your shell may not call another shell (e.g., running commands via the
system function or executing
bash,
sh, etc.). Do not use
strtok to tokenize input. Your code must compile and run on your VM set up with Arch Linux as described in class. Failure to follow these guidelines will will result in a grade of 0.
Changelog
- Added note about
rl_line_buffer(3/20)
- Added a note about the
&in the jobs listing (3/20)
- Updated starting history index: 1 (3/20)
- Added note about
getlinein scripting mode (3/5)
- Initial project specification posted (10/1) | https://www.cs.usfca.edu/~mmalensek/cs326/assignments/project-2.html | CC-MAIN-2020-16 | refinedweb | 2,009 | 64.41 |
Description.
Tz alternatives and similar packages
Based on the "Date and Time" category.
Alternatively, view Tz alternatives based on common mentions on social networks and blogs.
timex9.8 7.8 Tz VS timexA complete date/time library for Elixir projects.
calendar8.8 0.0 Tz VS calendardate-time and time zone handling in Elixir
tzdata8.2 3.0 Tz VS tzdatatzdata for Elixir. Born from the Calendar library.
filtrex7.5 0.0 Tz VS filtrexA library for performing and validating complex filters from a client (e.g. smart filters)
Cocktail7.3 6.6 Tz VS CocktailElixir date recurrence library based on iCalendar events
chronos6.6 0.0 Tz VS chronosAn elixir date/time library
Crontab6.6 1.5 Tz VS CrontabParse Cron Expressions, Compose Cron Expression Strings and Caluclate Execution Dates.
repeatex4.9 0.0 Tz VS repeatexNatural language for repeating dates
good_times4.9 0.0 Tz VS good_timesExpressive and easy to use datetime functions in Elixir.
ex_ical4.8 0.0 Tz VS ex_icalICalendar parser for Elixir.
Ex_Cldr_Dates_Times4.8 6.7 Tz VS Ex_Cldr_Dates_TimesDate & times formatting functions for the Common Locale Data Repository (CLDR) package
open_hours4.0 0.0 Tz VS open_hoursTime calculations using business hours
moment3.7 0.0 Tz VS momentMoment is designed to bring easy date and time handling to Elixir.
jalaali3.5 6.4 Tz VS jalaaliA Jalaali (Jalali, Persian, Khorshidi, Shamsi) calendar system implemention for Elixir
tiktak2.9 0.0 Tz VS tiktakFast and lightweight web scheduler
timex_interval2.4 0.0 Tz VS timex_intervalA date/time interval library for Elixir projects, based on Timex.
timelier1.9 0.0 Tz VS timelierA cron-style scheduler application for Elixir.
block_timer1.9 0.0 Tz VS block_timerMacros to use :timer.apply_after and :timer.apply_interval with a block
calendarific1.8 2.7 Tz VS calendarificAn Elixir wrapper for the holiday API Calendarific
emojiclock1.0 0.0 Tz VS emojiclockAn Elixir module for returning an emoji clock for a given hour
milliseconds0.5 0.0 Tz VS millisecondsSimple library to work with milliseconds
japan_municipality_key0.5 0.0 Tz VS japan_municipality_keyElixir Library for Japan municipality key converting
Calixir0.4 0.0 Tz VS CalixirCalixir is a port of the Lisp calendar software calendrica-4.0 to Elixir.
Calendars0.2 0.0 Tz VS CalendarsCalendar Collection based on Calixir
Do you think we are missing an alternative of Tz or a related project?
Popular Comparisons
README
Tz.
Features
Battle-tested
The
tz library is tested against nearly 10 million past dates, which includes most of all possible imaginable
edge cases.
Pre-compiled time zone data
Time zone periods are deducted from the IANA time zone data. A period is a period of time where a certain offset is observed. Example: in Belgium, from 31 March 2019 until 27 October 2019, clock went forward by 1 hour; this means that during this period, Belgium observed a total offset of 2 hours from UTC time.
The time zone periods are computed and made available in Elixir maps during compilation time, to be consumed by the DateTime module.
Automatic time zone data updates
tz can watch for IANA time zone database updates and automatically recompile the time zone periods.
To enable automatic updates, add
Tz.UpdatePeriodically as a child in your supervisor:
{Tz.UpdatePeriodically, []}
If you do not wish to update automatically, but still wish to be alerted for new upcoming IANA updates, add
Tz.WatchPeriodically as a child in your supervisor:
{Tz.WatchPeriodically, []}
This will simply log to your server when a new time zone database is available.
Lastly, add the http client
mint and ssl certificate store
castore into your
mix.exs file:
defp deps do [ {:castore, "~> 0.1.5"}, {:mint, "~> 1.0"}, {:tz, "~> 0.10.0"} ] end
Usage
To use the
tz database, either configure it via configuration:
config :elixir, :time_zone_database, Tz.TimeZoneDatabase
or by calling
Calendar.put_time_zone_database/1:
Calendar.put_time_zone_database(Tz.TimeZoneDatabase)
or by passing the module name
Tz.TimeZoneDatabase directly to the functions that need a time zone database:
DateTime.now("America/Sao_Paulo", Tz.TimeZoneDatabase)
Refer to the DateTime API for more details about handling datetimes with time zones.
Performance tweaks
tz provides two environment options to tweak performance.
You can decrease compilation time, by rejecting time zone periods before a given year:
config :tz, reject_time_zone_periods_before_year: 2010
By default, no periods are rejected.
For time zones that have ongoing DST changes, period lookups for dates far in the future will result in periods being dynamically computed based on the IANA data. For example, what is the period for 20 March 2040 for New York (let's assume that the last rules for New York still mention an ongoing DST change as you read this)? We can't compile periods indefinitely in the future; by default, such periods are computed until 5 years from compilation time. Dynamic period computations is a slow operation.
You can decrease period lookup time for such periods lookups, by specifying until what year those periods have to be computed:
config :tz, build_time_zone_periods_with_ongoing_dst_changes_until_year: 20 + NaiveDateTime.utc_now().year
Note that increasing the year will also slightly increase compilation time, as it will generate more periods to compile.
Installation
Add
tz for Elixir as a dependency in your
mix.exs file:
def deps do [ {:tz, "~> 0.10.0"} ] end
HexDocs
HexDocs documentation can be found at. | https://elixir.libhunt.com/tz-alternatives | CC-MAIN-2021-43 | refinedweb | 877 | 50.33 |
The Book of VB .NET: Migrating to Visual Basic .NET, Part 2
Common Migration Problems
In this section, we'll examine some of the problems that can derail .NET migration. If you can find these problems in your own Visual Basic 6 applications, it may be a good idea to fix them within that environment before migrating the project-or call off the migration process altogether.
TIP If you're still developing projects in Visual Basic 6, the information in this section will help you make choices that will facilitate migration in the future.
Arrays
Arrays can thwart any attempt at migration. Visual Basic .NET's new insistence that every array have a lower boundary of zero can cause all sorts of trouble. In our original VB6OrderMaker project, array indexes are chosen with specific meanings. For example, the elements 1 and greater are used to contain the items in an order. Element 0 contains a combined line with price totals, and negative array indexes are used to contain licensing information for the ordered items. Even though these specific array indexes are stored in variables instead of being hard-coded, updating them to comply with the zero-boundary requirement would not be easy, and would requires hours of modification and retesting. Some early Microsoft documents promised that the Upgrade Wizard would create special array classes that will mimic normal arrays and allow any lower boundary that you need. This flexibility never materialized in the beta or release versions, and it's uncertain whether or not the new array classes would help at all, or just complicate life even more.
However, it's fairly easy to create a Visual Basic 6 program that won't suffer from this array problem. The best choice is not to use zero-bounded arrays at all, but to move straight to collections or other custom classes. In our VB6OrderMaker application, the Visual Basic 6 code would be clearer and more elegant if orders were stored in an Order class that contained a collection of ordered items as a property (for example, Order.Items), and any other required license-specific properties. This class could also contain built- in methods for retrieving the total cost of all ordered items, and for converting prices to different currencies. The Order class approach would improve encapsulation, and would result in a data structure that doesn't depend on miscellaneous conversion and helper functions in other modules of the program.
Variants
Variants are a special Visual Basic 6 data type that can store different types of information, including strings or numbers. A variant converts itself automatically according to how you try to use it. Historically, this automatic conversion led to a variety of annoyances, although it was useful in some situations.
In Visual Basic .NET, variants aren't supported, but the System.Object type provides the same flexibility. If Option Strict is disabled for your application (as it is by default when you are migrating a project), you can use the generic object type in almost the exact same way as you would variants, with the same automatic conversion feature. If Option Strict is enabled, you need to convert object types manually when performing operations with them. This is explained in Chapter 7 of The Book of VB .NET, but a quick review is helpful:
Dim x As Object, y As Object, z As Object x = 1 y = 2 z = x + y ' Will only work in Option Strict is off. z = CType(x, Integer) + CType(y, Integer) ' Always works without a hitch.
The Upgrade Wizard will convert all variants into generic objects. After a typical migration, you may find yourself with many more generic objects than you expected. The problem is that even though variants are rarely used deliberately in VB 6 code, variables could be inadvertently defined without data types, as shown here:
' VB 6 code. Dim intA, intB As Integer ' intB is an Interger, but intA will be a variant.
This oversight, which occurs most often when simple counters and other unimportant temporary variables are defined, causes Visual Basic 6 to use its default data type, which is the variant. During the migration of the VB6Order- Maker program into .NET format, many unspecified counter variables ended up as objects. The Upgrade Wizard flagged every subsequent line of code that performs any operations with these variables, indicating that it can't determine the default properties for those objects:
Dim intA As Integer, intB As Object intA = 0
' UPGRADE_WARNING: Couldn't resolve default property of object intB. ' Click for more: ms-help://MS.MSDNVS/vbcon/html/vbup1037.htm intB = 0
This minor issue isn't a problem-in fact, this portion of the code will still work perfectly. However, this idiosyncrasy led to a large number of additional warnings in the VB6OrderMaker upgrade report.
Default Properties
Why is the Upgrade Wizard so aggressive in flagging the unstructured use of an object? In VB6OrderMaker, these objects really represent simple value types, and the default value is automatically available as long as Option Strict is Off. However, this type of operation could create a problem in other circumstances.
In .NET, standard default properties aren't supported, and attempts to use an object's default property will fail. Usually, the Upgrade Wizard will add the necessary information to qualify a default property (for example, change txtBox = "Text" to txtBox.Text = "Text"). However, when you have a mysterious late-bound type that's defined only as an object, this trick fails. For example, if x, y, and z were real objects with numerous properties (such as x.Value), the statement z = x + y wouldn't work. Visual Basic .NET would have no way of knowing what properties to use for this calculation.
The solution to this problem is simple. When programming in Visual Basic 6, be careful to always define data types. Also, don't use late-bound objects. Not only are they slower, because VB has to inspect them before they are used, but they may lead to migration headaches.
Load Statement
In Visual Basic 6, you could use the Load statement to create a form without displaying it:
' VB 6 code. Load frmMain
In Visual Basic .NET you can accomplish the same sort of thing by creating an instance of your form class, but not displaying it.
Dim frm As New frmMain()
Both of these techniques allow you to pre-configure the form and its controls before displaying the form. In VB6OrderMaker, Load statements are used extensively to provide Wizards that automatically load other forms, use their objects and procedures to calculate totals and create order items, and then unload them. This approach is well organized, but not nearly as efficient or easy to use as a real class- based design. It also leads to migration errors, because the Load statement is not automatically upgraded.
There is at least one easy way to replace the Load statement in a migrated project:
frmMain.DefInstance
This code initializes the form and makes it available through the shared DefInstance property.
Printing
The Upgrade Wizard is not able to update printing code. During the migration of VB6OrderMaker, the code used to select the printer, configure device settings, and output an order was flagged with error messages. The only way to resolve such problems is to rewrite the code for the new PrintDocument object in the .NET class library. If you've spent hours generating custom formatted output in your original application, you will not enjoy the migration process.
The Clipboard
Code that interacts with the Windows clipboard will also fail to work after a migration. Once again, the Upgrade Wizard leaves the hard work to you, and you need to rewrite the code with the .NET equivalent. In VB6OrderMaker, the clipboard was used to transfer information into the RichText control for a preview. Clearly, a better approach is to use .NET's new PrintPreview control. Unfortunately, there's no migration path between the two. If you are still working on a VB 6 project, you have no easy way to use print preview features similar to those available in VB .NET, and you will have to resort to third-party components or nontraditional approaches, such as those found in VB6OrderMaker. In .NET, however, there's really no reason not to use the bundled PrintPreview control.
Context-Sensitive Help
The HelpContextID property is not supported in Visual Basic .NET. If you want to create context-sensitive help, you'll need to use the HelpProvider control, which was discussed in Chapter 4 of The Book of VB .NET. This control provides a number of minor enhancements, but once again, the Upgrade Wizard won't help you make the coding changes. Any program-VB6OrderMaker, for instance-that makes significant use of context-sensitive help will need at least some rewriting.
Menu Controls
In Visual Basic .NET, you can't use the same menu component for an application (pull-down) menu and a context menu. In Visual Basic 6, you had to create a pull-down menu before you could use it in a context menu. Microsoft schizophrenia once again?
The VB 6 code used to display a context menu looked like this:
' VB 6 code. Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, _ Y As Single) If Button = 2 Then PopupMenu mnuOrderOptions End If End Sub
When importing a project that uses context menus, the Upgrade Wizard leaves the PopUpMenu command in its original state, and flags it as an error. Before you can make it work, you have to create a new ContextMenu object. Then, you have to copy the ordinary menu information into the ContextMenu:
Dim mnuPopUp As New ContextMenu() Dim mnuItem As MenuItem
For Each mnuItem In mnuOrderOptions.MenuItems ' The CloneMenu method ensures that the context menu and main menu items ' have the same event handlers. mnuPopUp.MenuItems.Add(mnuItem.CloneMenu()) Next
Me.ContextMenu = mnuPopUp
The last line here assigns the new context menu to the form's ContextMenu property. The only reason you should do this is to make sure that a reference to the context menu is conveniently available when you need it-for example, in the form's event handler for a MouseDown event. Because the current form is always available through the Me keyword, it provides a convenient place to attach the ContextMenu reference.
The code for displaying a context menu in VB .NET is similar to that used in VB 6, but not exactly the same:
Private Sub Form1_MouseDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown If e.Button = MouseButtons.Right Then Me.ContextMenu.Show(Me, New Point(e.X, e.Y)) End If End Sub
The best way to manage your context menus, and the best time to create them, are up to you. Once again, the Upgrade Wizard won't offer any help beyond identifying the problem.
Control Arrays
Control arrays present a particularly unpleasant example of what can go wrong with migration. In Visual Basic 6, control arrays were often the best way to solve problems. With a control array, numerous similar controls are placed into an array. In VB6OrderMaker, control arrays allow the program to loop through a series of controls and update them based on array information. For example, you can copy pricing information into a series of text boxes using this syntax:
' VB 6 code. For i = 0 to UBound(PriceArray) txtPrice(i).Text = Val(PriceArray(i) Next i
In .NET, this approach can be replaced in various different incompatible ways, including data binding, new list controls, or collection classes. Control arrays, however, aren't supported.
Control arrays also allowed a program to use a single event handler for numerous similar controls, which was an extremely useful convenience. For example, you could implement a set of dynamically highlighting labels, like this:
' VB 6 code. Private Sub Description_MouseMove(Index As Integer, Button As Integer, _ Shift As Integer, X As Single, Y As Single) Description(Index).ForeColor = &H800000 End Sub
In .NET, control arrays aren't needed to handle multiple events. Instead, you can use the Handles clause or the AddHandler statement to link up as many controls as you want to a single event handler. You can then use the sender parameter to interact with the control that fires the event, as discussed in Chapter 4 of The Book of VB .NET.
Private Sub Highlight(ByVal sender As Object, ByVal e As MouseEventArgs) _ Handles lblLine1.MouseMove, lblLine2.MouseMove ' You can add more events to the Handles list, ' or use the AddHandler statement instead. Dim lbl As Label = CType(sender, Label) lbl.ForeColor = Color.RoyalBlue End Sub
To summarize: Control arrays were a quirky if useful tool in VB 6, but they have been replaced with a more modern system in VB .NET. However, if you import a program such as VB6OrderMaker that uses control arrays, the Upgrade Wizard doesn't convert them. Instead, it uses a special compatibility class, depending on your control. For example, if you have a control array of label controls, you'll end up using Microsoft.VisualBasic.Compatibility.VB6. LabelArray. This control allows VB .NET to "fake" a control array, with predictably inelegant results.
This is an example of the Upgrade Wizard at its worst: importing legacy problems from VB 6 into the .NET world. There's no easy way to design around it in VB 6, since control arrays are often a good design approach in that environment. Unfortunately, this is one of the Upgrade Wizard's fundamental limitations.
Automatic Re-initialization
In Visual Basic 6, if you defined an object with the New keyword, it had the strange ability to automatically recreate itself:
' VB 6 code. Dim objPerson As New Person Person.Name = "John" Person = Nothing ' The Person object is destroyed. Person.Name = "John" ' At this point, an empty Person object is reinitialized.
This was generally not what programmers expected, and it led to quirky errors and memory waste. In Visual Basic .NET, the New keyword simply allocates space for the object; it does not cause any unusual re- initializing behavior.
If you've made use of this trick, either deliberately or unwittingly in VB 6, the code won't work in .NET. When you try to use the destroyed object, you will receive a null reference error. You'll have to rewrite the preceding example like this:
Dim objPerson As New Person() Person.Name = "John" Person = Nothing ' The Person object is destroyed.
Person = New Person() Person.Name = "John"
Re- initialization may be a minor detail, but it's also one more potential migration headache, particularly if the project you want to import has not been created using best practices.
GDI
Visual Basic 6 had built in methods for drawing circles and other shapes directly onto a form. In Visual Basic .NET, these graphical routines have been enhanced and replaced by the GDI+ library, which you can access through the System.Drawing namespaces. Once again, any original code you may have written will need to be scrapped. This includes palette management, which VB6OrderMaker used to ensure that the splash screen is displayed properly on older 256-color monitors.
Class_Terminate Code
In Visual Basic 6, you might have used the Terminate event to perform automatic cleanup tasks, such as closing a database connection or deleting a temporary file. In Visual Basic .NET, this technique is a guaranteed to cause problems, because the .NET framework uses non-deterministic garbage collection.
Garbage collection in VB .NET works in much the same way that garbage collection works in many actual communities. In most neighborhoods, residents can pinpoint the time that garbage is placed into the appropriate receptacle, but they really have no idea when someone will be motivated to take it out. Similarly, in .NET garbage collection may be put off until the system is idle, and can't be relied upon to release limited resources. You might find other surprises if you use the Terminate event to try and interact with other forms in your application. Generally, these techniques won't work in VB .NET.
As with control arrays, a substantial difference in programming philosophies underlies this problem. In Visual Basic 6, using the Terminate method was a useful approach to making sure that cleanup was always performed the moment the class was released. In Visual Basic .NET, you are better off adding a Dispose method, and relying on the programmer to call this method after using an object and just before destroying it. The Upgrade Wizard tries to encourage this change: It places code from the Terminate event into a new, separate method so that you can easily call it when needed. It also overrides the Finalize method and adds a call to the new method to ensure that cleanup is performed:
Public Sub Class_Terminate_Renamed() ' Code goes here. End Sub
Protected Overrides Sub Finalize() Class_Terminate_Renamed() MyBase.Finalize() End Sub
This a good start, but you would be better off putting the code in a method called Dispose (rather than Class_Terminate_Renamed, as the Upgrade Wizard uses in our example). You'll also still need to modify the code that uses the class, because you'll want to make sure that it calls the Dispose method before destroying the object.
VarPtr, StrPtr, ObjPtr
These undocumented functions have traditionally been used by Visual Basic experts to find the memory addresses where variables or objects were stored. These functions allowed addresses to be passed to a DLL routine or to the Windows API, which sometimes required this information. In Visual Basic .NET, you hopefully won't need to have this kind of low-level access to memory information, as it complicates programs and can introduce obscure bugs. If, however, you need to interact with a DLL or code component that needs an address, you can still retrieve it-but you need to "pin down" the memory first. Pinning down the memory ensures that the Common Language Runtime won't try to move a value between the time when you find its address and the time when the DLL tries to use it. (This automatic movement feature is one of the ways by which the .NET runtime attempts to improve performance.)
The following example creates and pins down a handle for an object called MyObj. It uses a special type called GCHandle in the System.Runtime. InteropServices namespace:
' You will need to import the namespace shown below to use this code as written. ' Imports System.Runtime.InteropServices
Dim MyGCHandle As GCHandle = GCHandle.Alloc(MyObj, GCHandleType.Pinned) Dim Address As IntPtr = MyGCHandle.AddrOfPinnedObject() ' (Invoke the DLL or do something with the Address variable here.)
' Allow the object to be moved again. MyGCHandle.Free()
Of course, the coding you use is up to you, but be aware that the Upgrade Wizard will simply place an error flag if it finds the unsupported VarPtr, StrPtr, or ObjPtr function.
Memory Storage for User-Defined Types
In Visual Basic 6, you could assume that user-defined types represented a contiguous block of memory. This is not true for the .NET equivalent, structures, which use a more efficient allocation of space. This change only has an effect if you are using low-level DLLs or COM components (for instance, a legacy database that expects data to be passed as a block of memory). To resolve this issues, you'll have to delve into some of .NET's advanced data type marshalling features, which are beyond the scope of this book, but detailed in the MSDN class library reference under the System.Runtime.InteropServices namespace.
Optional Parameters
Optional parameters in VB .NET require default values, as explained in Chapter 3 of The Book of VB .NET. This is a relatively painless change. However, one consequence is that you can't rely on IsMissing to tell if a value has been submitted (although you can check for your default value or use IsNothing, which is the Upgrade Wizard's automatic change). Keep in mind that overloaded functions often yield better .NET options than do optional values.
Goto and Gosub
Support for these statements was scaled down in early beta versions of VB .NET, but has been added back for the final release. But even though you can doesn't mean you should! Goto and Gosub are archaic programming concepts, and using them is a direct road to programming nightmares. It's a surprise that they remained all the way through Visual Basic 6, let alone made the jump to the .NET world.
Other New Behaviors
"New behavior" is the term that the Upgrade Wizard uses in its upgrade report when it makes a change from one property or method to another that is similar, but not identical. In many cases, this warning just represents an improvement to a control. In other situations, it may represent a deeper problem that requires significant reworking.
Most experienced Visual Basic developers have spent significant time learning their favorite controls, and know how to exploit all the associated quirks and idiosyncrasies. This poses a problem for migration, where optimized code might not work at all (or worse, might appear to work, but will then cause problems under unusual future circumstances).
NOTE This issue raises a larger question. Namely, when is it safe to migrate a project? Even if the process appears to succeed, you will need hours of testing to verify its success before you can trust the updated application enough to release it into a production environment.
Preparing for VB .NET
Are the migration features in Visual Basic .NET impressive or depressing? It really depends on how you look at it. Certainly, they represent a minor technological feat. At the same time, many developers argue that they are useless for using real VB 6 applications in the .NET environment. Even if you can import a project, the result may be a rather ugly mess of old concepts, dressed up with workarounds added by the Upgrade Wizard. This kind of application can be difficult to work with and enhance, thus defeating the purpose of migration.
If you're working on a Visual Basic 6 project today, your best choice is to make rigorous use of class-based designs. If you take this protective step, then even if you can't import an entire project into .NET, you will at least be able to import or recreate all of your business objects and data classes. Generally, data classes are much easier to import than other components, because they don't use such VB 6-specific features as file or printer access, and they don't directly create user interface or require forms support. You can then import your business objects, add a new .NET user interface tier (taking advantage of the latest features in Windows Forms), and add lower-level data access components, if necessary, to support ADO.NET or .NET file access through streams. The ability to upgrade is one of the remarkable benefits of a structured three-tier design. The more you can break your application down into functional units, the better chance you'll have to reuse at least some of its elements in the .NET environment.
What Comes Next?
This article has shown both the beauty and the ugliness of backward compatibility. Visual Basic .NET is at its most elegant when dealing with COM interoperability, allowing you to work with most components and even drop ActiveX controls into your application without a second thought. However, the picture sours if you need to import an average, mid-sized Visual Basic project, which is almost guaranteed to crumble in the face of numerous incompatibilities.
As always, remember that just because a program is created in an older version of Visual Basic it does not mean it needs to be brought to .NET. These "legacy" programs will be supported on the Windows platform for years to come. Conversely, just because an ActiveX control can be inserted into your project doesn't mean that you can't reap more benefits by trying to achieve the same effect using the class library. However, you're likely to have at least some third-party ActiveX controls that you don't want to abandon in certain situations. Remember to consider the tradeoff-if converting to .NET requires that you import dozens of COM components, then you may be better off maintaining your program in unmanaged Visual Basic 6.
If you are a COM guru (or are planning to become one), you will probably want to explore .NET's advanced COM support features. These include tools for handling COM interoperability on your own, such as the System.Windows. Forms.AxHost class and the types in the System.Runtime.InteropServices. Be forewarned: Unless you are a war-hardened COM veteran, you won't be able to do much with these namespaces that you can't do even better with the automatic wrapper class generation features in Visual Studio .NET.
).
| http://www.developer.com/net/vb/article.php/1007901/The-Book-of-VB-NET-Migrating-to-Visual-Basic-NET-Part-2.htm | CC-MAIN-2016-40 | refinedweb | 4,157 | 54.63 |
Check internet connection in PHP
In this article, we will discuss various methods in PHP to check the internet is present or not. We are going to create the scripts using predefined as well as user-defined methods to check internet connection in PHP.
How to check internet connection in PHP with predefined methods?
PHP offers a predefined method known as connection_status() that returns the state of the internet connection such as-
- CONNECTION_NORMAL
- CONNECTION_ABORTED
- CONNECTION_TIMEOUT etc.
Let us create the script using connection_status() method,
<?php //Checking internet connection status with predefined function switch (connection_status()) { case CONNECTION_NORMAL: $msg = 'You are connected to internet.'; break; case CONNECTION_ABORTED: $msg = 'No Internet connection'; break; case CONNECTION_TIMEOUT: $msg = 'Connection time-out'; break; case (CONNECTION_ABORTED & CONNECTION_TIMEOUT): $msg = 'No Internet and Connection time-out'; break; default: $msg = 'Undefined state'; break; } //display connection status echo $msg; ?>
Output:-
You are connected to internet.
How to check internet connection with user-defined methods?
This is the less effective way than the predefined methods and it involves the methods that use the ping methods to determine whether the internet connection is available or not. It usually tries to access a website and decide the status of the internet on the basis of that.
Let us create a PHP script using @fsockopen () method,
<?php //userdefined function for checking internet function check_internet($domain) { $file = @fsockopen ($domain, 80);//@fsockopen is used to connect to a socket return ($file); } //test with a website $domain=""; //verify whether the internet is working or not if (check_internet($domain)) { echo "You are connected to the internet."; } else { echo "You seem to be offline. Please check your internet connection."; } ?>
Output:-
You are connected to the internet.
Let us create another PHP script using @fopen() method,
<?php //checking connection with @fopen if ( @fopen("", "r") ) { print "You are connected to the internet."; } else { print "You seem to be offline. Please check your internet connection."; } ?>
Output:-
You are connected to the internet.
In the above ways, we can determine whether the internet connection is available or not usning PHP. If you have any doubt comment below.
See also,
I tried to use this code but when I try to open the page without internet connection. It says, no internet | https://www.codespeedy.com/check-internet-connection-in-php/ | CC-MAIN-2020-40 | refinedweb | 366 | 56.86 |
How to clean the save path if IsEmpty is FALSE
On 21/11/2015 at 13:04, xxxxxxxx wrote:
User Information:
Cinema 4D Version: 16
Platform: Windows ;
Language(s) : C.O.F.F.E.E ;
---------
Hello guys, I'm not a programmer but I like to try creating small solutions for my day to day.
I have wrote this script in COFFEE in order to quickly adjust some parameters in Render Settings. It's working fine but I wanted to improve it.
I wanted to automatically clear the save path if the condition IsEmpty was FALSE.
The solution I found was a popup requesting to user do it manually.
Anyone knows how can I do it (clear the save path)?
Thanks
Below, the C.O.F.F.E.E. script:
// Activate Save Image
if (renderdata()#RDATA_SAVEIMAGE=FALSE)
return NULL;
else(renderdata()#RDATA_SAVEIMAGE=TRUE);
var save_path=renderdata()#RDATA_PATH; // Store the currently save path
var file_name=doc->GetFilename()->GetLastString(); // Capture the name of c4d project
if (save_path->IsEmpty())
{
save_path->AddLast(file_name); // Add the c4d project name to save path
save_path->DelSuffix(); // Remove .c4d extension
renderdata()#RDATA_PATH=save_path; // Load it in the Save field
// Avoid duplicated name
// save_path->RemoveLast();
// renderdata()#RDATA_PATH=save_path;
renderdata()#RDATA_XRES_VIRTUAL=800; // Width
renderdata()#RDATA_YRES_VIRTUAL=600; // Height
renderdata()#RDATA_FORMAT=1104; // JPG format
CallCommand(12099); // Render to Picture Viewer
}
else
{
CallCommand(12161); // Edit Render Settings...
TextDialog("Clear the save path!", GEMB_OK);
}
On 21/11/2015 at 13:29, xxxxxxxx wrote:
Construct a new (and therefore empty) Filename object and assign that:
var f = new(Filename); renderdata()#RDATA_PATH = f;
On 21/11/2015 at 14:13, xxxxxxxx wrote:
Thanks a lot Cairyn!
It worked...
My new code:
if (renderdata()#RDATA_SAVEIMAGE=FALSE)
return NULL;
else(renderdata()#RDATA_SAVEIMAGE=TRUE);
var save_path;
var file_name=doc->GetFilename()->GetLastString();
var empty=new(Filename);
renderdata()#RDATA_PATH = empty;
save_path=renderdata()#RDATA_PATH;
save_path->AddLast(file_name);
save_path->DelSuffix();
renderdata()#RDATA_PATH=save_path;
renderdata()#RDATA_XRES_VIRTUAL=800;
renderdata()#RDATA_YRES_VIRTUAL=600;
renderdata()#RDATA_FORMAT=1104;
CallCommand(12099);
On 21/11/2015 at 14:54, xxxxxxxx wrote:
Good that it works for you. Mind if I ask?:
1. What is this code supposed to mean?
if (renderdata()#RDATA_SAVEIMAGE=FALSE) return NULL; else(renderdata()#RDATA_SAVEIMAGE=TRUE);
From the formatting, it looks as if you try to put a condition behind the "else". However, it's actually a command that sets the SAVEIMAGE value to TRUE. An "else" does not have a condition.
In this case it doesn't hurt, because the assignment is just setting the value of SAVEIMAGE to the same it already has (because the "if" has this value in the condition), but it doesn't do anything useful either.
2. You are doing a lot of assignments that are fairly pointless with the path, first setting the RDATA_PATH to an empty filename, then assigning that to some other variable, then assigning it back to RDATA_PATH...
The whole code could be shorter:
if (renderdata()#RDATA_SAVEIMAGE=FALSE) return NULL; var file_name=doc->GetFilename()->GetLastString(); var save_path=new(Filename); save_path->AddLast(file_name); save_path->DelSuffix(); renderdata()#RDATA_PATH=save_path; renderdata()#RDATA_XRES_VIRTUAL=800; renderdata()#RDATA_YRES_VIRTUAL=600; renderdata()#RDATA_FORMAT=1104; CallCommand(12099);
(Disclaimer: I didn't test it but it should be equivalent.)
On 21/11/2015 at 17:09, xxxxxxxx wrote:
Thanks again Cairyn, for your attention.
Actually I'm Noob in COFFEE, and as I said I'm not a programmer. This code I have builded trying parts of codes, observing another scripts.
You helped me to understand that logical issue, about the use of the condition "if".
I have tried your last suggestion, but with no success.
And then, eliminating that condition, it worked fine, just using renderdata()#RDATA_SAVEIMAGE=TRUE;
Tks
On 21/11/2015 at 17:41, xxxxxxxx wrote:
The only problem with your 'if' statement is that in order to test you use == and not =, so:
if (renderdata()#RDATA_SAVEIMAGE==FALSE) return NULL;
That should also avoid the inevitable problem when you realize that the renders aren't being saved or ALWAYS being saved with your non-conditional setting. :)
On 21/11/2015 at 17:50, xxxxxxxx wrote:
For more information about the comparison options, in the COFFEE documentation, go to Tutorials->The C.O.F.F.E.E. Primer->C.O.F.F.E.E. Flow Control
On 21/11/2015 at 17:50, xxxxxxxx wrote:
If I use ==FALSE, nothing happens when the save are disabled :-(
Thanks
On 21/11/2015 at 17:51, xxxxxxxx wrote:
Thank you Robert!
On 22/11/2015 at 02:33, xxxxxxxx wrote:
Originally posted by xxxxxxxx
The only problem with your 'if' statement is that in order to test you use == and not =
Oops, I completely overlooked that! Teaches me to answer forum questions at midnight ;-)
On 22/11/2015 at 03:36, xxxxxxxx wrote:
Originally posted by xxxxxxxx
If I use ==FALSE, nothing happens when the save are disabled :-(
Thanks
Wasn't that intended? RDATA_SAVEIMAGE represents the checkbox inside of the "Save" tab. If it is unchecked, then you cannot enter a string into the "File..." field because it is also disabled, and an assignment to the RDATA_PATH doesn't work.
I thought you wanted to have exactly that behavior because you had that "if" condition at the beginning.
What you actually got with your code was the behavior "set the Save checkbox to TRUE every time" because of the "=="/"=" confusion in the original code. Let me explain:
if (renderdata()#RDATA_SAVEIMAGE=FALSE) return NULL; else(renderdata()#RDATA_SAVEIMAGE=TRUE);
What does this do? "renderdata()#RDATA_SAVEIMAGE=FALSE" is an assignment that sets the "Save" flag to FALSE. It is not a check whether the flag is currently FALSE (as Robert rightfully said, that would be "renderdata()#RDATA_SAVEIMAGE==FALSE"), but a brutal overwrite.
Assignments however also return a value (the assigned value) at the same time, which is the only reason why you can syntactically write an assignment into an "if" condition (and earn the curses of a million desperate students of C, C++, and COFFEE...).
So practically the "if" condition gets a constant (the FALSE which you assign), and NEVER executes the "return NULL" part. It always jumps into the "else" part.
The "else" part has again an assignment, to the same variable: "renderdata()#RDATA_SAVEIMAGE=TRUE". This sets your flag to TRUE (checks the checkbox), so now you always have the "Save" enabled and can overwrite the "File..." string.
The code snippet above essentially compresses to
renderdata()#RDATA_SAVEIMAGE=TRUE;
(and I really should have caught that the first time ;-) )
and the full function is
var file_name=doc->GetFilename()->GetLastString(); var save_path=new(Filename); save_path->AddLast(file_name); save_path->DelSuffix(); renderdata()#RDATA_SAVEIMAGE=TRUE; renderdata()#RDATA_PATH=save_path; renderdata()#RDATA_XRES_VIRTUAL=800; renderdata()#RDATA_YRES_VIRTUAL=600; renderdata()#RDATA_FORMAT=1104; CallCommand(12099);
No "if", no "else".
You still need to have the "Save" generally enabled (different checkbox in the Renderer pane) or else your "Save" setting in the Save pane and the filename will not be written.
Sadly I have no idea how to access that checkbox, so question to support would be: What is the correct way to set the checkboxes "Save", "Multi-Pass", "Stereoscopic", and "Material Override" in the RENDERSETTING_STATICTAB? Can't find that for C++ or Python either...
On 22/11/2015 at 06:56, xxxxxxxx wrote:
Yes, you are right, what I wanted was just always keep Save on.
I used the condition "if" and "else" by a lack of knowledge.
I appreciate your class, I'm still learning and it motivates me.
I have read in another post about the Save you mentioned. Another user told that all those options in the left column of Render Settings are not accessible by COFFEE, just by Python or C++.
But for the purpose that I thought, the code that you helped me to fix is perfect for now. I have 50 folders each one with a .c4d and tex and different settings, whose I want to build an index with thumbnails.
Would be better if I had the control over the left column, so I could disable any effects, like Global Illumination, before to rendering.
Thanks a lot!
Have a good day.
PS. I'm sorry for my english, it's not my default language ;-)
On 22/11/2015 at 09:15, xxxxxxxx wrote:
Ah, now I found them. The four IDs I missed are actually part of the RDATA_ enumeration type, and accessible through Python:
renderdata[c4d.RDATA_GLOBALSAVE] = True renderdata[c4d.RDATA_STEREO] = True renderdata[c4d.RDATA_MATERIAL_OVERRIDE] = True renderdata[c4d.RDATA_MULTIPASS_ENABLE] = True
They were a bit hard to identify since they are just listed with all the other RDATA_ ids. I seem to have looked into a different enumeration at first too ;-)
Anyway, if you would use Python instead of COFFEE, your script would look like this, including the leftmost "Save" checkbox:
import c4d from c4d import gui def main() : file_name = doc.GetDocumentName() renderdata = doc.GetActiveRenderData() posLastDot = file_name.rfind(".") if posLastDot <> -1: file_name = file_name[:posLastDot] renderdata[c4d.RDATA_GLOBALSAVE] = True renderdata[c4d.RDATA_SAVEIMAGE] = True renderdata[c4d.RDATA_PATH] = file_name renderdata[c4d.RDATA_XRES_VIRTUAL] = 800 renderdata[c4d.RDATA_YRES_VIRTUAL] = 600 renderdata[c4d.RDATA_FORMAT] = 1104 c4d.EventAdd() if __name__=='__main__': main()
If you are just starting with programming, I would actually recommend using Python in the first place. COFFEE seems to be a bit behind the times, and I would not really be surprised if Maxon declares it "legacy" one day.
On 22/11/2015 at 14:18, xxxxxxxx wrote:
woow thanks!
Nice work!
On 23/11/2015 at 01:32, xxxxxxxx wrote:
Hello,
if you are starting to learn a script language for Cinema 4D you might want to focus on Python since the Python API covers more areas of Cinema 4D and offers more functionality.
Best wishes,
Sebastian | https://plugincafe.maxon.net/topic/9226/12260_how-to-clean-the-save-path-if-isempty-is-false/10 | CC-MAIN-2020-24 | refinedweb | 1,599 | 54.02 |
______________________________________________________________________________
pkg_mkIndex − Build an index for automatic loading of packages
pkg_mkIndex ?−direct? ?−lazy? ?−load pkgPat? ?−verbose? dir ?pattern pattern ...? _________________________________________________________________
Pkg_mkIndex is a utility procedure that is part of the standard Tcl library. It is used to create index files that allow packages to be loaded automatically when package require commands are executed. To use pkg_mk_mk −load option or adjust the order in which pkg_mkIndex processes the files. See COMPLEX CASES below.
[3]
Install the package as a subdirectory of one of the directories given by the tcl_pkgPath variable. If $tcl_pkgPath contains more than one directory, machine-dependent packages (e.g., those that contain binary shared libraries) should normally be_pkgPath it will automatically be found during package require commands.
If you install the package anywhere else, then you must ensure that the directory containing the package is in the auto_path global variable or an immediate subdirectory of one of the directories in auto_path. Auto_path contains a list of directories that are searched by both the auto-loader and the package loader; by default it includes $tcl_pkgPath. The package loader also checks all of the subdirectories of the directories in auto_path. You can add a directory to auto_path explicitly in your application, or you can add the directory to your TCLLIBPATH environment variable: if this environment variable is present, Tcl initializes auto_path from it during application startup.
[4]
Once the above steps have been taken, all you need to do to use a package is to invoke package require. For example, if versions 2.1, 2.3, and 3.1 of package Test have been indexed by pkg_mkIndex, the command package require Test will make version 3.1 available and the command package require −exact different interpreters.
The optional switches are:
−direct
The generated index will implement direct loading of the package upon package require. This is the default.
−lazy
The generated index will manage to delay loading the package until the use of one of the commands provided by the package, instead of loading it immediately upon package require. This is not compatible with the use of auto_reset, and therefore its use is discouraged.
−load pkgPat
The index process will pre-load any packages that exist in the current interpreter and match pkgPat into the slave interpreter used to generate the index. The pattern match uses string match rules, but without making case distinctions. See COMPLEX CASES below.
−verbose
Generate output during the indexing process. Output is via the tclLog procedure, which by default prints to stderr.
−−
End of the flags, in case dir begins with a dash.. If the −lazy.
Some packages, for instance packages which use namespaces and export commands or those which require special initialization, might select that their package files be loaded immediately upon package require instead of delaying the actual loading to the first use of one of the package’s command. This is the default mode when generating the package index. It can be overridden by specifying the −lazy argument.
Most complex cases of dependencies among scripts and binary files, and packages being split among scripts and binary files are handled OK. However, you may have to adjust the order in which files are processed by pkg_mkIndex. These issues are described in detail below.
If each script or file contains one package, and packages are only contained in one file, then things are easy. You simply specify all files to be indexed in any order with some glob patterns.
In general, it is OK for scripts to have dependencies on other packages. If scripts contain package require −load −load flag; it will not hurt to specify package patterns that are not yet loaded.
If you have a package that is split across scripts and a binary file, then you should avoid the −load flag. The problem is that if you load a package before computing the index it masks any other files that provide part of the same package. If you must use −load, then you must specify the scripts first; otherwise the package loaded from the binary file may mask the package defined by the scripts.
package(n)
auto-load, index, package, version | http://man.sourcentral.org/centos6/n+pkg_mkIndex | CC-MAIN-2018-43 | refinedweb | 690 | 55.03 |
20 September 2011 16:00 [Source: ICIS news]
LONDON (ICIS)--Czech agrochemical and foodstuffs group Agrofert will not appeal an arbitration court's decision to reject its koruny (Kc) 19.5bn ($1.1bn, €792m) compensation claim against Poland's PKN Orlen over the acquisition of Czech petrochemical producer Unipetrol, Agrofert said on Tuesday.
Agrofert's lawyers have advised there is not enough scope for a successful attempt at nullifying the verdict by the Arbitration Court of the Economic and Agrarian Chambers of the ?xml:namespace>
After losing the case in November last year, Agrofert claimed legal processes had been infringed.
The compensation claim was for alleged damage caused to Agrofert’s good name, lost profits and unfair business behaviour by Orlen.
Agrofert accused Orlen of failing to fulfil promises to sell it certain Unipetrol assets after the Polish company won 2004 privatisation tender for the company.
In July 2009, the arbitration court ordered Orlen to pay Agrofert €77m in compensation for failing to sell the assets to Agrofert.
($1 = Kc18.02, €1 = Kc 24 | http://www.icis.com/Articles/2011/09/20/9493780/czech-agrofert-will-not-appeal-against-courts-claim-rejection.html | CC-MAIN-2014-52 | refinedweb | 174 | 50.67 |
Bug #1388
cygwin-1.7, gcc4-4.3, and ruby-1.9. make btest #236 test_io.rb Segmentation fault
Description
=begin
Cygwin 1.7 is currently under beta testing. It is currently at cygwin-1.7.0-46. If nothing goes overly wrong, the official 1.7.1 is planned to be released in June.
Two issues blocking the release are:
1) Stabilization of gcc-4.3; It is currently at gcc4-4.3.2-2, and several to-do's remain.
Hopefully it will get ready in gcc4-4.3.2-3.
2) Compilation of all packages using the stable gcc-4.3.
This bug report is about making ruby-1.9 ready for these new cygwin-1.7 and gcc-4.3. These are some of the patches required to make ruby trunk get compiled.
- eval_intern.h [CYGWIN]: Remove #ifdef CYGWIN for _setjmp() and _longjmp(). Cygwin-1.7 has its own definition in /usr/include/machine/setjmp.h . This is the minimally required patch to make the compilation go through to the end.
--- origsrc/ruby-1.9.2-r23198/eval_intern.h 2009-02-22 10:43:59.000000000 +0900
+++ src/ruby-1.9.2-r23198/eval_intern.h 2009-04-18 01:26:41.843750000 +0900
@@ -66,9 +66,6 @@ char *strrchr(const char *, const char);
#define ruby_setjmp(env) RUBY_SETJMP(env)
#define ruby_longjmp(env,val) RUBY_LONGJMP(env,val)
-#ifdef CYGWIN
-int _setjmp(), _longjmp();
-#endif
#include
#include
- ruby.c (push_include_cygwin): Use cygwin_conv_path instead of cygwin_conv_to_posix_path which is deprecated in cygwin-1.7.
- ruby.c (ruby_init_loadpath_safe): Use cygwin_conv_path instead of cygwin_conv_to_posix_path which is deprecated in cygwin-1.7.
--- origsrc/ruby-1.9.2-r23198/ruby.c 2009-03-17 10:29:17.000000000 +0900
+++ src/ruby-1.9.2-r23198/ruby.c 2009-04-18 01:26:41.859375000 +0900
@@ -257,7 +257,8 @@ push_include_cygwin(const char *path, VA
p = strncpy(RSTRING_PTR(buf), p, len);
}
}
- if (cygwin_conv_to_posix_path(p, rubylib) == 0)
- if (cygwin_conv_path(CCP_WIN_W_TO_POSIX | CCP_RELATIVE, p, rubylib, 1)
- == 0) p = rubylib; push_include(p, filter); if (!*s) break; @@ -366,8 +367,10 @@ ruby_init_loadpath_safe(int safe_level) #elif defined CYGWIN { char rubylib[FILENAME_MAX];
- cygwin_conv_to_posix_path(libpath, rubylib);
- strncpy(libpath, rubylib, sizeof(libpath));
- if (cygwin_conv_path(CCP_WIN_W_TO_POSIX | CCP_RELATIVE,
- libpath, rubylib, 1)
- == 0)
strncpy(libpath, rubylib, sizeof(libpath));
}
#endif
p = strrchr(libpath, '/');
strftime.c [CYGWIN]: Cygwin defines _timezone, _daylight, *_tzname[2], and tzname
with dllimport attribute. But defines daylight and timezone without
dllimport attribute.
--- origsrc/ruby-1.9.2-r23198/strftime.c 2009-03-17 10:29:17.000000000 +0
900
+++ src/ruby-1.9.2-r23198/strftime.c 2009-04-18 01:26:41.859375000 +0900
@@ -120,12 +120,16 @@ extern char *strchr();
#define range(low, item, hi) max(low, min(item, hi))
-#if defined WIN32 || defined WIN32
+#if defined __CYGWIN_ || defined WIN32 || defined WIN32
#define DLL_IMPORT __declspec(dllimport)
#endif
#ifndef DLL_IMPORT
#define DLL_IMPORT
#endif
+#ifdef __CYGWIN_
+#define daylight _daylight
+#define timezone _timezone
+#endif
#if !defined(OS2) && defined(HAVE_TZNAME)
extern DLL_IMPORT char *tzname[2];
#ifdef HAVE_DAYLIGHT
With the above three patches, ruby-1.9.2-r23198 can get compiled with only one warning:
** PTHREAD SUPPORT MODE WARNING:
**
** Ruby is compiled with --enable-pthread, but your Tcl/Tk library
** seems to be compiled without pthread support. Although you can
...
This is expected because cygwin tcltk-20080420-1 is compiled without pthread support. But when I try to compile like
CC=gcc-4 configure --program-suffix="-19" --disable-pthread
make
compilation fails.
make: *** No rule to make target
thread_.h', needed byminiprelude.o'. Stop.
*** ERROR: make failed
This is because THREAD_MODEL is empty in Makefile. Looking into configure.in, I can see that when
if test "$rb_with_pthread" = "yes";
is false and
case "$target_os" in
when(cygwin*)
then THREAD_MODEL gets undefined. (when(mingw*) is true, THREAD_MODEL=win32.) If I compile like
CC=gcc-4 configure --program-suffix="-19" --disable-pthread
make THREAD_MODEL=w32
the compilation goes through to the end, and thread-win32.c seems to be used instead of thread-pthread.c. But the same warning persists.
** PTHREAD SUPPORT MODE WARNING:
**
** Ruby is compiled with --enable-pthread, but your Tcl/Tk library
** seems to be compiled without pthread support. Although you can
...
This is wrong because --disable-pthread is used. Looking into ext/tk/extconf.rb, I can see that this warning is emitted when
# check pthread mode
if (macro_defined?('HAVE_NATIVETHREAD', '#include "ruby.h"'))
# ruby -> enable
unless tcl_enable_thread
# ruby -> enable && tcl -> disable
But include/ruby/ruby.h has
#define HAVE_NATIVETHREAD
without any #ifdefs. So the pthread mode check in ext/tk/extconf.rb always evaluates to be true even when pthread support is disabled. This should be corrected. If these issues are corrected, then ruby-1.9 trunk can get compiled without warnings.
When I tried make run or make runruby, it failed.
- common.mk (TESTRUN_SCRIPT): Correct the path to test.rb
--- origsrc/ruby-1.9.2-r23198/common.mk 2009-04-10 11:32:15.000000000 +0900
+++ src/ruby-1.9.2-r23198/common.mk 2009-04-18 04:35:13.968750000 +0900
@@ -117,7 +117,7 @@
TESTSDIR = $(srcdir)/test
TESTWORKDIR = testwork
-TESTRUN_SCRIPT = $(srcdir)/test.rb
+TESTRUN_SCRIPT = $(srcdir)/sample/test.rb
BOOTSTRAPRUBY = $(BASERUBY)
With this patch, the results of make run or runruby are
make run
not ok/test: 900 failed 1
Fnot ok system 9 -- .../ruby-1.9.2-r23198/sample/test.rb:1948:in `'
make runruby
end of test(test: 900)
which is expected and good. miniruby.exe does not support euc-jp, shift_jis, windows-1251, cp932 in Encoding.name_list, so make run is expected to fail at that test. But the result of make btest is bad.
#236 } IO.copy_stream(r1, w2) rescue nil r2.close; w2.close r1.close; w1.close #=> killed by SIGABRT (signal 6)
| bootstraptest.tmp.rb:2: [BUG] Segmentation fault
| ruby 1.9.2dev (2009-04-15 trunk 23198) [i386-cygwin]
|
| -- control frame ----------
| c:0004 p:---- s:0010 b:0010 l:000009 d:000009 CFUNC :p
| c:0003 p:0011 s:0006 b:0006 l:000aec d:000005 BLOCK bootstraptest.tmp.rb:2
| c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
| c:0001 p:0000 s:0002 b:0002 l:000aec d:000aec TOP :19
| ---------------------------
| bootstraptest.tmp.rb:2:in
block in <main>'p'
| bootstraptest.tmp.rb:2:in
|
| [NOTE]
| You may have encountered a bug in the Ruby interpreter or extension libraries.
| Bug reports are welcome.
| For details:
|
FAIL 1/890 tests failed
make: *** [btest] Error 1
make btest-ruby also emits several errors, but I will submit it as another issue because this report is already too long...
=end
Updated by neomjp (neomjp neomjp) almost 11 years ago
=begin
Thanks for the quick and thorough review. I am sorry that I could not
report back earlier.
On 2009/04/19 20:12, Nobuyoshi Nakada wrote:
At Sat, 18 Apr 2009 04:56:10 +0900,
neomjp neomjp wrote in [ruby-core:23241]:
-#ifdef CYGWIN
-int _setjmp(), _longjmp();
-#endif
The definitions seem just with extern and arguments, and above
declaration doesn't seem conflict with them, what error does
occur?
In file included from .../ruby-1.9.2-r23198/eval.c:14:
.../ruby-1.9.2-r23198/eval_intern.h:70: error: conflicting types for '_longjmp'
/usr/include/machine/setjmp.h:318: error: previous declaration of '_longjmp' was here
make: *** [eval.o] Error 1
Conficting part is _longjmp. Here is the relevant part of setjmp.h from
cygwin-1.7 .
$ cygcheck -f /usr/include/machine/setjmp.h
cygwin-1.7.0-46
$ sed -n 317,323p /usr/include/machine/setjmp.h
#ifdef CYGWIN
extern void _longjmp(jmp_buf, int);
extern int _setjmp(jmp_buf);
#else
#define _setjmp(env) sigsetjmp ((env), 0)
#define _longjmp(env, val) siglongjmp ((env), (val))
#endif
In contrast, cygwin-1.5 did not have _setjmp or _longjmp
$ cygcheck -f /usr/include/machine/setjmp.h
cygwin-1.5.25-15
$ grep -Ecr --include=setjmp* "_longjmp|_setjmp" /usr/include/
/usr/include/machine/setjmp-dj.h:0
/usr/include/machine/setjmp.h:0
/usr/include/setjmp.h:0
- if (cygwin_conv_to_posix_path(p, rubylib) == 0)
- if (cygwin_conv_path(CCP_WIN_W_TO_POSIX | CCP_RELATIVE, p, rubylib, 1)
- == 0)
I suspect it should use CCP_WIN_A_TO_POSIX and sizeof(rubylib)
instead of 1, am I wrong?
You are totally right. Stupid me, I just read "If size is 0 ...
Otherwise, ...", and set it to a non-zero value.:
VM_CORE_H_INCLUDES = {$(VPATH)}vm_core.h {$(VPATH)}vm_opts.h \
{$(VPATH)}thread_$(THREAD_MODEL).h \
{$(VPATH)}node.h $(ID_H_INCLUDES)
thread.$(OBJEXT): {$(VPATH)}thread.c {$(VPATH)}eval_intern.h \
$(RUBY_H_INCLUDES) {$(VPATH)}gc.h $(VM_CORE_H_INCLUDES) \
{$(VPATH)}debug.h {$(VPATH)}thread_$(THREAD_MODEL).c
So, the variable THREAD_MODEL is not used in any rules.
thread_$(THREAD_MODEL).c is #included from thread.c like this:
#if defined(_WIN32)
#include "thread_win32.c"
................................
#elif defined(HAVE_PTHREAD_H)
#include "thread_pthread.c"
....................................
#else
#error "unsupported thread type"
#endif
But in cygwin, _WIN32 is undefined, and HAVE_PTHREAD_H is defined. So
thread_pthread.c is included. If I run the preprocessoer like
gcc-4 -v -E -O2 -pipe -I. -I.ext/include/i386-cygwin
-I.../ruby-1.9.2-r23311/include -I.../ruby-1.9.2-r23311 -DRUBY_EXPORT
-o thread.o -c .../ruby-1.9.2-r23311/thread.c
This gives:
/usr/lib/gcc/i686-pc-cygwin/4.3.2/cc1.exe ... -D_CYGWIN32_
-D_CYGWIN_ -Dunix -D_unix_ -D__unix ...
and
static void timer_thread_function(void *);
# 182 ".../ruby-1.9.2-r23311/thread.c"
# 1 ".../ruby-1.9.2-r23311/thread_pthread.c" 1
# 17 ".../ruby-1.9.2-r23311/thread_pthread.c"
# 1 "/usr/include/sys/resource.h" 1 3 4
# 41 "/usr/include/sys/resource.h" 3 4
typedef unsigned long rlim_t;
....
Note that thread_pthread.c is #included instead of thread_win32.c.
So what happens with
CC=gcc-4 configure --program-suffix="-19" --disable-pthread
make THREAD_MODEL=w32
is
- thread_pthread.c is #included from thread.c. (not thread_win32.c)
- Objects are linked without -lpthread.
What kind of thread is working here? Anyway, both with/without
--disable-pthread passed test_thread.rb in make btest. .
make run is supporsed to run your own script, so test.rb is a
file which you should make. test-sample is what you want.
I see. "make test-sample" passes without errors, both with/without
--disable-pthread.
Segfaults in the at_exit block. I'll investigate it.
Thanks.
=end
Updated by nobu (Nobuyoshi Nakada) almost 11 years ago
=begin
Hi,
At Fri, 1 May 2009 00:57:41 +0900,
neomjp neomjp wrote in [ruby-core:23340]:
Conficting part is _longjmp. Here is the relevant part of setjmp.h from
cygwin-1.7 .
$ sed -n 317,323p /usr/include/machine/setjmp.h
#ifdef CYGWIN
extern void _longjmp(jmp_buf, int);
extern int _setjmp(jmp_buf);
Yes of course, longjmp() never return and must not be int.:
I meant very early implementation, but not current one. It had
used Windows threads at first.
--
Nobu Nakada
=end
Updated by neomjp (neomjp neomjp) almost 11 years ago
=begin
On 2009/05/01 0:57, neomjp neomjp wrote:
CC=gcc-4 configure --program-suffix="-19" --disable-pthread
make THREAD_MODEL=w32
- Objects are linked without -lpthread.
It seems the miniruby was still using pthread even when linked
without -lpthread. The only difference in
"strings miniruby | grep -i pthread"
with/without --disable-pthread was the absence/presence of
pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)
All other pthread functions were the same. miniruby was still
using pthread.
So, I tried forcing the compilation of thread_win32.c by replacing
#if defined(WIN32)
with
#if defined(_WIN32) || defined(CYGWIN_)
in thread.c:172 and vm_core.h:25 (r23390), and
CC=gcc-4 configure --program-suffix="-19" --disable-pthread
make THREAD_MODEL=w32
The compilation went through to the end (with some warnings), but
"make btest" failed miserably with numerous segfaults and four test
failures.
Hmm, now I understand that win32 thread does not work in cygwin.
I will take back my claims about the option to --disable-pthread in
cygwin-1.7. It was not the main topic of this bug, anyway.
Besides, it was a rather low-priority feature request in a non-default
setting.
Finally, an update:
- eval_intern.h: FIXED in r23317. Thanks.
- ruby.c: Nobu's fix in [ruby-core:23255] will be fine.
- strftime.c: A patch proposed in [ruby-core:23241].
- common.mk :INVALID, WONTFIX
- Segfault in #236 test_io.rb: This was what this bug was about.
--
neomjp
=end
Updated by yugui (Yuki Sonoda) over 10 years ago
- Assignee set to nobu (Nobuyoshi Nakada)
=begin
=end
Updated by mame (Yusuke Endoh) over 9 years ago
- Priority changed from Normal to 3
- Target version set to 2.0.0
=begin
Hi,
neomjp, we really appreciate your contribution for cygwin support, but
very sorry, we can't afford to review and test your patch because there
is no maintainer for cygwin.
Also, we have no enough time to test it for 1.9.2 release.
So I set this ticket to Low-priority.
A maintainer is required to add cygwin into "best effort" platform:
Are you interested?
--
Yusuke Endoh mame@tsg.ne.jp
=end
Updated by usa (Usaku NAKAMURA) over 9 years ago
- Status changed from Open to Assigned
=begin
=end
Updated by neomjp (neomjp neomjp) over 9 years ago
=begin
Hi,
After a long hiatus, I checked the status of this make btest, test_io.rb, segfault bug.
In trunk,
ruby-1.9.2-r23198 segfault (<- when this bug was reported.)
ruby-1.9.2-preview1 (r24184) segfault
ruby-1.9.2-preview2 (r24782) segfault
ruby-1.9.3-r27622 segfault
ruby-1.9.3-r27623 timeout or pass but no segfault (<- fix for test_io.rb
megacontent-copy_stream deadlock)
ruby-1.9.3-r28731 timeout or pass but no segfault
In ruby_1_9_2 branch,
ruby-1.9.2-preview3 (r28108) Too many "[BUG] pthread_mutex_unlock : Operation not permitted
(EPERM)" errors. Not sure if this segfault occurs.
ruby-1.9.2-r28508 timeout or pass but no segfault (<- fix for pthread bug)
ruby-1.9.2-rc1 (r28522) timeout or pass but no segfault
ruby-1.9.2-rc2 (r28613) timeout or pass but no segfault
ruby-1.9.2-r28724 timeout or pass but no segfault
In ruby_1_9_1 branch,
ruby-1.9.1-p429 (r28522) segfault
ruby-1.9.1-r28641 segfault
So, this segfault was seen only before the test was changed in r27623. After the
fix, the test will either pass, or timeout as show below:
#246; r2.close } IO.copy_stream(r1, w2) rescue nil w2.close r1.close t1.join t2.join #=> killed by SIGKILL (signal 9) (timeout) megacontent-copy_stream
FAIL 1/925 tests failed
make: *** [yes-btest] Error 1
What happens when it timeouts? When this test was isolated in a file and executed, it
sometimes showed a hang (or deadlock?). Maybe, the pipes were not properly killed?
- I do not see a segfault any more. I see a pass or timeout (a hang or deadlock, meaning the pipes were not properly killed) instead.
- r27623 may be ported also to ruby_1_9_1 branch. It would turn the second test failure reported in Bug #3292 [ruby-core:30238] from a segfault into a timeout.
- The patch for ruby.c in [ruby-core:23255] was incorporated in r23468.
- The declarations in strftime.c that the patch in [ruby-core:23241] [Bug #1388] tried to fix were removed in r28592. So, the patch is no more valid.
- As for maintainership, I would be glad if I could be of some help, but I do not think I can promise to keep the 3 months rule in [ruby-core:25764]. Sometimes, I can compile ruby and run tests, but other times, my daily work will not allow me the time. I should better remain just another cygwin tester. =end
Updated by mame (Yusuke Endoh) almost 7 years ago
Updated by mame (Yusuke Endoh) over 2 years ago
- Status changed from Assigned to Rejected
Sorry for leaving this ticket untouched, but Ruby 1.9 has been EOL status since a long time ago. If there is anyone who is willing to maintain cygwin ruby, please investigate the current status of the issue and write a patch.
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/1388 | CC-MAIN-2020-10 | refinedweb | 2,642 | 61.53 |
Linux Tools Project/Libhover/Developers Guide
Contents
Introduction
The Libhover plug-in from the Linux Tools project provides a common interface for supplying C and C++ hover help for libraries. The plug-in uses a CDT (C/C++ Developer Tools) Help extension to register itself with the CDT. When a C or C++ file is presented in the editor and a hover event occurs, the CDT will call the Libhover plug-in to get information. In turn, the Libhover plug-in supplies its own extension which allows the end-user to specify a set of valid hovers to use. Each hover library can be enabled or disabled for a C/C++ project via the Project->Properties->C/C++ General->Documentation page. There a list of the valid hovers are shown and the user can check or un-check them as desired. Note that Libhover help suppliers set the language of the hover help and so a C project will ignore any C++ hover libraries. For a C++ project, both C and C++ library hovers are valid so they will all appear on the Documentation page.
Libhover Extension
The Libhover plug-in adds a new org.eclipse.linuxtools.cdt.libhover.library extension to be used in a plug-in. Let's examine an example which specifies libhover help for the glibc C Library:
<extension id="library" name="Glibc C Library" point="org.eclipse.linuxtools.cdt.libhover.library"> <library docs="" location="./data/glibc-2.7-2.libhover" name="glibc library" type="C"> </library>; </extension>;
Fields are as follows:
- id - unique id for this extension (required)
- name - name of the extension (required)
- library - details of the library (1 or more)
- docs - URL location of external help documentation (optional)
- location - location of libhover binary data (either URL or relative location to plug-in) (required)
- name - name that will appear in the C/C++ Documentation page for this hover help (required)
- type - one of (C, C++, or ASM) (required)
Note that the location can be specified local to the plug-in that declares the extension. This obviously saves time when accessing the data before a hover event.
Libhover Data
So what is Libhover data? Libhover data is merely a Java serialized class that is stored in binary format. Java serialization allows one to save and restore a class to/from a file. The Libhover class is really org.eclipse.linuxtools.cdt.libhover.LibhoverInfo:
public class LibHoverInfo implements Serializable { private static final long serialVersionUID = 1L; public HashMap<String, ClassInfo> classes = new HashMap<String, ClassInfo>(); public HashMap<String, TypedefInfo> typedefs = new HashMap<String, TypedefInfo>(); public TreeMap<String, FunctionInfo> functions = new TreeMap<String, FunctionInfo>(); }
The class is just a collection of Maps from name to C++ class, name to C++ typedef, and name to C function. A C library hover info will only fill in the last map whereas a C++ library hover info will typically only fill in the first two.
C Library Data
The simplest form of Libhover data is for C functions. Looking at org.eclipse.linuxtools.cdt.libhover.FunctionInfo:
public class FunctionInfo implements Serializable { private static final long serialVersionUID = 1L; private String name; private String prototype; private String desc; private String returnType; private ArrayList<String> headers; private ArrayList<FunctionInfo> children; }
we see the class is made up of String fields containing the function data that will be pieced together in the hover window. The prototype does not include the outer parentheses. The desc field is the description of the function and can is treated as html format. The children field is for future support of C++ overloaded functions. This is due to the fact that we look-up a function by name in the HashMap to make it quickly referenced. When there is overloading of function names (C++ only), then we register the first function found in the map and use the children field to store all others in no particular order. Currently, overloaded functions are not supported by the Libhover look-up mechanism, but this functionality could be added if required. All the fields are accessed via get and set methods (e.g. getName(), setDesc()).
C Library Hover Utility
To aid in building C library hover data, a utility has been created that will take xml and create the libhover binary data in the form of a file with suffix ".libhover". The utility is found in the org.eclipse.linuxtools.cdt.libhover plug-in as org.eclipse.linuxtools.cdt.libhover.utils.BuildFunctionInfos.java. Run the file as a Java application (it has a static main method) and pass to it two parameters:
- the URL or file location of the xml file to parse
- the location where the output should be placed
Once finished you can place the .libhover file in your plug-in and use the Libhover Library extension to specify a local location.
XML files referenced must adhere to the following xml structure:
<!DOCTYPE descriptions [ <!ELEMENT descriptions (construct)*> <!ELEMENT construct (structure|function)*> <!ATTLIST construct id ID #REQUIRED type CDATA #REQUIRED > <!ELEMENT structure (synopsis?, elements?)?> <!ELEMENT elements (element*)> <!ELEMENT element (synopsis*)> <!ATTLIST element content CDATA #REQUIRED > <!ELEMENT synopsis (#PCDATA)*> <!ELEMENT function (prototype,headers?,synopsis)> <!ATTLIST function returntype CDATA #REQUIRED > <!ELEMENT prototype (parameter+)?> <!ELEMENT parameter (#PCDATA)*> <!ATTLIST parameter content CDATA #REQUIRED > <!ELEMENT headers (header+)?> <!ELEMENT header (#PCDATA)*> <!ATTLIST header filename CDATA #REQUIRED > ]>
Note that function ids need to be prefixed by "function-". For example, for the C atexit function:
<descriptions> <construct id="function-atexit" type="function"> <function returntype="int"> <prototype> <parameter content="void (*function) (void)"/> </prototype> <headers> <header filename = "stdlib.h"/> </headers> <synopsis> The <CODE>atexit</CODE> function registers the function <VAR>function</VAR> to be called at normal program termination. The <VAR>function</VAR> is called with no arguments. <br><br> The return value from <CODE>atexit</CODE> is zero on success and nonzero if the function cannot be registered. </synopsis> </function> </construct> </descriptions>
Also note that the synopsis is output as html. To specify html tags, one needs to use < and > as delimeters in place of "<" and ">". In the previous example, VAR tags are used for variable references, CODE tags for the function name, and br tags for forcing paragraph breaks. All of these make the hover look more interesting when displayed.
For glibc, a parser was written to parse the glibc/manual directory and process the texinfo files to form the xml file format above.
C++ Library Hover
C++ library hover data is more complex because a member cannot be accessed just by name. One needs to first know from which class the member is being accessed and the signature of the call since member names can be overloaded. Additional complexities arise because the member might actually belong to a base class of the given class used in the call or the class may be a typedef of another class or a template instance. Template instances are tricky because there is substitution that occurs for parameterized types.
A utility org.eclipse.linuxtools.cdt.libhover.libstdcxx.DoxygenCPPInfo was created to parse the Doxygen documentation output for the libstdc++ library. If you can get your library documentation into the same format, then all you need to do is to use the utility, passing two parameters:
- location of the Doxygen xml input
- location to place the output libhover data file
Failing that, you will need to create your own library hover info. Let's look at the fields of interest in org.eclipse.linuxtools.cdt.libhover.ClassInfo
public class ClassInfo implements Serializable { private static final long serialVersionUID = 1L; private String templateParms[]; private String className; private String include; private ArrayList<ClassInfo> baseClasses; private HashMap<String, MemberInfo> members; private ArrayList<ClassInfo> children; }
The following describes each field:
- templateParms - this is used to store the template parameters of this class (e.g. A<_T, _U, Integer> would store "_T" and "_U". Real types are not part of this list. These are needed to perform replacement in the description text (e.g. the return value of a member function may be specified as a template parameter).
- className - this is the name of the class including the template specification. Any template parameters from templateParms are replaced with a generic regex "[a-zA-Z0-9_: *]+" which allows us to do a quick regex match on a template (e.g. A<Integer, Double> would match A<_T, _U>.
- include - this is the name of the header file that contains this class
- baseClasses - the ClassInfo data of any base classes of this class
- members - maps member names to MemberInfo (only 1 per name with MemberInfo chaining when overloading exists).
- children - this is the set of template classes with the same name as this class
Note that the name used to hash the ClassInfo in the LibhoverInfo class map is the class name minus any template specification.
The TypedefInfo is merely a way to find the actual class we are seeking:
public class TypedefInfo implements Serializable { private static final long serialVersionUID = 1L; private String[] templates; private String typedefName; private String transformedType; private ArrayList<TypedefInfo> children = null; };
- typedefName - name of the typedef with any template parameters replaced with a generic regex string "[a-zA-Z0-9_: *]+"
- templates - this the set of template parameters from the transformed class name
- transformedType - what the typedef transforms into
- children - used when there are multiple typedefs of the same name (e.g. partial templates)
It is assumed that the typedef will use the same template parameters as the class it represents. For example, if we have class A<_T, _U> and we could have a typedef B<_T> which transforms to A<_T, Integer>.
The MemberInfo class is much like the FunctionInfo class:
public class MemberInfo implements Serializable { private static final long serialVersionUID = 1L; private String name; private String prototype; private String desc; private String returnType; private String[] paramTypes; private ArrayList<MemberInfo> children; };
and contains the actual hover data of interest. The following are the fields of interest:
- name - member name
- prototype - prototype minus outer parentheses
- desc - member description in html format
- returnType - the return type of the member function
- paramTypes - an array of just the parameter types of this function without template replacement. The array is used in conjunction with template types to verify we have the correct member being used (e.g. a(_T, _U) of A<_T, _U> is a match for a(Integer k, Double l) of A<Integer, Double> class).
- children - members with the same name as this (i.e. overloaded method signatures)
Devhelp Library Hover
The org.eclipse.linuxtools.cdt.libhover.devhelp plug-in adds support for dynamically processing installed documentation formatted for use by the devhelp API browser.
Documentation is generated by gtk-doc either from specially formatted comments in the C code or via adding to template files created after gtk-doc parses the header files. From these files, gtk-doc creates a Docbook xml file or sgml file which can be used to create html. Various packages use the form of documentation which is installed in a common area for the devhelp API browser to locate.
The Devhelp libhover plug-in provides a new preferences page under Libhover->devhelp
A text entry is provided to specify where the devhelp documentation is installed on the current system (default /usr/share/gtk-doc). An additional button is provided to start the generation (or regeneration) of the devhelp libhover documentation. Pressing the button starts an Eclipse Job that can be put into the background or cancelled.
The results of the job replace the current devhelp libhover binary data currently loaded.
To create documentation in a format that can be used, see the gtk-doc manual
Libhover Logic
For C hover, Libhover is given the name of the C function to find and a list of C HelpBooks that are enabled. These HelpBooks correspond to the Project->Properties->C/C++ General->Documentation items that are enabled and that were registered by the Libhover plug-in (these correspond to "C" type library hover infos included by the Libhover Library extension). For each C Library info in the list, Libhover does a find of the name in the FunctionInfo map. If any FunctionInfo is found, it is transformed into the CDT format required. Otherwise, null is returned.
For C++, it is more complicated. The CDT provides the location in the editor that the hover is for. From this, Libhover consults the CDT indexer for the context of the hover which includes the class name and the member signature. Once this is acquired, Libhover first looks for the class name in the TypdefInfo map. If it is found and this isn't a templated typedef, the transformed name is then used as the class name. In the case of a template, the TypedefInfo and all its children are checked one by one for a regex match of the typedef name with the given typedef. Remember that for template parameters we substituted a generic regex string in the typedef name.
Now we have a class name. We use that class name to access the ClassInfo map. If we don't match, we return null. Otherwise, we may have to resolve templates so we perform a regex match of the class name with the class name in question, again we have substituted a generic regex string for template parameters. If no match, we return null.
Now we have a ClassInfo and only need to find the member in question. We start by searching the immediate members of the ClassInfo and if needed, we then start looking in base classes. We start by accessing the MemberInfo map by name. If we have a match, we need to check if the MemberInfo has children, indicating overloading. If overloading has occurred, we need to check the parameter types and return type of each member to find a match. The same check applies if we are forced to look in the base classes. It is assumed that base classes are not typedefs themselves. If this needs to be modified in the future, then the baseClasses list would be of type String and then a new transform would have to be performed.
Once the correct MemberInfo is located, the details are used to supply the CDT hover information. Any template parameters are substituted in the prototype, return type, and name of the member function. Currently, this substitution is not performed on the member description though it would be simple to add if needed. | http://wiki.eclipse.org/Linux_Tools_Project/Libhover/Developers_Guide | CC-MAIN-2017-17 | refinedweb | 2,389 | 53.21 |
Evening Folks,
Having a bit of a problem with somthing i am trying to code, wondering if anyone here can help....
The basic idea is that i am trying to build a Priority Queue of binary tree nodes so that they are stored in ascending order by a number stored in each of the tree nodes.
Each binary tree node is constructed from a CharNode and are definately being constructed properly. The problem seems to be in the BinaryNode's compareTo method as the Priority Queue is using this to sort the elements.
BinaryNode.java
public class BinaryNode implements Comparable<BinaryNode>{ private BinaryNode left; private BinaryNode right; private int frequency; private char character; public BinaryNode(int f, char c){ this.left = null; this.right = null; this.frequency = f; this.character = c; } public BinaryNode getLeft() { return left; } public void setLeft(BinaryNode left) { this.left = left; } public BinaryNode getRight() { return right; } public void setRight(BinaryNode right) { this.right = right; } public int getFrequency() { return frequency; } public void setFrequency(int frequency) { this.frequency = frequency; } public char getCharacter() { return character; } public void setCharacter(char character) { this.character = character; } public int compareTo(BinaryNode x) { // Assume neither string is null. Real code should // probably be more robust if (x.getFrequency() > this.getFrequency()) { return -1; } else if (x.getFrequency() < this.getFrequency()) { return 1; } else if (this.equals(x)) return 0; else { System.out.println("ERROR"); return 0; } } public String toString(){ //String s = ""; return this.character + "/" + this.frequency; } public boolean equals(BinaryNode x){ if (this.frequency == x.frequency && this.character == x.character){ return true; } return false; } }
The code that uses the PriorityQueue to
public void buildTree(){ PriorityQueue<BinaryNode> queue = new PriorityQueue<BinaryNode>(); for (CharNode element : this.frequencyList.getFreqList()){ BinaryNode node = new BinaryNode(element.getFrequency(), element.getCharacter()); System.out.println("Adding Node " + node + " to queue."); queue.add(node); System.out.println("Queue is now :" + queue); } System.out.println(queue); }
Ive tried using compartors but i come up against the same problem, the above code gives the following output:
Adding Node t/4 to queue.
Queue is now :[t/4]
Adding Node h/3 to queue.
Queue is now :[h/3, t/4]
Adding Node e/2 to queue.
Queue is now :[e/2, t/4, h/3]
Adding Node /4 to queue.
ERROR
Queue is now :[e/2, t/4, h/3, /4]
Adding Node c/1 to queue.
Queue is now :[c/1, e/2, h/3, /4, t/4]
Adding Node a/2 to queue.
Queue is now :[c/1, e/2, a/2, /4, t/4, h/3]
Adding Node i/1 to queue.
ERROR
Queue is now :[c/1, e/2, i/1, /4, t/4, h/3, a/2]
Adding Node n/1 to queue.
ERROR
Queue is now :[c/1, n/1, i/1, e/2, t/4, h/3, a/2, /4]
[c/1, n/1, i/1, e/2, t/4, h/3, a/2, /4]
I realise this might be a complicatedly worded etc, but if anyones willing to help ill glady explain any code etc...
Cheers,
Logi. | https://www.daniweb.com/programming/software-development/threads/233928/compareto-and-priority-queue-problems | CC-MAIN-2018-43 | refinedweb | 507 | 50.02 |
Why is QtMobility required to use Multimedia in QML?
I tried a simple Qt Quick application with
import Qt.multimedia 1.0
and I got errors as QtMobility package is missing,
why do I need to install QtMobility to create a QML Desktop application which uses multimedia?
hi ashwin, this might be of interest to you
"":
another interesting read:
"":
hi again,
chk this out too: "":
Thanks Chetan,
The roadmap looks good,
But my concern is - QML is intended for Designer and people who are non-developers,
and do not want to do C++ or any other coding,
So installation, developing and packaging of pure-QML applications, should be as easy as and simple like installing from an .exe or .deb etc, and then exporting the app to the phone also should be direct,
And all the libraries that my be required for all my QML apps like multimedia etc should be installed at one go, and those designers should not be asked to install missing plugins by executing something from command line etc. They are non-developers.
ashwin I fully agree :) ...
even as a developer I'd want things to be as simple as click and go :P and don't want to spend hours trying to get my environment right.
maybe this is already in the plan with Qt going fully modular and the smart installer as it evolves.
But only some Troll should confirm or comment on this ...
We definitely agree! That's the whole point of things like the Nokia Qt SDK and Smart Installer -- to make it as easy as possible to develop and deploy your Qt (and QML) applications. If there are specific pain points you'd like to see addressed, please report them via bugreports.qt.nokia.com so we can continue to improve.
I have not tried the Nokia Qt SDK yet. I was under the impression that was for mobile development only. I guess I thought that because there was (until a few days ago) a separate Qt SDK that included QtCreator and was suitable for desktop installations (discontinued now). I don't think there is any question that developers are confused about how to get there environment up and running, especially new developers (and who wants to discourage them?).
I strongly agree with whatever Ashwin had said,even i needed multimedia package for QML but in order to get that i need to install QTMobility first,which was so painful (when errors appears while compiling, u dont knw wht to do) ,so many environmental variables need to be set, atleast QTcreator is better in tht ;) | https://forum.qt.io/topic/1662/why-is-qtmobility-required-to-use-multimedia-in-qml/1 | CC-MAIN-2020-16 | refinedweb | 434 | 57.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.