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 |
|---|---|---|---|---|---|
Fault description
Modify the ~/.vimrc configuration file to run the py script with one click. The
content of the vimrc configuration file is as follows
map <F5> :call CompileRunGcc()<CR> func! CompileRunGcc() exec "w" if &filetype == 'c' exec '!g++ % -o %<' exec '!time ./%<' elseif &filetype == 'cpp' exec '!g++ % -o %<' exec '!time ./%<' elseif &filetype == 'python' exec '!time python %' elseif &filetype == 'sh' :!time bash % endif endfunc
vim a.py press F5 as follows
Use script
" <f5> run python programmer map <f5> :w<cr>:!python %<cr>
Can run normally
In other words, the contents of the function body cannot be executed.
The cause of the fault
was resolved on December 23, 2020. The cause of the
/etc/profilealias
alias vim='/usr/bin/vi, there is an alias in the file , that is, the vim command actually uses vi
Solution
to
/etc/profilefile
alias vim='/usr/bin/vichange
alias vim='/usr/bin/vimcan be.
Here are the solutions to other problems
. The VI in Centos only installs vim-minimal-7.x by default. No matter you enter vi or vim to view the file, the syntax function cannot be enabled normally. Therefore, two other components need to be installed with yum: vim-common-7.x and vim-enhanced-7.x.
#View vim components [[email protected] ~]# rpm -qa | grep vim vim-enhanced-7.4.629-7.el7.x86_64 vim-filesystem-7.4.629-7.el7.x86_64 vim-X11-7.4.629-7.el7.x86_64 vim-common-7.4.629-7.el7.x86_64 vim-minimal-7.4.629-7.el7.x86_64 #install vim yum -y install vim*
Read More:
- Setting up automatic networking alias for Mac Terminal
- Using common file upload to upload files in SSH project
- Vue implements page caching with keep alive
- How to Use Apt get Command Under Mac OSX
- How to Fix Linux sub process /usr/bin/dpkg returned an error code (1)
- The prefix “mvc” for element “mvc:view-controller” is not bound
- The use of Android setgravity()
- Running shell script reports an error: “syntax error near unexpected token solution ‘”
- Android converts a view to bitmap + to handle the black edge of the view with rounded corners
- Nginx Error: [emerg] bind() to [::]:80 failed (98: Address already in use)
- linux tomcat Run (DWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [debugIni)
- Linux Nagios failed to log in to internal server error (Fixed)
- Linux: Configure Network address through Netplan
- How to Solve Rosep Problem in ROS Initialization (Sudo Rosep Init)
- Make update-api Error: ckati failed with: signal: killed
- Linux Ubuntu ImportError: Libtk8.5.so: cannot open shared object file:No such file Install tkinter Library
- Termux setting path environment variable
- PM2 user defined Log, PID and other Log File Locations
- How to Skip testing when Maven is packaged
- ls: cannot access /com: Host is down | https://programmerah.com/how-to-solve-error-vim-call-compilerungcc-26760/ | CC-MAIN-2021-21 | refinedweb | 463 | 54.02 |
ORLite - Extremely light weight SQLite-specific ORM
package Foo; # Simplest possible usage use strict; use ORLite 'data/sqlite.db'; my @awesome = Foo::Person->select( 'where first_name = ?', 'Adam', ); package Bar; # All available options enabled or specified. # Some options shown are mutually exclusive, # this code would not actually run. use ORLite { package => 'My::ORM', file => 'data/sqlite.db', user_version => 12, readonly => 1, create => sub { my $dbh = shift; $dbh->do('CREATE TABLE foo ( bar TEXT NOT NULL )'); }, tables => [ 'table1', 'table2' ], cleanup => 'VACUUM', prune => 1, };
SQLite is a light single file SQL database that provides an excellent platform for embedded storage of structured data.
However, while it is superficially similar to a regular server-side SQL database, SQLite has some significant attributes that make using it like a traditional database difficult.
For example, SQLite is extremely fast to connect to compared to server databases (1000 connections per second is not unknown) and is particularly bad at concurrency, as it can only lock transactions at a database-wide level.
This role as a superfast internal data store can clash with the roles and designs of traditional object-relational modules like Class::DBI or DBIx::Class.
What this situation would seem to need is an object-relation system that is designed specifically for SQLite and is aligned with its idiosyncracies.
ORLite is an object-relation system specifically tailored for SQLite that follows many of the same principles as the ::Tiny series of modules and has a design and feature set that aligns directly to the capabilities of SQLite.
Further documentation will be available at a later time, but the synopsis gives a pretty good idea of how it works.
ORLite discovers the schema of a SQLite database, and then generates the code for a complete set of classes that let you work with the objects stored in that database.
In the simplest form, your target root package "uses" ORLite, which will do the schema discovery and code generation at compile-time.
When called, ORLite generates two types of packages.
Firstly, it builds database connectivity, transaction support, and other purely database level functionality into your root namespace.
Secondly, it will create one sub-package underneath the namespace of the root module for each table or view it finds in the database.
Once the basic table support has been generated, it will also try to load an "overlay" module of the same name. Thus, by created a Foo::TableName module on disk containing "extra" code, you can extend the original and add additional functionality to it.
ORLite takes a set of options for the class construction at compile time as a HASH parameter to the "use" line.
As a convenience, you can pass just the name of an existing SQLite file to load, and ORLite will apply defaults to all other options.
# The following are equivalent use ORLite $filename; use ORLite { file => $filename, };
The behaviour of each of the options is as follows:
The optional
package parameter is used to provide the Perl root namespace to generate the code for. This class does not need to exist as a module on disk, nor does it need to have anything loaded or in the namespace.
By default, the package used is the package that is calling ORLite's import method (typically via the
use ORLite { ... } line).
The compulsory
file parameter (the only compulsory parameter) provides the path to the SQLite file to use for the ORM class tree.
If the file already exists, it must be a valid SQLite file match that supported by the version of DBD::SQLite that is installed on your system.
ORLite will throw an exception if the file does not exist, unless you also provide the
create option to signal that ORLite should create a new SQLite file on demand.
If the
create option is provided, the path provided must be creatable. When creating the database, ORLite will also create any missing directories as needed.
When working with ORLite, the biggest risk to the stability of your code is often the reliability of the SQLite schema structure over time.
When the database schema changes the code generated by ORLite will also change. This can easily result in an unexpected change in the API of your class tree, breaking the code that sits on top of those generated APIs.
To resolve this, ORLite supports a feature called schema version-locking.
Via the
user_version SQLite pragma, you can set a revision for your database schema, increasing the number each time to make a non-trivial chance to your schema.
SQLite> PRAGMA user_version = 7
When creating your ORLite package, you should specificy this schema version number via the
user_version option.
use ORLite { file => $filename, user_version => 7, };
When connecting to the SQLite database, the
user_version you provide will be checked against the version in the schema. If the versions do not match, then the schema has unexpectedly changed, and the code that is generated by ORLite would be different to the expected API.
Rather than risk potentially destructive errors caused by the changing code, ORLite will simply refuse to run and throw an exception.
Thus, using the
user_version feature allows you to write code against a SQLite database with high-certainty that it will continue to work. Or at the very least, that should the SQLite schema change in the future your code fill fail quickly and safely instead of running away and causing unknown behaviour.
By default, the
user_version option is false and the value of the SQLite
PRAGMA user_version will not be checked.
To conserve memory and reduce complexity, ORLite will generate the API differently based on the writability of the SQLite database.
Features like transaction support and methods that result in
INSERT,
UPDATE and
DELETE queries will only be added if they can actually be run, resulting in an immediate "no such method" exception at the Perl level instead of letting the application do more work only to hit an inevitable SQLite error.
By default, the
readonly option is based on the filesystem permissions of the SQLite database (which matches SQLite's own writability behaviour).
However the
readonly option can be explicitly provided if you wish. Generally you would do this if you are working with a read-write database, but you only plan to read from it.
Forcing
readonly to true will halve the size of the code that is generated to produce your ORM, reducing the size of any auto-generated API documentation using ORLite::Pod by a similar amount.
It also ensures that this process will only take shared read locks on the database (preventing the chance of creating a dead-lock on the SQLite database).
The
create option is used to expand ORLite beyond just consuming other people's databases to produce and operating on databases user the direct control of your code.
The
create option supports two alternative forms.
If
create is set to a simple true value, an empty SQLite file will be created if the location provided in the
file option does not exist.
If
create is set to a
CODE reference, this function will be executed on the new database before ORLite attempts to scan the schema.
The
CODE reference will be passed a plain DBI connection handle, which you should operate on normally. Note that because
create is fired before the code generation phase, none of the functionality produced by the generated classes is available during the execution of the
create code.
The use of
create option is incompatible with the
readonly option.
The
tables option should be a reference to an array containing a list of table names. For large or complex SQLite databases where you only need to make use of a fraction of the schema limiting the set of tables will reduce both the startup time needed to scan the structure of the SQLite schema, and reduce the memory cost of the class tree.
If the
tables option is not provided, ORLite will attempt to produce a class for every table in the main schema that is not prefixed with with
sqlite_.
use ORLite { file => 'dbi:SQLite:sqlite.db', user_version => 2, cache => 'cache/directory', };
The
cache option is used to reduce the time needed to scan the SQLite database table structures and generate the code for them, by saving the generated code to a cache directory and loading from that file instead of generating it each time from scratch.
When working with embedded SQLite databases containing rapidly changing state data, it is important for database performance and general health to make sure you VACUUM or ANALYZE the database regularly.
The
cleanup option should be a single literal SQL statement.
If provided, this statement will be automatically run on the database during
END-time, after the last transaction has been completed.
This will typically either by a full
'VACUUM ANALYZE' or the more simple
'VACUUM'.
In some situation, such as during test scripts, an application will only need the created SQLite database temporarily. In these situations, the
prune option can be provided to instruct ORLite to delete the SQLite database when the program ends.
If any directories were made in order to create the SQLite file, these directories will be cleaned up and removed as well.
If
prune is enabled, you should generally not use
cleanup as any cleanup operation will be made pointless when
prune deletes the file.
By default, the
prune option is set to false.
In some situtations you may wish to make extensive changes to the behaviour of the classes and methods generated by ORLite. Under normal circumstances all code is generated into the table class directly, which can make overriding method difficult.
The
shim option will make ORLite generate all of it's methods into a seperate
Foo::TableName::Shim class, and leave the main table class
Foo::TableName as a transparent subclass of the shim.
This allows you to alter the behaviour of a table class without having to do nasty tricks with symbol tables in order to alter or replace methods.
package My::Person; # Write a log message when we create a new object sub create { my $class = shift; my $self = SUPER::create(@_); my $name = $self->name; print LOG "Created new person '$name'\n"; return $self; }
The
shim option is global. It will alter the structure of all table classes at once. However, unless you are making alterations to a class the impact of this different class structure should be zero.
You can use this option to tell ORLite that your database uses unicode.
At the moment, it just enables the
sqlite_unicode option while connecting to your database. There'll be more in the future.
All ORLite root packages receive an identical set of methods for controlling connections to the database, transactions, and the issueing of queries of various types to the database.
The example root package Foo::Bar is used in any examples.
All methods are static, ORLite does not allow the creation of a Foo::Bar object (although you may wish to add this capability yourself).
my $string = Foo::Bar->dsn;
The
dsn accessor returns the dbi connection string used to connect to the SQLite database as a string.
my $handle = Foo::Bar->dbh;
To reliably prevent potential SQLite deadlocks resulting from multiple connections in a single process, each ORLite package will only ever maintain a single connection to the database.
During a transaction, this will be the same (cached) database handle.
Although in most situations you should not need a direct DBI connection handle, the
dbh method provides a method for getting a direct connection in a way that is compatible with ORLite's connection management.
Please note that these connections should be short-lived, you should never hold onto a connection beyond the immediate scope.
The transaction system in ORLite is specifically designed so that code using the database should never have to know whether or not it is in a transation.
Because of this, you should never call the ->disconnect method on the database handles yourself, as the handle may be that of a currently running transaction.
Further, you should do your own transaction management on a handle provided by the <dbh> method.
In cases where there are extreme needs, and you absolutely have to violate these connection handling rules, you should create your own completely manual DBI->connect call to the database, using the connect string provided by the
dsn method.
The
dbh method returns a DBI::db object, or throws an exception on error.
my $dbh = Foo::Bar->connect;
The
connect method is provided for the (extremely rare) situation in which you need a raw connection to the database, evading the normal tracking and management provided of the ORM.
The use of raw connections in this manner is strongly discouraged, as you can create fatal deadlocks in SQLite if either the core ORM or the raw connection uses a transaction at any time.
To summarise, do not use this method unless you REALLY know what you are doing.
YOU HAVE BEEN WARNED!
my $active = Foo::Bar->connected;
The
connected method provides introspection of the connection status of the library. It returns true if there is any connection or transaction open to the database, or false otherwise.
Foo::Bar->begin;
The
begin method indicates the start of a transaction.
In the same way that ORLite allows only a single connection, likewise it allows only a single application-wide transaction.
No indication is given as to whether you are currently in a transaction or not, all code should be written neutrally so that it works either way or doesn't need to care.
Returns true or throws an exception on error.
While transaction support is always built for every ORLite-generated class tree, if the database is opened
readonly the
commit method will not exist at all in the API, and your only way of ending the transaction (and the resulting persistent connection) will be
rollback.
Foo::Bar->commit;
The
commit method commits the current transaction. If called outside of a current transaction, it is accepted and treated as a null operation.
Once the commit has been completed, the database connection falls back into auto-commit state. If you wish to immediately start another transaction, you will need to issue a separate ->begin call.
Returns true or throws an exception on error.
Foo::Bar->begin; # Code for the first transaction... Foo::Bar->commit
commit_begin method is used to
commit the current transaction and immediately start a new transaction, without disconnecting from the database.
Its exception behaviour and return value is identical to that of a plain
commit call.
The
rollback method rolls back the current transaction. If called outside of a current transaction, it is accepted and treated as a null operation.
Once the rollback has been completed, the database connection falls back into auto-commit state. If you wish to immediately start another transaction, you will need to issue a separate ->begin call.
If a transaction exists at END-time as the process exits, it will be automatically rolled back.
Returns true or throws an exception on error.
Foo::Bar->begin; # Code for the first transaction... Foo::Bar->rollback
rollback_begin method is used to
rollback the current transaction and immediately start a new transaction, without disconnecting from the database.
Its exception behaviour and return value is identical to that of a plain
commit call.
Foo::Bar->do( 'insert into table (foo, bar) values (?, ?)', {}, $foo_value, $bar_value, );
The
do method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
selectall_arrayref method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
selectall_hashref method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
selectcol_arrayref method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
selectrow_array method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
selectrow_arrayref method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
selectrow_hashref method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction.
It takes the same parameters and has the same return values and error behaviour.
The
prepare method is a direct wrapper around the equivalent DBI method, but applied to the appropriate locally-provided connection or transaction
It takes the same parameters and has the same return values and error behaviour.
In general though, you should try to avoid the use of your own prepared statements if possible, although this is only a recommendation and by no means prohibited.
# Get the user_version for the schema my $version = Foo::Bar->pragma('user_version');
The
pragma method provides a convenient method for fetching a pragma for a datase. See the SQLite documentation for more details.
When you use ORLite, your database tables will be available as objects named in a camel-cased fashion. So, if your model name is Foo::Bar...
use ORLite { package => 'Foo::Bar', file => 'data/sqlite.db', };
... then a table named 'user' would be accessed as
Foo::Bar::User, while a table named 'user_data' would become
Foo::Bar::UserData.
my $namespace = Foo::Bar::User->base; # Returns 'Foo::Bar'.
print Foo::Bar::UserData->table; # 'user_data'
While you should not need the name of table for any simple operations, from time to time you may need it programatically. If you do need it, you can use the
table method to get the table name.
# List the columns in the underlying table my $columns = Foo::Bar::User->table_info; foreach my $c ( @$columns ) { print "Column $c->{name} $c->{type}"; print " not null" if $c->{notnull}; print " default $c->{dflt_value}" if defined $c->{dflt_value}; print " primary key" if $c->{pk}; print "\n"; }
The
table_info method is a wrapper around the SQLite
table_info pragma, and provides simplified access to the column metadata for the underlying table should you need it for some advanced function that needs direct access to the column list.
Returns a reference to an
ARRAY containing a list of columns, where each column is a reference to a
HASH with the keys
cid,
dflt_value,
name,
notnull,
pk and
type.
my $user = Foo::Bar::User->new( name => 'Your Name', age => 23, );
The
new constructor creates an anonymous object, without reading or writing it to the database. It also won't do validation of any kind, since ORLite is designed for use with embedded databases and presumes that you know what you are doing.
my $user = Foo::Bar::User->new( name => 'Your Name', age => 23, )->insert;
The
insert method takes an existing anonymous object and inserts it into the database, returning the object back as a convenience.
It provides the second half of the slower manual two-phase object construction process.
If the table has an auto-incrementing primary key (and you have not provided a value for it yourself) the identifier for the new record will be fetched back from the database and set in your object.
my $object = Foo::Bar::User->new( name => 'Foo' )->insert; print "Created new user with id " . $user->id . "\n";
my $user = Foo::Bar::User->create( name => 'Your Name', age => 23, );
While the
new +
insert methods are useful when you need to do interesting constructor mechanisms, for most situations you already have all the attributes ready and just want to create and insert the record in a single step.
The
create method provides this shorthand mechanism and is just the functional equivalent of the following.
sub create { shift->new(@_)->insert; }
It returns the newly created object after it has been inserted.
my $user = Foo::Bar::User-
Foo::Bar::User object, or throws an exception if the object does not exist.
The
id accessor is a convenience method that is added to your table class to increase the readability of your code when ORLite detects certain patterns of column naming.
For example, take the following definition where convention is that all primary keys are the table name followed by "_id".
create table foo_bar ( foo_bar_id integer not null primary key, name string not null, )
When ORLite detects the use of this pattern, and as long as the table does not have an "id" column, the additional
id accessor will be added to your class, making these expressions equivalent both in function and performance.
my $foo_bar = My::FooBar->create( name => 'Hello' ); # Column name accessor $foo_bar->foo_bar_id; # Convenience id accessor $foo_bar->id;
As you can see, the latter involves much less repetition and reads much more cleanly.
my @users = Foo::Bar::User->select; my $users = Foo::Bar::User->select( 'where name = ?', @args );
The
select method is used to retrieve objects from the database.
In list context, returns an array with all matching elements. In scalar context an array reference is returned with that same data.
You can filter the results or order them by passing SQL code to the method.
my @users = DB::User->select( 'where name = ?', $name ); my $users = DB::User->select( 'order by name' );
Because
select provides only the thinnest of layers around pure SQL (it merely generates the "SELECT ... FROM table_name") you are free to use anything you wish in your query, including subselects and function calls.
If called without any arguments, it will return all rows of the table in the natural sort order of SQLite.
Foo::Bar::User- ( Foo::Bar::User->select ) { print $_->name . "\n"; }
You can filter the list via SQL in the same way you can with
Foo::Bar::User-.
Foo::Bar->iterate( 'select name from user order by name', sub { print $_->[0] . "\n"; } );
my $everyone = Foo::Bar::User->count; my $young = Foo::Bar::User->count( 'where age <= ?', 13 );
You can count the total number of elements in a table by calling the
count method with no arguments. You can also narrow your count by passing sql conditions to the method in the same manner as with the
select method.
# Delete a single object from the database $user->delete; # Delete a range of rows from the database Foo::Bar::User->delete( 'where age <= ?', 13 );
The
delete method will delete the single row representing an object, based on the primary key or SQLite rowid of that object.
The object that you delete will be left intact and untouched, and you remain free to do with it whatever you wish.
# Delete a range of rows from the database Foo::Bar::User->delete( 'age <= ?', 13 );
The
delete_where static method allows the delete of large numbers of rows from a database while protecting against accidentally doing a boundless delete (the
truncate method is provided specifically for this purpose).
It takes the same parameters for deleting as the
select method, with the exception that the "where" keyword is automatically provided for your and should not be passed in.
This ensures that providing an empty of null condition results in an invalid SQL query and the deletion will not occur.
Returns the number of rows deleted from the database (which may be zero).
# Clear out all records from the table Foo::Bar::User->truncate;
The
truncate method takes no parameters and is used for only one purpose, to completely empty a table of all rows.
Having a separate method from
delete not only prevents accidents, but will also do the deletion via the direct SQLite
TRUNCATE TABLE query. This uses a different deletion mechanism, and is significantly faster than a plain SQL
DELETE.
- Support for intuiting reverse relations from foreign keys
- Document the 'create' and 'table' params
Bugs should be reported via the CPAN bug tracker at
For other issues, contact the author.
Adam Kennedy <adamk@cpan.org>
ORLite::Mirror, ORLite::Migrate, ORLite::Pod
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module. | http://search.cpan.org/~adamk/ORLite-1.98/lib/ORLite.pm | CC-MAIN-2016-26 | refinedweb | 4,084 | 50.87 |
Give your environment a quick test run to make sure you’re all set up:
docker run hello-world
It’s time to begin building an app the Docker way. We’ll."]
This
Dockerfile refers to a couple of files we haven’t created yet, namely
app.py and
requirements.txt. Let’s create those next.
from flask import Flask from redis import Redis, RedisError import os import socket # Connect to Redis red.
We are ready to build the app. Make sure you are still at the top level of your new directory. Here’s what
ls should show:
$ ls Docker images REPOSITORY TAG IMAGE ID friendlyhello latest 326387cea398
Run the app, mapping your machine’s port 4000 to the container’s published port 80 using
-p:
docker run -p 4000:80 friendlyhello
You should see a notice, including “Hello World” text, the container ID, and the Redis error message.
You can also use the
curl command in a shell to view the same content.
$ curl <h3>Hello World!</h3><b>Hostname:</b> 8fc990912a14<br/><b>Visits:</b> <i>cannot connect to Redis, counter disabled</i>
Note: This port remapping of
4000:80is to demonstrate the difference between what you
EXPOSEwithin the
Dockerfile, and what you
publishusing
docker run -p. In later steps, we’ll just map port 80 on the host to port 80 in the container and use.
Hit
CTRL+C in your terminal to quit. ls CONTAINER ID IMAGE COMMAND CREATED 1fa4ab2cf395 friendlyhello "python app.py" 28 seconds ago
You’ll see that
CONTAINER ID matches what’s on.
Now use
docker stop to end the process, using the
CONTAINER ID, like so:
docker stop 1fa4ab2cf395
To demonstrate the portability of what we just created, let’s upload our built image and run it somewhere else. After all, you’ll need to learn’ll be using Docker’s public registry here just because it’s free and pre-configured, but there are many public ones to choose from, and you can even set up your own private registry using Docker Trusted Registry.
If you don’t have a Docker account, sign up for one at cloud.docker.com. Make note of your username.
Log in to the Docker public registry on your local machine.
docker login
part1
Run docker images to see your newly tagged image. (You can also use
docker image ls.)
$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE friendlyhello latest d9e555c53008 3 minutes ago 195MB john/get-started part1 d9e555c53008 3 minutes ago 195MB python 2.7-slim 1c7128a655f6 5 days ago 183MB ...
Upload your tagged image to the repository:
docker push username/repository:tag
Once complete, the results of this upload are publicly available. If you log in to Docker Hub, you will see the new image there, with its pull command.
From now on, you can use
docker run and run your app on any machine with this command:
docker run -p 4000:80 username/repository:tag
If the image isn’t available locally on the machine, Docker will pull it from the repository.
docker image rm <image id>
$ docker run -p 4000:80 john/get-started:part1 Unable to find image 'john/get-started:part1' locally part1: Pulling from orangesnap1 * Running on (Press CTRL+C to quit)
Note: If you don’t specify the
:tagportion of these commands, the tag of
:latestwill be assumed, both when you build and when you run images. Docker will use the last version of the image that ran without a tag specified (not necessarily the most recent image).
No matter where
docker run executes, it pulls your image, along with Python and all the dependencies from
requirements.txt, and runs your code. It all travels together in a neat little package, and the host machine doesn’t have to install anything but Docker to run it.
That’s all for this page. In the next section, we will learn how to scale our application by running this container in a service.
Here’s a terminal recording of what was covered on this page:
Here is a list of the basic Docker commands from this page, and some related ones if you’d like to explore a bit before moving on.
docker build -t friendlyname . # Create image using this directory's Dockerfile docker run -p 4000:80 friendlyname # Run "friendlyname" mapping port 4000 to 80 docker run -d -p 4000:80 friendlyname #. | http://docs.w3cub.com/docker~17/get-started/part2/ | CC-MAIN-2018-13 | refinedweb | 736 | 61.56 |
Hi,
I found a way to reproduce a bug found in "set_viewport_position"
1 - With default sublime installation and no plugins. Even with all the default py files uninstalled (this makes no difference).2 - Save this script as file set_viewport_position_bug.py :
>>> sublime.active_window().active_view().viewport_position()
(0.0, 500.0)
4 - Now, here is the bug.Open the same file via the sidebar. And you will notice that the view is not scrolled.
>>>.
This is very strange because is only happening with some file types.
For example if I rename Monokai.tmTheme to Monokai.css this is not reproducible.
This seems to be reproducible with xml, txt, html and I don't know if more files.
I just updated the example:
import sublime, sublime_plugin
class setviewport_bug(sublime_plugin.EventListener):
def on_load(self, view):
view.set_viewport_position((0, 500), False)
print (view.viewport_position())
Save this a bug.py
Problems:Now not only the view is not scrolled, the following API call is lying.
print (view.viewport_position())
is printing
(0.0, 500.0)
But that is not correct because the first visible line is 1. And also this is confirmed by
sublime.active_window().active_view().viewport_position()
Which display
(0.0, 0.0)
It looks like sublime text, overwrite the scroll the first time the file is opened.The problem is always reproducible when you open a file from -> File -> Open Recent -> Pick the file.
Please fix!
bump
Please fix this. BufferScroll relies on it and it is an invaluable plugin. Thanks.
^ Creating an account to just post this, deserves a fix , unfortunately, not on my end.
same problem.
if view.scope == text.*: sublime won't restore.
only restore view.scope == source.* | https://forum.sublimetext.com/t/please-fixme-a-reproducible-bug-in-set-viewport-position/5064/4 | CC-MAIN-2016-30 | refinedweb | 274 | 70.8 |
tag:blogger.com,1999:blog-8712770457197348465.post5954818268460046146..comments2019-09-15T00:45:19.202-07:00Comments on Javarevisited: Top 15 Data Structures and Algorithm Interview Questions for Java Programmer - Answersjavin paul MARica, I have added it. Thanks MARica, I have added it. Javin Paul for the article! Could you add link to ques...Thanks for the article!<br />Could you add link to question 14 - you've already writem the post with the answer <br /> cheat sheet is a good resource, backed up by ...This cheat sheet is a good resource, backed up by a github repo - you please provide the code for you own hashta...Can you please provide the code for you own hashtable implementation with you own hashcode functionPayel Das, if I open the applications on my desktop one ...sir, if I open the applications on my desktop one after another immediatly,then on which data structure the applications stored?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-55808956770967226452015-12-03T18:46:24.265-08:002015-12-03T18:46:24.265-08:00For Java Developers, I would say to prepare well f...For Java Developers, I would say to prepare well for DS and Algo, you can check some <a href="" rel="nofollow">sample Data structure questions</a> here, once you are good at that, just prepare some <a href=" did u dind the answer for this question? Could ...hi did u dind the answer for this question? Could u pls share it<br />ThanksAnas Zyoud for it I didn't see breaksorry for it I didn't see breakAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-10550085147842454812015-03-12T11:26:13.922-07:002015-03-12T11:26:13.922-07:00this code never print its an infinite while loop u...this code never print its an infinite while loop u madeAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-60626368318421366712014-12-17T01:50:04.506-08:002014-12-17T01:50:04.506-08:00Some more algorithm interview questions for true c...Some more algorithm interview questions for true coders :<br /><br />- write code to implement radix sort <br />- write code for two pivot quicksort algorithmAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-53044637733505481712014-12-10T16:20:54.038-08:002014-12-10T16:20:54.038-08:00Your solution for finding the 3rd node from the en...Your solution for finding the 3rd node from the end of the list while may work is not a solution that will get a pass in an interview. Using two pointers shows a fundamental lack of understanding of how to properly traverse lists.<br /><br />There's two ways I would accept as 'correct'. One using a loop and a pointer. Or the even better way of using recursion. Both of them would The Pest help visual c++ define structuer employee ...anybody help<br />visual c++<br />define structuer employee with name,salary,employmantday then define array of 4 employees then print name of the employee with highst salary and names of all employees who works more than 10 yearsAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-88624701513071922102014-09-18T08:39:59.498-07:002014-09-18T08:39:59.498-07:00@Taurun Once again(parser kills my code) Here is O...@Taurun<br />Once again(parser kills my code)<br />Here is O(n) solution:<br /><br /> was asked this question at Deutsche bank. If yo...I was asked this question at Deutsche bank. <br />If you were given all the prices of a stock for a given day in an array of double, you need to find the best buy and sell price. <br />You can only buy stock first and then sell it after that (short-selling is not allowed). <br /><br />The hint is to find the buy and sell prices that give you maximum profit.<br /><br />I've a solution that is Tarun a lot for all the blogs. It helped me get a...Thanks a lot for all the blogs. It helped me get a job at major investment bank.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-54215872283562810102014-07-08T13:47:53.346-07:002014-07-08T13:47:53.346-07:00Whenever looping is blocked, the next resort is re...Whenever looping is blocked, the next resort is recursive and vice versa<br /><br />void printstararray(int N)<br />{<br /> if (n == 0) return;<br /> printNstars(N);<br /> printstararray(N-1);<br />}Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-15923559888816779052014-05-20T11:35:18.275-07:002014-05-20T11:35:18.275-07:00can any one help me Write code in Java that prints...can any one help me<br />Write code in Java that prints:<br /><br />For n = 5<br />*****<br />****<br />***<br />**<br />*<br /><br />You are given this routine<br /><br />private static void printNstars(int n) {<br /> for (int i = 0; i < n; ++i) {<br /> System.out.print("*") ;<br /> }<br /> System.out.println() ;<br />}<br /><br />YOU NEED to write the routine below, whichAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-37278017028221113132014-05-20T11:32:53.721-07:002014-05-20T11:32:53.721-07:00Write a routine X in Java that takes an integer n ...Write a routine X in Java that takes an integer n and returns sum of 1+2+.. +n and square of number n<br /><br />If n = 5, sum = 15 and square is 25. <br /><br /> Write routine X in Java<br /><br />can any one,please give me the soloution<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-91877098174625098502014-01-16T20:12:20.448-08:002014-01-16T20:12:20.448-08:00Regarding Q-2 we can do it by storing the next poi...Regarding Q-2<br />we can do it by storing the next pointer values of each node , if any duplicate comes then it's a loop.<br />or<br />we can also do with two pointers in O(n). simply say one slow pointer and one fast pointer. slow pointer will increase one time where as fast pointer will increase twice. so if we get fastpointer==slowpointer then there is loop , and if fastpointer==null thentech show Question number nine if we just have to find t...For Question number nine if we just have to find the Duplicate values and not their occurance below code is sufficient:<br /><br />import java.util.HashSet;<br />import java.util.Set;<br /><br />public class DuplicateFinder <br />{<br /> public Set getDuplicateValues(T[] arr)<br /> {<br /> Set duplictes = new HashSet();<br /> Set hashSet = new HashSet(arr.length);<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-66227911847731532292013-10-31T06:29:25.269-07:002013-10-31T06:29:25.269-07:00ans of q4 is not correct. ans would be int[] o = ...ans of q4 is not correct.<br />ans would be <br />int[] o = {1,2,3,4,5,6,2,8,9,10};<br />int[] n = new int[o.length+1];<br />for(int i= 0; i < o.length; i++){<br /> n[o[i]]++;<br />}<br /> <br />for(int i= 0; i < o.length; i++){<br /> System.out.println("no of "+ o[i] + " is "+ n[o[i]]);<br />}<br /> Tapan Kumar Dinda you help me: Consider the file named cars.txt...can you help me:<br /><br />Consider the file named cars.txt, each line in the file contains information about a <br />car (Year, Company, Manufacture, ModelName, Type ). <br />1) Read the file. <br />2) Add each car which is represented using one line of the file to a singular link <br />list. Use an object of the following class. <br />Class node <br />{ <br />int year; <br />stringCompany; <brshouq alshammari gyuz, I want to check the two strings are match...HI gyuz, I want to check the two strings are matching 70% or not. Can anyone help me out?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-38576256031559564862013-06-19T22:32:25.522-07:002013-06-19T22:32:25.522-07:00Given a string S, and a list of strings of positiv..Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-68865247237971823792013-04-30T00:28:21.744-07:002013-04-30T00:28:21.744-07:00Which data-structure should I use to detect deadlo...Which data-structure should I use to detect deadlock between threads? This was asked as write a routine to detect deadlock from a pool of threads to me in a Java interview.Venkynoreply@blogger.com | https://javarevisited.blogspot.com/feeds/5954818268460046146/comments/default | CC-MAIN-2019-39 | refinedweb | 1,424 | 66.13 |
This is a cross-post from and was originally written years ago. I wanted to import it from my site's RSS feed but dev.to only appears to scrape the last 10 posts.
I've been on a quest over the last year or so to understand fully how a program ends up going from your brain into code, from code into an executable and from an executable into an executing program on your processor. I like the point I've got to in this pursuit, so I'm going to brain dump here :)
Prerequisite Knowledge: Some knowledge of assembler will help. Some knowledge of processors will also help. I wouldn't call either of these necessary, though, I'll try my best to explain what needs explaining. What you will need, though, is a toolchain. If you're on Ubuntu, hopefully this article will help. If you're on another system, Google for "[your os] build essentials", e.g. "arch linux build essentials".
The Birth of a Program
You have an idea for a program. It's the best program idea you've ever had so you quickly prototype something in C:
#include <stdio.h> int main(int argc, char* argv[]) { printf("Hello, world!\n"); return 0; }
A work of genius. You quickly compile and run it to make sure all is good:
$ gcc hello.c -o hello $ ./hello Hello, world!
Boom!
But wait... What has happened? How has it gone from being quite an understandable high level program into being something that your processor can understand and run. Let's go through what's happening step by step.
GCC is doing a tonne of things behind the scenes in the
gcc hello.c -o hello command. It is compiling your C code into assembly, optimising lots in the process, then it is creating "object files" out of your assembly (usually in a format called ELF on Linux platforms), then it is linking those object files together into an executable file (again, executable ELF format). At this point we have the
hello executable and it is in a well-known format with lots of cross-machine considerations baked in.
After we run the executable, the "loader" comes into play. The loader figures out where in memory to put your code, it figures out whether it needs to mess about with any of the pointers in the file, it figures out of the file needs any dynamic libraries linked to it at runtime and all sorts of mental shit like that. Don't worry if none of this makes sense, we're going to go into it in good time.
Compiling from C to assembly
This is a difficult bit of the process and it's why compilers used to cost you an arm and a leg before Stallman came along with the Gnu Compiler Collection (GCC). Commercial compilers do still exist but the free world has standardised on GCC or LLVM, it seems. I won't go into a discussion as to which is better because I honestly don't know enough to comment :)
If you want to see the assembly output of the
hello.c program, you can run the following command:
$ gcc -S hello.c
This command will create a file called
hello.s, which contains assembly code. If you've never worked with assembly code before, this step is going to be a bit of an eye opener. The file generated will be long, difficult to read and probably different to mine depending on your platform.
Now is not the time or place to teach assembly. If you want to learn, this book is a brilliant place to start. I will, however, point out a little bit of
weirdness in the file. Do you see stuff like this?
EH_frame0: Lsection_eh_frame: Leh_frame_common: Lset0 = Leh_frame_common_end-Leh_frame_common_begin .long Lset0 Leh_frame_common_begin: .long 0 .byte 1 .asciz "zR" .byte 1 .byte 120 .byte 16 .byte 1 .byte 16 .byte 12 .byte 7 .byte 8 .byte 144 .byte 1 .align 3
I was initially curious as to what this was as well, so I checked out stack overflow and came across a really great explanation of what this bit means, which you can read here.
Also, notice the following:
callq _puts
The assembly program is calling
puts instead of
printf. This is an example of the kind of optimisation GCC will do for you, even on the default level of "no optimisation" (
-O0 flag on the command line).
printf is a really heavy function, due to having to deal with a large range of format codes.
puts is far less heavy. I could only find the NetBSD version of it.
puts itself is very small and it delegates to
__sfvwrite, the code of which is here. If you want more information on how GCC will optimise
printf, this is a great article.
Also, if assembler is a bit new to you, a few things to note is that this post is using GAS (Gnu Assembler) syntax. There are different assemblers out there, a lot of people like the Netwide Assembler (NASM) which has a more human friendly syntax.
GAS suffixes its commands with a letter that describes what "word size" we're dealing with. Above, you'll see we used
callq. The
q stands for "quad", which is a 64bit value. Here are other suffixes you may run in to:
- b = byte (8 bit)
- s = short (16 bit integer) or single (32-bit floating point)
- w = word (16 bit)
- l = long (32 bit integer or 64-bit floating point)
- q = quad (64 bit)
- t = ten bytes (80-bit floating point)
Assembling into machine code
By comparison, turning assembly instructions into machine code is pretty simple. Compiling is a much more difficult step than assembling is. Assembly instructions are often a 1 to 1 mapping into machine code.
At the end of the assembling stage, you would expect to have a file that just contained binary instructions right? Sadly that's not quite the case. The processor needs to know a lot more about your code than just the instructions. To facilitate passing this required meta-information there are a variety of binary file formats. A very common one in *nix systems is ELF: executable linkable format.
Your program will be broken up into lots of sections. For example, a section called
.text contains your program code. A section called
.bss stores statically initialised variables (globals, essentially), that are not given a starting value, thus get zeroed. A section called
.strtab contains a list of all of the strings you plan on using in your program. If you statically initialise a string anywhere, it'll go into the
.strtab section. In our
hello.c example, the string
"Hello, world!\n" will go into the
.strtab.
This article, from issue 13 of Linux Journal in 1995, gives a really good overview of the ELF format from one of the people who created it. It's quite in depth and I didn't understand everything he said (still not sure on relocations), but it's very interesting to see the motivations behind the format.
Linking into an executable
Coming back from the previous tangent, let's think about linking. When you compile multiple files, the
.c files get compiled into
.o files. When I first started doing C code, one thing that continuously baffled me was how a
.c file referenced a function in another
.c file. You only reference
.h files in a
.c file, so how did it know what code to run?
The way it works is by creating a symbol table. There are a multitude of types of symbols in an executable file, but the general gist is that a symbol is a named reference to something. The
nm utility allows you to inspect an executable file's symbol table. Here's some example output:
$ nm hello 0000000100001048 B _NXArgc 0000000100001050 B _NXArgv 0000000100001060 B ___progname 0000000100000000 A __mh_execute_header 0000000100001058 B _environ U _exit 0000000100000ef0 T _main U _puts 0000000100001000 d _pvars U dyld_stub_binder 0000000100000eb0 T start
Look at the symbols labelled with the letter
U. We have
_exit,
_puts and
dyld_stub_binder. The
_exit symbol is operating system specific and will be the routine that knows how to return control back to the OS once your program has finished, the
_puts symbol is very important for our program and exists in whatever libc we have, and
dyld_stub_binder is an entry point for resolving dynamic loads. All of these symbols are "unresolved", which means if you try and run the program and no suitable match is found for them, your program will fail.
So when you create an object file, the reason you include the header is because everything in that header file will become an unresolved symbol. The process of linking multiple object files together will do the job of finding the appropriate function that matches your symbol and link them together for the final executable created.
To demonstrate this, consider the following C file:
#include <stdio.h> extern void test(void); int main(int argc, char* argv[]) { printf("Hello, world!\n"); return 0; }
Compiling this file into an object file and then inspecting the contents will show you the following:
$ gcc -c hello.c $ nm hello.o 0000000000000050 r EH_frame0 000000000000003b r L_.str 0000000000000000 T _main 0000000000000068 R _main.eh U _puts U _test
We now have an unresolved symbol called
_test! The linker will expect to find that somewhere else and, if it does not, will throw a bit of a hissy fit. Trying to link this file on its own complains about 2 unresolved symbols,
_test and
_puts. Linking it against libc complains about one unresolved symbol,
_test.
Unfortunately, because we don't actually have a definition for
test() we can't use it. This may sound confusing, seeing as we defer the linking of
puts() until runtime. Why can't we just do the same with
test()? Build an executable file and let the loader/linker try and figure it out at runtime?
In the linking process you need to specify where the linker will be able to find things on the target system. Let's step through the original
hello.c example, doing each of the compilation steps ourself:
$ gcc -c hello.c
This creates
hello.o with an unresolved
_puts symbol.
$ ld hello.o
This craps out. We need to give it more information. At this point I'm going to mention that I'm on a Mac system and am about to reference libraries that have different names on a Linux system. As a general rule here, you can replace the
.dylib extension with
.so:
$ ld hello.o /usr/lib/libc.dylib
This still craps out. Check out this error message:
ld: entry point (start) undefined. Usually in crt1.o for inferred architecture x86_64
What the hell? This is a really good error to come across and learn about, though. It leads us nicely into the next section.
Running the program
Wait, didn't we finish the last section with an object file that wouldn't link for some arcane reason? Yes, we did. But getting to a point where we can successfully link it requires us to know a little bit more about how our program starts running when it's loaded into memory.
Before every program starts, the operating system needs to set things up for it. Things such as a stack, a heap, a set of page tables for accessing virtual memory and so on. We need to "bootstrap" our process and set up a good environment for it to run in. This setup is usually done in a file called
crt0.o.
When you started learning programming and you used a language that got compiled, one of the first things you learned was that your program's entry point is
main() right? The true story is that your program doesn't start in main, it starts in
start. This detail is abstracted away from you by the OS and the toolchain, though, in the form of the
crt0.o file.
The osdev wiki shows a great example of a simple
crt0.o file that I'll copy here:
07/08/2013 UPDATE: In a previous version of this post I got this bit totally wrong, confusing the 32bit x86 calling convention with the x86-64 calling convention. Thanks to Craig in the comments for pointing it out :) The below should now be correct.
The line that's probably most interesting there is where
main is called. This is the entry point into your code. Before it happens, there is a lot of setup. Also notice that
argc and
argv handling is done in this file, but it assumes that the loader has pushed the values into registers beforehand.
Why, you might ask, do
argc and
argv live in
%rsi and
%rdi before being passed to your main function? Why are those registers so special?
The reason is something called a "calling convention". This convention details how arguments should be passed to a function call before it happens. The calling convention in x86-64 C is a little bit tricky but the explanation (taken from here) is as follows:
For example, take this C code:
void add(int a, int b) { return a + b; } int main(int argc, char* argv[]) { add(1, 12); return 0; }
The assembler that would call that function goes something like this:
movq $1, %rdi movq $12, %rsi call add
The
$12 and
$1 there are the literal, decimal values being passed to the function. Easy peasy :) The convention isn't something that needs to be followed in your own assembly code. You're free to put arguments wherever you want, but if you want to interact with existing library functions then you need to do as the Romans do.
With all of this said and done, how do we correctly link and run our
hello.o file? Like so:
$ ld hello.o /usr/lib/libc.dylib /usr/lib/crt1.o -o hello $ ./hello Hello, world!
Hey! I thought you said it was
crt0.o? It can be...
crt1.o is a file with exactly the same purpose but it has more in it.
crt0.o didn't exist on my system, only
crt1.o did. I guess it's an OS decision. Here's a short mailing list post that talks about it.
Interestingly, inspecting the symbol table of the executable we just linked together shows this:
$ nm hello 0000000000002058 B _NXArgc 0000000000002060 B _NXArgv U ___keymgr_dwarf2_register_sections 0000000000002070 B ___progname U __cthread_init_routine 0000000000001eb0 T __dyld_func_lookup 0000000000001000 A __mh_execute_header 0000000000001d9a T __start U _atexit 0000000000002068 B _environ U _errno U _exit U _mach_init_routine 0000000000001d40 T _main U _puts U dyld_stub_binder 0000000000001e9c T dyld_stub_binding_helper 0000000000001d78 T start
The reason is that
.dylib and
.so files (they have the same job, but on Mac they have the
.dylib extension and probably a different internal format) are dynamic or "shared" libraries. They will tell the linker that they are to be linked dynamically, at runtime, rather than statically, at compile time. The
crt*.o files are normal objects, and link statically which is why the
start symbol has an address in the above symbol table.
The Death of a Running Program
You return a number from
main() and then your program is done, right? Not quite. There is still a lot of work to be done. For starters, your exit code needs to be propagated up to any parent processes that may be anticipating your death. The exit code tells them something about how your program finished. Exactly what it tells them is entirely up to you, but the standard is that 0 means everything was okay, anything non-zero (up to a max of 255) signifies that an error occurred.
There is also a lot of OS cleanup that happens when your program dies. Things like tidying up file descriptors and deallocating any heap memory you may have forgotten to
free() before you returned. You should totally get into the habit of cleaning up yourself, though!
Wrapping up
So that's about the extent of my knowledge on how your code gets turned into a running program. I know I missed some bits out, oversimplified some things and I was probably wrong in places. If you can correct me on any point, or have anything illuminating about how non-x86 or non-ELF systems do the above tasks, I would love to have a discussion about it in the comments :)
Discussion (0) | https://dev.to/samwho/the-birth-and-death-of-a-running-program-2bk0 | CC-MAIN-2021-49 | refinedweb | 2,765 | 72.97 |
Java is strictly Pass By Value !Pass by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments are always passed by value whether its Java primitive types or Java Objects. In the case of Java Objects, Java copies and passes the reference by value, not the object.
Sample Java code to TEST java parameter passing
package com.as400samplecode; import java.awt.Point; public class ParameterTest { public static void main(String[] args) { int myVariable1 = 100; int myVariable2 = 200; SimpleTest(myVariable1,myVariable2); System.out.println("Variable1: " + myVariable1); System.out.println("Variable2: " + myVariable2); Point pointA = new Point(100,100); Point pointB = new Point(200,200); System.out.println("AX: " + pointA.x + " AY: " +pointA.y); System.out.println("BX: " + pointB.x + " BY: " +pointB.y); ObjectTest(pointA,pointB); System.out.println("AX: " + pointA.x + " AY: " +pointA.y); System.out.println("BX: " + pointB.x + " BY: " +pointB.y); } private static void SimpleTest(int variable1, int variable2) { int myVariable = variable1; variable1 = variable2; variable2 = myVariable; } private static void ObjectTest(Point pointA, Point pointB) { pointA.x = 500; pointA.y = 500; Point myPoint = pointA; pointA = pointB; pointB = myPoint; } }
Results from the above Java ProgramVariable1: 100
Variable2: 200
AX: 100 AY: 100
BX: 200 BY: 200
AX: 500 AY: 500
BX: 200 BY: 200
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing. | https://www.mysamplecode.com/2011/06/java-parameter-passing-method-by.html | CC-MAIN-2019-39 | refinedweb | 248 | 52.05 |
Getting Started with JSON in C# Using Json.NET
Course info
Course info.
Section Introduction Transcripts
Serialization Fundamentals
Hello and welcome to the next module of this Json. NET course, Serialization Fundamentals. Serialization and deserialization is the main functionality of Json. NET. Let's get into the details and understand why it is so important and how it can help you. Serialization and deserialization involves taking a data structure or object and converting it back and forth between JSON text and. NET objects. A. NET object when serialized can be stored as a stream of bytes of file or in memory and later it can be used to recreate the original object. You have to be careful though. In some cases there are private implementation details that are not available when deserializing or serializing, so you need to review the recreated object to determine if there is any information missing. In the serialization and deserialization process, you map property names and copy their values using the main JSON serializer class with the support of JsonReader and JsonWriter. I will show you important considerations to take like working with dates, collections, error handling, along with a few useful tips and tricks. In this module we'll work closely with the next module where I will show you available settings and attributes that help you control the serialization process.
Settings & Attributes
Hello, and welcome to this next module of JSON and Json. NET course. In this module we will learn how to control and customize the serialization process via settings and attributes. So what is a setting? A setting is a user preference that is supplied during the conversion process. It can be specified as a property on the JsonSerializer class or using the JsonSerializer settings on JsonConvert. And what is an attribute? An attribute is a declarative tag that is supplied on classes, properties, and more, that is taking into account during the serialization and deserialization process.
Custom Serialization
Hello, and welcome to the next module of this Json. NET course, Custom Serialization. Json. NET is very powerful with some key features that include conditional serialization, serialization callbacks, debugging, and more. In this module I will teach you how to customize your serialization process with Json. NET along with a few more pieces of information that will prove invaluable and will save you time while coding. Given that we already covered serialization and deserialization, the next step involves taking it a notch further and explaining the more advanced topics around handling JSON. I will be covering conditional serialization. It may be the case that you want to control the serialization process based on specific conditions. I will show you how. Custom JsonConverter. It may be possible that you want to extend or customize the serialization and deserialization process. Let's learn how we can create our own custom JsonConverter to get exactly the results that we need. Serialization callbacks in general are used to raise events before and after the serialization and deserialization process. I will teach you what events are available and when during the process they occur. ITraceWriter. Debugging the serialization is not a common scenario, but being able to do it using ITraceWriter for logging and debugging could be important. Learn the process in this demo to be prepared.
Performance Tips
Hello, and welcome to this next module of this Json. NET course, Performance Tips. In a lot of cases, performance is one of the most critical features of an application. A badly performed application can affect sales, delivery, and in general it can be problematic. So what if your application works with large amounts of JSON or requires quick responses on code that rely on JSON serialization? Json. NET is the way to go. When you compare Json. NET with other serializers, Json. NET is faster. In this module I will demonstrate tips on how to improve performance when using Json. NET, but more than comparing with other serializers, I will teach you multiple tips to make Json. NET serialization even faster including reading and writing JSON directly instead of serializing, working with fragments, populate objects, control what get serialized, and lowering your memory utilization. We will get started with manual serialization. What's this? When you use the JsonSerializer class, serialization uses reflection which is slower than writing and reading JSON directly. We will then go to fragments where I will show you how to work only with a subset of the JSON objects to make reading much faster. With populate objects I will show you how to populate specific properties of a large JSON object instead of working with the full JSON object, which is similar to merge array handling where I will show you how to control when two JSON objects are merged. Then we learn how to improve serialization speed by using attributes to control what is serialized and finally, we will learn how to optimize memory usage when working with JSON. And most importantly, in several of the demos we will be using a stopwatch to capture timings as proof. It is very easy to use. The code is only a few lines long.
LINQ to JSON
Hello, and welcome to the next module of this Json. NET course, LINQ to JSON. LINQ to JSON is an API used to work with JSON objects. LINQ in general has been available for many years, but just in case, I will take a step back and start by talking about LINQ. So what is LINQ? LINQ stands for language integrated query. It extends powerful query capabilities to C# and VB. NET and also it includes functions. Its standard and easily learned patterns for querying and updating data potentially to any store. Among those we have LINQ to SQL, LINQ to XML, LINQ to ADO. NET, LINQ to objects, and of course, LINQ to JSON. It started around Visual Studio 2008 and I'll show you how we can use it with Json. NET. LINQ to JSON can be found under the Newtonsoft. JSON. Linq namespace. You can use it with JTokenReader or JTokenWriter for fast, non-cached, forward only reading and writing of JSON in a LINQ style. It is also possible to parse JSON using JObject. Parse. The parse method is not only available in the JObject class; it is available under many of the LINQ to JSON classes. If you want to create JSON there are many ways. You can do it in an imperative, in a declarative, or in a from object way. Also you can query JSON in a very simple notation or you can use JSON path with SelectToken. Let's learn what can be done with this namespace and how it can help you improve your code.
JSON & XML
Hello, and welcome to the next module of this Json. NET course, JSON and XML. JSON is a data interchange format which is easy for humans to read and write. It is easy for machines to parse and generate. On the other hand, XML is a markup language that defines a set of rules for encoding documents in a format which is also both supported by humans and machines. They both can serve the same purpose; however, converting between them can be a little bit tricky and there are several different considerations to take. In this module I will teach you how to convert between JSON and XML using JSON convert with an understanding of possible scenarios. Let's talk about JSON and XML. Xml is a markup language. It can be used as a data interchange format and it is both easy for humans to understand and machines to process and JSON is a text based data interchange format. It's made up of key value pairs, arrays, and objects. By now you should be very familiar with JSON. It's also easy for humans to understand and machines to process. XML can be used in multiple different ways, but JSON is specifically used as a data interchange format which means that you don't have to guess about the structure of the data that you're receiving. It is very straightforward, so when you're converting data from XML and JSON, there is no standard way of converting it. In many cases the conversion can be simple, but in others, that round trip conversion can be hard. | https://www.pluralsight.com/courses/json-csharp-jsondotnet-getting-started | CC-MAIN-2019-09 | refinedweb | 1,400 | 64.51 |
I am creating an OnCollisionEnter trigger, but having syntax trouble.
if I want OnCollisionEnter to stop transform.translate, how do I write that?
OnCollisionEnter; transform.translate(0,0,0)
I read the documentation, which wrote OnCollisionEnter as a void, however I get an error regarding the 'void' part.
Surely you should use OnTriggerEnter?
I didn't think about that.
...And don't call me Shirley.
for the "void" part: make sure you use C#
for the stop "transform.translate": we need a bit more information here, if you translate you objekt in the update method a simple "transform.translate(0,0,0)" in the OnCollisionEnter/OnTriggerEnter will not work
Answer by Cepheid
·
Apr 21, 2016 at 12:55 PM
Hi there @TheRedGuy90
It's pretty plain to me here that you're probably misunderstanding what OnCollisionEnter is. OnCollisionEnter is a method and thus cannot be used as a statement. To use the OnCollisionEnter method you must define the method within your class and then perform the statements within it, for example:
void OnCollisionEnter (Collision other)
{
transform.Translate(0,0,0);
}
That will now check for a collision and then stop the player's movement when they collide with an object. If this does indeed sound like the problem you were having I would highly recommend you pick up a beginner's book on C# before attempting to go any further otherwise it's going to be an uphill struggle.
I hope this helps!
Parsing error: Member names cannot be the same as their enclosing type
Could please post the entire class that is causing this problem? The error you have shown is occurring because you have named the method the same name as the class. Please ensure that your class name is seperate from the OnCollisionEnter() method. For example:
using UnityEngine;
using System.Collections;
public class Exampleclass : MonoBehaviour
{
void OnCollisionEnter (Collision other)
{
transform.Translate (0, 0, 0);
}
}
I changed the name of the class, which fixed it.
But the script does nothing so far. I would like my character (which the script is attached to) to recognize this when it runs into any collider. I'd like to get rid of Unitys physics, I'm having too many problems with it, so I am writing my.
Sphere bouncing back on edges of aligned objects
0
Answers
Unity 2D colliders not triggering,Unity 2D collider not triggering
0
Answers
Bounce between two exact points
1
Answer
What's the best way to get clean, smooth collision physics?
0
Answers
Colliding multiple enemys but only one at a time attacked
1
Answer | https://answers.unity.com/questions/1174384/oncollisionenter-trigger.html | CC-MAIN-2020-29 | refinedweb | 430 | 64.3 |
Adapt Designs Based on Platforms
Where to Go From Here: Flutter Widgets Catalog
Take the existing material-based app and adapt it to fit cupertino design specification if the underlying platform is iOS.
We’ve covered both material and cupertino based widgets. Sometimes, we might want to show a widget based on the platform. Flutter offers us a way to manually check for the platform our app is running on. We can then use this information and adapt our designs based on the underlying platform.
First, we’ll create a widget that shows the
CircularProgressIndicator on android devices and the
CupertinoActivityIndicator on iOS devices. Create a file named
platform_spinner.dart inside the widgets folder. Update this file to the following:
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class PlatformSpinner extends StatelessWidget { const PlatformSpinner({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final isIOS = Theme.of(context).platform == TargetPlatform.iOS; return Center( child: isIOS ? const CupertinoActivityIndicator() : const CircularProgressIndicator(), ); } }
Save your work. This widget checks the platform the app is running on and displays a
CupertinoActivityIndicator if the platform iOS else it displays a
CircularProgressIndicator. The
Theme.of(context).platform is used to get the defaultTargetPlatform of the app. The key point to note here is that whenever you want to create a platform specific widget, create a custom widget and encapulate the platform checking logic inside that widget.
Next, let’s head over to the
ArticleCard widget. Scroll to the
CardBanner widget and update the
... return Center(child: PlatformSpinner()); ...
Save your work. Then do a hot restart. The android spinner shows up. Let’s try it out for iOS. Head over to
main.dart file and uncomment the platform line. Do a hot restart. You can see the
CupertinoActivityIndicator shows up.
We could also update the spinner in the home page to use this widget. You can go ahead and try that out, and remember to do a hot restart when you change it.As you can see, creating a widget that adapts to different platforms is simple. So if you want to create a platform specific tab bar, create a separate widget that checks the plaform and returns the corrensponding widget.
You can see the
PlatformSpinner widget we just created, we pass it in and it adapts accordingly.
Finally, let’s update the
ArticleCard class to correctly check the underlying platform. Scroll up to the
ArticleCard class. Currently we manually pass an
isIOS boolean. Let’s update this to the correct code like so:
// Remove the isIOS boolean member ... @override Widget build(BuildContext context) { bool isIOS = Theme.of(context).platform == TargetPlatform.iOS; if (isIOS) { ...
Now, with this, we correctly check if the target platfom is iOS then we display the wide card. We also removed the previous definition from the constructor. Save your work. And there you have it, everything works as expected and changing the platorm would display the corresponding design. | https://www.raywenderlich.com/26933987-flutter-ui-widgets/lessons/15 | CC-MAIN-2022-40 | refinedweb | 487 | 52.26 |
On 03/10/2011 12:50 PM, Andrew Morton wrote:> On Thu, 10 Mar 2011 12:35:32 +0300 Pavel Emelyanov <xemul@parallels.com> wrote:> >> On 03/08/2011 02:58 AM, Andrew Morton wrote:>>> On Thu, 03 Mar 2011 11:39:17 +0300>>> Pa>>> namespace. Anyone who was depending on the old behaviour might run>>> into problems?>>>> Hardly. If the behavior of some two apps depends on its synchronous change,>> these two might want to run in the same pid namespace.> > I don't understand your answer. What is this "synchronous change" of which> you speak? Does your "might want to run" suggestion mean that userspace > changes would be required for this operation to again work correctly?Your concern was about "anyone who was depending on the old behaviour", wherethe old behavior meant "a write to sys.pid_max will change the max pid on allprocesses".I wanted to say, that if someone changes pid_max and expects someone else toact differently after this, then these two should live in the same pid namespace.IOW, if X raises the pid_max, then all the processes X sees in its pid namespace*may* have pids up to this value. All the other process, that are not visiblein X's pid space will have other values, but X doesn't see them, so why shouldwe care?> "In current kernels a write to /proc/sys/kernel/pid_max will change the> max pid on all processes." Is this incorrect?Not 100%. If I have some process with pid N and then I change the pid_max to N/2,that process will still have its pid N which is obviously greater, than N/2.> "After this change (ie: this patch), that write will only affect> processes in the current namespace.". Is this incorrect?With the exception stated above - yes, but I don't understand your concern afterthese two questions :(Thanks,Pavel | https://lkml.org/lkml/2011/3/10/110 | CC-MAIN-2015-48 | refinedweb | 314 | 72.36 |
Noob needs help.
I have a situation where I'm asked to ask the user to enter in the number of cities to calculate an average temperature for and then use each of the 3 basic loop structures.
Now where I am is this. I ask the suer how many cities? Then I have a basic for loop wich is working. I can't seem to figure out how to get the program to add up all the temps to do the average. I am also not sure bout the variables.
I'm very new to this. Here is my code
Code:#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { //declare variables int Temp = 0; int averageTemp = 0; int numCities = 0; //double sum = 0; not sure? cout << "Enter the number of cities you would to average: "; cin >> numCities; for ( int i=0; i<=numCities; i++ ) { cout <<"Enter the Temp: "; cin >> Temp; } //for ( int Temp=0; //this is where I'm stuck //averageTemp = (temp + sum) /numCities; cout << "Average temp: " << averageTemp <<endl; system("pause"); return 0; | https://cboard.cprogramming.com/cplusplus-programming/111372-noob-need-help.html | CC-MAIN-2017-22 | refinedweb | 179 | 71.24 |
Hi, Randy Evans here. I’m a principal developer on the Information Security Tools team.
On one of our projects we had a requirement to dynamically load different web parts into a web page at run time. The challenge was that the specific web part needing to be loaded was determined by the user’s action on the web page. Thus, we couldn’t directly reference the web part in the web page’s code. We needed a way to provide the web part’s URL to the page at run time and dynamically load and render the web part. Here is how we solved it.
The first step is knowing how to virtually load a web part to a page at run time. A web part is just a type of web control. A control can be virtually loaded to a page (or any control that has a method to add a child control to it) using the Add method. Example: Page.Controls.Add(Control control). The first problem is how do you instantiate a control object at run time if you don’t know which control you’ll need at design time. The class System.Web.UI.TemplateControl contains a method called LoadControl(string virtualPath). This method returns a System.Web.UI.Control object. The control object can then be loaded on the page using the Add method.
Since the virtualPath parameter of the LoadControl method is a string, you don’t need to write the “new” statement to create the Control object. The LoadControl method does that for you. So, now the only problem is how to get the virtual path of the control. Our solution was to place all dynamically loaded web parts into the same directory of the web site. We added a configuration to the web.config that provides the path to this folder. With this in place, it’s only a matter of determining which web part the user has selected and map that to the web parts filename. This can be done in many different ways depending on the how the particular web site functions. Once you have the filename, concatenate it to the control folder path and pass the string to LoadControl.
The included code demonstrates the use of the objects mentioned above. It is not intended to compile and run as written.
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; public partial class MyWeb : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {} protected void SelectedNodeChanged(object sender, TreeNodeEventArgs e) { try { //The user selects an item out of a tree view control. The item (array[0]) is //passed to a static method that returns the web control's filename. TreeNode selectedNode = e.Node; if (selectedNode != null) { string[] array = selectedNode.Value.Split(','); if (array.Length == 2) { //These next three statements demonstrate how to load a web control dynamically. //Get the path the control folder. string urlPath = ConfigurationManager.AppSettings["ControlFolderPath"]; //Create the virtual path string. string virtualPath = string.Format("{0}/{1}", urlPath, MyStaticUtil.GetControlName(array[0])); //Load the control into the page. It's more likely that you would load the control into a panel. Page.Controls.Add(LoadControl(virtualPath)); } } } } } | https://blogs.msdn.microsoft.com/securitytools/2009/09/25/dynamically-load-web-controls-at-run-time/ | CC-MAIN-2017-47 | refinedweb | 536 | 60.31 |
When building a web application with React, you sometimes have the need to display a large amount of data. Simply rendering it all in a list can become very slow, which can affect the rest of the application.
react-window seeks to solve this problem by rendering only the items in the list that are currently visible. This allows for efficiently rendering lists of any size.
You may be aware of a similar library, react-virtualized. The two libraries are actually made by the same person;
react-window is a complete rewrite with the goal of being smaller, faster, and easier to learn. Because of these goals, however,
react-window does not have every feature implemented in
react-virtualized. Be sure to read the documentation and decide which library works best for you.
Getting Started
To get us started, I’ve set up a small application using create-react-app and Ant Design. To see a more in-depth introduction to Ant Design, check out the blog post: Crafting Beautiful UIs in React Using Ant Design.
Here is what our root component looks like. All I’ve done so far is add a reference to the list component we’re about to create.
index.js
import React from "react"; import ReactDOM from "react-dom"; import List from "./list"; import "./styles.css"; function App() { return ( <div className="App"> <List numItems={100} /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
Now we need to create our list.
Building the List Component
For this demo, I’ll be rendering a list of quotes with a small image next to them. The quotes will be provided by the
random-quotes package, so install that first:
$ yarn add random-quotes # or, using npm: $ npm install random-quotes --save
Create a new file named
list.js. All we need to do is pass our array of quotes into Ant Design’s
<List /> component. For sake of clarity, I’ve extracted this into its own component called
<RegularList />.
list.js
import React from "react"; import randomQuotes from "random-quotes"; import { List, Avatar } from "antd"; import "antd/dist/antd.css"; function RegularList(props) { return ( <List dataSource={props.quotes} renderItem={item => ( <List.Item> <List.Item.Meta avatar={ <Avatar src="" /> } title={item.body} description={item.author} /> </List.Item> )} /> ); } export default class extends React.Component { constructor(props) { super(props); this.state = { quotes: [] }; } componentDidMount() { this.setState({ quotes: randomQuotes(this.props.numQuotes) }); } render() { return <RegularList quotes={this.state.quotes} />; } }
Now our list is perfect! Or is it? Try bumping up the value for the
numItems prop. You’ll see that large values (> 1000) can begin to lag quite terribly, depending on your computer.
Virtualizing our List with react-window
As you can see, I’ve increased
numItems to 10,000:
index.js
// --- snip --- function App() { return ( <div className="App"> <List numItems={10000} /> </div> ); } // --- snip ---
This is very, very slow when used with our
<RegularList /> component. This is where
react-window comes in! Of course, we first need to install it:
$ yarn add react-window # or, with npm: $ npm install react-window --save
react-window provides several different components, but we only need the simplest one,
<FixedSizeList />. This needs the
height,
width,
itemCount, and
itemSize passed as props, and a function which we’ll call
renderRow() passed as a child.
In the
list.js file, create a new component called
<VirtualList />:
list.js
import React from "react"; import randomQuotes from "random-quotes"; import { List, Avatar } from "antd"; import { FixedSizeList as VList } from "react-window"; // -- snip -- class VirtualList extends React.Component { renderRow = ({ index, key, style }) => { const quote = this.props.quotes[index]; return ( <List.Item key={key} style={style}> <List.Item.Meta avatar={ <Avatar src="" /> } title={quote.body} description={quote.author} /> </List.Item> ); }; render() { return ( <List dataSource={this.quotes}> <VList height={window.innerHeight} width={window.innerWidth} itemCount={this.props.quotes.length} itemSize={75} > {this.renderRow} </VList> </List> ); } } export default class extends React.Component { constructor(props) { super(props); this.state = { quotes: [] }; } componentDidMount() { this.setState({ quotes: randomQuotes(this.props.numQuotes) }); } render() { return <VirtualList quotes={this.state.quotes} />; } }
And we’re done! Try scrolling around, the slowdowns are completely gone!
However, you might notice list elements “popping in” if you scroll quickly enough. This is because the elements are being rendered a fraction of a second after they enter the screen. To prevent this from happening, you can simply add the prop
overscanCount to the
<VList />:
list.js
// --- snip --- render() { return ( <List dataSource={this.quotes}> <VList height={window.innerHeight} width={window.innerWidth} itemCount={this.props.quotes.length} itemSize={75} overscanCount={3} > {this.renderRow} </VList> </List> ); } // --- snip ---
That’s it! This tells
react-window to render an extra three items off-screen, so the pop-in isn’t so apparent.
To learn more about
react-window see its website and its Github repository. The full code for this post is available on CodeSandbox. | https://alligator.io/react/lists-with-react-window/ | CC-MAIN-2020-34 | refinedweb | 805 | 60.72 |
putenv - change or add a value to environment
#include <stdlib.h> int putenv(char *string);
The putenv() function uses the string argument to set environment variable values. The string argument should point to a string of the form "name=value". The putenv() function makes the value of the environment variable name equal to value by altering an existing variable or creating a new one. In either case, the string pointed to by string becomes part of the environment, so altering the string will change the environment. The space used by string is no longer used once a new string-defining name is passed to putenv().
This interface need not be reentrant.
Upon successful completion, putenv() returns 0. Otherwise, it returns a non-zero value and sets errno to indicate the error.
The putenv() function may fail if:
- [ENOMEM]
- Insufficient memory was available.
None.
The putenv() function manipulates the environment pointed to by environ, and can be used in conjunction with getenv().
This routine may use malloc() to enlarge the environment.
A potential error is to call putenv() with an automatic variable as the argument, then return from the calling function while string is still part of the environment.
None.
exec, getenv(), malloc(), <stdlib.h>.
Derived from Issue 1 of the SVID. | http://pubs.opengroup.org/onlinepubs/7990989775/xsh/putenv.html | CC-MAIN-2013-20 | refinedweb | 211 | 66.03 |
May 2012
SPECIAL POST-MIFF ISSUE
The official magazine of the Malaysian International Furniture Fair
FURNITURE 360Ëš What industry is doing
NOW to CREATE
digital, 3D, and APP-related product experiences that
SELL MORE STUFF
g n i r o Expl ds of n s r e n n Wi
i the M
A
Superhero Visits
MIFF: Why?
Design and Green
Are Critical Issues of Our Time
contents 04-05 10-11
So Far So Good MIFF 2012 show statistics and visitor feedback
06-07
Buyer Profile A new superhero visits MIFF with some important travel tips
06-07
08-09
05
12-14
Trophy Room Who are the MIFF award winners, really?
15
Cozy Chat Meet Marc—a guy with a lot to say about outdoor furniture
16-20
12-14
So Fa SoG o o d
Cover Story Enter the matrix of cutting edge, digital furniture promotion
Official Show Report Malaysian International Furniture Fair 2012 (MIFF 2012) 6-10 March 2012 Putra World Trade Centre PWTC & MATRADE Exhibition & Convention Centre (MECC) Exhibition size:
75,000 spm
Total Export Sales Generated:
US$ 830 million
Number of Exhibitors:
Total 433
Malaysia 294
International 139 (from 10 countries)
Number of Visitors:
Total 19,118
Malaysia 6,605
International 7,368 (from 140 countries)
04
North America
Africa
Invited Guests 5,145
15
INTErNaTIoNal VISITorShIp By CoMpaNy'S MaIN aCTIVITy
INTErNaTIoNal VISITorShIp By rEGIoN (%)
Architect Government Departmental Official Construction Store Trade Hotel & Catering
Buying Interior Agent Decorator
South America
Australacia Exporter
MIFF Update Why UBM and MIFF have united in partnership
Inti Chain Store Others
Far East Middle East Trading
Importer Other Asian Countries
ASEAN
Retailer
Europe Wholesaler
Manufacturer
INTErNaTIoNal VISITorShIp By purpoSE of VISIT
Place Order
08-09
To Source New Product Seek Representative/ JV Make Contract/ Visit Supplier
Gather Information To Evaluate For Future Participation
0
5
10
The official magazine of the Malaysian International Furniture Fair
15
20
25
16-20
MIFF Industry Seminars Intelligent thought on contemporary furniture issues—right from the show
To Look for Business Opportunities
12
10-11
30
21-25
21-25
Fabulous Furniture Great products on display last March at MIFF
The official magazine of the Malaysian International Furniture Fair Editorial Team
Published by:
Editor & Publisher Matt Young Designers Gan Wei Kiat, Rachel Tang Writers Majella Gomes, Alexandra Wong, Khaw Chia Hui, Chan Li Jin, Yeo Li Shian, Ee-Tan Chow
Media MICE Pte. Ltd. Phone +60 16 778 9871 / + 65 8186 7677 Fax +60 7224 6404 / + 65 6298 6316 Email enquiry@mediamice.com Web
Le tte r to Re a d e rs
You’re Back—Already
I
n the small amount of time that has
passed
since
the
Malaysian
an increase of 6.68 percent over 2011 orders. More overseas buyers also were present, although more importantly, the number of buying companies increased very significantly. While there may have been fewer representatives per
(MIFF)
company travelling to Malaysia—likely as a cost-saving
occurred in March, I’ve noticed an
measure in the current economy—there were about 15-20
International
Furniture
Fair
are
percent more buying companies represented compared to
buying up space more quickly than
2011, which likely accounted for such a large increase in MIFF’s
interesting
trend:
exhibitors
ever before.
sales volume.
As I write this letter, exhibitors
As you will read in the pages of Furnish Now, Malaysian
already have taken up 40 percent
manufacturers have improved drastically over the last 10
of the total show space for MIFF
years. Designs are more innovative and presentation of those
2013. Even before MIFF 2012
designs is getting better.
closed in March, more than 10
In this issue, we focus on digital presentation of furniture
exhibitors reconfirmed space for
in our cover story, which we believe is very important in our
next year. Now more than 100 have
contemporary wired age. We feature some no- to low-cost
reconfirmed.
electronic tools that can help exhibitors and buyers launch
I’m not sharing this to toot
further into the digital presentation sphere right away.
MIFF’s horn, but rather as an
We also include comprehensive coverage of MIFF 2012
interesting phenomenon that’s
speaker sessions for those who may have missed them. MIFF’s
occurring. After all, this trend was
latest award winners also share their personal views on what
not occurring in 2010 or 2011, when
got them to where they are. And of course, we feature more
many exhibitors only began signing
Fabulous Furniture – great pieces indeed from our recently
up two or three months post-show for
exhibited show furniture. Lots more great reading awaits you
the subsequent year’s fair.
What has happened?
in Furnish Now. We hope you enjoy. Best Wishes,
We believe that because of the encouraging response at MIFF 2012, exhibitors are signing up slightly faster than before. Part of the reason may be our new partnership with UBM, the region’s leading tradeshow organiser that acquired MIFF earlier this year. We explain more about that partnership in this issue of Furnish Now. Another reason could be the success of MIFF 2012 itself, which logged record high sales transactions at US$830 million,
Dato’ Dr. Tan Chin Huat Chairman, MIFF
SPECIAL POST-MIFF ISSUE May 2012
03
So Fa r
SoG oo d
Official Show Report Malaysian International Furniture Fair 2012 (MIFF 2012)
6-10 March 2012, Putra World Trade Centre (PWTC) & MATRADE Exhibition & Convention Centre (MECC)
T
his year MIFF posted another record high sales turnover of US$830 million, an increase of 6.68 percent over 2011 orders of US$778 million. This percent over 2011, as interest in MIFF, one of the top 10 furniture fairs in the world, remained buoyant. “This year’s fair opened very strongly, you can sense the vibrancy right from the start," said MIFF Chairman Dato' Dr. Tan Chin Huat. "This shows that MIFF is still attractive to international buyers and this is very good for our exhibitors. So long as the exhibitors continue to be innovative and offer good value and quality, we will bring in the buyers."
Among the visitors was a 40-member Even before the 2012 show was over, Japanese group led by Mr. Atsumasa exhibitors were already lining up for Kawasaki, chairman of furniture retailer SH MIFF 2013 scheduled from Mar 5 to 9, Group, one of the largest furniture chains in 2013. Among them were major Malaysia Japan. In the group were buyers from areas exporters such as Poh Huat Furniture hit by the 2011 earthquake and tsunami. Industries (M) Sdn Bhd, Hin Lim Furniture Impressed with what he saw, Mr Manufacturer Sdn Bhd, Shantawood Kawasaki said: “Malaysian furniture has Manufacturing Sdn Bhd, Safari Office improved tremendously from previous System Sdn Bhd, Oasis Furniture Industries, years, hence I have been buying since Day Kinheng Furniture Sdn Bhd and the Taiwan 1. The quality and design coupled with Furniture Manufacturers’ Association. reasonable pricing has made Malaysian products attractive. Another plus point of International Visitorship By Company's Main Activity buying Malaysian products is consistent quality. In some countries, what you see, Government Architect, feel and touch in the booths might not be Official, 2.7% Department Store, 0.9% what is delivered after we placed orders. 1.4% Construction Thus, we get a lot of complaints from Hotel & Catering, Buying Trade, consumers. Buying in Malaysia makes us Agent, 2.1% 3.1% feel safe.” International Interior 4.5% Chain Store, Decorator, 1.2% 7.6% Exporter, 5.1%
Exhibition size:
75,000 sqm
Total Export Sales Generated:
US$ 830 million
Number of Exhibitors:
Total
Malaysia
International
433
294
139 (from 10 countries)
Total
Malaysia
International
Invited Guests
19,118
7,368
6,605 (from 140 countries)
5,145
Number of Visitors:
Trading, 11.2%
International Visitorship By Region Africa, 9.4%
North America, 6.1%
Australasia, 8.9%
South America, 2.1%
Middle East, 11.1%
ASEAN, 21.4% Far East, 15.4%
Retailer, 12.0%
Manufacturer, 12.5%
Wholesaler, 12.5%
Place Order, 15.76% To Source New Product, 26.9% Seek Representative/ JV, 4.65% Make Contract/ Visit Supplier, 20.38% To Look for Business Opportunities, 18.9% Gather Information, 12.68% To Evaluate For Future Participation, 0.74%
0
04
Importer, 19.0%
International Visitorship By Purpose of visit
Europe, 12.9%
Other Asian Countries, 12.8%
Others, 4.0%
The official magazine of the Malaysian International Furniture Fair
5
10
15
%
20
25
30
So Fa r
J
ulian Bowen, owner of Nottingham, U.K.-based Julian Bowen Ltd., has been coming to the Malaysian International Furniture Fair (MIFF) for 10 years, and by now, he knows a thing or two about doing furniture business in Malaysia. We asked him, pictured at left, his impressions about Malaysian furniture, and why he keeps coming back for more.
MIFF Insider
SoGo o d
Furnish Now (FN): What’s your interest in Malaysia all about?
FN: Have you seen any changes at MIFF over the decade that you’ve attended?
Julian Bowen (JB): For many years now we have been buying a lot of furniture from Malaysia. The Malaysians generally speaking produce a quality we’re happy with. And they seem to be well tuned to the requirements of the U.K. market, which is fairly specialized. I think the history of the U.K.’s association with Malaysia over many years has opened the country up to understand the requirements of the marketplace.
JB: The [furniture] quality has improved enormously over the last 10 years. We have seen quite a definite trend initiated by Malaysia in design terms. They are far more creative today in design than they ever have been previously. About 35 to 40 percent of our business these days is coming out of Malaysia, and this over the last few years has increased quite dramatically.
What Other MIFF Insiders Said about the 2012 Show:
FN: So you’re pretty well settled buying from Malaysia? JB: We are not a company that regularly changes suppliers every 10 minutes. We like to find the people with whom we can do business and stay with them indefinitely.
“MIFF was better than last year. The buyers that come into my booth – both in terms of quantity and quality – are better. I’ve been coming to MIFF for 9 years and I’ve already signed up for MIFF 2013.” – Steven Wong, Sales and Marketing Director, BJ Cabinet Sdn Bhd.
“MIFF is good for business to meet customers – current customers or new
“Our
customers. We have been with MIFF for
California and we buy a lot of furniture from
all years, from the start.” – Amos Lee, General Manager, Asia Tube Industries Sdn Bhd.
headquarters
are
in
Freemont,
“We have been with MIFF since the first year.
Malaysia. I was [at MIFF] every year. We go [to
We grew with MIFF. I think I will come back
MIFF] because we have a lot of our suppliers
next year. Buyers come from more than 80
showing there and we are showing there
countries.”
too. Also, there are a lot of promotional items
– K .S. Lim, Manager, SYF Group of Companies
in Malaysia.”
“I can say that I’m very busy. Until
– Kent Bong, Merchandiser, Homelegance Inc.
yesterday [on Day 4], I didn’t take my lunch. I can say there was very good response to our booth.” – Shoba Balakrishnan, Senior Sales Executive, Oasis Furniture Industries Sdn Bhd.
“MIFF is very good, excellent and marvelous. If we took 100 namecards this year, maybe 80 percent have intention to buy from us. We sold 50 containers already. Last year we sold 10 containers. So we are selling 5 times as much this year.” – Pele Hui, International Trade Manager, Chief Designer, and Factory Manager, Anji Qidi Furniture Co Ltd. “The crowd is quite encouraging. I’ve
“Most of the office furniture we have seen was excellent. The manufacturers in this category are extremely innovative. Very often we have seen high end products which are internationally competitive.”
been here for two days. MIFF is better than last year.” - C.M. Yong, Marketing Executive of Trade Development, Malaysian Timber Industry Board
– Helmut Merkel, Chief Judge, Furniture Excellence Award SPECIAL POST-MIFF ISSUE May 2012
05
Bu ye r P ro fi l e
Quite possibly the World’s Lightest Traveller visits MIFF with some packing tips
“I
normally
charge all my gadgets at night
By Khaw Chia Hui Furnish Now writer
via USB ports on the laptop,” Mr.
There’s
nothing
unusual
about
Myhre said. “This
spending time in airports and planes
helps me save time
when you are a regular at furniture trade
and space. If the item
exhibitions around the world.
I want to get is unable
How you spend that time though –
to charge via a USB
now that could be unusual.
port, I don’t get it.”
At least it is for Finn Myhre, who makes
However, Mr. Myhre’s secret
George Clooney’s character in the movie
travel weapon comes in the form of
Up in the Air look like a flying pack rat.
a jacket. The jacket is specially modified to
Mr. Myhre travels not just light, or even
have 18 pockets where he keeps any items
super light. If he were a superhero, his
that could not fit into his carry-on luggage.
name would be “Ultralight.”
Like Batman or Spiderman, he doesn’t
You see, Mr. Myhre is wary of checking in luggage or even “buying” weight for his belongings aboard flights. In order to keep costs as low as possible, he has a carry-on that sticks to the 8 kilogram limit. Bear in mind that Mr. Myhre, who owns Chesterfield Norway AS, which specialises in high-end leather furniture with classical designs, didn’t come straight to the Malaysian International Furniture Fair (MIFF) this year from Norway, where he would have originally packed. He came to MIFF directly from another
You might call what he carries his luggage, his survival kit—or maybe even his life. But you’d definitely have to call it 8 kilograms. That’s how Ultralight rolls. “Believe it or not, I pack two pairs of trousers, a lot of T-shirts that are light and space-saving, a sweater, a razor and a toothbrush,” Mr. Myhre said. “I also have a camera and a laptop. As you might notice I never carry any chargers except for short USB wires.” What? How do you power a laptop without a charger?
business trip to Turkey.
06
The official magazine of the Malaysian International Furniture Fair
mind when he gets stares. For him, it’s not the Spandex, spider webs or Batmobile that draw attention. It’s his unusually large jacket. “As long as I get to travel the way I want and not lose my things, I could not care less about what others think,” he added. Wise advice, indeed.
Buye r Pro fi l e
We’re glad that Mr. Myhre sells
delights such as Chinese,
Chesterfields too so that he can lounge
Malay and even Thai cuisine. It
comfortably when he’s not super-packed
is also within walking distance
30,000 feet above.
of Jalan Alor, Changkat Bukit
And where does Mr. Myhre like to go
So, how did I become Ultralight?
Bintang and Petaling Street. Each
when he’s not fighting the sinister world of
of these places offers different
luggage weight?
types of outlets ranging from
“Since I visited the Philippines way back
upscale Western restaurants to the
when I was 18 years old, Southeast Asia holds a special place in my heart,” he said. Malaysia is currently one of his favourite places. He loves the exotic people, food and various places of interest. This year, MIFF also was a pivotal stop for him, right in the middle of his busy season. “March, April and May is one of the busiest time of the year for me,” Mr. Myhre
Things Once Were Heavy!
said. “I have to go to many places to check
humble
out furniture fairs, visit factories and
roadside stalls, presenting
oversea business dealings.”
all sorts of unique food items.
For him, MIFF is a pleasant place to
Mr. Myhre also likes to saunter around
conduct business, especially because it
Kuala Lumpur when he has some spare
affords him the opportunity to feel alive.
time although he admits that one would
This year, he stayed at Citin Hotel, right
need another week just to give the place
smack in the heart of old Kuala Lumpur
a thorough walkabout. Unknown to most
along Jalan Pudu.
of his Malaysian associates, Ultralight is an
“I don’t believe in staying at luxury hotels, but rather a clean and decent place,”
ER
i i BB
He dove in Mindoro Islands off the coast of Luzon, and at the
experience and people-watch in Pudu.”
White Beach off Boracay in the Philippines. More recently, he has
spot overweight luggage hogging up the
been to Tioman Island. Tioman is off
sidewalk.
the southeast coast of Peninsular
In fact, weightlessness apparently
Malaysia, just north of the Johor-
makes one hungry, and Pudu is the perfect
Pahang state borders. It has more
place for foodies.
than 20 diving spots and a rare place
“Normally, when I’m done visiting
iii Gi
avid diver too.
he said. “It also gives me an opportunity to You wonder whether he’s trying to
But they weren’t always heavy… I remembered my pet monkey Oscar was a lot lighter.
… Like here to Malaysia, to travel light. Ultralight!
So I decided when I travel…
These images are of Finn Myhre during his lifetime; artistic license was used in developing the captions.
where you can see schools of dolphins.
the fair grounds, I would head back to
“I love the sea and diving is one of
time come the next MIFF to travel outside
the hotel area to grab dinner,” he said.
the ways I get away from work,” Mr.
Kuala Lumpur. When asked where he might
“Malaysian food has always appealed to
Myhre said. “For me, Tioman is one of my
be heading, he said, “I was told Penang is a
the adventurous side of me. If you have
favourite places. If not for the lack for time
place for my time.”
tasted Norwegian fare, you will agree that
in Malaysia during MIFF, I would certainly
Malaysian flavours win hands down.”
make a detour for a couple of days there.”
For those unfamiliar with the Pudu
On his future visits to Malaysia, Mr.
area, it is filled with many delectable
Myhre expressed interest in extending his
Just don’t take an AirAsia flight there, Mr. Myhre. Max carry-on weight is only 7 kilograms. What could be worse? Kryptonite?
SPECIAL POST-MIFF ISSUE May 2012
07
Tro p hyRoo m
Who Are These Winners?
Furnish Now speaks with MIFF 2012 award winners to find out what makes them tick, and win
By Alexandra Wong and Ee-Tan Chow Furnish Now writers
I
f the Malaysian International Furniture
guess how Mr. Korb’s steely
Fair (MIFF) had a rock star, Swiss architect-
determination
designer Daniel Korb would be it.
his
eventual
defined success
as
Since bursting onto the Malaysian
the driving force of Korb
scene in 2010, his winning collaborations
+ Korb, the Baden-based
with TaZ Corporation are one of MIFF’s
company he and his wife
most anticipated events. XF, the company’s
Susan, also an architect,
third consecutive Furniture Excellence
founded
Award winner, is but the latest addition to
design expertise has found
a towering stack of international and local
expression in architecture,
awards for the designer.
communication and design.
in
1989.
Daniel Korb on Simple Determination
Their
“As a child I liked to build and do things
As a designer, Korb is
with my hands,” Mr. Korb said. When he
guided by one overarching
met an industrial design company’s owner
tenet: to contribute to a
remains
after school, he immediately offered his
better world through the act of creating
infatuated
services. Unfortunately, as he lacked the
inspiring spaces with good looking and
with the design
qualifications, the boss turned him down.
working products.
process.
Undeterred, the young man offered to clean his workshop! Over three months, the boy helped the designers construct models and
XF
Daniel Korb
While he believes that simple is better,
“Every stage [of the design process] has
he also feels that we should not be limited
its own beauty,” Mr. Korb said. “When you
by the thinking that the creative process is
hold the first piece from a mould in your
linear.
hand or the parts are assembled to the whole, these are special moments.”
prototypes, impressing the boss so much
“There is not a starting point and [it is
that the latter told the young Korb to stay
not] necessary that one gets straight to the
His most valuable lesson?
on.
goal,” he said.
“Don´t think, try,” he said. “Often we try
From that small anecdote, one can
After more than twenty years, he
Sim Chia Yi on Diverse Designing
A
too little because we think too much.”
s a product design student, Sim Chia Yi created items as diverse as vacuum cleaners and “assistive devices,” whatever those are.
Entering the Malaysian International Furniture Fair’s (MIFF’s) Ideation
award, announced last March, was her first attempt at designing furniture. She won. “The same design we learn in product design applies to furniture design: You have to find the problem and solve the problem, the fundamental principle in product design studies,” Ms. Sim said. “The beauty of designing
Just Like Old Times
furniture is you can use a lot more imagination. The creative process goes beyond rigid formula. Yes, it has elements of technicality and you have to
solve the problem of structure and engineering. But you can be intuitive and spontaneous without restricting to logic, giving you the leeway to generate lots and lots of interesting ideas. You can experiment with new things and different methods. Furniture design is like an art piece.” Pumped up from her victorious debut at one of the world’s top 10 furniture fairs, the recent graduate is now giving furniture design career serious thought. The chance to work with industry talents was a big factor. “In coming up with the winning design, my brainstorming sessions with industrial designer Ee Kang got me to think out of the box to come up with something fun, controversial yet quintessentially Malaysian,” Ms. Sim said. “I also appreciated the chance to work with Ralph Ong. Helpful and open-minded, he’s exactly the kind of role model the Malaysian furniture industry needs.”
08
The official magazine of the Malaysian International Furniture Fair
Tro p hyRo o m
Lim Chee Min on the Hard Life
L
im Chee Min is about to pour some cold water on any of you wannabe designers.
“As a young man, I thought being an interior designer was a
glamorous job,” Mr. Lim said. Reality was a different story. Hen Hin Furniture Manufacturing's winning shell scheme booth
Lim Chee Min
“You certainly don’t sit in an office and draw all day!” he laughed. Nor is it about indulging one’s artistic whims and fancies. “In designing a kitchen, you need to think about your client’s health,”
said Mr. Lim, whose company, Hen Hin Furniture Manufacturing Sdn Bhd, won the 1st Prize Best Presentation Award for shell scheme booths at MIFF 2012. “Clients are discerning these days. The material you propose for their kitchen, they want to know—does it contain chemicals that will affect my children’s wellbeing? You have to do extensive studies and research to adequately address your client’s needs.” The most difficult part of his job? “Project management, because you must be able to handle all kinds of people skillfully,” said Mr. Lim, Hen Hin's project designer. He explained: “A designer produces a drawing with detailed instructions on constructing a cabinet. Sometimes, the end product may not end up as you imagine after the process of construction. As a project manager, you must justify the discrepancies to the client.” While hardly a walk in the park, managing end-to-end projects successfully offers a satisfaction that money can’t buy. “I love optimizing my creative process to make our clients’ dream come true and do my best to involve the client during the idea developing process,” Mr. Lim said. “I love to see them smile, which gives me the momentum to stay strong and move forward in this industry. For this moment, I still take myself as a student. Design is a learn-as-you-go career.” While Hen Hin started with and primarily specialises in loose furniture, it recently started an interior design department to capitalise on the increasing stream of walk-in customers who require renovation service. Mr. Lim is a key member of the department.
Chen Chao-Ken on Market Understanding
S
ome industry people couldn’t care less
Since its establishment in
about children’s furniture.
1984, Tay Huah Furniture has
That’s a fantastic thing for Taiwan-
been a pioneer in kids furniture,
based Tay Huah Furniture Corp., which has
in particular study desks and
filled that niche nicely.
chairs.
“The
children’s
market
is
often
“Many parents told me after
neglected in our industry,” said Chen Chao-
they bought our desks and chairs
Ken, founder and designer of Tay Huah.
that the children could better
“But nowadays, parents are willing to pay
concentrate in their studies,”
for a good quality desk for their children.
said Mr. Chen, whose innovative
While other children’s chairs need to be
designs have been recognised
changed as the years go by, Tay Huah’s
overseas. In 2000, Tay Huah won an IFFT/
at MIFF is a modification of that winning
designs are meant to outlast their growth.”
Interior Lifestyle Living Award in Japan for
chair.
Mr. Chen’s Comf-Pro `Match Chair’
an environmental-friendly children’s chair.
“I want to encourage young designers
won the Platinum award in the MIFF
Besides the ergonomic and innovative
to be more innovative, and to come out with
2012 Furniture Excellence Awards office
design of the chair, the components can be
new ideas and concepts rather than copying
category in March this year.
re-used and recycled.
existing designs in the market,” he said.
Mr. Chen said the winning `Match Chair’
SPECIAL POST-MIFF ISSUE May 2012
09
Coz yC h a t
Making a ‘Marc’ in Outdoor Furniture By Chan Li Jin Furnish Now writer
Dr. Marc Koo
10
The official magazine of the Malaysian International Furniture Fair
Coz yCh a t It’s easy to forget you are talking to a furniture manufacturer when meeting Dr. Marc Koo, Founder and Managing Director of award-winning, Malaysian-based Laval Furniture. Dr. Koo describes his products like an artisan, exuding the passion and devotion only master craftsmen possess. The Mauritius-born former engineer with 25 years experience in outdoor furniture has since made Malaysia his home. In an exclusive interview with Furnish Now, Dr. Koo reveals his winning furniture secrets. Furnish Now (FN): How did Laval get started?
FN: What are the latest trends in outdoor furniture?
Dr. Marc Koo (MK): When I first moved here, I noticed there were a lot of saw mills where unused wood was just discarded. A friend invited me to start a furniture business and we started making outdoor furniture. In 1980s, we were the largest supplier of outdoor furniture to the U.S., U.K. and Japan. As the competition grew, we developed a niche in high-end outdoor furniture.
MK: We don’t follow trends; we set the trend for the market. In recent years, we introduced the trend of making furniture using recycled materials, like an old rain tree or discarded railway sleepers. We want to show new designers we can use anything to create something beautiful.
What you have in your garden or patio is not just furniture; they are talking points that showcase your taste and personality
FN: What defines good outdoor furniture?
MK: We like unique designs that are non-conventional. What is important in outdoor furniture is to have new designs and work with manufacturers who can work with what you want. We are very design-oriented and our furniture is very durable, some lasting more than 20 years. FN: Is it difficult to find good designers? MK: We are well-known, so designers come to us. If their designs are used, they get a royalty cut. I have good designers who are not afraid to try new design concepts using technology to merge materials such as steel and wood. FN: Is it a problem sourcing for raw materials?
FN: Does outdoor special care?
furniture
require
MK: Good quality outdoor furniture needs less maintenance. Generally, you should not put them in the open, but in sheltered spaces. Every year, sand it down and oil it with wax or wood oil. When not in use for a long time, have it covered. FN: Are your markets limited to tropical countries? MK: They are also very popular in Europe and Japan, because they have summertime there. These are expensive products, so people buy one or two pieces and place them in strategic spots outside their house as talking points. People are proud to own our furniture, like a piece of art. FN: What keeps you going after 25 years? MK: I love what I do; I get ideas when I sleep, I dream about my work. I’m looking forward to better designs next year.
MK: For us, it is not a problem because we use recycled materials. Our production is also small, about 1000 pieces in a year, so we easily find enough materials.
SPECIAL POST-MIFF ISSUE May 2012
11
Cove rSto r y
By Matt Young Furnish Now editor
Many Malaysian manufacturers are getting savvy about promoting products digitally; you should too
I
n a day and age where every company
“Furniture is like that. It’s like
seemingly has a website, Timber Tone
a fashion. Once you display it at an
Industries Sdn Bhd doesn’t.
exhibition, people will walk through, and
“Most do have a website, but [many
[other] designers’ eyes are very sharp.”
furniture companies] showcase their old
Instead of worrying about that, Ms.
designs,” Timber Tone General Manager
Tio is happy to promote the images of her
Teoh Peng Hoe told Furnish Now last year.
furniture.
“For me, I might as well forget about it.
That effort led to a major spread of
Showing old designs are useless—it gives
the ‘Kayla’ bed set in the Furnish Now
the wrong perception about my company.” In 2011, Mr. Teoh said old designs were ‘in’ online because of the plethora of copycats in the furniture manufacturing
December issue,
industry. Mr. Teoh, who has won numerous
when Chinfon’s bed
Furniture Excellence Awards from the
was chosen to be part of the
Malaysian
“Editor’s Presentation Picks,” which
International
Furniture
Fair
‘Kayla’ bed set
(MIFF), preferred to keep copycats at bay
featured the best local furniture photos
by giving them nothing Web-wise to work
from the magazine’s perspective.
with.
Chinfon also has a pretty suave website
Today, Timber Tone still has no
–
Chinfonfurniture.com
–
compared
On the iPad, she had a spiffy brochure explaining a new Oasis product: the Achievor chair. “Do you often use an iPad to interact
website—not that there’s anything wrong
to competitors. Dragging your mouse
with that. Mr. Teoh still spearheads the
over various portions of the homepage
“Sure,” she said. “The look is very
making of great furniture with much
produces different visual effects, making
colourful and it attracts attention. It helps
success. But few Asian companies are
Chinfon’s furniture an exciting visual
a lot. Many customers then ask me to send
following his anti-digital lead.
experience.
the PDF file to them by email.”
Ignoring copiers and forging ahead, Malaysian
companies
like
with customers?” I asked Ms. Lee.
“People can see it’s very interesting,”
But Ms. Lee is a talented storyteller too.
Chinfon
Ms. Tio said. “It means [we] are putting in
She didn’t simply read from the brochure.
Furniture Industries Sdn Bhd are showing
effort and creativity. Furniture is not just
She used the iPad to capture my attention,
what can be done in order to lead the way
something that can be displayed at home.
gliding through pages and images while
online, digitally and with cutting-edge
It can be displayed as fashion.”
she told her own story about the Achievor,
showmanship to promote furniture in bold new ways. “Everyone is copying everyone,” said Ely Tio, general manager of Chinfon.
12
Meanwhile, at MIFF 2012, Jane Lee, marketing executive of Oasis Furniture Industries Sdn Bhd, was walking around her booth with an iPad.
The official magazine of the Malaysian International Furniture Fair
aided by images of horses and saddles in the brochure. “We describe our chair as a horse,” Ms. Lee said. “The horse has to understand
Cove rSto r y
It was therefore a combination of digital showmanship and storytelling
them has improved.”
ability that allowed Oasis to reach out to
But will better furniture pictures—
potential customers. It apparently worked
whether they are displayed on an iPad,
at MIFF 2012.
blown up as still photos in booths, or
“I can say that I’m very busy,”
the rider. Likewise,
are second generation. Promotion of
showcased in a digital catalogue—work?
Oasis senior sales executive Shoba
“I believe so,” Dato’ Tan said. “Particularly
Balakrishnan said. “Until yesterday [on
for the home furnishings sector. Office
day 4 of the show], I didn’t take my
vendors
have
been
producing
nice
lunch. I can say there was very good
catalogues for many years. Obviously they
response to our booth.”
have had a better response. Home furniture
Again, said MIFF Chairman Dato’ Dr.
people should be rolling out concepts, like
Tan Chin Huat, with such visual marketing,
lifestyle concepts. It will work. Show an
copying is not to be feared.
outstanding product coupled with some
“In those days [some time ago], it
pre-recorded video at your booth—that
and feel comfortable with
would be a most concerning topic for
will really attract buyers and make them
a chair that understands you, you feel
furniture exhibitors,” Dato’ Tan said. “I
stand still for a while. We are human beings.
better and do things better that lead to
think now, it’s not such a concern. Things
We are attracted by these [technology]
higher achievement.”
have improved. Many furniture vendors
things when we go anywhere.”
when you sit on a chair
N
owadays, videos are easy to create and post on YouTube. Yuki
page and our YouTube movie, and now, we still have questions
Sugihara, director of Japanese product design firm Atelier
about price and shipping costs from all over the world,” Mr.
OPA, did just that, and received 169,532 hits on YouTube, and counting.
Sugihara said. Furniture promoters from Malaysia to Japan clearly are thinking
“Seventeen years ago, it took half a day to make a five-minute
differently about what they do, and are using modern tools like
movie,” said Mr. Sugihara, whose major in university was ‘Images
iPads, YouTube and unique photography to lead the way in the
and Sciences.’ “Today, it takes 30 minutes. “
showmanship qualities of tomorrow.
“Architectural Furniture,” his quickly made YouTube video about foldaway guest rooms and office space, went viral within days. “I released the video on YouTube on September 19th, 2008 in Tokyo,” he said. “One week after, I and [colleague] Toshihiko were in New York. When we checked statistics of it, we were very surprised to know of its 10,000 views. After one month, it recorded 60,000 views. Now the number grows day by day. Sometimes we hear ‘I know your movie’ from someone we met at an architecture and design conference or exhibition.’” The movie also led to magazine and newspaper coverage around the world, including in Hong Kong, Greece, Germany, Israel, the United States and Brazil, he said. “Then some blog linked to our
Furniture designed by Atelier OPA unfolds, then folds right back up to save space, and a video about it went viral. Click Here to see the video.
SPECIAL POST-MIFF ISSUE May 2012
13
Cove rSto r y
Great Digital Techniques to Promote Furniture
W
ebsites, catalogues, posters—these are tried and true methods of displaying furniture images to get customers interested in what you sell.
But wake up: It’s 2012. There are so many imaging techniques available now that are innovative, and
many are low- or no-cost too. You can’t afford to ignore them anymore. Here’s a sample of what’s at your disposal digitally to show off your furniture in the best new light. And remember, you don’t have to be a digital pro to use any of these tools.
SnapShop
Photosynth Microsoft’s Photosynth is a set of online tools that allow you to take a virtual 3D tour of a given room or object. In our view, this can be particularly useful for capturing and viewing pieces of furniture or showrooms in 3D. The tools allow you to capture images in two different ways. First, you can use the “panorama” tool set, which gives a sense of what it feels like to be in one particular place, and then turn around in a 360 degree fashion to see what’s around you. Second, you can use the “synth” tool set, which allows you to navigate a place or an object virtually via a series of photos that are taken and integrated.
It gives the sense of walking around a place or object as if you’re part of a
T
here’s a difference between seeing a piece of furniture
3D tour, and witnessing great detail.
online or at an exhibition, and understanding how that
piece of furniture will fit in a showroom or living room back home. SnapShop can bridge this gap in understanding. It allows you, the vendor, to list pieces from your furniture collection in
Click Here to See the Photosynth We Created for EURO from MIFF 2012
the SnapShop database. Interested customers can then use their fingers to place your furniture—let’s say a couch for example— in their iPhone camera. A picture then can be taken of any living
Animoto
room, den, or even showroom, with this couch positioned in the
The founders of Animoto are
photo. Once the couch is positioned, customers can change the
described as a combination of
colour of it, reposition it, reverse it, or choose another couch or
people who produced shows for
furniture item to fit in that space.
MTV, studied music in London and
So essentially, SnapShop can allow vendors to have an interactive, branded catalog of their furniture that consumers can relate to their spatial surroundings. The app could benefit both MIFF exhibitors and buyers. Exhibitors could use the app to help buyers better understand how
played in indie rock bands in Seattle. Animoto is their love child. It allows users to create brilliant video animations by merely uploading a set of photos, words and musical choices to the Animoto website or app. In minutes, Animoto transforms these items into animated bliss.
their furniture would fit in showrooms back home. Buyers could
The technology would be perfect for animating a showroom or
use the app to help end consumers understand how furniture
furniture set, and making it come alive in the minds of consumers.
would fit in their own living rooms or bedrooms. SnapShop is
Furniture rocks! Yes it could, with Animoto. Visit Animoto.com to
available at the App Store, or visit it online at Snapshopinc.com.
find out more.
14
The official magazine of the Malaysian International Furniture Fair
M I FFU p d a te
Dato’ Tan (Chairman of MIFF) & Mr Jime Essink (President & CEO of UBM Asia) at MIFF 2012 Welcome Reception
UBM
F F I M
ed MIFF nk launch & Mr. Essi n IFF 2012 M Ta t ’ a to t a h D ig Buyers’ N g n ri u d 2013
T
he Malaysian International Furniture
Fair’s
(MIFF’s)
growth over the past 18 years could
hardly
unnoticed
have
in
gone
UBM and MIFF Uni te as Par tners
exhibition
circles, but nowhere is the show’s success more evident than in the partnerships that it has cultivated in the last two decades. “MIFF first appeared on the UBM radar about eight years ago,” said Jime
By Majella Gomes Furnish Now writer
MIFF will now leverage impeccable capabilities of UBM organiser
Essink, President & CEO of UBM Asia Ltd.,
highest-grossing jewellery exhibition in
improving customer service for buyers and
the region’s leading trade show organiser
Hong Kong, so it is advantageous to us to
sellers alike.
that acquired MIFF earlier this year. “But
add an event like MIFF to our portfolio.”
like all successful partnerships, it was
The MIFF-UBM partnership will see
“Although there is strength in numbers, and coming together under one banner is
a matter of getting the timing right
both
and
good, we firmly believe there should not be
before things could fall into place and
complementing each other’s strengths.
work out to everyone’s benefit.”
For instance, UBM organises Hotelex,
a dominant player,” he stated. “Competition
UBM is present in more than 40 countries
worldwide,
and
helps
companies
leveraging
on
which focuses on hotels. Meanwhile,
to
hotel furniture manufacturers feature
connect businesses primarily via trade
quite prominently at MIFF. Participating in
shows. UBM Asia currently organises 150
another trade exhibition under the banner
trade shows, conferences and exhibitions
of the same organiser would therefore be
in Asia, which cover a slew of industries
facilitated.
including building, food, hotel and
“There is also the UBM brand,” Mr.
leisure, maritime, water and jewellery.
Essink explained. “We are already an
“MIFF’s
databases and other shared resources. This will be facilitated with partnerships like the MIFF-UBM one.” In what direction should the Malaysian trade show market develop? “If Malaysia wants to catch up with other cities, you will need a new, modern
be
established name in exhibition circles on most continents. Being affiliated to
within the context of the three
us will mean being linked to a reputable
UBM
have
organiser, and garner more attention for
organiser in Malaysia. This offers better and
identified in Asia: China, India and
exhibitors in the markets where they are
more career opportunities that will attract
trying to establish themselves.”
better talent. We are also expanding into
growth
areas
cannot
be able to take advantage of networks,
ignored, especially when viewed strong
success
is always good, but industry players should
we
Southeast Asia, particularly the ASEAN region,” he continued. “UBM already has
Ultimately, UBM’s aim is to increase
successful events in Asia, including the
exhibitors’ return on investment, besides
venue,” he remarked. “Also, size matters. is now the largest trade show
conferences, where content management will be vital.” SPECIAL POST-MIFF ISSUE May 2012
15
M I FFI n d u s tr y Se m i n a rs
Seminar attendees line up to hear insights at MIFF 2012
Industry Seminars Explore Hard Questions
B
MIFF GOES BEYOND DEAL-MAKING INTO THE LEARNING SPHERE
esides being a top-10 furniture show in
necessity of design, and whether the
the world, the Malaysian International
furniture industry can be truly sustainable.
Furniture Fair (MIFF) delivers some of the
Speakers included Klaus Kummer, President
best insights into furniture development and design in the region.
By Majella Gomes and Yeo Li Shian Furnish Now writers
Industry seminars are delivered by some of the industry’s most acclaimed experts and specialists.
16
& CEO of KDT International Co Ltd, Thailand; Dr Jegatheswaran Ratnasingam of Universiti Putra Malaysia; Noraihan Abdul Rahman of
MIFF 2012 saw four such presentations that tackled hard questions like the
The official magazine of the Malaysian International Furniture Fair
the Malaysian Timber Council, and Chen Neng Xin of Ason Design Studio, China.
M I FFI n d u str y Se m i n a rs
idea of furniture upside down, and made fun of the industry.” Where was Asia in all this? Actually, the Asian culture is totally different. “Life here happens on the floor,” Mr. Kummer explained. “Asians had little need of furniture until Western influence had spread far enough.”
A
Today, however, the focus is on re human designers relevant in the computer age?
“With the Internet, designs can be
accomplished in a day,” Mr. Kummer said. “Everything is executed by computers, from design to production. But we need to ask ourselves: do we need these kinds of products? Computers do not tell you what is the right or wrong design; the thinking process is lost. Designers are not stylists. They do not dress products up and make them look good. They deal with the situation and make the best of what is
Klaus Kummer on Drivers for the
MALAYSIAN FURNITURE MANUFACTURING INDUSTRY
available.”
creating furniture with an Asian identity, using local resources, including nontraditional materials like leaves and flowers. In Thailand, for instance, water hyacinths, widely regarded as a pest, are being turned into raw material for the furniture industry. In the Philippines, banana leaves are gaining popularity. “Banana leaf chairs are being sold by Armani stores in Europe,” he divulged. So, what do designers need to do in order to perform optimally? “We have to find a way to educate
He said that most of what is considered good design today
designers to make them deliver what is required,” he said.
evolved from designs that debuted in the 1920s and 30s. This was
“Manufacturers and designers both have a lot to offer but they
the beginning of the Bauhaus era, when furniture began to be
need to talk to each other and find a common platform for mutual
functional and produced for the masses.
benefit. Every designer has an idea but sometimes the industry
“The Scandinavians ‘woke up’ in the 40s and 50s, in the wake
cannot see it. There is talent everywhere. We have to be able
of WWII,” he said. “Then in the late 1970s, the Italians began what
to see, develop and enable it. The capabilities – equipment,
is popularly referred to as the Memphis Movement, which was
technology, human resources – are already available; it is time for
essentially a revolt, a rejection of all existing designs. It turned the
Asia to be daring enough to start a new trend.”
SPECIAL POST-MIFF ISSUE May 2012
17
M I FFI n d u s tr y Se m i n a rs
technology, water and waste management, and
the
transportation
sector
are
concerned. These are major industrial players in moving the green technology agenda; anything which happens in these sectors creates a major impact on the environment. One
of
the
problems
requiring
immediate attention is the unwillingness of retailers to pay premium prices for green furniture. “Currently,
the
market
does
not
recognise the value of being green,” he
continued.
“But
the
market
is
becoming more competitive, and some manufacturers
Dr. Jegatheswaran Ratnasingam on GREEN
TECHNOLOGY IN FURNITURE MANUFACTURING
have
instituted
green
practices in response to market forces. This has been mainly in the use of certified wood, environment-friendly adhesives and coatings, preservatives and packaging. The use of certified sustainable wood, for instance, is the easiest green move that can be adopted by manufacturers. They have started using recyclable packaging too.”
I
t’s
not
enough
‘green’
even in Asia—which is widely regarded
Advocating for the adoption of green
technology as technology and processes
as the centre of the world’s economy.
practices throughout the manufacturing
that are environmentally-friendly and
Manufacturing, he said, was always prone
process (including administration and
incorporate principles of sustainability.
to the 3D Syndrome–dirty, dangerous and
management), Dr. Ratnasingam said that
Materials used also should be available in
degenerative–but green technology offers
proper legislation was also necessary
perpetuity, said Dr. Ratnasingam.
alternatives because its avowed aims are to
for a seamless transition to totally green
improve the quality of life, society, energy
operations.
“Sustainability
to
define
and
environmental
friendliness go hand in hand,” he pointed out. in
“If
materials
perpetuity,
are
not
businesses
available
cannot
be
and the environment.
“As long as legislation is not in place, it
Unfortunately, Malaysia is about 25
will be difficult to move to green practices,”
years behind Europe where green building
he stated. “Currently, conservation is driven
sustained. Ensuring renewable resources
by market demand, and cost is high. Buyers
also mitigates the problem of destruction
prefer cheaper furniture which is not
of natural resources in general–not just
green, so going green is related to cost,
forests but water supply and soil quality, for example. Everything is interdependent, so there is really
procedure and premium. But there is a compelling argument for adopting green
practices;
manufacturers
a need to conserve the entire
who have adopted the ISO 14000
ecosystem.”
standard have reduced their
There has been an increasing
energy use by up to 17%, and
need for conservation even
substantially reduced waste as
as
well.”
18
global
growth
slows—
The official magazine of the Malaysian International Furniture Fair
M I FFI n d u str y Se m i n a rs
Noraihan Abdul Rahman on
THE MALAYSIAN TIMBER COUNCIL’S PROMOTION PROGRAMME FOR 2012/2013
W
hile it’s clear there’s great value in Malaysian timber exports,
this can be hard to comprehend for the average person. After all, how do you get your head around a number like US$6.6 billion (or RM20 billion), which was the value of Malaysian timber exports in 2011?
China, South Korea, U.K. and Thailand–the
Well, think of it this way….
top ten timber markets for Malaysian wood of
and wood products. We also export to
Malaysia’s GDP. It also accounted for 2.5%
emerging markets like Ukraine, Kazakhstan
of the nation’s workforce. Now, that seems
and Qatar.”
That
figure
constituted
2.3%
quite significant, doesn’t it? Armed with statistics like these, the Malaysian Timber Council (MTC) presses on, full speed ahead to sustain, grow and maintain the country’s timber industry.
In the face of increasingly difficult global constraints, the 20-year old MTC has
and Saudi Arabia. Our missions will be to
its work cut out for it.
the Netherlands, Belgium, Germany, South
Its main programmes will consist of
Africa and Mauritius, as well as to the U.S.,
arranging for Malaysian companies to
Canada, Singapore, Italy, and Australia.
The MTC also has been tasked with
participate in trade fairs, missions abroad,
Business visits have been planned for
seeking out new or emerging markets, and
and business matching visits in 2012 and
Mexico, Sweden, Poland, Slovakia, the
strengthening existing ones. In parallel,
2013. These will be held in more than 25
Czech Republic and Brazil.”
it has to provide market intelligence
countries on four continents. MTC also has
Participants of these activities stand
that will be of relevance to Malaysian
set up a Raw Material Supply Programme
to gain more than just exposure to
manufacturers.
and
Development
international markets. MTC is prepared to
“The amount of timber being logged in
Programme, aimed at helping Malaysian
provide incentives to those who qualify,
Malaysian forests will decline in the years to
manufacturers obtain raw materials as well
import
come because of conservation measures,
as develop networks.
freight charges. In addition to all this, MTC
a
Resource
&
assistance
and
subsidies
for
so proper management of this resource is
“MTC organises more than 230 trade
organises the biennial 288-booth MTC
imperative,” Ms. Noraihan said. “Wooden
fair delegations annually,” Ms. Noraihan
Global Woodmart, a one-stop platform for
furniture makes up 31% of timber products
divulged. “In 2012 and 2013, we will be
buyers of wood products, which will be
from Malaysia. This goes mainly to Japan,
participating in fairs in India, Dubai,
held at the KLCC Convention Centre from
U.S.A., India, Taiwan, Australia, Singapore,
Thailand, London, France, Qatar, Egypt
October 4th to 6th 2012.
SPECIAL POST-MIFF ISSUE May 2012
19
M I FFI n d u s tr y Se m i n a rs
Through his observation, Mr. Chen noticed that the collaboration between designers
and
entrepreneurs
in
the
Malaysian context “are only based on creativity, but not overall relationship.” “Apart
from
the
importance
of
manufacturers’ readiness in accepting designers’ point of views (and vice-versa), manufacturers
should
put
emphasis
on promoting the designers’ brands,” explained Mr. Chen, who has close to two decades of furniture designing experience under his belt. He added that a great collaboration between designers and manufacturers regardless of where they are from or what beliefs they subscribe to, will contribute to the success of an innovation. “There have not been too many Malaysian products that have been
Chen Nengxin on
THE DESIGNER/ MANUFACTURER RELATIONSHIP
I
n the furniture business, it is essential for
from designing and production
designers and entrepreneurs to reach a
to branding and marketing. It
consensus in order to achieve desirable end
requires full understanding from both
results which are practical and functional.
parties.
Strong business relationships between
“There should be mutual respect
the two however “should never be confined
between the two to achieve the best
only to design drafts,” said Mr. Chen, an
results or output,” he said.
award-winning furniture designer. “It doesn’t end there,” the China-based design icon said.
biggest challenge in the designer and entrepreneur relationship is how to unify
According to Mr. Chen, a good relationship comprises the overall process;
20
By any measure, this is not easy. The
two totally different perspectives into one focused direction.
The official magazine of the Malaysian International Furniture Fair
with
injected cultural
elements,” he
said.
“There’s still a lot to work on.”
Fa b u l o u sFu r n i tu re The furniture of MIFF 2012
01
02
“I used to sell furniture for a living. The trouble was, it was my own.”
-Les Dawson, comedian
03
04
01 Artmatrix Technology Sdn Bhd; 02 Benithem Sdn Bhd; 03 BJ Cabinet Enterprise Sdn Bhd; 04 Hin Lim Furniture Manufacturer Sdn Bhd; 05 Euro Chairs Manufacturer (M) Sdn Bhd; 06 Ascent Furniture International Sdn Bhd; 07 Decor Suria Industries Sdn Bhd;
05
07
06 Continued on page 21
SPECIAL POST-MIFF ISSUE May 2012
21
Fa b u l o u sFu r n i tu re The furniture of MIFF 2012
“My ideal relaxation is working on upholstery. I spend hours in junk shops buying furniture. I do all the upholstery work myself, and it’s like therapy.”
– Pamela Anderson, model 12 11
09 08
10
08 Hume Furniture Industries Sdn Bhd; 09 Inspiwood Furniture Sdn Bhd; 10 Intersit Industries (M) Sdn Bhd; 11 Kinheng Furniture Sdn Bhd; 13
12 Kokuyo (M) Sdn Bhd; 13 Kuek Brothers Furniture Sdn Bhd; 14 Lanouva (Sin Lian Lee Manufacturing Sdn Bhd); 15 LY Furniture Sdn Bhd; 15 14
Continued on page 22
22
The official magazine of the Malaysian International Furniture Fair
Fa b u l o u sFu r n i tu re The furniture of MIFF 2012
19
17
21 20
“Know your lines and don’t bump into the furniture.”
22
–Spencer Tracy, actor
18
23
16 Merryfair Chair System Sdn Bhd;
22 Timber Tone Industries Sdn Bhd; timbertone@myjaring.net
17 MG Furniture Sdn Bhd;
23 Titov Sdn Bhd;
18 Oasis Furniture Industries Sdn Bhd; 19 Poh Huat Furniture Industries (M) Sdn Bhd; 20 Safari Office System Sdn Bhd; 21 THS Industries Sdn Bhd;
16
Continued on page 23
SPECIAL POST-MIFF ISSUE May 2012
23
Fa b u l o u sFu r n i tu re The furniture of MIFF 2012
24
25
26
27
28
“What do I wear in bed? Why, Chanel No. 5, of course.”
– Marilyn Monroe, actress
24 Bowlman Furniture Sdn Bhd; 25 L.B. Furniture Sdn Bhd; 26 Ken Yik Furniture Industry Sdn Bhd; 27 Reliable Furniture Sdn Bhd;
29
28 Woody furniture Industries Sdn Bhd; 29 Home Best Ent. Corp. Sdn Bhd;
Continued on page 24
24
The official magazine of the Malaysian International Furniture Fair
Fa b u l o u sFu r n i tu re The furniture of MIFF 2012
30
31
32
“I have never, honestly, thrown chair in my life.”
a
– Steve Ballmer, CEO
30 Chernyen Industries Sdn Bhd; 31 Hen Hin Furniture Manufacturing Sdn Bhd; 33
32 Oasis Furniture Industries Sdn Bhd; 33 Aik Chee Furniture Sdn Bhd; 34 Len Cheong Furniture Sdn Bhd; 35 Apex Office Furniture Exporter Sdn Bhd;
35
34
SPECIAL POST-MIFF ISSUE May 2012
25
Special post-show magazine issue of the Malaysian International Furniture Fair (MIFF). | https://issuu.com/mediamice/docs/furnishnowmagazine3 | CC-MAIN-2021-39 | refinedweb | 9,512 | 62.68 |
I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number
1234567 as
1,234,567. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.
'{:,}'.format(value) # For Python ≥2.7 f'{value:,}' # For Python ≥3.7
import locale locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8' '{:n}'.format(value) # For Python ≥2.7 f'{value:n}' # For Python ≥3.7
Per Format Specification Mini-Language,
The
','option signals the use of a comma for a thousands separator. For a locale aware separator, use the
'n'integer presentation type instead.
I got this to work:
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'en_US') 'en_US' >>> locale.format("%d", 1255000, grouping=True) '1,255,000'
Sure, you don't need internationalization support, but it's clear, concise, and uses a built-in library.
P.S. That "%d" is the usual %-style formatter. You can have only one formatter, but it can be whatever you need in terms of field width and precision settings.
P.P.S. If you can't get
locale to work, I'd suggest a modified version of Mark's answer:
def intWithCommas(x): if type(x) not in [type(0), type(0L)]: raise TypeError("Parameter must be an integer.") if x < 0: return '-' + intWithCommas(-x) result = '' while x >= 1000: x, r = divmod(x, 1000) result = ",%03d%s" % (r, result) return "%d%s" % (x, result)
Recursion is useful for the negative case, but one recursion per comma seems a bit excessive to me. | https://pythonpedia.com/en/knowledge-base/1823058/how-to-print-number-with-commas-as-thousands-separators- | CC-MAIN-2020-16 | refinedweb | 301 | 59.8 |
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
No handler found
Hi, installed V7 on a W7 Pro 64bit machine and worked fine for a week. No i get : no handler found. Tried to look into server/server/loggin were there are 2 PYC files _init_ and handlers. I get stuck there. what to do ? thanks
Hi Frank,
The error is due to some dependency or code which is broken. Now to trace which code is causing this issue, there are multiple ways:
1. Check the server logs
2. Open the project in some IDE and run the openerp/odoo using that. In the console you can see full trace of the issue. For this you can search on youtube for videos related to openerp setup in that IDE (i prefer aptana studio)
3. In openerp server directory, there may be a file named openerp-server. If not create a file named openerp-server and copy the content to it.
#!/usr/bin/env python
import openerp
if __name__ == "__main__":
openerp.cli.main()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
On terminal, open that directory and run 'python openerp-server'. You can see full trace on console. Let me know if you need any further help in tracing the issue.
Once you found the complete error message, last 3 lines will tell you 90% of the issue cause. Search on google and I'm sure you can resolve the issue yourself.
Regards,
Tarun Behal
Hi all, if you suggest a possible solution is it possible to specify how to ?
ex :
vote
In Majority of the cases, this might be due to addons-path not able to find the web module.
Please check.: Frank : How ?
or
There might be following case:
- Check your addons or web addons path as SerpentCS said.
- You should check the access rights of the modules/addons.
Hope this will help you to solve your issue. Frank : guys, thanks for the responses but being new to this I do not now how to check Server log or look at primary log file. Can you advise on how to do stuff like that ? Thanks | https://www.odoo.com/forum/help-1/question/no-handler-found-54994 | CC-MAIN-2016-50 | refinedweb | 381 | 75.4 |
This post is part of a series about programming Arduino applications in C.
I like playing with my Arduino Uno board and its graphical development environment. It’s a tool that makes it easy to create programs and hides many details, but that leaves me wanting to look beneath, to understand the details that are normally hidden.. C is adopted worldwide to program for small microprocessors because it gives a good trade-off between development effort and program efficiency, and because of its history there are well-optimized libraries, extensive guides and ways to solve problems.. This was very useful to understand what the graphical user interface is doing, which turns out is a common workflow for C and C++ builds. We cam mimic this flow, build our program from C calling the avr-gcc command with the right options and upload it running avrdude with the right options. The diagram below shows the “toolchain” flow from writing C code to uploading to Arduino board.
To make it simple I implemented the classic blink program that toggles the output pin connected to the on-board LED. names and where they go: everything can be found in the Atmega328p datasheet. Instead from the Arduino Uno schematics we can find out where the pins are connected, for example we can find that the LED is connected to the PB5 pin of the Atmega328p chip, so that’s the pin we need to control. Now we need to write the code that toggles the PB5 pin. The AVR compiler is complemented with a C library: avr-libc, which contains useful functions and headers to access the functionalities and I/Os of AVR chips. It also makes it easy to write complete C programs without using assembly language. Inside the avr-libc manual and the Atmega328p datasheet there are many examples on how to toggle IOs, and with them I prepared the following code in a file called “
led.c“:
#include <avr/io.h> #include <util/delay.h> #define); } }
The Port “B” of the microcontroller can be changed bit by bit with special instructions called “
sbi” and “
cbi“. In C we use the bitwise “|=” and “&=” assignment operators, which usually read and write a variable, but the compiler recognizes those kind of accesses generating optimized assembly in case of bit-wise operations, and there is no read operation involved. The “
_BV” macro together with PORTB5 is used to build a value that contains one on the bit that corresponds to PB5. The main function contains an infinite loop that raises and lowers the bit 5 of PORTB register and between these operations waits for one second using the library function “
_delay_ms“. If you installed avr-gcc on your Linux machine, the ports definitions and useful macros (like “
_BV“) can be found in the “
/usr/lib/avr/include/avr/iom328p.h” and “
/usr/lib/avr/include/avr/sfr_defs.h” headers, or in the directory where the library has been installed.
The compiler is able to create an ELF executable program that contain machine code and other information such as program section memory layout and debug information. In order to compile a program and upload it to the Arduino Uno, We need to create an IHEX file and use the
avrdude tool to load it inside the Flash. The tool to convert the ELF into IHEX in our case is avr-objcopy. Now it’s time to run the command lines that build and upload the LED blink program. first command line takes the C source file and compiles it into an object file. The options tell the compilerto optimize for code size,what is the clock frequency (it’s useful for delay functions for example) and which is the processor for which to compile code. The second commands links the object file together with system libraries (that are linked implicitly as needed) into an ELF program. The third command converts the ELF program into an IHEX file. The fourth command uploads the IHEX data ito the Atmega chip embedded flash, and the options tells avrdude program to communicate using the Arduino serial protocol, through a particular serial port which is the Linux device “
/dev/ttyACM0“, and to use 115200bps as the data rate.
After the commands are done the code is uploaded and the led starts blinking. That went well at the first try, mostly due to the fact that the tools have good support for the Arduino.
It is possible to list the ELF program in terms of assembly instructions (disassemble the program) by using this command:
$ avr-objdump -d led >led.lst
Note that this guide is written for Linux machines, but it could be adapted to work on Windows and Mac. In particular the compilation that builds the ELF program file should be roughly the same, but the upload part could be very different.
See also:
- Can’t hack, won’t hack: Programming the Arduino in Pure C
- Johannes Hoff: Arduino on the command line
- Martin’s Atelier: Arduino from the command line (arduino-mk) don’t think it can be done either and that is why I asked, coz it is what your article seemed to suggest 🙂 I know how to use the IDE+Arduino as an AVR programmer (and have done so many times), but that only works for IDE developed programs :-(, not (to my knowledge) for externally developed Hex files.
The method you describe now, is however an interesting one and it may well work, provided one first loads the ‘Arduino as ISP programmer’ sketch (otherwise one might reprogram the arduino chip.
I am gonna give that a try 🙂 🙂.
ck
2013/10/18
i am a newbie.so help me to get following things clear.
1.the above tutorial you gave is about uploading a .c file(which may be created in other editor) to arduino uno board using arduino bootloader as a programer.
ck
2013/10/18
also is this tutorial only for free bsd.
i am using ubuntu 13.04
Balau
2013/10/18
ankit
2014/01/21
sir how to program aeduino uno for “google android operated smart home”.. please tell me.
Balau
2014/01/23
I really don’t know how to help you, sorry…
greenwitch
2014/03/25
thank youuuuuuuuuuuuuuuuuuuuu, but i still need the board bring up code from crtm328p.o.
can u help get us start from first assembly instruction to be executed on arduino uno r3 and how to setup all HW for code to run
Balau
2014/03/25
In my example
avr-gccautomatically links “
crtm328p.o“, but if you need the source code you can find it on avr-libc project, specifically in file “
crt1/gcrt1.S“.
Denis Brion
2014/04/08
This post taught me a lot, but something worries me: suppose I want to port an existing arduino software into pure C? If I port module after module, there will be a (many) stage(s) where I will need Arduinos libraries and I do not know how to find and link them…
I know theis way of porting leads to intermediate stages which are very suboptimal w/r size, but sometimes, it would be very pleasant to link pure C with Arduino’s libraries (at least for a given provcessor / i know they are systematically recompiled and should exist ….somewhere) from the command line.
Balau
2014/04/08
Arduino libraries are free open source. In my installation (Debian) the source code is present in
/usr/share/arduino/libraries. They are C++ files, so the porting can be done in many ways:
1. use C++ as the language of your main software and use the Arduino libraries as they are.
2. use C as the language of your main software and use the Arduino libraries by wrapping them to be used as C (see here for example).
3. use C as the language of your main software and translate the Arduino libraries in C (tedious work)
It depends on what you really want to accomplish.
Nora Schillinger
2014/04/14
Hiya I’m using your code in my university project as the base of other outputs and will need to cite the site, I’d be very grateful if you could send me an email containing your (author’s name), and if you could confirm that the below infos are correct. My address is nora.schillinger@students.plymouth.ac.uk Also I can’t understand what _BV actually do? And finally that’s just pure curiosity, if I write DDRB &= ~_BV(DDB4); would that configure the port as an input and how could I read and store that input value as an int? Thanks for teh very helpful code!!
Bibliography: Freedom Embedded. 2011. Programming Arduino Uno in pure C. [online] Available at: [Accessed: 14 Apr 2014].
Balau
2014/04/14
My name is Francesco Balducci and it was available at the right side of the page under the “License” section. See also my About Me page. The information you intend to write is correct.
_BV is a preprocessor macro defined in
avr/sfr_defs.hheader (in my Debian installation these headers are in
/usr/lib/avr/include/) and it’s a transformation from bit number to a byte value that contains a 1 only in the position indicated by the bit number. So _BV(2) means that only the bit number 2 (the third bit from least-significant bit) is one, the others are zero.
DDRB &= ~_BV(DDB4);works in setting the pin 4 of port B as input because it’s basically
DDRB = DDRB & 0xEF;which sets to 0 bit number 4 and keeps the other bits unchanged.
To read it you can use another macro from
avr/sfr_defs.hsuch as
val = bit_is_set(PORTB, PORTB4)?1:0;or use some basic bit twiddling to do something like
val = (PORTB >> PORTB4) & 1;.
Lewis
2014/07/16
Thanks so much for this. I brought an arduino to learn more about architecture and microcontrollers, but the magical IDE that fixes source files up for me was obscuring what I wanted to learn. I spent hours scouring the internet and downloading broken make-files
Fernando França
2014/09/11
Many thanks for this introduction Francesco. I started with Arduino a couple of years but as I’m a electronic engineering undergraduate student, well, it’s time to go deeper with microcontrollers. I really love Arduino platform but now I’m trying to use ATMega with C to implement my undergraduate final project. Cheers from Brazil.
Gustavo
2014/10/14
Thanks for this posts, they are extremely informative!
Just to clarify something, should I need to use an ethernet shield on an Arduino Uno while coding in c++, I’d just have to directly call the ethernet libraries and code as normal?
Do you know of any way to use it on Assembly?
Thanks in advance!!!!
Balau
2014/10/14
I’m not familiar with Ethernet shield or libraries. I already gave some suggestions in this comment above but your situation is not clear to me. If you code on Arduino “normally”, then you are coding in something similar to C++ and you surely can use Ethernet libraries “normally” because that’s the intended usage. If I understand correctly you want to use Assembly to talk directly to the Ethernet shield (probably for network speed reasons). It surely can be done, but it’s surely a lot harder and I wouldn’t know where to start.
Harris
2014/12/01
Hi Balau, I have done according to the way you did but the led doesn’t light up.
First It worked when I uploaded the file through given Arduino program. But after I created and uploaded the file as you did, the led just didn’t light up anymore. Any idea what is the problem?
Balau
2014/12/01
Are you using Arduino Uno or another board?
What version of
avrdudeand
avr-gccare you using? mine are
avrdude 6.1and
avr-gcc 4.8.1.
Did some warning appear when you compiled and uploaded the program? Is the output of
avrdudedifferent from mine?
What sections are listed with
avr-objdump -h led? You should probably have only
.text,
.dataand
.comment, and at most
.eeprombut it should be removed by
avr-objcopy -R .eepromcommand.
Does the output of
avr-objdump -d ledlook OK? It should have
__vectorsat address 0, then somehow it should jump to main which should contain the
sbi 0x05,5and
cbi 0x05,5that turn on and off the LED.
Have you tried removing the calls to
_delay_ms? Or having a
mainthat just turns on the LED and then does an infinite loop doing nothing with
while(1);?
Hope this helps.
Harris
2014/12/02
Hi Balau, mine is Arduino Uno. I have solved the problem by changing PORTB and DDRB to PORTD and DDRD. Btw, do you have any idea of doing analogRead in pure C? Is it the same as doing digitalRead?
Balau
2014/12/03
I never tried myself. Surely it’s not the same because it involves the ADC. Everything should be written in atmega328p ref manual.
Parikshit
2014/12/29
Hi sir,
Thank you so much for the tutorial.. I would be thankful to you if you can provide me with the make file.
Thank you in advance
Balau
2014/12/29
You can get the code from my GitHub repository balau/arduino_c.
Go in the
blinkdirectory and run “
make” to build and “
make upload” to flash the program.
The Makefiles are in the
blinkand
commondirectories.
Parikshit Sagar
2014/12/30
Thank you so much.. 🙂
sai
2015/02/18
how to execute .ino file??what is the use of that??
Balau
2015/02/18
There are no “
.ino” files involved here: “
.ino” is the file extension for Arduino sketches. This post is for writing a program in C, which is a different programming language.
prasanpro
2015/04/16
Great stuff
shahana
2015/04/23
plz upload program for automatic railway gate using arduino…
manoj kumar shet
2015/05/14
is it possible to convert the AT COMMANDS used in the arduino to connect with HC-05 into the embedded c code…??
Ajinkya
2015/05/15
hi balau,
I’m getting this error after exactly following your instructions:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x06
.. and so on upto 10 out of 10.
i’m using ubuntu 13.04.
it works perfectly when done with the ide.
Balau
2015/05/17
@manoj kumar shet: I’m not sure what you are asking, it seems to me that you are using Arduino libraries to connect to the HC-05 and send it AT commands, and you want to use C instead. This can surely be done and it involves implementing the functionality provided by the Arduino libraries that you are using, for example the SoftwareSerial library. You can also use the Arduino libraries from C, there’s some information around (), and also many articles explaining how to use C++ functions from C.
Balau
2015/05/17
@Ajinkya: Maybe the command options is different in your version. The Arduino IDE should have a verbose option, if you activate it and then upload the code it should print the actual commands that it is using. Then you can copy that command and run it yourself outside of the IDE.
Mahsa
2015/06/22
This is an great article. I didn’t find many article about bare metal with Arduino. Wish you could tell us how to set up the programming tools for bare metal programming of the Arduino using avrgcc and avrdude.
Sasha
2015/06/23
You’ve used pure C for programming. But how did you load the program into avr? in your comment on 2012/01/02, you ‘ve clearly said that you didn’t use arduino IDE.
I think this is the the main and most interesting part of what you did but you have explained it in just 2 lines. the rest of the post is about C which is not a concern 🙂
Seriously this page is the only page I can find for bare metal programming with arduino, you have done it successfully but you didnt explain it well 🙂 maybe you can post a new article with picture and more explanation.
Balau
2015/06/25
Thanks to @Mahsa and @Sasha for the suggestions. I already planned to enrich this post with more information, and your comments gave me a push so now the page is longer and with a new diagram. I will probably upgrade this post more in the future, expanding on the tool installation and details on what avrdude is doing.
Sasha
2015/06/27
Thank you! Now its very clear.
I can program the Arduino with its own IDE, but when I want to try pure C, I cannot even compile my code.
avr-gcc: error: LED.c: No such file or directory
avr-gcc: fatal error: no input files
I guess it should be related to PATH, but I don’t get it
echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
any idea?
Balau
2015/06/27
It’s not a problem of
PATH: the error messages are printed by
avr-gccprogram, so it means the system is able to find it and launch it.
The compiler can’t find “
LED.c” source file. Is it in the same directory where you are launching the compilation? Is it really called “
LED.c” or is it “
led.c“? Remember that most things in computers are case sensitive, and when in doubt, assume they are (Windows gave us bad habits).
The second command where you launch
avr-gccwithout arguments gives an expected error: if you don’t give it anything, it doesn’t know what to do.
Vincent
2015/07/12
Very interesting tutorial. One question.
Don’t you think it’s “easier” to use C pointer to point to register memory address directly?
This is my code…
#include <util/delay.h>
#define ddrb_Addr (unsigned char *) 0x24
#define portb_Addr (unsigned char *) 0x25
#define bit5_Mask 0x20
#define BLINK_DELAY_MS 1000
int main(void) {
volatile unsigned char *portDDRB;
volatile unsigned char *portB;
portDDRB = ddrb_Addr;
*portDDRB |= bit5_Mask;
portB = portb_Addr;
return (0);
}
Balau
2015/07/13
Be aware that AVR I/O registers are not memory mapped: you need specific instructions such as IN, OUT, SBI and CBI. These instructions are generated by the compiler if it knows that the code needs to access an I/O register. In your code you want to access memory at addresses 0x24 and 0x25, and avr-gcc will do the right thing and recognize that address because it knows it compile-time. If you dig into the header files you will find in sfr_defs.h and iom328p.h that the registers are already specified using a similar approach as yours. If you compile from .c to .o with –save-temps it will generate a .i that contains the output of the pre-processor. In that file you will find lines such as “
*(volatile uint8_t *)((0x05) + 0x20)) |= (1 << (5));” that show that by following my post you are already doing what you want to do, underneath.
Pero
2015/07/20
Hi, great article, I really liked how you explained what avr-gcc and avrdude are. One question: did you have any experience in using libraries that were originally made for arduino IDE, such as Wire.h or Serial.h? Is it possible to use them in the same way in pure C code? E.g.
include <serial.h>
int main(void)
{
serial.setup(9200);
while(1)
serial.print(“hi”);
}
would this work?
Balau
2015/07/20
I don’t have experience with it, but what you want to do is “calling c++ from c“. In general you need a wrapper to export C++ functionality as an API for C, you can’t use them as they are.
Pero
2015/07/21
Thanks for the fast reply.. I found out that it is actually possible:
and
Balau
2015/07/21
Yeah, that’s not what you asked because its not C, it’s C++, but if that’s OK for you all the better. Be aware that if C++ is OK for you then you can use also avr-gcc by copying the way Arduino IDE runs, if you enable verbosity you can find the commands
TTrevor
2015/10/05
Hi Balau
Great site
I have been able to use a Mega ADK as a development board with AVRISP mkII and Studio4 connected through the ICSP on the board.
I was able to program the board using C to give rise to a robot controlled by bluetooth and a keyboard using putty.
However when I tried to program the Mega ADK using the The Arduino IDE with the stanard Blink program on compilation I received a list of errors..
Is there any way I can reinstate the original or default settings. or be able to toggle between C using the AVRIAP mkII and Arduino IDE.,
If not I will just continue to us the board as an AVR Development Board.
Balau
2015/10/05
In order to troubleshoot most computer errors it’s important to look at the error messages. My guess without looking is that you removed the Arduino bootloader when you programmed the Mega ADK; try to understand if the errors occur when it tries to upload. In that case in my opinion your best bet is to connect the board to the AVRISP, open the Arduino IDE, choose your board from Tools->Board menu, choose the AVRISP mkII from Tools-Programmer and launch Tools->Burn Bootloader. I never tried it myself, though.
Ali Muhammed
2015/10/28
Great Thanks; )
For The Great Post; )
Ask The Almighty help you
Tego
2015/11/06
Thanks ! – I’ve always done “bare metal” programming with micros. This article proves I can buy “Arduno” boards and program “my way”. Having the bootloader is a plus for quick development.
bakaren2013
2015/12/03
Hi, thanks for a great tutorial. I’m running a mac os x and at the last step (avrdude) I get the error ‘input in flex scanner failed’. I googled it but don’t find any threads on the subject… Do you have any idea what might be wrong?
$AVRTOOLS/bin/avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodemFA131 -b 115200 -C $AVRTOOLS/etc/ -U flash:w:testavr.hex
Balau
2015/12/07
I am sorry but I never encountered this error and I am not familiar with mac os x environment. It seems related to
avrdudeinternal working so you might have more luck asking directly the developers in their mailing list.
Ali
2015/12/08
hi, I am new at this and I want to send a string serially to arduino, I have installed arduino IDE but I can code only in assembly or C, can you help
Balau
2015/12/10
I wrote a post some time ago: Using a rain sensor with Arduino Uno in C, where I used the serial port (USART) to write text. You can take a look at “Configuring USART” section of that post to find the code. I used
avr-gccwith
avr-libc, without Arduino IDE.
Daniel Berger
2016/01/02
Thanks a lot for the posting!
I whish I had found this article ealier, because it had spared me of a lot of troubles!
Each details you exposed here take a lot of research and experiments if you learn it by yourself
(Which I unfortunately did in the last weeks)
Thanks again!
Andrew Paul
2016/02/17
How do I convert program written in pic microcontroller to arduino uno R3 plis
Balau
2016/02/17
Probably you have to do it by hand.
Toni Homedes i Saun
2016/02/21
Created a github project with an example of this:
Manjunath Choori
2016/04/16
Really nice work! Loved it!!
Amândio
2016/10/25
Hello,
With this process is possible to use arduino libraries in pure c?
coloneldeguerlass
2016/10/27
Well, using Arduino’s libraries in pure C is possible… if they are written in C (not in C++) . This can be deduced from their headers
ex : I look for wire.h by typing
answer is :
/cygdrive/e/ardu/Arduino/hardware/arduino/avr/libraries/Wire/Wire.h
(I know my arduino PC software resides in /cygdrive/e/ardu/Arduino/
I want to know what is inside Wire.h
and I deduced it is a C++ library.–> it would be very difficult to use it
OTOH
is obviously pure C (assigns pins numbers to ports, which is slow ;
handles milliseconds counts (used in blinkWithoutDelay arduino example, which is a very intersting part)
This seems rather (at least partly) frustrating, but the gcc suite contains … avr-g++ and one can almost always manage to write in pure C (as one is accostumed to) into a cpp file (c++ was an extension of c, and gcx optimiser can hide the differences).
Balau
2016/10/30
As @coloneldeguerlass said, the source code of the libraries can be found in the installation path. There are some C libraries and some C++ libraries. The C ones can be called from C code directly, but for C++ libraries you need to write a wrapper. I suggest this site as a start, but you will find plenty of examples online about how to do it in general, and you can apply it to Arduino libraries.
ector jones
2016/12/16
Many thanks… you’ve written one of the most concise and trouble-free howto’s I’ve ever followed. Very glad to be able to use arduino for avr-gcc dev and NOT be using ICSP since I need to use SPI hardware and not worry about conflicts during development. Many thanks, doug jones
gdobbins
2017/01/28
Thanks for this great page. It helped me accomplish an important project, and I was concerned that the Arduino runtime library would impose too great an overhead and limit my direct control of the chip.
Since adopting the toolset this page describes, I’ve noted that the Arduino IDE also uses the GNU avr-libc and the same compiler and loading tools, which led me to wonder:
In what ways do the methods and tools used here produce a more efficient runtime result than just using the Arduino IDE?
Balau
2017/02/04
I see two causes of overhead in the Arduino IDE versus the pure C approach. First the Arduino IDE includes the abstraction layer that makes programming any board almost the same. Second, the Arduino way uses C++ instead of C, and that might create a bigger footprint.
rym
2017/02/19
Can you explain to me in detail the components of the Arduino and the role of each component of it
In addition, other ways to write a C program
For I, beginning and I want to learn programming well
Balau
2017/03/05
Hi rym, this blog post is targeted for people who already know Arduino or already know to program in C, since you seem to want to start on both, this post probably isn’t for you. The web is full of already written explanations on both subject, I don’t think I am in the position to help you.
Adnan Ptb
2017/03/15
Hi Balau,
This post is really helpful. Balau I have to run a stepper motor using an Arduino Uno and a stepper motor driver in C. I’m completely new to programing world. I’m trying to run your code to see if I can talk to Arduino in C. I’m using Windows 7. I ran your commands in CMD and everything is ok until the last command. “/dev/ttyACM0“ is the problem. How can I fix this for windows.
Thanks
Adnan Ptb
2017/03/15
I modified it and it worked. This was the modification:
avrdude -F -V -c arduino -p ATMEGA328P -P \.\com4 -b 115200 -U flash:r:flash_backup.hex:i
Memhave
2017/03/30
Have you considered using the Visual Micro Extension? It might be easier than having to use the whole toolchain.
David
2017/05/09
Very nice and informative but lacking a few things. I made a blog on LQ to fill in the missing but if you’re not registered you can’t see it. Here are the points I deal with:
Reusing the ArduinoIDE bundled cross toolchain without installing another one.
APPDIR=”$(dirname — “$(readlink -f — $(type -p arduino))”)”
export TOOLCHAINDIR=$APPDIR/hardware/tools/avr
export LD_LIBRARY_PATH=$TOOLCHAINDIR/lib
export PATH=”${TOOLCHAINDIR}/bin:${PATH}”
Minor changes to the avrdude flags and parameters to get it to work on my system
removed some banc space that caused avrdude nto parse incorrectly some options
used the same baud rate as the Arduino IDE
added the -D flag (like the Arduino IDE) to dissipate further the fear of removing the arduino bootloader
added the same avrdude config file that the Arduino IDE uses when it uploads
added the upload field where Intel hex format is specified
Boudhayan Dev
2017/06/14
Hi , amazing post .
I have been coding Arduino Mega 2560 in C language using Eclipse IDE . Recently I have started working on OV5640 camera module. I am having a really tough time to figure out the setup connections required for it . Can you please share the steps that need to be done in order to interface a camera to Arduino in C language ?
Thank You.
Balau
2017/06/18
I never dealt with camera modules. It seems the OV5640 needs at least a low-speed control interface, SCCB, and a high-speed data interface that can be MIPI or DVP. I would start with the Arduino libraries here: and try to convert them to C. Hope this helps.
Thanh
2018/03/22
Thanks! it works for me. | https://balau82.wordpress.com/2011/03/29/programming-arduino-uno-in-pure-c/?shared=email&msg=fail | CC-MAIN-2018-26 | refinedweb | 4,995 | 70.84 |
- 01 Jan, 2009 1 commit
- 25 Sep, 2008 1 commit
- 27 Feb, 2008 1 commit
- 08 Feb, 2008 1 commit
- 31 Oct, 2007 1 commit
0.4. Lots of things changes, which broke lots of our code. There are still a couple of failures in the test suite that I don't understand. It seems that for pending.txt and requests.txt, sometimes strings come back from the database as 8-bit strings and other times as unicodes. It's impossible to make these tests work both separately and together. users.txt is also failing intermittently. Lots of different behavior between running the full test suite all together and running individual tests. Sigh. Note also that actually, Elixir 0.4.0 doesn't work for us. There's a bug in that version that prevented zope.interfaces and Elixir working together. Get the latest 0.4.0 from source to fix this. Other changes include: - Remove Mailman/lockfile.py. While I haven't totally eliminated locking, I have released the lockfile as a separate Python package called locknix, which Mailman 3.0 now depends on. - Renamed Mailman/interfaces/messagestore.py and added an IMessage interface. - bin/testall raises turns on SQLALCHEMY_ECHO when the verbosity is above 3 (that's three -v's because the default verbosity is 1). - add_domain() in config files now allows url_host to be optional. If not given, it defaults to email_host. - Added a non-public interface IDatabase._reset() used by the test suite to zap the database between doctests. Added an implementation in the model which just runs through all rows in all entities, deleting them. - [I]Pending renamed to [I]Pended - Don't allow Pendings.add() to infloop. - In the model's User impelementations, we don't need to append or remove the address when linking and unlinking. By setting the address.user attribute, SQLAlchemy appears to do the right thing, though I'm not 100% sure of that (see the above mentioned failures).
- 11 Oct, 2007 1 commit
is moved to Mailman.lockfile. Remove a few more MailList methods that aren't used any more, e.g. the lock related stuff, the Save() and CheckValues() methods, as well as ChangeMemberName(). Add a missing import to lifecycle.py. We no longer need withlist to unlock the mailing list. Also, expose config.db.flush() in the namespace of withlist directly, under 'flush'.
- 19 Jan, 2007 1 commit
- 27 Aug, 2005 1 commit
- 02 Dec, 2002 1 commit
- 04 Nov, 2002 1 commit
- 16 Mar, 2002 1 commit
- 25 May, 2001 1 commit
- 18 May, 2001 1 commit
- 15 Feb, 2001 1 commit
- 22 Sep, 2000 2 commits
-
appearing in index. pipermail generated several indexes by assuming that date was unique. If two messages arrived with, e.g., the same author and date, then the author index treated them as identical. As a result, both messages were archived, but only the last one was included in the index. Solution is to always include the msgid, which is unique, in the index key. Change database keys to combine elements using tuples instead of string concatenation with \000 as separator. Fix was accomplished by refactoring on pipermail.Database and its subclasses. Push index-key generation into common concrete base class Database; rename abstract base class to DatabaseInterface. Break up addArticle method into several pieces. TBD There is still more refactoring to do on Database class. Because date key has changed, HyperDatabase method to return first and last date changed to reflect format of date key. Refactor pipermail.T.add_article into several pieces.
- 23 Jun, 2000 1 commit
to be more robust so that if either fail, we end up with an empty self.dict and self.sorted. Note that the archiver subprocess will still fail with an exception. Fixing this will require much more work on the archiver as a whole, and isn't worth it right now. But this fix averts the problem when regenerating the archive from scratch using bin/arch, so at least corrupt archives can be rebuilt.
- 21 Mar, 2000 1 commit
- 30 Oct, 1999 1 commit
- 21 Aug, 1999 1 commit
should considerably help the performance of the archiver. Specifically: class DumbBTree: Don't sort the self.sorted list unless some client is actually traversing the data structure. This saves a lot of work when items are added. See also Jeremy's XXX comment for further optimization ideas. class HyperDatabase: Jeremy also has questions about the usefulness of the cache used here. Because the items are traversed in linear order, there isn't much locality of reference, so cache eviction doesn't buy you much (it's actually more expensive than just keeping everything in the cache, so that's what we do). That's a space for time trade-off that might need a re-evaluation. Clearly, more work could be done to improve the performance of the archiver, but this should improve matters significantly. Caveat: this has been only minimally tested in a production environment. I call this the Hylton Band-aid.
- 01 Jul, 1999 1 commit
This isn't part of the bsddb.btree interface assumed by Pipermail, but it's only used in one place and /dramatically/ improves Mailman's performance. HyperDatabase.clearIndex(): Use DumbBTree.clear(). These changes may not fix all the performance problems with Mailman, but certainly nails the most serious problem I've been experiencing.
- 04 Nov, 1998 1 commit
Import open_ex() from Mailman.Utils and assign it to open in the module's globals, so this gets picked up before builtin open. Saves rewriting lots of occurances of open(), but could be confusing when reading a method. Hmmm... __openIndices(): If the `database' directory does not exist, create it specifically with mode = 02770. We want o-rx so this directory is not accessible when the archive is public. But we must have g+wxs or the competing processes (mail and web) that try to update these files (when a message is posted, or web approved after being held), can get to and write the files.
- 26 Oct, 1998 1 commit
- 22 Oct, 1998 2 commits
package. Details: changed Makefile to add the sub package as a directory to make recursively in changed configure to make the replacements to Mailman/Archiver/Makefile.in changed Mailman/Makefile.in to add Archiver as a sub package moved Mailman/Archiver.py to Mailman/Archiver/Archiver.py and Mailman/Hyper* to Mailman/Archiver Mailman/pipermail.py to Mailman/Archiver/ created Mailman/Archiver/__init__.py to do a "from Archiver import *" in order to make it's interface identical to previously. import change: changed imports to import Mailman.<module> from import <module> in order to accomodate the package import semantics, also localized <module> by calling <module> = Mailman.<module>. see diffs for details if this sounds confusing, it's not. this change was applied to all of the moved files except pipermail, which didn't need it. did a basic new installation test to make sure all the Makefile/configure changes took place atleast basically correctly. scott
the native python bsddb replacement wasn't protected in all cases from HyperArch.Archive's locking. added a single global lock uses the flock module to HyperDatabase.DumbBTree so that only one process may access it at a time. specifics: 1) removed previously added locking around the pipermail.T.__init__ line in HyperArch.Archive.__init__, as the database locking should take care of this 2) added lock and unlock methods to HyperDatabase.DumbBTree making multple calls to unlock, and therefore multple calls to HyperDatabase.DumbBTree.close() ok, as the comments from pipermail indicate this might happen. scott
- 13 Oct, 1998 1 commit
- 09 Oct, 1998 1 commit
Original patches are from The Dragon de Monsyne with the following changes: -added support for private archives as well as public -added support for archiving daily and weekly -made archiving happen in real time -replaced use of pipermail's BSDBDatabase with homegrown python version -took out the need for DocumentTemplate here's a listing of changed files and relevant changes: Makefile.in - added public_html/archives to installdirs Mailman/Archiver.py - changed ArchiveMail to do real time archiving Mailman/Defaults.py.in - added archive frequency and and archive url extension variables Mailman/MailList.py - changed .Save() to alter perms on public vs. private archives Mailman/htmlformat.py - changes directly from The Dragon do Monsyne's patches. I don't know what they are exactly, but all the cgi's seem to work fine, so I assume they are OK. Mailman/versions.py - changes to add archiving based variables back to the list Mailman/Cgi/private - changed to make it work with default installation and made background white on login page src/Makefile.in - changes to make all wrappers setuid mailman: since various processes may access an archive, and the archiving mechanism uses "chmod", all archives must be owned by mailman, so all wrappers need to be owned by and setuid mailman added files: Mailman/HyperArch.py - from The Dragon de Monsyne with changes made noted above Mailman/HyperDatabase.py - the replacement for pipermail.BSDBDatabase scott | https://gitlab.com/mailman/mailman/-/commits/3f4f4b12d3e60bec5ac3136be86e4c2abe152c2f/mailman/Archiver/HyperDatabase.py | CC-MAIN-2020-16 | refinedweb | 1,514 | 58.69 |
Given that module
Foo is defined elsewhere what is the difference between
this snippet:
class Foo::Bar ... end
and this:
module Foo class Bar ... end end
Answer inside ;)
Given that module
Foo is defined elsewhere what is the difference between the
following 2 code snippets?
class Foo::Bar ... end
and this
module Foo class Bar ... end end
It is actually quite simple. The following code:
# foo.rb module Foo BAR = 123 end module Foo class A puts BAR end end class Foo::B puts BAR end
will output:
123 foo.rb:13:in `<class:B>': uninitialized constant Foo::B::BAR (NameError) from foo.rb:12:in `<main>'
Simply put, while
A has access to the insides of the module’s
Foo
namespace, class
B is defined outside of this namespace, only the result of
the definition is put as a constant inside
Foo.
I most frequently stumble on this when I want to define some common constants in the parent module, just like in the example above. Given that and the fact that the 2nd form doesn’t actually require the module to be defined, the 2nd form is probably better and is a safer bet in most cases. | https://astrails.com/blog/2012/09/04/parent-module-scoping-in-ruby | CC-MAIN-2018-43 | refinedweb | 199 | 71.44 |
Gemma+NeoPixel 1: random_same
This post is the first in a planned series of articles about my experiments with an Arduino Gemma and a NeoPixel ring with 16 RGB LEDs.
I’m not going to go into detail about how to install or configure the Arduino IDE. Start with the Adafruit Gemma setup instructions and then the NeoPixel library installation instructions that are part of the NeoPixel Überguide.
Make sure you are using a USB cable that is not power-only!
Wiring
Let’s start simple. Grab some small alligator clips from Adafruit and follow the wiring instructions from the Gemma Hoop Earrings project.
Code
We are going to write a really simple program that randomly chooses a color between 0 and 255 and then assign that color to all LEDs. The code is pretty simple C++ and uses the Adafruit NeoPixel library and will run on our Arduino Gemma.
Create a new sketch in the Arduino IDE. Click the “Save” button and name your sketch “random_same”.
Let’s start off by letting the compiler know about the Adafruit NeoPixel
library with an
include directive.
#include <Adafruit_NeoPixel.h>
We can now go ahead and create an object that manages all the interaction with
the NeoPixel. The
Adafruit_NeoPixel call we are using takes the number of
pixels as its first argument and pin number as the second. My NeoPixel has 16
LEDs and is wired to the
D0 pin on my Gemma.
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, 0);
There is an optional, third argument to the
Adafruit_NeoPixelfunction that lets you specify the type of NeoPixel. The default choice worked for me. Consult the NeoPixel documentation to see if you need to explicitly configure its type.
Your sketch may already contain a
setup function definition. We are going to
replace that with a version that initializes the NeoPixel strip and sets an
initial brightness. Your Gemma will call the
setup function when it starts
executing your program, so it’s a great place for anything we want to do once.
The
strip.begin call will configure our
D0 pin so it is ready to send
instructions to the NeoPixel. The
strip.setBrightness call will prevent you
from going blind. Those NeoPixels can get bright! Feel free to experiment with
other brightness values or removing the call to
strip.setBrightness
altogether.
void setup() { strip.begin(); strip.setBrightness(30); }
The NeoPixel is ready to go. Let’s give it some color. We do that by defining
a
loop function which the Gemma will execute over and over again.
Our
loop implementation uses a
Wheel function that takes an eight-bit
number between 0 and 255 (inclusive) and translates that into a 32-bit number
the NeoPixels use as color choice. I talk about
Wheel in another post. Make sure to include a
copy at the end of your program.
We use the Arduino
random
function to compute our input to
Wheel.
Once we have our color, we use a
for loop to assign that color to each pixel
with the
strip.setPixelColor call. This function takes the index of the LED
as its first argument (the first LED is at index
0) and a 32-bit color as
its second.
A call to
strip.setPixelColor does not immediately send any instructions to
the NeoPixel. Instead, all color choices are buffered in-memory by the
NeoPixel library and sent to the device when
strip.show is called.
We add a
delay at the end of
loop to make our code pause after each color choice. The
delay function
takes a number of milliseconds as its only argument. Increase the delay value
to wait longer. Decrease the value to make the color change more often.
Things will blink really quickly if you remove the call to
delay entirely!
// Randomly give the same color to all pixels. void loop() { uint32_t c = Wheel(random(256)); uint8_t i; for (i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, c); } strip.show(); delay(200); }
The whole program
Here’s the entire program.
#include <Adafruit_NeoPixel.h> Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, 0); void setup() { strip.begin(); strip.setBrightness(30); } // Randomly give the same color to all pixels. void loop() { uint32_t c = Wheel(random(256)); uint8_t i; for (i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, c); } strip.show(); delay(200); } //); }
As you get a little more comfortable writing code for your Gemma and NeoPixel,
you should poke through the source for the
NeoPixel library. The
examples may give you some ideas for further experimentation. The NeoPixel
calls themselves can also be helpful. I read the implementations of
setPixelColor and
getPixelColor more than once! | https://aronatkins.github.io/posts/2016-02-22-gemma-neopixel-1-random_same/ | CC-MAIN-2021-49 | refinedweb | 771 | 67.04 |
Regex.GroupNameFromNumber Method
Gets the group name that corresponds to the specified group number.. (For more information, see Grouping Constructs.).
using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class Example { public static void Main() { string pattern = @"(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)"; string[] cityLines = {"New York, NY 10003", "Brooklyn, NY 11238", "Detroit, MI 48204", "San Francisco, CA 94109", "Seattle, WA 98109" }; Regex rgx = new Regex(pattern); List<string> names = new List<string>(); int ctr = 1; bool exitFlag = false; // Get group names. do { string name = rgx.GroupNameFromNumber(ctr); if (! String.IsNullOrEmpty(name)) { ctr++; names.Add(name); } else { exitFlag = true; } } while (! exitFlag); foreach (string cityLine in cityLines) { Match match = rgx.Match(cityLine); if (match.Success) Console.WriteLine("Zip code {0} is in {1}, {2}.", match.Groups[names[3]], match.Groups[names[1]], match.Groups[names[2]]); } } } // The example displays the following output: // Zip code 10003 is in New York, NY. // Zip code 11238 is in Brooklyn, NY. // Zip code 48204 is in Detroit, MI. // Zip code 94109 is in San Francisco, CA. // Zip code 98109 is in Seattle, WA.
The regular expression pattern is defined by the following expression:
(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)
The following table shows how the regular expression pattern is. | https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.groupnamefromnumber(v=vs.100).aspx | CC-MAIN-2018-09 | refinedweb | 224 | 53.78 |
clog, clogf, clogl — natural logarithm of a complex number
Synopsis
#include <complex.h>
double complex clog(double complex z);
float complex clogf(float complex z);
long double complex clogl(long double complex z);
Link with -lm.
Description
These functions calculate the complex natural logarithm of z, with a branch cut along the negative real axis..
Attributes
For an explanation of the terms used in this section, see attributes(7).
Conforming to
C99, POSIX.1-2001, POSIX.1-2008.
See Also
cabs(3), cexp(3), clog10(3), clog2(3), complex(7)
Colophon
This page is part of release 5.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
Referenced By
cacos(3), casin(3), catan(3), cexp(3), clog10(3), clog2(3), complex(7), log(3).
The man pages clogf(3) and clogl(3) are aliases of clog(3). | https://dashdash.io/3/clogl | CC-MAIN-2022-27 | refinedweb | 156 | 66.84 |
conf.py - Sphinx configuration for generating CodeChat’s documentation¶
This file configures Sphinx, which transforms restructured text (reST) into html. See Sphinx build configuration file docs for more information on the settings below.
This file was originally created by sphinx-quickstart, then modified by hand. Notes on its operation:
- This file is
execfile()d by Sphinx with the current directory set to its containing dir.
- Not all possible configuration values are present in this autogenerated file.
- All configuration values have a default; values that are commented out serve to show the default.
Use the CodeChat version date in its generated documentation.
import CodeChat
Import the Alabaster theme customizations.
import alabaster
If extensions (or modules to document with autodoc) are in another directory, add these directories to sys.path here. If the directory is relative to the documentation root, use os.path.abspath to make it absolute, as shown here.
##sys.path.insert(0, os.path.abspath('.'))
Project information¶
project and copyright: General information about the project. Change this for your project.
project = 'CodeChat' copyright = '2016, Bryan A. Jones'
The version info for the project you’re documenting, acts as replacement for
|version| and
|release|, also used in various other places throughout
the built documents. Change these for your project.
version: The short X.Y version.
version = CodeChat.__version__
release: The full version, including alpha/beta/rc tags.
release = version
There are two options for replacing
|today|:
1. If you set today to some non-false value, then it is used:
##today = ''
2. Otherwise, today_fmt is used as the format for a strftime call.
##today_fmt = '%B %d, %Y'
highlight_language: The default language to highlight source code in.
highlight_language = 'python'
pygments_style: The style name to use for Pygments highlighting of source code.
pygments_style = 'sphinx'
add_function_parentheses:
If true, ‘()’ will be appended to
:func: etc. cross-reference text.
##add_function_parentheses = True
add_module_names:
If true, the current module name will be prepended to all description unit
titles (such as
.. function::).
##add_module_names = True
show_authors: If
true,
sectionauthor and
moduleauthor directives will be shown in the
output. They are ignored by default.
##show_authors = False
modindex_common_prefix: A list of ignored prefixes for module index sorting.
##modindex_common_prefix = []
General configuration¶
extensions: If your documentation needs a minimal Sphinx version, state it here. CodeChat note: CodeChat has been tested with Sphinx 1.1 and above. Older versions may or may not work.
needs_sphinx = '1.3'
Add any Sphinx extension module names here, as strings. They can be extensions
coming with Sphinx (named ‘sphinx.ext.*’) or your custom ones. CodeChat
note: The
CodeChat.CodeToRestSphinx extension is mandatory; without it,
CodeChat will not translate source code to reST and then (via Sphinx) to html.
extensions = ['CodeChat.CodeToRestSphinx', 'alabaster']
templates_path: Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
source_suffix:
The suffix of source filenames. Add
.in and
.spec files (see below).
source_suffix = '.rst'
CodeChat note: A dict of {glob, lexer_alias}, which uses lexer_alias (e.g. a lexer’s short name) to analyze any file wihch matches the given glob.
CodeChat_lexer_for_glob = {
CodeChat.css is auto-detected as a CSS + Lasso file by Pygments,
causing it to display incorrectly. Define it as CSS only, both in the
root path and in the template subdirectory.
'CodeChat.css': 'CSS',
The
MANIFEST.in files uses # as a comment.
So does Python. Ugly, no?
'MANIFEST.in' : 'Python', }
source_encoding: The encoding of source files.
##source_encoding = 'utf-8-sig'
master_doc: The master toctree document.
master_doc = 'index'
language: The language for content autogenerated by Sphinx. Refer to documentation for a list of supported languages.
##language = None
exclude_patterns: List of patterns, relative to source directory, that match files and directories to ignore when looking for source files.
exclude_patterns = [
Ignore Mercurial repo.
'.hg',
Ignore setup.py output.
'build', 'dist', 'CodeChat.egg-info',
Ignore Sphinx output.
'_build',
Ignore this file’s output.
'sphinx-enki-info.txt',
Ignore file from external web site.
'ez_setup.py',
Ignore HTML – the license and test output.
'**.html', ]
default_role: The reST default role (used for this markup: text) to use for all documents.
##default_role = None
keep_warnings: If true, keep warnings as “system message” paragraphs in the built documents. Regardless of this setting, warnings are always written to the standard error stream when sphinx-build is run. CodeChat note: This should always be True; doing so places warnings next to the offending text in the web view, making them easy to find and fix.
keep_warnings = True
Options for HTML output¶
html_theme: The theme to use for HTML and HTML Help pages.
html_theme = 'alabaster'
html_theme_options: Theme options are theme-specific and customize the look and feel of a theme further.
##html_theme_options = {}
html_style: The style sheet to use for HTML pages.
##html_style = None
html_theme_path: Add any paths that contain custom themes here, relative to this directory. Set this per the Alabaster theme customizations.
html_theme_path = [alabaster.get_path()]
html_title: The
name for this set of Sphinx documents. If None, it defaults to
<project>
v<release> documentation.
##html_title = None
html_short_title: A shorter title for the navigation bar. Default is the same as html_title.
##html_short_title = None
html_logo: The name of an image file (relative to this directory) to place at the top of the sidebar.
##html_logo = None
html_favicon: The name of an image file (within the static path) to use as favicon of the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 pixels large.
##html_favicon = None
html_static_path:
Add any paths that contain custom static files (such as style sheets) here,
relative to this directory. They are copied after the builtin static files, so
a file named
default.css will overwrite the builtin
default.css.
CodeChat note: This must always include
CodeChat.css.
html_static_path = ['CodeChat.css']
html_last_updated_fmt: If not ‘’, a ‘Last updated on:’ timestamp is inserted at every page bottom, using the given strftime format.
html_last_updated_fmt = '%b, %d, %Y'
html_use_smartypants: If true, SmartyPants will be used to convert quotes and dashes to typographically correct entities.
html_use_smartypants = True
html_sidebars: Custom sidebar templates, maps document names to template names. Set this per the Alabaster theme customizations.
html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', 'searchbox.html', 'donate.html', ] }
html_additional_pages: Additional templates that should be rendered to pages, maps page names to template names.
##html_additional_pages = {}
html_domain_indices: If false, no module index is generated.
##html_domain_indices = True
html_use_index: If false, no index is generated.
##html_use_index = True
html_split_index: If true, the index is split into individual pages for each letter.
##html_split_index = False
html_show_sourcelink: If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
html_show_sphinx: If true, “Created using Sphinx” is shown in the HTML footer. Default is True.
##html_show_sphinx = True
html_show_copyright: If true, “(C) Copyright ...” is shown in the HTML footer. Default is True.
##html_show_copyright = True
html_use_opensearch: If true, an OpenSearch description file will be output, and all pages will contain a <link> tag referring to it. The value of this option must be the base URL from which the finished HTML is served.
##html_use_opensearch = ''
html_file_suffix: This is the file name suffix for HTML files (e.g. ”.xhtml”).
##html_file_suffix = None | https://pythonhosted.org/CodeChat/conf.py.html | CC-MAIN-2018-30 | refinedweb | 1,157 | 59.9 |
- Advertisement
ethancodesMember
Content Count172
Joined
Last visited
Community Reputation19 Neutral
About ethancodes
- RankMember
Personal Information
- RoleProgrammer
- InterestsDesign
DevOps
Programming
Recent Profile Visitors
The recent visitors block is disabled and is not being shown to other users.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingActually I've somewhat got it figured out. Maybe. I moved the Managers object to the Start scene instead of the level1 scene. Now when I start, I get two errors. They are both for Awake functions on two different managers. The errors are caused because the stuff they are trying to reference don't exist until Level1 scene is loaded. However, errors aside, the game will now switch between scenes just fine without losing the reference to the game manager. I'm gonna try to do a little reworking on these couple of methods and see if it works.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingHere is a picture of my console when switching from the MainMenu scene to the Level1 scene. You can see the MainMenu state's Update function being hit. The "This is a game manager" is the update function of the GameManager. So then we hit MainMenu state's OnDeactivate, and the GamePlay state's OnActivate. We can see the game manager update is still being hit. Then the Update function of the GamePlay state. and finally we see the GameManager being destroyed. That is when the reference ("This is null") is lost in the Managers game object. However, right after that we can see the GameManager update is getting hit still. So I'm not sure if it is 1.Destroying the old game manager and making a new one, or 2. Keeping the old game manager and destroying the new one. It's hard to say, but I guess number 2 since it's losing the reference. But I have no idea how it could be doing that since the singleton is in place and DontDestroyOnLoad should be preventing that.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingI have not... You mean just to see when it's getting called? Or if it is getting called? I could certainly try this. Should we expect to see it called once, when it tries to make another one and finds that there is already one made so it gets destroyed? Is that what you are suggesting we try to find out? So I just found this: Sounds like a few people here had the same issue and had to unsubscribe from global events. I'm not entirely sure what that means or how to do it?
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingStill have not found a solution to this, if anyone has any more insight I would be truly grateful
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingI put a debug.Log in the Gamemanager class and even when the Manager is saying it's null, it is still firing the debug.Log every update from the GameManager. I tried to put a function in the Managers class that I could call after loading a new scene to find the GameManager component again, but still got the same error. Any other ideas? I've posted this in a few other places as well hoping to find something. I've pretty well run out of ideas myself.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingDoes it matter which scene the Managers game object is in? I have it in the Level_01 scene simply because that's where I'm always working in for most of the game so it makes it convenient to have in there so I don't have to switch between scenes for it. Then when the game starts it loads the Start scene (main menu). I don't believe it should be a problem though since that game object should be persistent anyways right?
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingSorry I put in my edit on the previous post that I did try that and it did not work. Error was the exact same. I tried it from both the individual scripts of the various managers, and also as gameObject.GetComponent<> on the Managers script.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingSo I put a Debug.Log in the Managers script in the Update function that checks Managers.Game == null. If it is, it puts a message in the Console. When the game starts up and pulls up the Menu scene, it works fine. However, it is returning null as soon as we switch scenes. So, important question that maybe someone had previously answered incorrectly. I was told I only need to put the DontDestroyOnLoad on the Managers script and since everything else is on that, they would also not be destroyed on load. Is it possible that I need to put DontDestroyOnLoad on each script? EDIT: I tried this and it did not make a difference. Still trying to figure out the issue, I have attached the error I am getting.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingI will get the exact error text when I get home tonight, and I can certainly try to set the order, but if this is the problem, shouldn't it be getting an error when the GetComponent fails? Not later when it tries to call a method on the GameManager? It's also not the first time the GameManger is being called on as it is already being used to load the Menu state when the game starts, and then called again to move from the Menu state to the Gameplay state. So I'm certainly using it a few times before I'm getting this error.
GameManager destroyed error
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingNo I apologize that was my mistake. It says Game Manager has been destroyed. I edited the original post.
C# GameManager destroyed error
ethancodes posted a topic in General and Gameplay ProgrammingI've got a state machine set up that I'm having an issue with. I have a Start scene, a Level_01 Scene, and a GameOver Scene. Each scene has a corresponding state. When the game starts, it sets the game to the Start scene. When I click the start button, it loads the Gameplay state. The game plays fine, but when you lose, the GameOver state does not load, the game continues to run, and I get one error that says the Game Manager has been destroyed and I am still trying to reference it. I have my managers set up on a Singleton pattern and I'm not sure how it's getting destroyed. This is my first time using both the state machine and the singleton, and I also have very little experience switching between scenes so I may be doing something simple wrong. The main thing I can tell you is that the currentState variable is coming back as null when I go to hit the GameOver state, and that the code is not even getting far enough to hit the OnDeactivate for the GamePlay state (probably because currentState is null). I'm really out of ideas on this one and haven't been able to find anything useful online. Hopefully someone can show me what I'm doing wrong. Thanks! //Managers object code: public class Managers : MonoBehaviour { public static Managers instance = null; private static GameManager _gameManager; public static GameManager Game { get{ return _gameManager; } } private static UIManager _uiManager; public static UIManager UI { get{ return _uiManager; } } private static LevelManager _sceneManager; public static LevelManager Level { get{ return _sceneManager; } } private static BoardManager _boardManager; public static BoardManager Board { get{ return _boardManager; } } private static PickUpManager _pickUpManager; public static PickUpManager PickUp { get{ return _pickUpManager; } } private static SoundManager _soundManager; public static SoundManager Sound { get { return _soundManager; } } void Awake () { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } DontDestroyOnLoad(gameObject); _gameManager = GetComponent<GameManager>(); _uiManager = GetComponent<UIManager>(); _sceneManager = GetComponent<LevelManager>(); _boardManager = GetComponent<BoardManager>(); _pickUpManager = GetComponent<PickUpManager>(); _soundManager = GetComponent<SoundManager>(); } } //GamePlayState code, other states are basically the same public class GamePlayState : _StatesBase { public override void OnActivate () { Debug.Log("GamePlay OnActivate"); Managers.Level.LoadLevel("Level_01"); Managers.Game.isGameActive = true; } public override void OnDeactivate () { Debug.Log("GamePlay OnDeactivate"); Managers.Game.isGameActive = false; } public override void OnUpdate () { Debug.Log("GamePlay OnUpdate"); } } //GameManager code public class GameManager : MonoBehaviour { public static MonoBehaviour monoBehaviour; public bool isGameActive; private int level = 50; private _StatesBase currentState; // Use this for initialization void Awake () { isGameActive = false; InitGame(); monoBehaviour = this; } public _StatesBase State { get { return currentState;} } void InitGame () { Managers.Board.SetupScene (level); } public void SetState (System.Type newStateType) { if (currentState != null) { currentState.OnDeactivate (); } currentState = GetComponentInChildren (newStateType) as _StatesBase; if (currentState != null) { currentState.OnActivate(); } } void Update () { if (currentState != null) { currentState.OnUpdate(); } } void Start () { SetState(typeof(MainMenuState)); } } //The load level method from the LevelManager public void LoadLevel (string name) { SceneManager.LoadSceneAsync(name); Brick.breakableCount = 0; }
problem activating and deactivating states
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingI removed the UnloadSceneAsync because apparently when you LoadScene in Single mode it automatically gets rid of the other one so the problem was it wouldn't unload the original scene yet because I was trying to do it before the other scene was loaded.
problem activating and deactivating states
ethancodes replied to ethancodes's topic in General and Gameplay Programming@Shaarigan I've got an on going issue related to this problem. I added some Debug.Logs in all my state methods so I could see when they were being called. When I start the game and I'm in the main menu, it seems to be working right. Then I hit start and the gameplay screen flashes for a second then goes back to the main menu. After that the debug.Log keeps alternating betwen the Gameplay State update method and the MainMenu State update method. I have no idea how they could both be active at the same time. I've tried all kinds of stuff. I do get this warning (see below) but I'm not entirely sure what it's about. I took the UnloadSceneAsync out of the OnDeactivate method on the MainMenu and that got rid of the warning but didn't change the behavior. Any ideas what's going on here and what the proper way to dispose of the MainMenu scene would be when the game starts?
problem activating and deactivating states
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingOk perfect, thank you!
problem activating and deactivating states
ethancodes replied to ethancodes's topic in General and Gameplay ProgrammingGot this figured out. My Managers object was not instantiated in the Start scene. I have a question though. Obviously I only ever want one Managers object, which should contain all my managers. In the Hierarchy panel, do I just put it in one scene and then make sure I always start the game from that scene? Or do I put one in each scene?
- Advertisement | https://www.gamedev.net/profile/248797-ethancodes/ | CC-MAIN-2018-51 | refinedweb | 1,879 | 54.22 |
Foundation Drupal 7
samzenpus posted more than 3 years ago | from the read-all-about-it dept.
(2)
Frosty Piss (770223) | more than 3 years ago | (#34957772)
Cock lovers (-1)
Anonymous Coward | more than 3 years ago | (#34958072)
Fuck Dupral, whatever it is...
Re:Cock lovers (1)
MightyMartian (840721) | more than 3 years ago | (#34958110)
That certainly explains your conception.
Re:Drupal (0)
Anonymous Coward | more than 3 years ago | (#34958122)
Spaghetti code.
The retort:
Yet that would only be a valid charge as a result of Drupal's great power and flexibility — particularly in the hands of a knowledgeable Drupal developer.
In a nutshell, Drupal is a pain in the ass because it has been built upon over time and seriously needs to be redesigned and rewritten to incorporate all of the "great power and flexibility". it's kind of like the "great power and flexibility" of a lot of object libraries that are a nightmare to actually use because they've gained their "great power and flexibility" from the hap-hazard add-ons over the years - there's nothing like trying to use a feature that won't work because namespaces clash - YUMMY!
Re:Drupal (0)
Anonymous Coward | more than 3 years ago | (#34958316)
Don't worry, they've made it far worse in Drupal 7. Among other great ideas:
* They removed the ability for third party modules to validate comments. Apparently no one at Drupal has ever had the idea of writing a spam filter.
* You can no longer write SQL queries directly. Instead you must use their library, which bloats what used to be a single SQL query into at least three lines of object calls. More if you want to do joins. Which you almost certainly will if you're doing anything useful.
That's all I've run into so far. If you have the option, stick with your existing working Drupal, or just use a better CMS.
Re:Drupal (1)
MightyMartian (840721) | more than 3 years ago | (#34958360):Drupal (1)
sprior (249994) | more than 3 years ago | (#34959390)
Mollem (written by Dries himself) implements a spam filter and has a Drupal 7 release - wouldn't your first statement make this impossible?
Re:Drupal (0)
Anonymous Coward | more than 3 years ago | (#34959762)
The bug report where the Drupal devs basically said "fuck you" to the guy trying to validate comments mention Mollem too. The issue is that Mollem doesn't just filter comments, it filters every single user-submitted block of text anywhere on the site. This happens to include comments.
I'm not sure how it does that since as far as I know there's no way to hook into that, so however it works, it's doing something that involves modifying Drupal's core. There's no API for filter comments any more. It was removed "by design" and will not be added back.
Essentially, if you're willing to hook into non-public APIs, you too can filter comments. But there is no official way to do it - there used to be, and it was removed.
Re:Drupal (2)
sprior (249994) | more than 3 years ago | (#34960050):Drupal (1)
Ice Station Zebra (18124) | more than 3 years ago | (#34961406)
I guess things like hook_comment_update, hook_comment_insert are not good enough for you, you'd rather have a conspiracy theory that Drupal is somehow hiding its api ala Microsoft. [drupal.org] [drupal.org]
Re:Drupal (0)
Anonymous Coward | more than 3 years ago | (#34962780)
Those don't work for filtering comments, since those happen AFTER the comment has already been accepted. The best you can do with those is cause a server error, but you can't do anything USEFUL like return, say, a useful error message. (Since if you try, the comment will be submitted anyway once your hook completes.)
Let me guess, you must be one of the Drupal developers who declared removing existing functionality that people still used to be "working as designed." Because, after all, it's possible to hack something together that doesn't actually work.
Re:Drupal (0)
Anonymous Coward | more than 3 years ago | (#34960432)
1. Use hook_field_attach_validate('comment, $comment, &$errors)
2. No one is forcing you to not be able to use db_query() and write the damn SQL yourself.
Try running into it harder.
Re:Drupal (0)
Anonymous Coward | more than 3 years ago | (#34958486)
+5 true
CMS only half the issue... (0, Funny)
Anonymous Coward | more than 3 years ago | (#34957800)!
Re:CMS only half the issue... (1)
MightyMartian (840721) | more than 3 years ago | (#34957866):CMS only half the issue... (1)
miknix (1047580) | more than 3 years ago | (#34958264)
Why fuck around with C++ when you can code it all in C, like CGI programmers did twenty years ago
Why to program webpages in C when you can do it in ASM?
Oh wait! I know where this is going...
Re:CMS only half the issue... (2)
cpu6502 (1960974) | more than 3 years ago | (#34959488)
Re:CMS only half the issue... (0)
Anonymous Coward | more than 3 years ago | (#34961546)
Uh, yes, CGI is a pain in the bum. But there's no reason a truly hardcore programmer would have to use the klunky CGI mechanism -- just write your own webserver in assembly/C/C++ !! Now that's speed!
Re:CMS only half the issue... (2)
kbielefe (606566) | more than 3 years ago | (#34958482)
I know what you mean. Slashdot, facebook, yahoo, wikipedia, whitehouse.gov, and all those other low-traffic scripting language powered websites are mere amateurish attempts. I demand a professional C++ website like, uh, help me out here...
Re:CMS only half the issue... (1)
JonySuede (1908576) | more than 3 years ago | (#34959662)
like... like google ?
Re:CMS only half the issue... (1)
musicmaker (30469) | more than 3 years ago | (#34962266)
Yeah, cos that's a typical use case... NOT.
Re:CMS only half the issue... (3, Interesting)
musicmaker (30469) | more than 3 years ago | (#34962270)
Have you looked at some of those folk infrastructures and white papers on 'cool' things they've invented to get around the unbelievable limitations of scripting langues and MySQL?
Re:CMS only half the issue... (1)
hawguy (1600213) | more than 3 years ago | (#34958752).
Yeah, but it's Drupal. (0)
Anonymous Coward | more than 3 years ago | (#34959004)
I can throw another 8 cores + 8GB of RAM at my Drupal installation for $2K
Multiply that by a few dozen boxes and you just might be able to scale!
Maybe not the best way to scale to many thousands of users, but most people that are using Drupal only need to scale to hundreds (or 10's) of simultaneous users.
Having worked extensively with Drupal sites attempting to scale to thousands of users, no, by god, it is not. But it *is* doable. It involves being rather selective with contrib modules, not writing crap PHP, properly indexing and maintaining databases, and most importantly: Not having a core that's been hacked to hell by cheap 'developers' in random third world nations.
Supporting infrastructure certainly helps. You can't go wrong with having CDN offload, lighttpd/nginx over Apache, Varnish or some other solution for caching; potentially memcached (which more often than not, does NOT help and makes things worse - sorry, conventional Drupal community wisdom!)... But no matter what additional sexiness and what additional hardware you throw at Drupal, if you want any sort of viable scalability, it all comes down to code.
Re:CMS only half the issue... (0)
Anonymous Coward | more than 3 years ago | (#34963166).
PHP programmers are cheap? That's not what my paycheck shows.
Re:CMS only half the issue... (1)
musicmaker (30469) | more than 3 years ago | (#34962326) pretty sure most of OS X is C, then Objective-C then some C++. Pretty sure BSD isn't, and looking at the Open Solaris site, looks like C, AIX, nope, True64, nope, OS400, nope. Windows, I'm fairly sure they sucked in a good chunk of BSD, which is C, and honestly, who cares about the rest of it, it's a piling of stinking shit, not too many folks who would disagree.
I think the only popular web framework I recall that used C++ to build modules was ColdFusion, and about a year later, they switched to Java.
Yes, but what we really want to know... (3, Funny)
XxtraLarGe (551297) | more than 3 years ago | (#34957832)
Re:Yes, but what we really want to know... (1)
cultiv8 (1660093) | more than 3 years ago | (#34959964)
Steepest learning curve ? (1)
foobsr (693224) | more than 3 years ago | (#34957850)
CC.
Re:Steepest learning curve ? (1)
freedumb2000 (966222) | more than 3 years ago | (#34958468)
Re:Steepest learning curve ? (1)
qpqp (1969898) | more than 3 years ago | (#34964040)
drupal compicated? (0)
Anonymous Coward | more than 3 years ago | (#34957868)
LOL
what ever
It's more like useless as anyone can write their own CMS with PHP as PHP is set up for things like this
Re:drupal compicated? (1)
hazah (807503) | more than 3 years ago | (#34965478)
Sounds Like Drupal (2)
howlinmonkey (548055) | more than 3 years ago | (#34957950)
Re:Sounds Like Drupal (1)
drinkypoo (153816) | more than 3 years ago | (#34959704):Sounds Like Drupal (1)
Hognoxious (631665) | more than 3 years ago | (#34963298)
Are you saying it's like the Star Trek movies, but backwards?
Re:Sounds Like Drupal (1)
kkruecke (540019) | more than 3 years ago | (#34962626):Sounds Like Drupal (0)
Anonymous Coward | more than 3 years ago | (#34963104)
How bout E107?
Re:Sounds Like Drupal (1)
kkruecke (540019) | more than 3 years ago | (#34968142)
Re:Sounds Like Drupal (2)
petes_PoV (912422) | more than 3 years ago | (#34963960) their hype and which ones are simply turkeys.
The dead tree format is a good way to separate the amateurs from people with a professional outlook. If people can't be bothered to describe what they've done, then what they've done is in all practical terms useless.
Re:Sounds Like Drupal (1)
loxosceles (580563) | more than 3 years ago | (#34965102) (3, Insightful)
Anonymous Coward | more than 3 years ago | (#34958046) (1)
unity100 (970058) | more than 3 years ago | (#34959446)
Re:ditto (1)
theskipper (461997) | more than 3 years ago | (#34961776):ditto (1)
unity100 (970058) | more than 3 years ago | (#34961968)
Re:ditto (1)
theskipper (461997) | more than 3 years ago | (#34962584) to your experience level with computers. But in time, as you gain more experience with programming languages, try it again. It's a much different view once you see if from the big picture.
Best of luck.
Re:ditto (1)
unity100 (970058) | more than 3 years ago | (#34965000)
check it out. and tell me how do you evaluate drupal's strength as such, as compared to the ease of use, curve and modifiability of the code you see in the signature.
Re:ditto (1)
RagingMaxx (793220) | more than 3 years ago | (#34962808) function required to achieve this in your existing module. If you aren't developing a custom module for your client, it's likely that Drupal wasn't the best choice of CMS for the project.
In my experience Drupal is an incredibly flexible starting point for a medium/large web project. However, to take advantage of the major features of Drupal there is a significant learning period required as the system is designed differently from any other PHP framework I've had experience with. Whether you consider this learning period wasted time or a knowledge investment I suppose is a matter of opinion which will differ from web developer to web developer.
Personally I found it a very worthwhile "expenditure", and now use many Drupal concepts even in completely custom PHP projects where Drupal isn't a practical choice.
Re:ditto (1)
unity100 (970058) | more than 3 years ago | (#34964998)
Re:ditto (1)
RagingMaxx (793220) | more than 3 years ago | (#34969682) most cases for PHP frameworks this just involves extracting an archive into the proper directory and writing over any files that need to be updated. However in the case of your code that would mean writing over the config file, erasing my project's settings. I am aware that it's simple to backup a file before upgrading, but that's not the point. The point is that I shouldn't have to modify any core code to use your codebase in my project.
My third criticism would be code quality. Even in the brief reading of your code I found a bug (line 70, application_header.php) and I found that your files have closing php tags which in my experience is very bad practice.
All of these are criticisms of the code itself, and ignore the elephant in the room when it comes to Drupal: community. Drupal is in its 7th actual version. Experienced web developers have re-designed that project 6 times, keeping the successful concepts and replacing the ineffective ones with better solutions. There are scores of community maintained modules already available, some of which themselves are on their 4th or 5th version. Security updates are released regularly, as well as bug fixes and feature updates.
Even if your project were superior in quality, it would take a mammoth effort by a large group of people to make it more "efficient" to start a new project with your code than Drupal.
Kudos for putting the effort in, but you have a long road ahead of you and a large number of competing PHP frameworks that many people are already familiar with. If you are really keen to help people you might consider shifting your efforts to contribute to an existing PHP project? Just a suggestion, and coming from someone who has actually taken the time to look at your project.
Re:ditto (1)
unity100 (970058) | more than 3 years ago | (#34971970) and present tables properly. it is proper for people who work in big corporate salary jobs, dealing with whatever their i.t. department is able to pass from management, which in turn generally end up the 'latest hottest', therefore not having to deal with very curious and intricate, odd requests of dev clients. however as someone who makes his pay in the trenches, i have seen that the caprice of many browsers + div+css can mean going into loss in a project whereas you could pass the hurdle easily by just implementing tables. client does not give a flying fsck about what's in there in behind, rightfully too - they are ok as long as their thing looks the same in as much devices and it can, and - note this part down - they dont want to spend much money for it. and no, you cant make them spend more money on browser compatibility with any reason or justification either - our justifications and self-righteousness as programmers in our own world, have little importance for the people outside it.
MOREOVER, and more importantly, despite it is clearly stated on the project website that code separates ALL design from tables, you still went on to link the oh-so-bad table usage on the website with the code and concept. which shows further shallowness. i could have made the project site one big whopping centered blinking text page, and it still would be separated from code.
The point is that I shouldn't have to modify any core code to use your codebase in my project.
and you dont have to. the core code stays as it is. you create new functionality through modules. i am translating an entire website that serves 10,000+ content from database for 6 years into that system, in just that fashion. i can lump the entire functionality of the website into a single module, or multiple modules, and all still would be totally self contained complete with their language, code, template files.
My third criticism would be code quality. Even in the brief reading of your code I found a bug (line 70, application_header.php) and I found that your files have closing php tags which in my experience is very bad practice.
further proof of your extreme elitism, which doesnt work well in the trenches. just like tables 'just work', closing php tags, also, just work. as for bugs, bugs are normal for weekend projects and BETA code.
Even if your project were superior in quality, it would take a mammoth effort by a large group of people to make it more "efficient" to start a new project with your code than Drupal.
doubtful. you talk of elephant in the room, yet you forget that what huge a mess and pile the drupal code has become over the years. just like any other code which was started as a hobby, but, was developed rather rapidly without any direction, guideline by many people. yes, there is huge functionality, yes there are a lot of modules, a lot of community support, and the code is still INEFFICIENT.
your concerns you expressed, apart from elitism, had centered on totally irrelevant things than the code you have seen was produced of - efficiency. as said, i am translating an entire website code, which was built more than 5 years ago, and with register globals, magic quotes and so on, in procedural fashion (no oop at all) into a module in this codebase, with mainly copy-pasting. and, whats important is, all the problems like register globals, spaghetti code and so on, are going away while im doing it, automatically. compared to running around jumping through hoops (!) in drupal for a single fscking web form look change, this is major efficiency.
If you are really keen to help people you might consider shifting your efforts to contribute to an existing PHP project? Just a suggestion, and coming from someone who has actually taken the time to look at your project.
there are enough people doing what you are talking about. i havent seen any people doing what i have done. and i have seen the need for it for over 7 years, during my professional career. i think you havent read the website's project description attentively.
Re:ditto (1)
RagingMaxx (793220) | more than 3 years ago | (#34972074) other professionals for their opinions, and if you do, perhaps try to retain a modicum of courtesy in your response.
Re:ditto (1)
unity100 (970058) | more than 3 years ago | (#34972660) al for hard practicalities of production environment in which you have to deal with small businesses or individuals' demands and needs. understandable - if i had been working in corporate environments or i.t. divisions in which i would be isolated from the demands and needs of clients in direct form, and had an i.t. manager or division fighting for what i think was right, i would also be approaching these like you do.
take the table versus div/css example. you can easily argue that it is better for usability to have less elements in a webpage, and then easily use div/css for positioning elements in such a clean interface and make sure it looks the same in many browsers and old devices as a corporate i.t. unit justifying it to management, but, as a professional who deals with clients directly, there is no way in hell that you will be able to do the same to a client who wants to put hundreds of elements, content items, listings in a single webpage. justifications, rationalizations dont matter at this point. client wants it, s/he will have it. even if you argue and persuade a few clients to what you think as the correct practice in your eyes, the third client will want it, and will have it. moreover, it is their right. and, you will end up having to place innumerable elements in the shifty div/css format, and will need to fight discrepancies here and there that may come up in random browser+device whenever you change something somewhere. in comparison, tables will stay where they are, as they are put, regardless of device, platform, software.
may sound ugly and unprofessional to you, in your current mindset. it is neither ugly, nor unprofessional. as i have said, the biases, justifications and rationale of us programmers do not have much importance in the eyes of the public.
the codebase you have reviewed, has been built to solve these problems. but, you have reviewed it with your conventional wisdom, which apply little in the world of practicalities.
Re:ditto (1)
FictionPimp (712802) | more than 3 years ago | (#34994370):ditto (1)
unity100 (970058) | more than 3 years ago | (#34994610)
not so much different from still logging in with wheel user to a *nix box and and then su ing to root.
Foundation (1)
Anonymous Coward | more than 3 years ago | (#34958118)
Will the next book be titled Foundation and Empire: Drupal 8?
What does Drupal look like (1)
merlock18 (1533631) | more than 3 years ago | (#34958120)
Re:What does Drupal look like (2)
theskipper (461997) | more than 3 years ago | (#34958202)
Seriously? [whitehouse.gov]
Re:What does Drupal look like (0)
Anonymous Coward | more than 3 years ago | (#34958536)
That's not Drupal. If it were Drupal, [whitehouse.gov] wouldn't 404. But it does. Likewise, you'd be able to pull up nodes using URLS like [whitehouse.gov] , but again, you can't.
Re:What does Drupal look like (1)
hawguy (1600213) | more than 3 years ago | (#34958820):What does Drupal look like (1)
kc8jhs (746030) | more than 3 years ago | (#34959548)
Re:What does Drupal look like (0)
Anonymous Coward | more than 3 years ago | (#34959774)
There's a module that will disable any duplicate links if you're using clean urls or pathauto.
Re:What does Drupal look like (1)
cpu6502 (1960974) | more than 3 years ago | (#34959372)
From the front page:
Sites Made With Drupal [drupal.org]
Re:What does Drupal look like (0)
Anonymous Coward | more than 3 years ago | (#34958228)
Re:What does Drupal look like (1)
FictionPimp (712802) | more than 3 years ago | (#34958234)
Whitehouse.gov comes to mind...
Re:What does Drupal look like (1)
sourcerror (1718066) | more than 3 years ago | (#34958292):What does Drupal look like (1)
armanox (826486) | more than 3 years ago | (#34958408) [whitehouse.gov] comes to mind.
Re:What does Drupal look like (1)
/dev/trash (182850) | more than 3 years ago | (#34968002)
technically yes. But the back end? Not at all Drupal.
Re:What does Drupal look like (0)
Anonymous Coward | more than 3 years ago | (#34959188)
Well in addition to the other links, here are a few of my own sites:
My personal tech/political blog. Drupal 6.
The website for my county Libertarian Party that I admin. Also Drupal 6.
Re:What does Drupal look like (0)
Anonymous Coward | more than 3 years ago | (#34959328)
I developed the Gabby Jack Ranch website using Drupal 6. It was chosen over other CMS systems because Drupal 6 allows for Multi-User / Multi-Roles / Multi-Blogs. In other words, you can have different users with different roles. And you can have a separate blog assigned to each user. I don't know if Joomla supports that feature now, but we moved away from Joomla because previously it didn't.
Currently I am redeveloping the site using Drupal 7 and updating the style of the site a little.
Still have a long way to go on that one. Only the front page has a template assigned to it. Still need to design and prepare the base template and other special templates. But, there is what I have.
House of Reps just standardized on Drupal (1)
snowwrestler (896305) | more than 3 years ago | (#34960020) [washingtontechnology.com]
The House of Representatives will be moving all their sites to Drupal; the freshmen of the 112th Congress get theirs first. Here's one example: [house.gov]
Re:What does Drupal look like (1)
gujjuguy (825157) | more than 3 years ago | (#34960142):What does Drupal look like (1)
Compaqt (1758360) | more than 3 years ago | (#34966522):What does Drupal look like (1)
/dev/trash (182850) | more than 3 years ago | (#34967902)
the Onion is no longer a Drupal site.
I wonder why.
Whats up (1)
design1066 (1081505) | more than 3 years ago | (#34958180)
Its a CMS people. If you hate it soooooo much then don't use it.
Re:Whats up (0)
Anonymous Coward | more than 3 years ago | (#34958240)
The question is why use it at all? Why read a book about developing for Drupal when you can learn about developing for a language that can do what you want just as easily and so much more? If the CMS doesn't work out of the box with maybe some plugin installation, just forget it and make your own to do what you want. Its much much easier and don't let anybody tell you otherwise.
Re:Whats up (1)
kbielefe (606566) | more than 3 years ago | (#34959096):Whats up (1)
kenrblan (1388237) | more than 3 years ago | (#34960758)
Re:Whats up (1)
musicmaker (30469) | more than 3 years ago | (#34962382):Whats up (1)
musicmaker (30469) | more than 3 years ago | (#34962368) for usual constructs like Users and Roles, a database configuration and a base set of graphics.
Those 90 thousand lines of production tested code? Everybody's use case is different, and everybody pretty much has to write a custom extension at some point. As they say, a chain is only as strong as the weakest link, and anyone writing a module for a CMS is likely to produce a pretty weak link, no matter how well tested the base system is.
again? (2)
HeavensTrash (175514) | more than 3 years ago | (#34958190)
are
/. contributors reading nothing but drupal books these days?
Re:again? (0)
Anonymous Coward | more than 3 years ago | (#34962200)
Yup, it is money in the bank as far as I'm concerned.
My opinion having read that book (1)
Gizzmonic (412910) | more than 3 years ago | (#34958368) will be a read for the ages, unlike this 'Drupal' nonsense which is clearly a fad.
Steepest Learning Curve?? (1)
ModernGeek (601932) | more than 3 years ago | (#34958760)
Long gone are the days of the true Systems Engineers.
Learning Curve (3, Insightful)
lymond01 (314120) | more than 3 years ago | (#34959048)
"Drupal is oftentimes criticized for having the steepest learning curve."
That award goes to Plone. The curve looks almost like a backwards C.
Re:Learning Curve (0)
Anonymous Coward | more than 3 years ago | (#34961290)
That award certainly goes to Plone, I worked with Plone for 3 years, the learning curve of Drupal is nothing in comparison! Just to theme plone 3 on the file system is incredibly convoluted.
Re:Learning Curve (1)
rgviza (1303161) | more than 3 years ago | (#34982786)
Agreed... Drupal is one of the easiest of CMSs to figure out.
Try dealing with interwoven...
Hosting Plans (1)
gorzek (647352) | more than 3 years ago | (#34959378) using too many resources.
Re:Hosting Plans (1)
drinkypoo (153816) | more than 3 years ago | (#34959792) ? (1)
unity100 (970058) | more than 3 years ago | (#34959484)
why is this cms being pushed all over others in slashdot ? is someone from the admin crowd participating in drupal (gasp) development ?
In other words (2)
tgrigsby (164308) | more than 3 years ago | (#34959582)
:In other words (1)
drinkypoo (153816) | more than 3 years ago | (#34959744)
I'm going to assume that there are better solutions out there or that there is an opportunity for a better solution to be created.
There is certainly opportunity for a superior CMS. Problem is, nobody seems interested in actually doing it.
Re:In other words (1)
Hognoxious (631665) | more than 3 years ago | (#34963472)
Furthermore, it's a given that anyone who was interested would be incapable.
This, of course, wouldn't stop them.
GROAN! Drupal -- never got into it (1)
pacergh (882705) | more than 3 years ago | (#34959584)
else. Still, like a moth to the flame I go . .
.
Pro Drupal 7 Development -- (bad review) (1)
unil_1005 (1790334) | more than 3 years ago | (#34960110)
Re:Pro Drupal 7 Development -- (bad review) (1)
Hognoxious (631665) | more than 3 years ago | (#34965886)
Well it got a below average score - usually everything scores 7/10.
I've read this book before. (1)
fucket (1256188) | more than 3 years ago | (#34960452)
Drupal Sucks (1)
LS (57954) | more than 3 years ago | (#34964056) of them, and you'll be waiting a while. I18n is a disaster. No support built in, and the 3rd party module sucks. You have to have a separate node for each language, so multiple languages can not be edited simultaneously. So much seemingly core functionality is only provided by 3rd party modules, and the quality of the modules varies greatly. If you want to do anything more complicated than a blog or a magazine style website, you will be writing a ton of code.
Unless you want to use Drupal as is, avoid it at all costs. If you are going to use PHP, just build your site using a framework instead, such as Zend or Code Igniter or Yii or Agavi. You will have more freedom with the structure of your site, it will be faster, and you will understand how it works.
LS | http://beta.slashdot.org/story/146612 | CC-MAIN-2014-42 | refinedweb | 4,880 | 69.72 |
Answer: Type of ‘size_t’ is what type sizeof operator returns. Standard C indicates that this is unsigned. But which unsigned is this? If it’s unsigned int or unsigned long. Let’s clear this out! Consider an example:
/* type_size_t.c -- program determines type of 'size_t' */ #include <stdio.h> int main(void) { int byte_count; printf("\n*****Program shows type of size_t*****\n\n"); printf("\"sizeof(size_t)\" returns %d bytes.\n", sizeof(size_t)); if (sizeof(size_t) == sizeof(unsigned long)) printf("\nType of \"size_t\" is \"unsigned long\".\n\n"); /* Maximum value an `unsigned long int' can hold. (Minimum is 0)*/ # if __WORDSIZE == 64 # define ULONG_MAX 18446744073709551615UL # else # define ULONG_MAX 4294967295UL # endif return 0; }
Observe below output of program on Linux Machine:
*****Program shows type of size_t***** "sizeof(size_t)" returns 8 bytes. Type of "size_t" is "unsigned long".
Actually, unsigned values can never be negative! So is type ‘size_t’ values. Several, string functions, like, strlen returns value of type ‘size_t’, strn– functions, like strncpy, strncat, strncmp etc. take one of their arguments as type ‘size_t’. Also, memory functions like memcpy, memmove, memset etc. each takes its 3rd argument as type ‘size_t’. Remember that type ‘size_t’ is treated as type unsigned long on Linux. But why do we need for type ‘size_t’? We’ll see this later.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials. | http://www.sanfoundry.com/c-tutorials-type-size-t/ | CC-MAIN-2017-09 | refinedweb | 220 | 70.7 |
SyndicationTextContentKind Enumeration
Enumeration used to identify text content of syndication item..
When you specify a value of Xhtml for the TargetTextContentKind attribute, you must ensure that the property value contains properly formatted XML. The data service returns the value without performing any transformations. You must also ensure that any XML element prefixes in the returned XML have a namespace URI and prefix defined in the mapped feed.
Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. | http://msdn.microsoft.com/en-us/library/vstudio/system.data.services.common.syndicationtextcontentkind(v=vs.90).aspx | CC-MAIN-2014-10 | refinedweb | 111 | 50.53 |
).
>
> > > > + /*
> > > > * Reserved space for exception handlers.
> > > > * Necessary for machines which link their kernels at KSEG0.
> > > > */
> > > > .fill 0x400
> > > > +#endif /* CONFIG_PMC_MSP */
> > >
> > > This is getting kind of ugly. There are a whole lot of config choices
> > > that need to use the 'j kernel_entry'. Do they all have to have their
> > > own? I'm not sure what the best way is to handle them all.
> >
> > I agree but don't know the best way to handle this. I could introduce a
> > SYS_NO_EXEPT_FILL or similar flag but this seems excessive.
> >
> > Any other ideas from arch/mips folks?
>
> Something like
>
> #if LOADADDR == 0xffffffff80000000
> .fill 0x400
> #endif
>
> but by defining an appropriate name in arch/mips/Makefile instead of
> externalizing the load-y/LOADADDR there.
Thanks for the suggestions Thiemo.
We only need one of these solutions and I think the second one is cleaner.
I do have a few questions before respinning the patch:
1. Why do you want to create another name, wouldn't there be less confusion
and chance for errors by reusing LOADADDR and ensuring it's the same as what
the linker script uses?
2. Looking at arch/mips/Makefile there are many boards not using
0xffffffff80000000. If we introduce this check it seems that all of these
boards will have their _stext changed and it'll affect their "jump" address
from monitor/boot scripts?
Marc | http://www.linux-mips.org/archives/linux-mips/2007-02/msg00393.html | CC-MAIN-2015-14 | refinedweb | 223 | 75.81 |
Hi:
<!
<
< Search result show unauthorized Files Share
MIKE
<!
<
Hi, i have created a simple class:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace MCPro
{
class DataServer
{
Public string GetValue(string value)
{
return value;
}
}
}
i build it by pressing shift+ctrl+B, then i get the DLL from Bin\Debug\MCPro.dll
then on my website i click add reference, then my MCPro.dll was added to the Bin folder, thne i press shift+ctrl+B to build my website and when i try to type"Using MCPro" the namespace or the class is not available in the intellisense??
why??
my reference on this process is this link
thnx
simple question:
ÃÂ
IÃÂ have create a web site in visual studio with form user authentication.ÃÂ Thats create a mdf database in this path:
c:\inetpub\wwwroot\website\app_data\aspnetdb.mdf
thats use Sql server
i would like to access this database with c# form application on a network with multi-user.
if i changeÃÂ the drive letter of theÃÂ pathÃÂ above to f:\ (mapped drive)ÃÂ or \\server\c\, i got this message
System.Data.SqlClient.SqlException: The file "h:\Inetpub\wwwroot\website\App_Data\ASPNETDB.MDF" is on a network path that is not supported for database files.An attempt to attach an auto-named database for file h:\Inetpub\wwwroot\website\App_Data\ASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
i read that
I need to intall a WCF as a windows service. In side this WCF , I need to copy files from a network location to the local machine and run them.
I tried to give a specific user account ( which has access to the shared location)for the windows service processinstaller and install the service. but this account cant host the WCF since it does not have admin rights.
Is there a way to host the WCF using local account.. and then to access network location in side the wcf using a specific account. ( impersenation??/ )
Thanks in advance. , | http://www.dotnetspark.com/links/27459-loading-static-files-website-from-network.aspx | CC-MAIN-2018-17 | refinedweb | 351 | 65.73 |
This is the mail archive of the cygwin mailing list for the Cygwin project.
STC - this program does nothing useful when executed; it merely exists to show a compilation problem extracted from a larger program: $ cat foo.c #ifdef WORKAROUND # include <sys/socket.h> #endif #include <sys/un.h> #include <sys/socket.h> int main(void) { const struct msghdr msg; return sendmsg(0, &msg, 0); } $ gcc -o foo -Wall foo.c foo.c: In function 'main': foo.c:9:5: warning: passing argument 2 of 'sendmsg' from incompatible pointer type /usr/include/sys/socket.h:42:11: note: expected 'const struct msghdr *' but argument is of type 'const struct msghdr *' $ gcc -o foo -Wall foo.c -DWORKAROUND $ Gcc has a less-than-stellar error message (expect type X but have type X); it could do a better job about pointing out that it is complaining about two different 'type X' declarations, and where they come from. But the root cause is that if <sys/un.h> is included first, then the use of 'struct msghdr' applied in the declaration of sendmsg() is somehow scoped incorrectly (local to the declaration rather than the global type), so that the compiler really is complaining about two different incompatible 'struct msghdr' layouts. I'm not quite sure what the fix should be, but since I hit the problem today, I'm at least pointing it out. The same test case compiles without needing a workaround on Linux with glibc 2.16. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library
Attachment:
signature.asc
Description: OpenPGP digital signature | http://cygwin.com/ml/cygwin/2013-05/msg00451.html | CC-MAIN-2015-48 | refinedweb | 266 | 56.66 |
Wiki
Migratory / Tutorial
Tutorial
Let’s learn by example. And let's use, for example, the Django Tutorial 1.
Create Your Project
Following the example, create a new project:
django-admin.py startproject mysite
Go into
mysite/ and edit your new
settings.py to adjust your database settings, and add migratory to your INSTALLED_APPS, for instance:
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.migratory', # Migratory )
When you're ready, do a
python manage.py syncdb to setup the base tables.
Create the polls app:
python manage.py startapp polls
Edit
polls/models.py to match the django tutorial:
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()
And then edit your
settings.py again to add the new app:
INSTALLED_APPS = ( ... 'django.contrib.migratory', 'mysite.polls' )
And now finally, perform a syncdb:
python manage.py syncdb
Create Some Data
Following the Django Tutorial, create a poll in the shell:
python manage.py shell
>>> from mysite.polls.models import Poll, Choice >>> import datetime # Create a poll >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now()) >>> p.save() # Add some choices >>> p.choice_set.create(choice='Not much', votes=0) >>> p.choice_set.create(choice='The sky', votes=0) # Add your vote >>> c = p.choice_set.get(choice='The sky') >>> c.votes = 1 >>> c.save()
Now, if you want to add the extra
__unicode__ and
was_published_today() go ahead, it's not really important for this tutorial.
Make Changes
Okay, so this is where it gets interesting.
We created some data, but now we realize that we need to be able to turn on and off seperate polls. We need to add an "enabled" field. Okay, no problem:
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') enabled = models.BooleanField(default=True) # New Field class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()
Now we have to reflect the changes in our database. To do so, we create a migration:
> python manage.py migrate polls add-enabled-on-polls
Let's break it down:
- python manage.py
- The usual manage.py start.
- migrate
- Create a new migration.
- polls
- The app we want to create the migration for.
- add-enabled-on-polls
- A slug for our migration used as an identifier.
We then see an overview of what's going on:
Adding '2008-12-30-add-enabled-on-polls.py' to manifest... Writing migration to: ../mysite/polls/migrations/2008-12-30-add-enabled-on-polls.py Writing snapshot to: ../mysite/polls/migrations/2008-12-30-add-enabled-on-polls.snap Changes to the model 'Poll': Add the new field 'enabled'. Please look over the changes. When you feel confident they are correct, issue a 'syncdb': > python manage.py syncdb
It tells us that it added a new migration script named '2008-12-30-add-enabled-on-polls.py', although the date will be changed for you. Where is the script? Well the app layout will now look like this:
polls/ __init__.py migrations/ 2008-12-30-add-enabled-on-polls.py 2008-12-30-add-enabled-on-polls.snap __manifest__.py models.py views.py
You can see it also created the file
2008-12-30-add-enabled-on-polls.snap, which is a snapshot of our current models for reference, and is important in executing the migration later on.
In addition, it tells us that it added the script to the manifest, which is the newly created
__manifest__.py in the
migrations/ folder. This file lists, in order, each migration script, it looks like:
[ '2008-12-30-add-enabled-on-polls.py', ]
The output also gives us a description of everything that the migration will do:
Changes to the model 'Poll': Add the new field 'enabled'.
Ah, correct! We want to add the new field 'enabled', exactly. Let's look at what the script actually does:
""" Django Migration 2008-12-30-add-enabled-on-polls.py """ def up(database): database.add_field('Poll', 'enabled')
Pretty simple, the migration defines an
up() function that takes a Database Manager as its one and only argument. The database manager allows you to adjust the database and, in between adjustments, use the models as normal with the Django ORM.
Well, that looks perfectly good to me, so let's execute it:
python setup.py syncdb
And we're done, our database should now represent our models.py quite well.
>>> from mysite.polls.models import Poll, Choice >>> p = Poll.objects.get() >>> p.question u"What's up?" >>> p.enabled True
Updated | https://bitbucket.org/DeadWisdom/migratory/wiki/Tutorial | CC-MAIN-2017-30 | refinedweb | 790 | 55.1 |
Suddenly, The Password Is `Value'Jeffrey M. Laderman
Some 18 months ago, Robert Martorelli watched in amazement as recession-wary mutual-fund managers flocked to supergrowth stocks such as Amgen, The Gap, and Home Depot that could prosper in a sick economy. "We saw incredible values as people threw away stocks that didn't have earnings momentum," says Martorelli, who runs the $240 million Merrill Lynch Phoenix Fund, which invests in unloved and unwanted companies. So, he selected investments "for the upturn"--and waited. The fund logged a respectable 37% total return in 1991. But that was far behind funds that had loaded up with high-octane growth stocks.
Now, with the economic recovery in hand, Martorelli's patience is paying off. His fund was up 18.69% for the first quarter (through Mar. 27), the best growth fund and fifth-best of some 1,200 equity funds tracked by Morningstar Inc. Now, it's Martorelli and his unglamorous stocks, such as Anacomp, National Semiconductor, and Navistar International, that are looking snazzy.
The eclipse of growth stocks by economically sensitive or "value" stocks was the most dramatic shift in a market that, on the surface, looked placid. The Dow was up about 2%, the Standard & Poor's 500-stock index down 2.8%. The average U.S. diversified equity fund neither made nor lost money. That may disappoint those who piled a record $14.2 billion into equity funds in the first two months--a figure that could easily reach $20 billion when March sales are tallied. Investors tend to buy last year's winners, and those who picked 1991's hot growth funds were more disappointed.
The move away from high-growth stocks was evident in the largest funds: Twentieth Century Select Investors, a growth-stock fund, slid 7.29% during the quarter. By contrast, the Windsor Fund, which makes big bets on cyclical companies, delivered a 4.52% return (table). Even more graphic evidence: The quarter's top-performing fund specialized in one of the U.S.'s most cyclical industries. Fidelity Select Automotive Fund (table) jumped nearly 25% on the rally in auto stocks. The fund's assets under management exploded, too, going from $2.4 million at yearend to $82 million by the end of March.
ILL HEALTH. Health care funds, previously regarded as the prescription for investment success, took the worst drubbing--an average loss of 10.77% for the quarter. Oppenheimer Global Bio-Tech, which soared 121.1% last year to become the best-performing fund of all, dropped 13.82%. Fidelity's Biotechnology, Health Care, and Medical Delivery sector funds, all among last year's top 20, have taken ill, too. They're taking up the rear along with the long-suffering Japanese and precious-metals funds.
Compared with the health care funds, the diversified growth-stock funds that led the charge last year just have the sniffles. Of 1991's top 10 growth funds, six are in the red so far this year. Still, the worst of the lot, the Janus Twenty Fund, was down just 7.94% in 1992--hardly a serious stumble after last year's 63.9% climb.
Not all of last year's leaders were dethroned. Financial specialty funds, for instance, are still riding high. In 1991, financial-services companies rallied mightily as interest rates dropped dramatically. Although interest rates are creeping up this year, the financial funds are still eking out gains. That's because investors now figure that banks and thrifts, heavily represented in these funds, have the worst of their losses behind them. Strength in the financial sector is also bolstering more diversified funds with major holdings in financial companies. "Finance stocks are important for us," says Heiko Thieme, manager of the American Heritage Fund, one of the few 1991 leaders that is still leading. His fund reaped about a third of its 16.67% return from financial stocks.
Small-company funds, whirlwinds in 1991, are still making gains. But among funds that invest in small stocks, there was a changing of the guard, too. Again, high-growth has been giving way to value issues with rock-solid fundamentals.
A typical example: Last year's red-hot Montgomery Small Cap Fund, which built a stellar 98.7% return with shrewd investments in high-growth emerging companies, is off 5%. Now the leading small-company fund is the more sober Heartland Value Fund, up 19.74%. Like Merrill Lynch Phoenix, Heartland kept pace with its peer group last year, but it really broke away from the pack in January. Like Phoenix, it invests in companies with good fundamentals that are out of favor with investors. They include companies in prosaic businesses, such as auto parts and small-town banking, which are cheap by most investment yardsticks. Says Heartland portfolio manager William Nasgovitz: "We never buy a stock with a p-e greater than 10."
ILLIQUID. Not surprisingly, other top-performing funds--Pioneer Capital Growth, Babson Enterprise, and Skyline Special Equities--also practice small-cap value strategies. Even more telling is that two top funds, Colonial Small Stock Index, up 16.09%, and the DFA U.S. 9-10 Small Company Fund, up 13.89%, are index funds that buy the smallest-capitalization stocks. Last year, they underperformed the average small-company fund; this year, they're beating all but two. The reason is that most small-cap managers shoot for fast-growing, leading-edge companies. The indexes, on the other hand, include the hundreds of mundane small companies that are more dependent on the economy for growth. It is those stocks, longtime laggards, that are now on the make.
While managers who buy Philip Morris Cos. and Exxon Corp. can deploy dollars easily, it's harder for those who invest in small-company stocks. Information about the companies is hard to find, and the stocks are often illiquid. That's why the Fidelity Low-Priced Stock Fund, which went from $200 million in assets to $800 million in just seven weeks, shut its doors on Mar. 9. "We need time to put that money to work," said Neal Litvack, senior vice-president at Fidelity. Other small-company funds that closed during the quarter include Montgomery Small Cap and Babson Enterprise.
Although the first-quarter performance derby was clearly won by the cyclical, or value-stock, players, the growth-stock portfolio managers have not cried "uncle." The case for health care stocks, for instance, is based on an aging population and new medical technologies, not on the economy. Should the recovery prove weak, investors could dump the economically sensitive stocks and return to reliable growth stocks--and the growth funds that soared in recent years will resume their flight.
Investors should get an idea of which way the winds are blowing when companies report first-quarter profits in coming weeks. If the cyclicals are still not up to speed, the value funds' newfound celebrity status may be short-lived. | https://www.bloomberg.com/news/articles/1992-04-12/suddenly-the-password-is-value | CC-MAIN-2017-17 | refinedweb | 1,162 | 65.73 |
Automating the world one-liner at a time…
We like to say that PowerShell uses Verb-Noun naming. If we were accurate, we would say that PowerShell uses Verb-PrefixNoun naming. For instance: Get-WinEvent . WIN is a prefix for Windows. Every now and again people look at this and ask “what's up with command prefixes ?!?”. Actually, the question usually comes from teams that are implementing Cmdlets and don't understand why they have to use prefixes. They sometimes feel like their noun is unique or they want to own the noun or they think they may get reorganized into a different group so they are not sure what a good prefix would be (hey - is a legitimate issue for some teams – it just has nothing to do with the customer.)
Prefixes mitigate naming collisions.
Consider the case of the recent cmdlet Get-WinEvent which was developed by the Windows Diagnostics team (the same great team that brought you the super awesome W7 troubleshooting [which uses PowerShell heavily]). What would've happened if they'd just called it Get-Event. The PowerShell team needed to use the name Get-Event Cmdlet (I'll explain why it doesn't use a prefix later) so without a prefix these two Cmdlet names would collide. So what happens with a collision? Well one wins and the other loses. Specifically, last writer wins. So if you had a script that uses Get-Event, it is going to use would ever last defined that name. In other words your script will break.
(NOTE: For the record – the story is much more complicated that that. The Diag team used the name “Get-Event” first and we OKed it with them and then sometime later we got crisp about our policy for when PowerShell needs to own generic nouns and made them change it. It was an unfortunate situation and the diag team ended up “taking one for the team” and doing a bunch of extra work so that we could deliver a great customer experience. We all owe them a big THANK YOU.)
No matter what we do, naming collisions will occur so let's talk about how you deal with that when it happens. The solution is simple, you use the full Cmdlet name. Full Cmdlet name? Yes that's right, every Cmdlet that has a short and a full name. The names you use all day long are the short Cmdlet names. The full name Get-WinEvent is Microsoft.PowerShell.Commands.Diagnostics\Get-WinEvent. That’s right, if anyone comes along and collides with Get-WinEvent, you just go change all your scripts to use Microsoft.PowerShell.Commands.Diagnostics\Get-WinEvent. OUCH! Clearly this is an undesirable situation but at the end of the day these things happen so you have to have a solution. That said, it should be obvious why we want to avoid collisions as much as possible.
Think through the problem.
When we thought through this problem we made some guesses about how many things needed to be named. It's been many years since we had the discussion but I believe the numbers were something like this:
The key observation here was that we had to minimize the possibility of short names colliding on a particular machine (not a customer site or the industry).
Verb names are meant to be standard so they're always going to collide - that's a good thing (because it means you can guess which you want to do in your guess will be correct). So this is really an issue of increasing the Hamming Distance of noun names. Adding a 2-4 character prefix (indicating the team or product that owns the noun) in front of the noun solves this problem.
NOTE: The side benefit of using prefixes is that it provides an easy way to find all the commands from a particular source. For instance, the Active Directory team chose the prefix “AD” so you can type: Get-Command *-AD* to find all their Cmdlets.
So that is the reason why we are hardcore on the guidance to use prefixes in front of your noun names.
Oh wait, I promised to tell you why PowerShell sometimes doesn't use the prefix PS in its Cmdlets. There are three reasons for this:
But I hope this clarifies the importance of prefixing. As a community it is in your best interest to enforce this standard quite getting grief to those teams and companies that don't adhere to it.
Enjoy!
Jeffrey Snover [MSFT] Distinguished Engineer Visit the Windows PowerShell Team blog at: Visit the Windows PowerShell ScriptCenter at:
we have a complete network and applications testing framework written currently in v1 (now porting to v2) and we have always used a prefix. our company name is Front Porch so we use the FP in front of the noun for most cmdlet/function names unless it is specific to a product application then we use a Three Letter Acronym to identify the product the command is targeted to. Prefixes are awesome and we need more of them so people can see were the command comes from!
It would be good if the prefixes were all consistent with the .dll / snapin. When you get multiple snapins loaded and potentially hundreds of cmdlets available in a session it would make tab-completion much easier. For instance, if all the Exchange cmdlets were prefixed with 'ex' it would speed up tabbing through a list of cmdlets if you don't remember the exact name, but know it's Exchange specific (eg get-user should have been get-exuser).
IMHO
I would have loved to see an aliasing capability for extremely long module names e.g. Set-ModuleAlias psdiag Microsoft.PowerShell.Commands.Diagnostics
Then you would disambiguate Get-WinEvent simply as psdiag\Get-WinEvent. The benefit is that you don't create a new namespace i.e. the prefixed nouns of a module. Rather, your just creating a convenient alias for an existing namespace - the module name. | http://blogs.msdn.com/b/powershell/archive/2009/09/20/what-s-up-with-command-prefixes.aspx | CC-MAIN-2015-06 | refinedweb | 1,009 | 70.13 |
import British actors regularly. Wasn't the second largest population to get affected by 9/11 were Brits in NYC?
I'm sure a good free-trade what-cha-ma-call-it will be fine within a NAFTA-like deal.
The following are the top 3 export markets for Britain in 2011.
1) USA = 31 billion
2) Germany = 27 billion
3) France = 18 billion....
Even without a free trade pact with the USA, Britain's largest export market is the USA. Imagine what British exports to the USA will look like with a free trade pact with the USA.
and do you seriously think the US is interested in a free trade deal or that it could be done quickly given the way congress works?
I guess you should take into account 2 things:
1)US has much bigger population and GDP than any single European country
2)You should count EU as a single unit
Taking those things into account it is clear that UK's economy is much more dependent on EU than US.
Of course, Congress will act within a week. There is a special relationship.
Which Ayatollah made this rule that one country should be compared to 27 countries?
Why stop at 27, why not compare the USA to 50 countries?
As for GDP can any of the EU elites enlighten us why USA & Canada with a total population of 340 million has the same GDP as 500 million EU?
How is it that North America which has 60% of the EU's population has the same GDP as the EU?
The US has a free trade pact with Australia and is currently negiotating a free trade deal with New Zealand.
Canada is negotiating a free trade pact with India.
USA and Canada are already trading freely within NAFTA.
It appears English speaking countries find it quite easy to implement free trade pacts with each other because of similar commercial laws, common language, etc.
The US congress recently passed a free trade pact with South Korea.
So yeah the US congress will be very much interested in a free trade pact with Britain given the deep economic ties between the two countries.
After all the USA is also Britain's biggest foreign investor and vice versa. I would venture that the US would also be interested in free movement of peoples within an UK-USA free trade pact given the huge numbers of Brits working in the USA and vice versa. There is a reason why Britain suffered the largest number of casualties in 9/11 after the USA.
"I guess you should take into account 2 things:"
How come you don't take into account the fact that Britain has no free trade pact with the USA?
The free trade treaty with S Korea took 20 yrs of negotiation and only in the end got passed because the US decided it really needed to lock S Korea into its sphere of influence.
Likewise the US has started negotiations with all Pacific rim countries that are not China for a wide free trade zone but the US motive is not primarily trade but a political aim of locking out Chinese influence and in this is it is being helped by belligerent Chinese nationalism in the South China Sea. Any trade talks with New Zealand are part of this and there are no bilateral US/NZ free trade talks. Its worth pointing out that these talks are in the doldrums anyway after >2yrs of negotiations due to US industry demanding unreasonable protectionism - eg US drug companies wanting the end of New Zealand's centralized pharmaceutical agency (PHARMAC) which ensures as low as possible prices and carefully vets the real evidence for all medications.
If the UK left the EU it would need to negotiate bilateral treaties with over 60 countries quickly and the UK would soon find that all of them know they have the UK over a barrel and will only agree to terms that suit them and not the UK. The USA would be cold eyed and quite ruthless in any negotiation with the UK.
1) USA = 31 billion
2) EU as a whole = £111.5 billion
The point being that the EU is one big export market. It's kinda what it's been doing for the last 30 years. So I don't understand why you just picked 2 EU countries to represent the whole **Common Market**
The South Korea free trade pact was only negotiated during George W. Bush era. It is news to me that Bush Jr was president 20 years ago.
As for the rest of what you said, they are filled with the same half truths, distortions and biased opinons masquerading as facts.
"there are no bilateral US/NZ free trade talks."
Maybe according to Goebbels. But reality is quite different.
"At the APEC meeting in Singapore in 2009, President Barack Obama announced a free trade deal with New Zealand would go ahead."...
You have failed to take into account that Britain has free trade with the EU but not with the USA.
Even without a free trade pact with the USA, Britain's exports to the US were higher than with Germany or France
I see that you are very bitter regarding EU and always choose to cherry pick what you want and disregard everything else.
1)EU has to be taken as a single unit because we are talking about market access and regulations and EU is a single market, with the same regulations.
2)Now regarding GDP per capita. I don't even know why you brought this up because to UK it is irrelevant. What is relevant is the value of the "whole market", not every single citizen of that market. Nevertheless, I'll play along.
2a)North America has 68% of the European population, but if you go into more detail into the demographics, you will see that EU has an older population and the labor force is EU = 228.3 million, whereas US + Canada = 175.3 million. Only the raw numbers regarding the labor force (without caring for the median age and the number of people they have to support) tell you that the ratio is not 68% anymore but 77%.
2b)Now you can add the fact that EU has a lot of Eastern European countries which still struggle with the damage Communism inflicted to their economies and productivity. They have very low income per capita compared with the countries of Western Europe.
2c)The cherry on the cake: US has vast mineral resources and agricultural land whereas EU is extremely lacking in both.
2d)This is not related to the amount of GDP but to its "quality": A big chunk of the GDP in US is a product of the war industry, bloated healthcare costs, management of prisons and prisoners etc. As a matter of fact if you go into accounting details, the enormous deficit of US adds 10% to the GDP every year. EU as a whole has a much lower deficit.
3) If UK signs a free trade agreement with US, don't expect the trade to increase 2 or 3 fold. The best you can expect is 20% increase. And as many other people mentioned in their comments, UK has a far smaller negotiating power, than EU. Just look at what happened to Argentina after they nationalized the assets of a big Spanish oil company in Argentina. EU backed Spain and now Argentina is throwing tantrums why EU blocked some of their products. Spain in its current economic situation would have no leverage whatsoever to counteract to the "theft" of the Argentinian government.
I know that you have already made your mind and will discount all of the above topics as irrelevant, but British citizens should really take this article into account when they will have the referendum (this seems like a certainty).
20 years ago Asian countries like South Korea, Taiwan etc were poorer than the communist eastern european countries and yet today they are more affluent. And there was no massive amounts of EU structural funds pouring into these countries.
So this excuse doesn't wash.
If you are jealous about US GDP there is nothing I can do about it. But feel free to indulge in excuses to feel better .
When the USA was created in 1776, it was a tiny population of 4 million struggling to make a living in a small patch of land on the east coast while France, Britain & Spain had much bigger economies.
Oh dear how the roles have reversed now. And there was no Marshall plan, no EU structural funds, no nothing.
You are a loss of time! The fact that South Korea and Taiwan grew faster than Eastern Europe tells nothing about EU. USA maybe didn't have a "Marshall plan" from Europe but they became such an important country because of Europe (whereas Western Europe after WW2 became such an important region thanks to US).
1)For God's sake, US population has been mainly of European descent. How can you say Europe has not contributed to US?
2)The Napoleonic Wars had 2 effects on US: first Napoleon sold the Midwest to USA because they couldn't control that because of the British Empire, second Napoleon saved USA during the British-American war.
3)WW1 increased the demand for US products (boosted US industry), while destroying European industry and manufacturing.
4)WW2 had the same boosting effect for the American economy as WW1. Also US took all the patents and intellectual property of Germany. I suggest you to read about this, there are some good articles online. The 2 most iconic industries of US that are a direct result of this intellectual theft are the Aeronautic industry (the jet engine was a German invention) and the rocketry and space industry.
5)The exodus of scientists and engineers from Europe after WW2.I guess there is no need to explain how much they have contributed to US.
I love US and I think it is the great country in the world, but it seems to me that US is a historical incident of European events. Even the most famous American landmark was a gift of France - the Statue of Liberty.
For me this discussion ends now.
Really? Yes the announcement of negotiations was made by Bush in 2005 and formal treaty signed in 2007 - quite a short time it would seem, but, the first discussions between S Korea and the US started back during the Reagan administration, and even though it was signed in 2007 the treaty was only enacted in full in March 2012. You seem to have missed the main point of by earlier post which is that trade treaties are primarily politically driven from inception to final enactment and are like marriages in that both sides must want it. If the UK leaves the EU it will need >60 trade agreements in a hurry and will find that the other parties are not so pressured and will extract as much as they can out of the UK.
The whole EU establishment is working towards dissolving the nation-state. The UK should leave, and so should The Netherlands. Up till 2-3 years ago I would have thought this an extremity, but now the conclusion is that we have no other choice if we want to preserve our freedom.
You sound like an American who is afraid of losing his freedom because of the communism.
They are not dissolving the nation-state. They are combining 20-27 nation-states into one federal empire, because this is required to make the Euro work long term. This was the whole point of the Euro from its founding.
Some European intelligentsia claim that the nation-state was a horrible idea cooked in the 19th Ct. to solve the crisis of the falling European Empires.
The main argument, if I recall correctly, is that the nation state has produced the patriot-politician ("scoundrel") ruling 'in the name of the nation.' Hence, the national resources have been hijacked by a political elite that redistributes as it wills for the sake of 'national interest.'.
Britain trades more with the US than with Germany,
Britain now pays 40% of the EU budget.
The EU will not miss Britain but the 30% budget cuts to internal subsidies will destabilize the EU which holds power only until the borrowed and other money runs out.
Europe is a virus, the EU has sucked the life out of the European economies.
"Britain now pays 40% of the EU budget"
No it doesn't - I think you mean closer to 4%. Britain contributed about £5 billion (rounded up) last year, which equates to 4.76%
My source:...
Rule Brittania. The continent needs Great Britain & not the other way round.
This is a great Romantic notion. It was once promoted asa sincere goal. In the US, the legal system that is based on English jurisprudence has taken a nose dive in credibility and accessibility. To rule; is to abide by laws.
The US has been taken over by a ruling class that understands that when the laws get in the way, one need only make new laws or destroy old ones. Has that happened in Britain too? W was fond of saying, "We are a nation of laws." They never showed the ease with which the fragile laws were broken and/or replaced in his tenure both as Governor and as President.
This land of laws has turned into a land of frauds. What's the point anymore of promoting any education beyond that? A more putrid situation can hardly be imagined. Let the gangs rule... oops; they already RULE !
"We have our own dream and our own task. We are with Europe, but not of it. We are linked but not combined. We are interested and associated but not absorbed."
Winston Churchill
you must be off your rocker, really..." ?
There are several assumptions in your second paragraph each backed up by an astonishing absence of evidence.
Yes, I was just guessing why, but I am still wondering why the anti-EU sentiment is so much more extreme in Britain than in the countries I mentioned. It is not something you can simply back up with scientific-like evidence.
The answer is very obvious.
Britain has a very different history from continental Europe.
?
2c - maybe the reason that anti EU feeling is stronger in the UK than in other net contributors is that because the UK was more sceptical at the outset; however, no one can doubt that anti EU sentiment in net contributors right across the EU has grown exponentially in recent times and has probably been growing faster than in the UK, as in the UK we had already got there!
This is a political issue - of course; at the last round of elections for a treaty change, didn't France, Ireland and the Dutch all vote NO?
There is no truly honest debate in the EU between the insiders (who have a massive self interest in continuing the consolidation of Europe) and the people of Europe. I don't see this as a good thing for any individual within Europe. Ask the Greeks, the Portuguese, the Irish, and even a fair few French, Add on the Dutch, the growing number of Germans and Finns. To single out the British is once again to avoid the real issue.
Lets have some honesty from Brussels. There is plenty of good stuff about the EU, but sadly it is outweighed by so much dreadful waste, unaccountability and democratic dishonesty.
"Personally I doubt whether UK big business and The City will let the UK leave the European Union. There's just too much at stake for them."
Why?
They do international business and only get a bit of their revenue from the dying European economy. Europe wants to regulate them and this regulation might end their global business.
They want to be part of the dynamic and growing global economy.
Dying European Economy??? German economy is far more superior than UK economy. Just do a walk around. You drive their cars every day !!! Osborn announces austerity until 2018. Is this because of EU ?
Aren't these lazy assumptions - and I'm just as guilty as you - that should not be accepted as true or indeed fixed? We are all the playthings of a rather frantic media world, and content to have them form out outlook for us.
To put things another way, the Brit is in my view not a jot more sceptical of the EU or jealous of his national sovereignty than monsieur Dup.
You are describing Francois Hollande and Bling Bling Sarkozy.
It would be terrible for the EU!! The EU sells far more to the UK than the UK sells to the EU!! France would be totally screwed.
Just about every country on the planet sells more to the UK than what the UK sells to them.
It is called a crisis of competitiveness - and God forbid you English should start not blaming Europe for your own moribund economy.
Another old chestnut endlessly recycled by the spoken and print media who slavishly broadcast what the Elysee palace and Chancellor's press offices feed them.
The article misses the main point and that is that the EU with political and financial union is on a collective suicide mission.
Before the Euro if a country in the EEC got into trouble then it was austerity and IMF loans the rest of the EEC carried on as normal.
With the advent of the Euro a country gets in financial trouble and this ripples out to the other countries and the countries that before the Euro would have survived unscathed get the virus and then they are in trouble and so on. Result every country in the EU is weakened.
If the EU goes for full political and financial union then what are now individual countries but in future EU regions will still take on masses of local debt, provide pensions that are unaffordable, bribe the electorate with unaffordable goodies, stoke consumer booms, full house price booms. All because the Central EU (well the Germans) are now legally responsible for picking up the tab. Let those Germans work hard whilst we eat cake and have a German standard of living.
Then when it goes wrong and it will go wrong because the EU is not as a whole competitive on the world stage, it can not out manufacture China, it can not create a Google and Intel, it can not compete with consumer goods from South Korea. So the only thing it can do to provide the quality of life its population is accustomed to is to borrow the cash for the purchases. When the borrowing stops it will be kaboom all over again.
I see no collective will in Brussels that says how does the EU become the manufacturing powerhouse of the world, all I see are taxes, regulations, laws, wasting huge amounts of time on protecting local markets like Camenbert production, that the Chinese and the Americans must be rubbing their hands with glee over.
Britain is better of out of the EU because it is a ticking time bomb that Germany can not afford to bail out.
Your allusion to "collective will" and "manufacturing powerhouse" are very important. I would posit, that, in this time of the ability to overproduce, it is time to rethink competitiveness in terms of who can produce more by cheaper means.
It is now time to try to conduct a cultivation of "collective will" that takes a quantum leap into benevolent research and production. Somehow fighting the nature to be lazy while at the same time not working ones self into an antisocial workaholism that tends to destroy families. It is deserved by the overworked and the newcomers by virtue of the past deaths in all wars and strifes. Do we have to compete till there is only one producer/consumer left? It is time for the philosophies of Mr. Smith and Marx to make friends; perhaps via Mr. Schumpeter.
Good article. However, another aspect should have been mentioned: defense policy
No country in western Europe is longer able to maintain a full spectrum force the question for the UK is how to solve the resulting issues, force structure and industrial base.
My feeling is that pragmatic solutions would be much easier within the EU.
.
The next generation of American leaders will withdraw from Nato and then it is Germany which will need to start worrying about its defense policy.
Incase you haven't noticed, Germany doesn't live next door to Canada.
Next time the Balkans blows up there will be no Uncle Sam to put out the fire. I hope Germany is up to the task as the leading power of Europe, not if but when a crisis erupts on Europe's backyard to take care of it.
If I were German, I would think about beefing up German naval power too. Yes, I know you thought God was protecting the major sea lanes for German exports but freedom of navigation which you took for granted as your right is an expensive privilege provided by the US navy since 1945 and paid by the US taxpayer.
This free lunch is coming to an end much sooner than your realize, so I suggest Germany start building now an adequate naval force to protect its shipping to Asia & the Americas.
Either that or paying protection money to the Chinese navy. I hear they drive a hard bargain.
In case you have not noticed, Emmafinney: The article is not about Germany.
It is about a country called Britain.
Stalking me again as one click of the link below shows.
emmafinney posted the same hogwash to me like 3 months ago.
She's on a mission to change the world by frantically copypasting.
flowfall,
Stop being Josh already.
:)
Hilarious.
What about you, Josh? LOL!
Tariffs on British textile and agricultural exports are NOT a valid argument against quitting the EU. Switzerland, Norway and Iceland all NON-EU members pay no such tariffs on their goods. The EU treaty gives all States quitting the EU the option by law to negotiate such free trade. Europe would be obligated by law and simple economic reality to comply. Even the French wouldn't think of throwing the British market for their agricultural exports away!
Otherwise,it is all GAIN and no pain quitting the EU at this juncture. Many Britons have established family and business ties with the Continent which can easily be recognized and protected.
The 5th century AD revisits the West again. Roman Britain losing ties to Honorius/Valentinian II in Brussels, Gaul. Only now, no Stilicho/Aetius/Avitus, the Saxons/Frisians are staying home, the Picts are threatening, and the peripheral provinces are falling away from the center run by the Franks. Scribatur nunc!
Excellent article, BTW.
Very good briefing, one of the best in the recent times. Now I know, that Britain will stay in the EU. Iceland is going to be a member in the forthcoming years, in Switzerland, business organisations, mainly export-oriented, strongly back, membership bid for Switzerland (although most of the society is against it). Only Norway seems to be outsider forever, their choice.
Everyone sees, that UK is too weak and too small to be a political force in the world, even, standing next to Russia, Mexico, Brazil, Indonesia. If Britons want to be "second Nigeria or Pakistan", their choice.
Most of financial services and industrial sector, work as EU's back.
UK is something like "Poland of the Western Europe", which also is EU's backwater and backstage for EU economy (main service sector is outsoursing, main industries are aseembly plants in the pan-European supply chain).
Beeing eurosceptic I would vote for leaving the EU, but I am pragmatic in the same time and the best choice for UK or Poland, now, is to stay within, but aside and not interfere, look at the rest of the world, search for business opportunities.
please TE ... sort yourself out; this article may make some good points, but half of it is waffle, twaddle and non- arguments made on the back of false supposition.The author has simply crammed in everything he/she could think of, regardless of quality; when i was doing my O-levels i used to make the same mistake. This article could/should be half as long -and twice as good as a result.
You stay clear of one major issue: Alba (also known as Scotland in English).
If such a referendum happens before the Scottish referendum, then England is basically kicking out Scotland from the UK, as for the Scots it may be more important to stay European than to stay British.
If the European referendum happens after a Scottish referendum where the SNP would have lost, then arguments for a new referendum are easy to make.
A win-win situation for Maighstir Alexander Salmond!
After leaving the EU, Britain's last sovereign act will be to burn Farage at the stake, then implode in endless street protests and strikes.
"Britain would have less diplomatic and military clout, too."
I find this to be the most telling effect of an EU withdrawal and it would only get worse over the years. I don't see how a country like the UK which fancies itself a big fish in international deplomacy and negotiations would fancy a slow decline into irrelevance on the international stage - this is despite being a nuclear power and being on the UN security council.
The scenario of UK referendum is inevitable in my view because it is David Cameron's only realistic hope of being reelected at the next election.
For what it's worth I think that exiting the Euro would be a disaster, but maybe people should just get on with it already so that they can stop whinging.
Great Article!
The UK is not in the 'Euro'... You do understand the debate, right?
We have a seat on the Security Council because we spend more on our military than Russia.
End of story. Nothing to do with the EU.
The rest of the EU is a joke.
The permanent members of the Security Council are the ones with large, deliverable nuclear arsenals. India will logically be the next to join this club.
Beautifully written... Excellent...
At last! An adult assessment of Britain's EU options. Please make sure copies are sent to all those head-banging Europhobes in both Houses of Parliament and in the national press.
I was disappointed in this article. It seemed to be rather superficial without the detailed analysis that this subject is crying out for in the UK press. I was expecting more.
I was however amused at thought of dairy tariffs making cheddar uncompetitive in the French market.
We shouldn't leave the EU because the French won't buy our Cheddar!! Oh wait, they don't already.
The UK has always been a square peg in a round EU hole -as it's a special case for historical reasons. Divorce is not really an option- but perhaps separation is. The UK should be allowed to leave the EU and have a free trade agreement with Europe that allows the free flow of goods, services and person to/from EU members. It can be a non-voting observer at the EU, still make an agreed upon contribution to EU coffers (but not to CAP)and follow EU rules if it is needed for trade. All the UK really wanted was a free trade deal and not to be shut out of Europe. France and Germany know this so it is in everybody's interest to pursue this and all will win. The broader EU project is worth pursuing, but as we have found out the hard way it was not well conceived and was applied rather slopply. There is a place in the EU for a separate UK. The UK should diversify its trade links as wide as possible to take advantage of opportunities and hedge bets--as should Europe. Queen, country, continent and globe.
This article has gone to some length to describe why this wouldn't work. People need to wake up to the fact that despite the many, many, many problems with it, we're fundamentally better in than out. An excellent article.
But the article had too narrow focus on why it would not work. It can work with the right negotiation and will--the Swiss or Norway options are not the only ways..
Because without the UK Europe is weaker and vice versa- they need each other in this special relationship.If not both will be less than the sum of their parts.
£50 billion (trade surplus with the UK for the rest of the EU) says an amical separation is not only possible but essential for the EU. BMW, Mercedes and Audi would lose their 3rd biggest market at a stroke for example.
"The continent is *pissed off* on the british behaviour" if that were true then it would be the only thing "the continent" does agree on! .Only if agreement on how to solve the eurozone problem were so easy. Or indeed, only if the british had been listened to during the euro negotiations in the early 90's, instead of ignored as obstinant for pointing out the realities and difficulties of a single currency.
"The continent is *pissed off* on the british behaviour"
However this didn't stop the continentals from greedily accepting British contributions to IMF eurozone bailouts.
Polar Resident
You are correct in your finding that both are less than the sum of both, but why do you believe that the EU would give the EU some special agreement when the UK was the one leaving is really above my head.
After the UK left the *we are less now* situation would have arisen anyway. The EU would be *less* and why should it give it leaving part a nice goodbye which than would possibly get others to the same thought.
Why should we stay in when we can have all the advantages without the disadvantages, so if you believe there will be quick negotations, sorry that is wishful thinking.
On top of having *pissed off* all other there are still old debts to be setteld. There are enough people/nations who clearly will demand you to pay for old wrong doings (real or only imagined ones).
That doesn't matter.
Can you tell me why the EU should loose the UK market when the UK will be the one who has to negiotate special agreements below the WTO line?
Now that cars will become more expensive in the UK but do you really believe that the people now driving around in BMW/ MERCEDES or AUDI will not order these car anymore.
What will they order instead? and who will loose out on this.
The UK can not take a higher customs tariff on cars than the WTO rules allow, but these rules would be subject to every car import worldwide as long as there are no special bilateral rules which are lowering them.
Now as far as I know the UK is more or less exporting 50 % of it's goods into the common market.
Do you really believe the EU would look nicely when you rise special tariff barriers on european goods, especially when you want access to the free market?
The higher you rise the barriwer the more likely it will be your access will be fully stopped - and if only to make an example.
Sorry but you are to s....d to discuss with
PLONK
double posting.
The article was pretty good, but did not answer the question or really explain why the anti-EU sentiment in the UK is so extreme in comparison to other EU countries, some of which pay big into the EU budget (Germany, Sweden, The Netherlands). I guess your comment is spot on. I was an undergraduate student in the UK in the late 1990s and I can indeed attest to this "Little England" mentality or psyche, which is somehow being in denial of Britain being part of Europe. This is very strange, because Britain is geographically part of Europe and has been shaped by many centuries B.C and A.D. by a shared European history. Modern Britain would not have existed if it hadn't been invaded from Normandy (mainland Europe/France) in 1066. | http://www.economist.com/comment/1788435 | CC-MAIN-2014-41 | refinedweb | 5,463 | 70.02 |
The source code for this Module is: Module 3 C/C++ source codes. and the related worksheet for your practice is: C lab worksheets 5.
Modifies the order of the statement execution.
Can cause other program statements to execute multiple times or not to execute at all, depending on the circumstances, condition imposed.
Other type of program control includes do, for and while that will be explained in detail in another Module.
This section introduced because many relational and logical operators are used in the expression of the program control statements.
The most basic if statement form is:
-
Evaluate an expression and directs program execution depending on the result of that evaluation.
-
If the expression evaluate as TRUE, statement(s) is executed, if FALSE, statement(s) is not executed, execution then passed to the code follows the if statement, that is the next_statement.
-
So, the execution of the statement(s) depends on the result of expression.
if statement also can control the execution of multiple statements through the use of a compound statement or a block of code. A block is a group of two or more statements enclosed in curly braces, { }.
Typically, if statements are used with relational expressions, in other words, "execute the following statement(s) only if a certain condition is true".
For example:
A program example:
// demonstrates the use of the if statements
#include <stdio.h>
int main()
{
int x, y;
// input the two values to be tested
printf("\nInput an integer value for x: ");
scanf("%d", &x);
printf("Input an integer value for y: ");
scanf("%d", &y);
// test values and print result
if (x == y)
{
printf("\nx is equal to y");
}
if (x > y)
{
printf("\nx is greater than y");
}
if (x < y)
{
printf("\nx is smaller than y");
}
printf("\n\n");
return 0;
}
We can see that this procedure is not efficient. Better solution is to use if–else statement as shown below:
The expression can be evaluated to TRUE or FALSE. The statement1 and statement2 can be compound or a block statement.
This is called a nested if statement. Nesting means to place one or more C/C++ statements inside another C/C++ statement.
A program example:
// demonstrates the use of if-else statement
#include <stdio.h>
int main()
{
int x, y;
// input two values to be tested
printf("\nInput an integer value for x: ");
scanf("%d", &x);
printf("Input an integer value for y: ");
scanf("%d", &y);
// test the values and print result
if (x == y)
{
printf("\nx is equal to y");
}
else if (x > y)
{
printf("\nx is greater than y ");
}
else {
printf("\nx is smaller than y ");
}
printf("\n\n");
return 0;
}
Keep in mind that we will learn if–else statements more detail in program controls Module. As a pre-conclusion, there are 3 form of if statements.
Form 1:
Form 2:
Form 3:
Expression using relational operators evaluate, by definition, to a value of either FALSE (0) or TRUE (1).
Normally used in if statements and other conditional constructions.
Also can be used to produce purely numeric values.
Another program example:
// demonstrates the evaluation of relational expression
#include <stdio.h>
int main()
{
int a;
// evaluates to 1, TRUE
a = (5 == 5);
printf ("\na = (5 == 5)\n Then a = %d\n", a);
// evaluates to 0, FALSE
a = (5 != 5);
printf ("\na = (5 != 5)\n Then a = %d\n", a);
// evaluates to 1 + 1, TRUE
a = (12 == 12) + (5 != 1);
printf("\na = (12 == 12) + (5 != 1)\n Then a = %d\n", a);
return 0;
}
Output:
x = 5, evaluates as 5 and assigns the value 5 to x. This is an assignment expression.
x == 5, evaluates as either 0 or 1 (depending on whether x is equal to 5 or not) and does not change the value of x. This is comparison expression.
Consider this, the wrong usage of the assignment operator ( = ),
if(x = 5)
printf("x is equal to 5");
The message always prints because the expression being tested by the if statement always evaluates as TRUE, no matter what the original value of x happens to be.
Referring to the above example, the value 5 does equal 5, and true (1) is assigned to 'a'. "5 does not equal 5" is FALSE, so 0 is assigned to 'a'.
As conclusion, relational operators are used to create relational expression that asked questions about relationship between expressions. The answer returned by a relational expression is a numeric value 1 or 0.
Similar to mathematical operators, in case when there is multiple operator expression.
Parentheses can be used to modify precedence in expression that uses relational operators.
All relational operators have a lower precedence than all mathematical operators.
For example:
(x + 2 > y)
Better written like this:
((x + 2) > y)
For example:
x == y > z equivalent to x == (y > z)
Avoid using the “not equal to” operator ( != ) in an if statement containing an else, use “equal to” ( == ) for clarity.
For example:
if(x != 5)
statement1;
else
statement2;
So, better written as:
if(x == 5)
statement2;
else
statement1;
C / C++ logical operators enable the programmer to combine 2 or more relational expressions into a single expression that evaluate as either TRUE (1) or FALSE (0).
These expressions use the logical operators to evaluate as either TRUE or FALSE depending on the TRUE/FALSE value of their operands.
For example:
For AND and OR operator are summarized in the following Tables:
For relational expression, 0 is FALSE, 1 is TRUE
Any numeric value is interpreted as either TRUE or FALSE when it is used in a C / C++ expression or statement that is expecting a logical (true or false) value.
The rules:
▪ A value of 0, represents FALSE.
▪ Any non zero (including negative numbers) value represents TRUE.
For example:
x = 125;
if(x)
printf("%d", x)
From the above example, we are given 3 conditions:
Is a less than b? , a < b // Condition 1
Is a less than c? , a < c // Condition 2
Is c less than d? , c < d // Condition 3
Condition 1 logical expression that evaluate as true if condition 3 is true and if either condition 1 or condition 2 is true. But this do not fulfill the specification because the && operator has higher precedence than ||, the expression is equivalent to a < b || (a < c && c < d) and evaluates as true if (a < b) is true, regardless of whether the relationships (a < c) and (c < d) are true.
For combining a binary mathematical operation with an assignment operation.
There is shorthand method.
For example:
x = x + 5;
→ x += 5;
The general notation is:
expression1 = expression1 operator expression2
The shorthand method is:
expression1 operator = expression2
The examples:
Another example:
If x = 12;
Then,
z = x += 2;
z = x = x + 2
= 12 + 2
= 14
Program example:
#include <stdio.h>
int main()
{
int a = 3, b = 4;
printf("Initially: a = 3, b = 4+1)---> a = a - (b + 1) = %d\n", a-=(b+1));
printf("a last value = %d\n", a);
return 0;
}
The C / C++ only ternary operator, it takes 3 operands.
The syntax:
Expression1 ? expression2 : expression3;
If expression1 evaluates as true (non zero), the entire expression evaluated to the value of expression2. If expression1 evaluates as false (zero), the entire expression evaluated to the value of expression3.
For example:
x = y ? 1 : 100;
Assign value 1 to x if y is true.
Assign value 100 to x if y is false.
It also can be used in places an if statement cannot be used, such as inside a single printf() statement. For example:
z = (x > y)? x : y;
Can be written as:
if(x > y)
z = x;
else
z = y;
A program example.
#include <stdio.h>
int main()
{
int a, b = 4, c= 50;
// here b is less than c, so the statement
// (b>c) is false, then 200 should be assigned
// to a, reflected through the output
a = (b>c) ? 100 : 200;
printf("Given: b = 4, c= 50\n");
printf("The statement:a = (b>c) ? 100 : 200\n");
printf("will be evaluated to a = %d\n", a);
return 0;
}
Change the (b>c) to (b<c), then recompile and rerun. Notice the output difference.
C & C++ programming tutorials
Related C and C++ reading and digging:
Check the best selling C/C++ books at Amazon.com.
The source code for this Module is: Module 3 C/C++ source codes. and the related worksheet for your practice is: C lab worksheets. | http://www.tenouk.com/Module3a.html | crawl-001 | refinedweb | 1,397 | 61.77 |
Chris Oliver's Weblog
- All
- F3
- JavaFX
- Programming
- Research
Key-Frame Animation
It's unfortunate that OpenJFX currently isn't a real open-source project. As such, it gives the appearance that progress isn't being made with JavaFX Script. Nevertheless, evolution has occurred, albeit internally.
I've worked on replacing the animation framework in JavaFX with something more complete and consistent. This was always intended to happen. The presently available animation mechanism (the "dur" operator) was a temporary solution added to F3 more than a year ago, was never thought to be an adequate solution, and clearly isn't to anyone who has ever actually tried to use it.
The supported animation idiom is now that of "Key Frame" animation, as in traditional animation and visual design tools. My view (after significant research) is that this same idiom is also the most effective technique for describing animations programmatically. The concept is that you describe the animated state transitions of your "scene" by declaring start and end "snapshots" of state at certain points in time, and declare interpolation functions to calculate the in-between states.
Given this input the system can automatically perform the animation, stop it, pause it, resume it, reverse it, or repeat it when requested. Thus it is a "declarative" animation technique.
Programmatically such "snapshots" consist of specifying the values for JavaFX variables - local variables and instance variables.
Here are some examples:
- Simple A very simple example, which demonstrates simultaneous animation of the rotation, scale, and fill color of a rectangle.Ball Consists of three concurrent repeating animations: one for the x coordinate of the ball, one which animates the y coordinate, and the one which animates the scale to create a "bounce" effect. See line 65 for the animations.
- Motomaxxve Consists of only one keyframe animation whose "position" is bound to a Slider, such that you can manually "play" it by moving the slider. Left-click on the content will play it forward, Right-click will reverse it. One interesting point is that the text animations are dynamically generated.
- EG Consists of several animations (fade, slide): one of which is a kind of ticker-tape view of the presenters at the 2007 "Entertainment Gathering" at the Getty Museum. The others support a slide show view.
- Poker Video poker game. Consists of two animations: 1 for the deal, and 1 for the draw, each of which animates the bet, turning over the cards, and scoring (if you have a winning hand).
You'll want to take a look at the examples for reference as you read the below, I think.
Time Literals
Since time is fundamental to animation, I've added time "literals" to the language. These are instances of the following primitive class:
public class Time extends java.lang.Comparable { public attribute millis: Integer; public attribute seconds: Number; public attribute minutes: Number; public attribute hours: Number; public operation toMillis():Integer; public operation add(other:Time):Time; public operation subtract(other:Time):Time; public operation multiplyBy(n:Number):Time; public operation divideBy(n:Number):Time; public operation equals(other): Boolean; }
Numeric Literals with one of the suffixes (h, m, s, ms) are interpreted as Time literals, e.g:
2s == Time {seconds: 2}; // trueRelational operators and arithmetic operators other than % are overloaded for Time types:
2.5s < 5000ms; // true 2.5s * 3 == 7.5s; // true
Timelines
A KeyFrame describes a set of end states of various properties of objects at a certain time instant relative to the start of the animation, together with interpolation specifications to calculate the in-between values relative to the previous frame. Lack of an interpolation specification indicates a "discrete" animation, meaning the value of the property instantaneously transitions to the value given in the key frame at the time instant of the key frame. A Timeline is an object that contains a list of key frames, together with operations to control the overall animation, to start it, stop it. repeat it, etc.
Timelines are instances of the following class:
public class Timeline { public attribute keyFrames: KeyFrame*; public attribute repeatCount: Number; public attribute autoReverse: Boolean; public operation start(); public operation stop(); public operation pause(); public operation resume(); public operation reverseNow(); public attribute position: Number?; // unit time interval }
where KeyFrame is:
public class KeyFrame { public attribute time: Time; public attribute keyValues: InterpolatedLValue*; public attribute action: function()?; public attribute timelines: TimeLine*; // included timelines }
InterpolatedLValue has the following definition:
public class InterpolatedValue { public attribute value: Object; public attribute interpolate: function(values:Object*, unitTimeInterval:Number):Object?; } public class InterpolatedLValue extends InterpolatedValue { public attribute target: &Object; }
InterpolatedValue describes a pair (<value>, <interpolation_function>).
InterpolatedLValue describes a triple (<target property>, <value>, <interpolation function>).
Properties
Specification of the target property required adding "pointers" to the JavaFX script language. Pointer types are declared with the "&" symbol (as in the target attribute above), and pointer instances are obtained with the unary "&" operator and dereferenced with the unary "*" operator, as in C, e.g:
var x = 2; var px = &x; *px == 2; // true *px = 3; x == 3; // trueProperties in JavaFX are pointers to local variables or object attributes. In cases where these are "sequences" a pointer to an element of such a sequence is also a valid property.
Syntax
Although KeyFrame animations are normal JavaFX objects, special syntax is provided to make it easier to express than is possible with the standard object-literal syntax.
The "tween" operator is a a literal constructor for InterpolatedValue.
100 tween LINEAR;is equivalent to
InterpolatedValue { value: 100, interpolate: LINEAR:Number }The "=>" operator provides a literal constructor for a list of InterpolatedLValues:
var x = 2; x => 100 tween LINEAR;is equivalent to the following
var x = 2; InterpolatedLValue {target: &x, value: 100, interpolate: LINEAR:Number};However, you can also apply "=>" to a whole set of object properties using an object-literal like notation rather than just single property or variable, for example like this:
var rect = Rect {}; rect => {height: 400 tween EASEBOTH, width: 500, fill: blue tween LINEAR, clip: { shape: Rect => {height: 500, width: 600} };The second line above is equivalent to this:
[InterpolatedLValue { target: &rect.height value: 500 interpolate: EASEBOTH:Number }, InterpolatedLValue { target: &rect.width value: 500 interpolate: null }, InterpolatedLValue { target &rect.fill value: blue:Color interpolate: LINEAR:Color }, InterpolatedLValue { target: &((Rect)rect.clip.shape).height value: 500 interpolate: null }, InterpolatedLValue { target: &((Rect)rect.clip.shape).width value: 600 interpolate: null }]Finally, the "at" and "after" operators are literal constructors of KeyFrame objects:
var x = 2; var rect = Rect {...}; at (2s) { x => 2 tween LINEAR; rect => {width: 400 tween EASEBOTH, fill: red tween EASEBOTH}; trigger { println("at 2 seconds..."); } } after (5s) { x => 100 tween EASEBOTH; }The "trigger" clause allows you to associate an arbitrary callback with the key frame.
The time specified by "at" is relative to the start of the Timeline. The time specified by "after" is relative to the previous key frame.
The first example above is equivalent to:
KeyFrame { time: 2s action: operation() { println("at 2 seconds..."); } keyValues: [InterpolatedLValue { target &x value: 2 interpolate: LINEAR:Number }, InterpolatedLValue { target: &rect.width value: 400 interpolate: EASEBOTH:Number }, InterpolatedLValue { target: &rect.fill value: red:Color interpolate: EASEBOTH:Color }] }Timelines and KeyFrames may be composed hierarchically - a KeyFrame may use the "include" operator to include any number of Timelines, in which case the key frames that make up the included timelines are merged into the containing timeline at the time instant of the key frame. The above "Ball" example demonstrates this, reproduced here:
var ax = Timeline { // x keyFrames: [at (0s) { x => 0; }, at (10s) { x => 700 tween LINEAR; }] autoReverse: true repeatCount: INFINITY } var ay = Timeline { // y repeatCount: INFINITY keyFrames: [at (0s) { y => 0; }, at (2.2s) { y => 375 tween SPLINE(0, 0, .5, 0); }, at (2.25s) { y => 375; }, at (4.5s) { y => 0 tween SPLINE(0, 0, 0, 0.5); }] } var sxy = Timeline { // scale x y repeatCount: INFINITY keyFrames: [at (2.15s) { sx => 1; sy => 1; }, at (2.25s) { sx => 1.2 tween LINEAR; sy => .7 tween LINEAR; }, at (2.5s) { sy => 1 tween LINEAR; sx => 1 tween LINEAR; }, at (4.5s) { sx => 1; sy => 1; }] } var clip = Timeline { repeatCount: INFINITY keyFrames: at (0s) { include ax, ay, sxy; } }In the above example, the "clip" timeline combines the other three animations. Playing "clip" will play all the animations simultaneously (yet still taking into account each ones individual repeat behavior).
Posted at 10:22AM Dec 20, 2007 by Christopher Oliver in JavaFX | Comments[93]
the "dur" operator was simple and clean that was it's beauty. Dont understand me wrong i like the Flash keyFrames i like the Flash as a tool for creating animations ( flex is good microsoft silverlight has a nice solution too ) and all they are keyframe oriented i like them but i like love the dur operator :) one line and u have it and it work ! :) so .. if you ask me ok make them keyFrame oriented if there is nice design tool but leave the "dur" too .. I like coding by hand.
Posted by JOKe on December 20, 2007 at 12:00 PM PST #
I'm not convinced by this approach. Too complicated to be productively usable, and the code itself is not very readable. And pointers - you gotta be kidding me! Is this still supposed to be a productive and easy to use language? You guys can do better then that!
Posted by Snowflake on December 20, 2007 at 01:34 PM PST #
Snowflake,
Pointers are not visible to the user - if you look at the examples.
It's a necessary implementation detail, however.
The examples given weren't necessarily designed to demonstrate the simplicity of the animation syntax, but rather the generality and credibility of it.
I've added an even simpler example, which shows an expression of a reversing, simultaneous scale, rotation, and color animation.
I personally, don't see how to make it easier than that. If you do, please let me know.
Try clicking on the rectangle while the animation is running.
Posted by Chris Oliver on December 20, 2007 at 03:17 PM PST #
It's good for you to admit you're not doing open source. The question is WHY???
You're pretty much undermining Sun overall open source effort by now doing this on a highly visible, yet far-from-baked project. I'm pretty sure it's actually hurting other open source projects at Sun.
Posted by John Doe on December 21, 2007 at 12:17 AM PST #
@John Doe
If you think I'm personally responsible for the fact that OpenJFX hasn't become a true open-source project, you're mistaken. That's the opposite of my personal recommendation.
On the plus side, the openjfx compiler project is a true open-source project, as is the new Java scene-graph project.
Hopefully, in the near future these will replace the current open-jfx binary code base.
Posted by Chris Oliver on December 21, 2007 at 11:25 AM PST #
@Patrick,
You can use variables in place of time literals:
var t1 = 0s;
var t2 = 1s
var t3 = 2s;
at (t1) {...}
at (t2) {...}
at (t3) {...}
Or any expression:
after (t3-t2) {...}
Posted by Chris Oliver on December 21, 2007 at 11:30 AM PST #
One recommendation from the peanut gallery: call them something other than pointers and use different symbols. People will mock the language for having "pointers" even though they're a different beast than their C counterparts.
Posted by 76.21.13.66 on December 21, 2007 at 09:48 PM PST #
Oncely your site is looks so nice for guests and have informations much more than the other blogs. I want to meet or conversation you
with msn, gtalk etc.
I think I have take so many informations from you.
Posted by youtube lig tv on August 25, 2008 at 04:06 AM PDT # Navigateur on September 09, 2008 at 02:13 AM PDT #
Let me revise that. Even better would be to make "bind" bidirectional by default, and use "affect" and "take" as the unidirectional binds in each direction. That would prevent any redundancy and/or confusion. Regards, N
Posted by Navigateur on September 10, 2008 at 01:02 AM PDT #,
Posted by ANITA BANULIS on November 07, 2008 at 11:39 PM PST #
Posted by dizi izle on December 01, 2008 at 07:39 PM PST #
<a href="" title="dizi izle">dizi izle</a>
thanks
Posted by dizi izle on December 01, 2008 at 07:40 PM PST #
thanks you..
Posted by dizi izle on December 25, 2008 at 02:55 PM PST #
thanks..
Posted by backlink sorgu on December 25, 2008 at 02:56 PM PST #
Bir KeyFrame, canlandırmanın başlangıcına göreli olarak kesin bir zaman anında nesnelerin çeşitli mallarının son durumlarının bir takımını tanımlar, arada içini hesaplamak için araya koyma tanımlamalarıyla beraber, önceki yapıya göreli olarak değer biçer. Bir araya koyma tanımlaması eksikliği, bir "Ayrı" canlandırmasını gösterir, aniden anahtar yapıda o zaman anahtar yapının anı verilen değere geçişlerin olduğu malın değerini ifade etmek. Bir zaman çizgisi, anahtar yapıların bir listesini içeren bir nesnedir, o başlamak, toplam canlandırmayı kontrol etmek için çalışmalarla beraber, onu durdurur. Onu tekrarla, vb.
Posted by dış cephe on December 25, 2008 at 02:59 PM PST #
türkçe açtığınız için teçekürler konuyu..
Posted by evden eve nakliyat on December 25, 2008 at 03:00 PM PST #
Daha zeytine ait sevgili Chris, lütfen göstergeleri kullanmaz, ama "Kızgınlık"'ın tam tersi olarak bir "Etkile" anahtar sözcüğünü kullanır. Seçmeli "Birectional"'la anahtar sözcük "Kızgınlık" ve "Etkile" (Güncel olarak "Tersle"), referanslar için tam ve mantıklı JavaFX değiştirmesi ve mesela C'de göstergeler ++ olacaktı. Odur, eğer sen, JavaFX'da neticede bağlamayı hurdaya çıkarmayı istemezsen.
Posted by bariyer on December 25, 2008 at 03:02 PM PST #
thanks..
Posted by izmir evden eve on January 01, 2009 at 08:26 AM PST #
paylaşım için teşekkürler..
Posted by evden eve on January 01, 2009 at 08:27 AM PST #
Thanks..
Posted by backlink sorgu on January 11, 2009 at 10:57 AM PST #
Thanks..
Posted by izmir evden eve on February 01, 2009 at 11:42 AM PST #
thanks you..
Posted by korkuluk on February 02, 2009 at 06:08 AM PST #
thanks you..
Posted by kanal açma on February 02, 2009 at 11:19 AM PST # Manavgat, side on February 08, 2009 at 05:01 AM PST #
thanks you..
Posted by boğaz turları on February 09, 2009 at 11:42 PM PST #
thansk you..
Posted by bursa evden eve nakliyat on February 12, 2009 at 03:22 AM PST #
paylaşım için teşekür ederim..
Posted by bursa evden eve nakliyat on February 18, 2009 at 03:53 AM PST #
paylaşım için teşekür ederim.
Posted by izmir evden eve on February 20, 2009 at 01:38 PM PST #
thanks you..
Posted by parça kontör on February 22, 2009 at 01:04 PM PST #
Thank You..
Posted by izmirde evden eve on March 23, 2009 at 04:58 AM PDT #
Thank You..
Posted by firma rehberi on April 05, 2009 at 11:18 PM PDT #
thanksss
Posted by alem on April 08, 2009 at 10:23 AM PDT #
thanksss
Posted by izmir on April 08, 2009 at 10:24 AM PDT #
thanksss
Posted by forum on April 08, 2009 at 10:24 AM PDT #
thankssss
Posted by izmir evden eve on April 15, 2009 at 12:30 PM PDT #
Thank You..
Posted by cam balkon on April 23, 2009 at 12:25 PM PDT #
Thank You..
Posted by erken rezervasyon on April 24, 2009 at 01:42 PM PDT #
Thank You..
Posted by erken rezervasyon on April 26, 2009 at 10:57 AM PDT #
Thank You..
Posted by bursa evden eve on April 28, 2009 at 09:38 AM PDT #
nice text, thanks for all
Posted by lig tv izle on April 29, 2009 at 10:03 AM PDT #
thankssss
Posted by izmir forumu on April 29, 2009 at 12:32 PM PDT #
thank you
Posted by worldkontor on May 01, 2009 at 01:43 AM PDT #
thank you..
Posted by beyaz eşya on May 04, 2009 at 11:22 PM PDT #
Thank You..
Posted by atv safari on May 08, 2009 at 01:16 PM PDT #
Thank You..
Posted by arama motoru on May 09, 2009 at 12:43 PM PDT #
Thank You..
Posted by karel on May 11, 2009 at 05:35 AM PDT #
Thank You..
Posted by otogaz on May 13, 2009 at 08:06 AM PDT #
Thank You..
Posted by bursa evden eve on May 17, 2009 at 03:21 AM PDT #
thanks admin
Posted by müzik dinle on May 20, 2009 at 07:52 AM PDT #
thank you
Posted by parça kontör on May 20, 2009 at 12:55 PM PDT #
thank you
Posted by canlıdivx on May 20, 2009 at 12:55 PM PDT #
thanks admin
Posted by network marketing on May 21, 2009 at 01:48 AM PDT #
thanks admin
Posted by parça kontör on May 24, 2009 at 05:43 PM PDT #
Thanks, really great
Posted by parça kontör on May 24, 2009 at 05:47 PM PDT #
thank
Posted by Bursa Evden Eve Nakliyat on May 24, 2009 at 09:18 PM PDT #
Thanks..
Posted by izmir evden eve on May 25, 2009 at 05:38 AM PDT #
biz bu cam balkon işi yapıyoruz adımızda tosun:)
Posted by cam balkon on May 25, 2009 at 11:20 AM PDT #
The o till I either make my mind up or someone invents an affordable cloning machine, I’ll just focus on my main blog.oky.
Posted by müzik dinle on May 29, 2009 at 07:09 AM PDT #
thank you very much
Posted by Müzik Dinle on June 11, 2009 at 09:38 AM PDT #
Thank you very much admin
Posted by Sikis on June 11, 2009 at 09:41 AM PDT #
Konuya tacizde bulunulmuş resmen (:
Posted by rehber on June 12, 2009 at 12:52 AM PDT #
thank you very much
Posted by DJ Remixleri on June 12, 2009 at 04:53 PM PDT #
asdad
Posted by DJ Remixleri on June 12, 2009 at 04:54 PM PDT #
thank you very much
Posted by DJS Productions on June 12, 2009 at 04:55 PM PDT #
thank you very much
Posted by Jinglesiz Türkçe Remixler on June 12, 2009 at 04:56 PM PDT #
[url=]DJS Productions[/url]
Posted by Jinglesiz Türkçe Remixler on June 12, 2009 at 07:59 PM PDT #
<a href="">Tribal</a>
Posted by Jinglesiz Türkçe Remixler on June 12, 2009 at 08:00 PM PDT #
thanks a lot =)
Posted by izmir parça kontör on June 13, 2009 at 02:28 AM PDT #
saldırımı var ne iş len burda ne oluyor :D
Posted by gencsite on June 13, 2009 at 04:46 AM PDT #
thanks admin.
Posted by beşiktaş marşları dinle on June 13, 2009 at 06:34 AM PDT #
thanks adminn
Posted by çet on June 14, 2009 at 06:56 AM PDT #
thanks
<a href="" rel="nofollow">vestel beko siemens arçelik bosch servisi ebys</a><br />
<a href="" rel="nofollow">trojan</a><br />
<a href="" rel="nofollow">attackerz</a><br />
Posted by vestelbeko on June 14, 2009 at 09:11 AM PDT #
teşekkürler.
Posted by klip izle on June 15, 2009 at 12:03 PM PDT #
Igor Stravinsky
Posted by Igor Stravinsky on June 16, 2009 at 05:35 PM PDT #
dation from the peanut gallery: call them something other than pointers and use different symbols. People will mock the language for having
Posted by sohbet99 on June 18, 2009 at 12:45 PM PDT #
Notify me by email of new comments
Posted by sohbet99 on June 19, 2009 at 12:17 AM PDT #
avestel beko siemens arçelik bosch servisi ebys</a><br />
Posted by sohbet99 on June 19, 2009 at 12:18 AM PDT #
<a href="" title="matbaa">matbaa</a>
Posted by matbaa on June 22, 2009 at 09:48 AM PDT #
Thank you so much for content, you would track;)
Posted by lida on June 26, 2009 at 05:30 AM PDT #
thanks
Posted by müzik dinle on June 26, 2009 at 03:01 PM PDT #
thnx so much
Posted by oyun indir on June 27, 2009 at 05:27 AM PDT #
thnx so much
Posted by remix programı on June 30, 2009 at 09:57 AM PDT #
The o till I either make my mind up or someone invents an affordable cloning machine, I’ll just focus on my main blog.oky.
Posted by nick oluşturucusu on July 01, 2009 at 03:06 PM PDT #
affordable cloning machine, I’ll just focus on my main blog.oky.
Posted by pagerank sorgulama on July 01, 2009 at 03:07 PM PDT #
estel beko siemens arçelik bosch servisi ebys
Posted by 2009 temmuz hitleri on July 01, 2009 at 03:09 PM PDT #
way be ne diyim
thanks admin
Posted by tavla oyna on July 02, 2009 at 06:48 PM PDT #
tahnk u
Posted by Tavla İndir on July 02, 2009 at 06:49 PM PDT #
good post
:)
Posted by erozyon on July 02, 2009 at 06:50 PM PDT #
wow good post
Posted by otomobil on July 02, 2009 at 06:50 PM PDT #
thank u
allah razı olsun
Posted by kumarcı on July 02, 2009 at 06:52 PM PDT #
Posted by çet on July 04, 2009 at 03:18 AM PDT #
Wowww Thank u Admin !:=)
Posted by Tavla on July 04, 2009 at 05:25 AM PDT # | http://blogs.sun.com/chrisoliver/entry/key_frame_animation | crawl-002 | refinedweb | 3,560 | 57.1 |
In this article, I am going to give some examples to get your own docker image with InterSystems Caché/Ensemble.
Let’s start from the beginning, from Dockerfile. Dockerfile is a plaintext configuration file which is used to build a docker image.
I would recommend using centos as a core distributive for the image because InterSystems supports RedHat, and Centos is the most compatible distributive.
FROM centos:6
You can add your name as an author of this file.
MAINTAINER Dmitry Maslennikov <mrdaimor@gmail.com>
In the first step, we should install some dependencies, and configure operating systems, as I configured TimeZone here. These dependencies needs for the installation process, and for Caché itself.
# update OS + dependencies & run Caché silent instal RUN yum -y update \ && yum -y install which tar hostname net-tools wget \ && yum -y clean all \ && ln -sf /etc/locatime /usr/share/zoneinfo/Europe/Prague
Let’s define the folder where we will store installation distributive.
ENV TMP_INSTALL_DIR=/tmp/distrib
Let's set up some arguments with default values. These arguments can be changed during the build process.
ARG password="Qwerty@12" ARG cache=ensemble-2016.2.1.803.0
Then we should define some environment variables for silent installation.
ENV ISC_PACKAGE_INSTANCENAME="ENSEMBLE" \ ISC_PACKAGE_INSTALLDIR="/opt/ensemble/" \ ISC_PACKAGE_UNICODE="Y" \ ISC_PACKAGE_CLIENT_COMPONENTS="" \ ISC_PACKAGE_INITIAL_SECURITY="Normal" \ ISC_PACKAGE_USER_PASSWORD=${password}
I decided to set security to the normal level, and I should set some password.
You can look at the documentation to find more options.
WORKDIR ${TMP_INSTALL_DIR}
Working directory would be used as a current directory for the next commands. If the directory does not exist, it would be created.
COPY cache.key $ISC_PACKAGE_INSTALLDIR/mgr/
You can include license key file if you are not going to publish this image in public repositories.
Now we should get the installation distributive, and there are several ways to do it:
- Download manually and place this file near to Dockerfile and use this line.
ADD $cache-lnxrhx64.tar.gz .
This command will copy and extract distributive to our working directory.
- Download file directly from the WRC.
RUN wget -qO /dev/null --keep-session-cookies --save-cookies /dev/stdout --post-data="UserName=$WRC_USERNAME&Password=$WRC_PASSWORD" '' \ | wget -O - --load-cookies /dev/stdin "" \ | tar xvfzC - .
In this case, we should pass login password for the WRC. And you can add this lines in this file above.
ARG WRC_USERNAME=”username” ARG WRC_PASSWORD=”password”
But you should know that in this case, login/password could be extracted from the image. So, it is not the secure way.
- And the preferable way, publish this file on internal FTP/HTTP server in the company.
RUN wget -O - "" \ | tar xvfzC - .
Now we are ready to install.
RUN ./$cache-lnxrhx64/cinstall_silent
Once installation is being completed shutdown the instance.
RUN ccontrol stop $ISC_PACKAGE_INSTANCENAME quietly
But it is not over. We should have some control process In a Docker image and this task could be done by ccontainermain project made by Luca Ravazzolo. So, download it directly from the github repository.
# Caché container main process PID 1 () RUN curl -L -o /ccontainermain \ && chmod +x /ccontainermain
Clean up the temporary folder.
RUN rm -rf $TMP_INSTALL_DIR
In case if your docker daemon uses overlay driver for storage, we should add this workaround to prevent starting Cache with error <PROTECT>.# Workaround for an overlayfs bug which prevents Cache from starting with <PROTECT> errors COPY ccontrol-wrapper.sh /usr/bin/ RUN cd /usr/bin \ && rm ccontrol \ && mv ccontrol-wrapper.sh ccontrol \ && chmod 555 ccontrol
Where ccontrol-wrapper.sh, should contain#!/bin/bash # Work around a werid overlayfs bug where files don't open properly if they haven't been # touched first - see the yum-ovl plugin for a similar workaround if [ "${1,,}" == "start" ]; then find $ISC_PACKAGE_INSTALLDIR -name CACHE.DAT -exec touch {} \; fi /usr/local/etc/cachesys/ccontrol $@
You can use this command to check which driver is using docker.docker info --format '{{.Driver}}'
Here we say that our image exposes two standard for Caché ports 57772 for web and 1972 for binary connections.
EXPOSE 57772 1972
And finally we should say how to execute our container.
ENTRYPOINT ["/ccontainermain", "-cconsole", "-i", "ensemble"]
In the end our file should look like this:
FROM centos:6 MAINTAINER Dmitry Maslennikov <Dmitry.Maslennikov@csystem.cz> # update OS + dependencies & run Caché silent instal RUN yum -y update \ && yum -y install which tar hostname net-tools wget \ && yum -y clean all \ && ln -sf /etc/locatime /usr/share/zoneinfo/Europe/Prague ARG password="Qwerty@12" ARG cache=ensemble-2016.2.1.803.0 ENV TMP_INSTALL_DIR=/tmp/distrib # vars for Caché silent install ENV ISC_PACKAGE_INSTANCENAME="ENSEMBLE" \ ISC_PACKAGE_INSTALLDIR="/opt/ensemble/" \ ISC_PACKAGE_UNICODE="Y" \ ISC_PACKAGE_CLIENT_COMPONENTS="" \ ISC_PACKAGE_INITIAL_SECURITY="Normal" \ ISC_PACKAGE_USER_PASSWORD=${password} # set-up and install Caché from distrib_tmp dir WORKDIR ${TMP_INSTALL_DIR} ADD $cache-lnxrhx64.tar.gz . # cache distributive RUN ./$cache-lnxrhx64/cinstall_silent \ && ccontrol stop $ISC_PACKAGE_INSTANCENAME quietly \ # Caché container main process PID 1 () &&", "ensemble"]
Now we are ready to build this image. Execute the following command in the same folder where you've placed our Dockerfile, execute command
docker build -t ensemble-simple .
You will see all process of building an image, since downloading source image, to installation Ensemble.
To change default password or build of cache
docker build --build-arg password=SuperSecretPassword -t ensemble-simple . docker build --build-arg cache=ensemble-2016.2.1.803.1 -t ensemble-simple .
And we are ready to run this image, with commad
docker run -d -p 57779:57772 -p 1979:1972 ensemble-simple
Here 57779 and 1979, are the ports which you can use to access to inside our container.
docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5f8d2cb3745a ensemble-simple "/ccontainermain -..." 18 seconds ago Up 17 seconds 0.0.0.0:1979->1972/tcp, 0.0.0.0:57779->57772/tcp keen_carson
This command shows all running containers with some details.
You can now open. Our new system running and available.
Sources can be found here on GitHub.
UPD: Next part of this article have already available here.
It's super satisfying being able to spin up full cache systems with a single command!
Have you got any strategies for persistence? Say I log in, add a cache user, edit some globals in USER and then notice Cache 2017.1 is out - how best to upgrade?
Stay tuned, I'm going to write next about it. In this article, we did a basic image. Wich will be as a source FROM for next images with some our application.
Hey Dmitry,
a couple of us on my team have been experimenting with windows containers and i see how easy it is to install cache on linux in a container what about on windows server core container. any ideas on direction with this.
Hi, I would not recommend thinking seriously about Caché in windows server core container, I think it is too early, yet.
Hi guys,
Thank you for the thread! Containers are here to stay, suffice to say that all public and most private cloud providers offers specific services to support just containers. However, we should look at them as a new system. There are many gotchas but also many aspects about them that will help the way we work.
I have some comments
On the Dockerfile above we need to make sure we tell the full story and educate as appropriate as we are all learning here:
-Container layer OS: Running an OS updates on every single triggered build from your CI/CD pipeline might not be the best thing to do if you truly want to know what you have running in production. It's better to ask for the exact OS version you desire in the FROM statement above. In general getting a Docker image "latest" is not such a great idea.
As a side effect and if you need a particular package installed, make sure it is what you know and pin-point the exact package version you desire (isn't an automated delivery pipeline and infrastructure-as-code about knowing exactly what you have and having it all versioned?). Use
$ apt-get install cowsay=3.03+dfsg1-6
-Provenance: we need to make sure we know we are getting the image we think we are getting. Man in the middle attacks do happen. Organisations should make sure they are covered. Please investigate this step and see tools like asking for an image hash image (
docker pull debian@sha256:cabcde9b6166fcd287c1336f5....) or even better Docker Notary if your image publisher has signed images.
-On Security: Watch those passwords in either Dockerfile definitions or env vars...
-Container image size: copying a tarball will expand the storage layer Docker creates as you make the statement "ADD file" and it's not contractable. One should try to use an ftp or http server to download AND run all commands into a single statement (fetch distribution, installation and removal of unwanted files). That way you can shrink that single layer you're working on. Your code then should read something like:
RUN curl -o /file.tgz
&& tar xzf /file.tgz
&& ./myInstall.sh
&& rm /file.tgz
-On Persistence: Obviously your data must be mounted on a volume. One of the nice things about containers is the clear demarcation between code and data. As far as Caché system data is concerned, like the cache.cpf file and %SYS we are working on a solution that will make Caché a 1st class citizen of the container world and it will be very easy to use and upgrades will just work.
HTH and thanks again for the thread!
Keep them coming :-)
This sounds perfect - can you possibly elaborate on details/timeframe?
We're rolling out Cache on Docker over the next few months, so it would be really nice to know to what extent we should roll our own infrastructure in the interim :)
"we are working on a solution", Sebastian :)
We are very pleased with further enhancements & improvements we have been making from the first internal version. The fundamental idea is that, while containers are ephemeral, databases are not and we want to assist in this area. While you can deal with your application database and make sure you mount your DBs on host volumes, there could be an issue as soon as you use %SYS. You use %SYS when you define your z* | Z* routines and/or globals or when you define user credentials, etc. In this case, right now, you'd have to create an export and an import process which would not be elegant, nor would it help to be agile. What we will offer is a very easy-to-use facility by which you can define where %SYS will reside on the host... and all using canonical Docker syntax. Stay tuned...
Is there a license model that supports containers and/or microservices ?
@Herman
You have the option to elect license servers for cooperating instances as per documentation.
HTH
AFAIK, docker encourages to implement microservices. What about classic Cache based app deployment, can docker be useful in this case? By classic I mean the system accessible via several services (ActiveX, TCP sockets, SOAP and REST), multi-tasking, etc with initial 1-2 GB database inside. At the moment I'm to choose a solution to roll up several dozen of rather small systems of such kind. Should I look at docker technology in this very case?
I am bound to ver. 2015.1.4. Host OS most likely will be Windows 2008/2012, while I'd prefer to deploy our system on Linux, that's why I am searching a light solution how to virtualize or containerize it. Thank you!
Alexey, yes, it is very easy to build a little application just in one container. I don't see any problem, to use any supported technologies as well. Even also possible some load balancing from docker, which also good for microservices. I'm going to show some example with application in the next article soon.
Thanks, Dimitri.
Alexey: Docker does not encourage anything aside using its container technology and its EE (Enterprise Edition and cloud to monetise their effort) :-) However, containers in general help and fit very well into a microservices type architecture. Please note how you can create a microservices architecture without containers via VM, jar, war, based solution with a different type of engine. Containers lend themselves to it more naturally.
It's worth pointing out that just because people talk about 1 process per container, it does not preclude you from using multiple processes in each container. You could naturally have 3 sockets open, for example, 57772, 1972 and 8384, all serving different purposes + various background processes (think of our WD & GC) and still be within the boundaries of a microservice definition with a clear "bounded context". For more info on microservices you might want to read Martin Fowler microservices article and books like Building Microservices by Sam Newman or Production-Ready Microservices by Susan J. Fowler. Also you should check out Domain Driven Design by Eric Evans where "bounded contexts" and similar concepts like context, distillation and large-scale structures are dealt much more in depth.
On the 2GB Database inside the container, I would advise against it. In general one of the advantages of containers is the clear separation of concerns between code and data. Data should reside on a host volume, while you're free to swap containers at will to test & use the new version of your application. This should be an advantage if you use a CI/CD provisioning pipeline for your app.
Having said all that, it depends on your specific use case. If I want my developers to all have a std data-set to work against, then I might decide that their container environments do indeed feature a CACHE.DAT. Our Learning Services department has been using containers for two years now, and every course you take on-line runs on Docker containers. As I said, it depends on the use-case.
In ref. to your last comment: right now -March2017- I would not use Windows for a container solution. Although Microsoft has been working closely with Docker for over a year, containers are born out of a sandboxing effect just above the Linux kernel (see Kernel namespace and cgroup).
HTH for now.
Thanks, Dmitry and Luca.
Meanwhile I read some docs and interviewed colleagues who had more experience with Docker than me (while w/o Caché inside). What I've got out of it: Docker doesn't fit well to this very case of mine, which is mostly associated with deployment of already developed app rather than with new development. The reasons are:
- Only one containerized app at the client's server (our case) doesn't mean so many benefits as if it would be several ones;
- Windows issues which Luca already mentioned;
- I completely agree that "data should reside on a host volume..." with only one remark: most likely that all this stuff will be maintained at the client's site by not very well skilled IT personal. It seems that in case of Doker/host volume/etc its configuring will be more complex than rolling up Cache for Windows installation with all possible settings prepared by %Installer based class.
@Alexey
It sounds like -as you say, having to deploy on-site -if I understand correctly, might not be the best use case.
If they use virtualization wouldn't be easier for you guys to deploy a VM that you prepare at your site and just mount the FS/DB they have? That way you'd still have the privilege to run and have guarantees on your build process vs having to do it all on-site.
Just a thought.
All the best
Luca,
It was clear that we can use VMs from the very beginning of the project, and maybe we'll take this approach at last. I've just looked at the Docker's side willing to search more light/reliable alternative.
Thank you again.
Hi, Dmitry!
What should I do if I want to use "prepared" docker image?
E.g. not the standard installation but the image with some 3rd party community software installed and set up like WebTerminal, ClassExplorer, MDX2JSON and DeepSeeWeb, cache-udl, Cache REST-Forms , etc...
Stay tuned, I'm going to show how to do it the next part.
Continuation of this article already available.
Tried this with cache 2017.1.2.217.0 but can't get it working
building gives no error but when i run the image
> docker run -i -p 57772:57772 -p 1972:1972 -t cache-simple
2018/02/14 08:02:24 Starting Caché...
2018/02/14 08:02:24 Seeked /opt/cache//mgr/cconsole.log - &{Offset:0 Whence:2}
2018/02/14 08:02:24 Something is preventing Caché from starting in multi-user mode,
2018/02/14 08:02:24 You might want to start the container with the flag -cstart=false to fix it.
2018/02/14 08:02:24 Error: Caché was not brought up successfully.
and image exist immediatly.
builded also on ubuntu:xenial but same problem there
This error will happen on Windows and macOS, due to docker uses overlay driver there, which is not supported. You should configure Docker daemon to use aufs as storage driver instead.
This screenshot from macOS, on Windows a bit different, but anyway, you should choose Daemon, and switch to advanced mode, where you can use daemon settings in JSON format, just add
"storage-driver": "
aufs
", and Apply this changes. It will apply and restart daemon. After that it should work.
I get the following message when trying to build the image
Step 9/13 : ADD $ensemble-2016.2.3.903.6-lnxrhx64.tar.gz .
lstat -2016.2.3.903.6-lnxrhx64.tar.gz: no such file or directory
not sure why
looks like you did some changes in your Dockerfile comparing to my example, and you did mistake there. Can you share your Dockerfile, so I could check it?
In my example I have line
where $cache is variable defined few lines above. And when build will run, it will be replaced with value. But in your case, I see $ensemble, and sure that you don't have such variable, and this follows to the error.
Dockerfile below, I have now changed it to reflect yours , and for some strange reason it has installed the software rather than created the image, after it finished the install I ran the docker images cmd and I can now see the image in the repository, but when I run
docker run -d -p 57779:57772 -p 1979:1972 ensemble-simple
All I get is a very long alphanumeric entry
When I run docker ps
the entry is blank so looks like ensemble isn't running
It happens because you still have $ensemble, replace all occurrences, and everything will be okay
Hi Dmitry
Was in the middle of the editing the response when you replied
when I run
docker run -d -p 57779:57772 -p 1979:1972 ensemble-simple
All I get is a very long alphanumeric entry
When I run docker ps
the entry is blank so looks like ensemble isn't running
This behaviour expected if you use default Docker configuration, look at mention about aufs above in comments.
But, you should use docker version 18.06, because in newest version already deleted support for AUFS, and InterSystems does not work on overlay driver wchich is used by default in Docker.
when your container run, and you can find it in running state, you can use command
which will show all existing containers in any state.
and then you can look at the logs of particular container
the latest version of docker for redhat I can find is 1.13.1-58.git87f2fab.el7 and not v18.06
Looking further into it v18.0 is for docker ce, is this the same as what is v1.13.1-58.git87f2fab.el7 for redhat
the storage driver at the moment is overlay2 , how do I go about changing it to aufs.
Ive looked on the internet but it always seems the instructions are going from aufs to something else and not vice versa.
this is current state of the install after running the docker run cmd
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ensemble-simple latest f0f078fe077e 52 minutes ago 3.53 GB
docker.io/centos 6 b5e5ffb5cdea 7 weeks ago 194 MB
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
729f26974733 ensemble-simple:latest "/ccontainermain -..." 29 mins Exited (1) 29 mins ago gifted_nobel
c3d623142529 ensemble-simple:latest "/ccontainermain -..." 29 mins Exited (1) 29 mins ago mystifying_williams
dd02951364cf ensemble-simple "/ccontainermain -..." 49 mins Exited (1) 49 mins ago affectionate_liskov
0eba399201a3 2f6ded0c1a4b "/bin/sh -c '#(nop..." About an hour ago Created happy_tesla
if you working on Linux, you can try to use device-mapper as storage-driver, which is also supported by InterSystems.
At Ionate, we run plenty of enterprise applications and device-mapper works better. Please keep in mind that docker storage default for device mapper is 10GB.
You can easily change it:
Docker in devicemapper and 50GB dm.size
/etc/docker/daemon.json
@Dmitry - Do you know how licensing and support from Intersystems works for Cache on Linux. Also, have you seen any performance issues?
Thanks,
InterSystems has licenses for Linux various systems, so, they can offer license for it, and they have license type especially for docker version based on ubuntu.
I'm don't see any issues in performance, and mostly because I don't have so much big projects, yet, and don't use it in production. Current cases are only CI/CD.
Getting the following error when trying to run the container, any ideas how to resolve this?:
# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
aaa854bd8d81 cache-docker "/ccontainermain -ccâ¦" 25 minutes ago Exited (1) 25 minutes ago modest_ritchie
# docker logs aaa854bd8d81
standard_init_linux.go:190: exec user process caused "exec format error"
FROM registry.access.redhat.com/rhel7/rhel
MAINTAINER Garth Cordery <garth.cordery@notmyaddress.com.au>
# update OS + dependencies & run Cachéilent instal
RUN yum-config-manager --add-repo \
&& yum -y --nogpgcheck update \
&& yum -y --nogpgcheck install which tar hostname net-tools wget \
&& yum -y clean all \
&& ln -sf /etc/locatime /usr/share/zoneinfo/Australia/Brisbane
ARG password="Password"
ARG cache=cache-2018.1.0.184.0
ENV TMP_INSTALL_DIR=/tmp/distrib
# vars for Cachéilent install
ENV ISC_PACKAGE_INSTANCENAME="cache" \
ISC_PACKAGE_INSTALLDIR="/usr/chachesys/" \
ISC_PACKAGE_UNICODE="Y" \
ISC_PACKAGE_CLIENT_COMPONENTS="" \
ISC_PACKAGE_INITIAL_SECURITY="Normal" \
ISC_PACKAGE_USER_PASSWORD=${password}
# set-up and install Cachérom distrib_tmp dir
WORKDIR ${TMP_INSTALL_DIR}
ADD $cache-lnxrhx64.tar.gz .
# cache distributive
RUN ./$cache-lnxrhx64/cinstall_silent \
&& ccontrol stop $ISC_PACKAGE_INSTANCENAME quietly \
# Cachéontainer main process PID 1 ()
&& export https_proxy= \
&&", "cache"]
Interesting looks like such error expectable for RedHat. But don't have any RedHat subscription, and I managed to build an image with RedHat, but with centos repo. And in my case, it works without any errors. Maybe you can contact me directly and send your image, so I can check on it?
My differences from your Dockerfile
and I used the latest version of ccontainermain from releases, maybe with this version will be better for you as well.
Thanks for the advice Dmitry, the latest version of ccontainermain sorted the issue, I did need to use the --privileged flag when running it so that mem tuning would work.
Thanks again for the quick response.
Garth | https://community.intersystems.com/post/containerization-cach%C3%A9 | CC-MAIN-2019-18 | refinedweb | 3,910 | 54.22 |
EcmaScript6: First "Bug" Found and Fixed
EcmaScript6: First "Bug" Found and Fixed
After playing around with ES6 features, I found a glitch in ES6 modules, but is it really more of a design flaw?
Join the DZone community and get the full member experience.Join For Free
Learn how to add document editing and viewing to your web app on .Net (C#), Node.JS, Java, PHP, Ruby, etc.
You can’t re-export your imports the way you can in other languages with native import/export support.
Here’s what I mean:
// Meta/index.jsx import Title from './Title'; export Title;
Seems reasonable, right? Yet it throws a syntax error.
Sure, it could be a bug in Babel.js, but I don’t think it is. If I'm reading the ECMAScript2015 Specification correctly, then you were never meant to do this. Which is even worse.
After an hour of figuring out why Babel won’t compile my code, I spent another hour or two figuring out why I shouldn’t have expected my code to compile in the first place. Let’s take a look.
Babel throws a syntax error like this:
Version: webpack 1.11.0 Time: 662ms [0] multi main 40 bytes {0} [built] [1 error] + 7 hidden modules ERROR in ./src/components/H1BGraph/Meta/index.jsx Module build failed: SyntaxError: /Users/Swizec/Documents/random-coding/react-d3js-experiment/src/components/H1BGraph/Meta/index.jsx: Unexpected token (7:18) 5 | import Title from './Title'; 6 | > 7 | export Title; | ^ 8 |
This is not a helpful error. Not only is this a reasonable thing to do, it’s also a very common thing to do in other languages with native module support. For example, when your organize files into a directory.
In this case, there is a
Title and a
Description. Both components inherit from a base component called
BaseMeta, but are used separately. It makes sense to put these three files and some helpers in a directory called
Meta.
Forcing programmers to write
import Title from './Meta/Title' breaks the abstraction. You shouldn’t have to know how components and classes internal to
Meta are organized. Writing
import Title from './Meta’ should be possible.
Right?
Sure, one could argue that both of these components fall under a common
Meta should be used through a parent
<Meta> component. Then you could use
Meta and not worry about importing either
Title or
Description. In many ways that’s true.
But the
Meta component should be able to expose any of its internal components for external use. If JavaScript or Babel disagree with the architecture, then they should complain about the architecture and not throw a syntax error.
To make that work, we need a dirty hack like this:
// Meta/index.jsx import {Title as T} from './Title'; export class Title extends T {};
Ugly, right?
We use an aliased import from
./Title only to turn around and export a new
Title component that extends
T, but adds nothing of its own.
We have to do this because ES6 imports are constants — creating a new class with the same name as already exists would throw an error. Re-exporting
Title with a different name would spread aliased imports through our codebase like a virus.
I wish none of this silliness was necessary, but it is.
Maybe the answer lies in what this code compiles to. Perhaps somewhere in the resulting ES5 code there is a deeper reason why JavaScript can’t re-export like everyone else.
When Babel is done, our import→export looks like this:
function(module, exports, __webpack_require__) { // Ugly but works :D 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; } var _Title = __webpack_require__(8); var Title = (function (_T) { _inherits(Title, _T); function Title() { _classCallCheck(this, Title); _get(Object.getPrototypeOf(Title.prototype), 'constructor', this).apply(this, arguments); } return Title; })(_Title.Title); exports.Title = Title; ; /***/ }
Damn, that’s a lot of code! Remember writing all of this every time you wanted class inheritance? Me neither, screw class inheritance if this is what it takes. No wonder everyone is so excited about ES6 modules.
Let’s look at the key part: where the
Title class is defined as a featureless extension of
T. This part:
var _Title = __webpack_require__(8); var Title = (function (_T) { _inherits(Title, _T); function Title() { _classCallCheck(this, Title); _get(Object.getPrototypeOf(Title.prototype), 'constructor', this).apply(this, arguments); } return Title; })(_Title.Title); exports.Title = Title; ;
Ok, that’s pretty familiar. If a human wrote the first line, it would be something like
var Foo = require('Foo’).
require() gives a class, and we assign it to a variable.
Then we create a closure, which wraps a scope around a function. Think of this function as a class factory—it takes a class and creates a new extended class.
To produce these new classes, the closure creates a function called
Title. This function acts as an object constructor, just like functions normally do in JavaScript. It uses
_get to perform some magic that’s beyond me. I think it calls the function on itself while also calling the superclass’s constructor, but I’m not sure.
Just to keep things interesting, Babel uses this opportunity to take advantage of JavaScript’s hoisting behavior, where functions that aren’t assigned to a variable are always global inside the current scope. The code calls
_inherits on the
Title function, but before it’s created. From the looks of
_inherits, it can replace the subclass’s prototype with the superclass’s object instance.
It’s weird, but it works. Praise the gods of open source that Babel writes this magic for us.
class X extends Y is not only easier to write than this JavaScript soup, but also easier (read: possible) to understand.
Now we know what
export class X extends Y {} transpiles into, but we still haven’t answered the main question: Why can’t we just re-export?
I don’t think it’s because JavaScript couldn’t handle something like this:
var Title = (function (_T) { // ... })(__webpack_require__(8));
While this isn’t the cleanest code, it *should* work. But take a look at the last line in the earlier example, the line that says
exports.Title = Title.
If we don’t tell the code what to export as, how will it know? It won’t. Without a name, the compiled code would look like this:
exports = __webpack_require__(8);
With that, we can only re-export a single module’s worth of code. Which does work by the way, you can always write
export default X.
If you want to re-export multiple modules, then you’ll have to stick to that ugly workaround. I think it’s silly, but it’s the best JavaScript can do until gets reflection, and we’re finally able to answer the question “Hey, what did the programmer name this variable?”
I think that’s coming in ES7. We’ll see.
PS: the official way to re-export modules in ES6 looks like this:
// to export a member export { encrypt as en } from 'lib/crypto'; // or to export everything export * from 'lib/crypto';
But that still looks weird, doesn’t play well with default exports, and doesn’t solve the “preserve the name” problem.
Thanks to Jure Čuhalev, Anže Pečar, Will Fanguy, Coletta Teske, and David Baird for reading draft versions of this article
Related
You should follow me on twitter, here. }} | https://dzone.com/articles/ecmascript6-first-bug-found-and-fixed?fromrel=true | CC-MAIN-2019-13 | refinedweb | 1,336 | 58.08 |
Help Session. How To Get Started Design Parameters Accessor and Mutator Methods. Okay, so now what?. In your last lab we introduced you to writing your own class. Now you are going to have to write several of your own classes (and a bit more Java Session
Okay, so now what?
LiteBrite Help Session
2 of 14
September 22, 2013
Getting Started
Assignment Specification (The Specs)
Create your own computerized LiteBrite. When the user clicks on the grid, colored pegs should be added at the proper location. There should be a palette with at least two color choices that are selected using LiteButtons. The palette should have a current color specified by whichever LiteButton was clicked last. When a peg is added to the grid, it should be the palette’s current color.
List the nouns. Which ones will we want to make into classes?
LiteBrite Help Session
3 of 14
September 22, 2013
And then there was Lite...
Support Code
LiteBrite Help Session
4 of 14
September 22, 2013
And then there was Lite...
Support Code (Continued)
LiteBrite Help Session
5 of 14
September 22, 2013
A (not so) Great Design
Problem: How do you make the pegs the same color as the current palette color?
One Possible Design:
--Have the Grid know about the Palette’s current color when the Grid is created
--The Grid can store this color in an instance variable and use it to set the peg colors
But, there are problems with this design, such as...
--How will the Grid know when the user selects a new color on the Palette?
LiteBrite Help Session
6 of 14
September 22, 2013
The Preferred Design
A better way to solve this problem:
--Associate the Grid with the Palette. Do this by passing the Palette as a parameter to the Grid‘s constructor, as outlined in the stencil code
--Make sure the current color is “set” in the setColor method already outlined by the stencil code (for you inquisitive folk: when the user clicks one of the LiteButtons, this method magically gets invoked by our support code)
--Provide a method in the Palette class to “get” its current java.awt.Color
--Then, the Grid can “get” the current color from the Palette by calling this accessor method
Why is this better?
-- What happens when the Palettecolor changes?
-- What would happen if the Grid knew directly about the color? Think about how this affects encapsulation.
LiteBrite Help Session
7 of 14
September 22, 2013
Containment Diagram
App
LiteBrite
Grid
Palette
LiteButton
Lite
LiteBrite Help Session
8 of 14
September 22, 2013
Formal vs. Actual Parameters
Two types of parameters
--Formal
--Actual
Formal parameters are used when you are declaring a method
Like x in: f (x) = 3x^2 + 5x + 2
Actual parameters are used when actually calling the method
Like 5 in: y = f (5)
Method Declaration
public void buyCar(Brand carBrand) {
//makes the car the specified brand
}
Method Invocation
(from another class)
_buyer.buyCar(bentley);
--What’s the formal parameter?
--What’s the actual parameter?
LiteBrite Help Session
9 of 14
September 22, 2013
On your mark, “GET” “SET”, go!
Accessor (get) and Mutator (set) methods
-Used to “get” (access) and “set” (mutate or change) variables.
public class CDPlayer {
private CD _currentCD;
public CDPlayer(CD myCD) {
_currentCD = myCD;
}
/**
* This is a mutator!
*/
public void setCD(CD newCD) {
_currentCD = newCD;
}
/**
* This is an accessor!
*/
public CD getCD() {
return _currentCD;
}
}
LiteBrite Help Session
10 of 14
September 22, 2013
Accessor Example
public class Car {
private CDPlayer _myPlayer;
private CD _jazzCD, _classicalCD,
_whatsPlaying;
public Car() {
_jazzCD = new CD();
_classicalCD = new CD();
_myPlayer = new CDPlayer(_jazzCD);
_myPlayer.setCD(_classicalCD);
this.seeWhatsPlaying();
}
public void seeWhatsPlaying() {
_whatsPlaying = _myPlayer.getCD();
}
}
What is the value of _whatsPlaying when the Car is instantiated?
LiteBrite Help Session
11 of 14
9 of 12
September 17, 2010
September 12, 2013
LiteBrite Help Session
Good Luck!
Dinosaurs do it.
Celebrities do it.
You should do it, too. | http://www.slideserve.com/shani/help-session | CC-MAIN-2017-04 | refinedweb | 658 | 62.38 |
AI2-THOR (The House Of inteRactions) is a near photo-realistic interactable framework for AI agents.
NewsNews
(6/2019) Version 2.0 update of the AI2-THOR framework is now live! We have over quadrupled our action and object states, adding new actions that allow visually distinct state changes such as broken screens on electronics, shattered windows, breakable dishware, liquid fillable containers, cleanable dishware, messy and made beds and more! Along with these new state changes, objects have more physical properties like Temperature, Mass, and Salient Materials that are all reported back in object metadata. To combine all of these new properties and actions, new context sensative interactions can now automatically change object states. This includes interactions like placing a dirty bowl under running sink water to clean it, placing a mug in a coffee machine to automatically fill it with coffee, putting out a lit candle by placing it in water, or placing an object over an active stove burner or in the fridge to change its temperature. Please see the full 2.0 release notes here to view details on all the changes and new features.
(3/2019) Introducing Version 1.0 of the AI2-THOR framework! This release includes a full rework of all Sim Objects and Scenes to have additional physics functionality and improved fidelity. Physics based interactions can now be modeled in the THOR environment in realistic ways like never before! Object collision when placed in receptacles, moveable receptacles that contain other objects, collision based object position randomization, Multi-Agent support— these are a few of the many exciting new features that come with this update. Please check the full 1.0 release notes here to view details on all the changes and new features.
(4/2018) We have released version 0.0.25 of AI2-THOR. The main changes include: upgrade to Unity 2017, performance optimization to improve frame rate, and various bug fixes. We have also added some physics functionalities. Please contact us for instructions.
(1/2018) If you need a docker version, please contact us so we provide you with the instructions. Our docker version is in beta mode.
RequirementsRequirements
- OS: Mac OS X 10.9+, Ubuntu 14.04+
- Graphics Card: DX9 (shader model 3.0) or DX11 with feature level 9.3 capabilities.
- CPU: SSE2 instruction set support.
- Python 2.7 or Python 3.5+
- Linux: X server with GLX module enabled
DocumentationDocumentation
Please refer to the documentation page on the AI2-THOR website for information on installation, API, metadata, actions, object properties and other important framework information.
InstallationInstallation
pip install ai2thor
Once installed you can launch the framework. Make sure X server with OpenGL extensions is running before running the following commands. You can check by running
glxinfo or
glxgears.
import ai2thor.controller controller = ai2thor.controller.Controller() controller.start() # Kitchens: FloorPlan1 - FloorPlan30 # Living rooms: FloorPlan201 - FloorPlan230 # Bedrooms: FloorPlan301 - FloorPlan330 # Bathrooms: FloorPLan401 - FloorPlan430 controller.reset('FloorPlan28') # gridSize specifies the coarseness of the grid that the agent navigates on controller.step(dict(action='Initialize', gridSize=0.25)) event = controller.step(dict(action='MoveAhead'))
Upon executing the
controller.start() a window should appear on screen with a view of the room FloorPlan28.
Each call to
controller.step() returns an instance of an Event. The Event object contains a screen capture from the point the last action completed as well as metadata about each object within the scene.
event = controller.step(dict(action=MoveAhead)) # Numpy Array - shape (width, height, channels), channels are in RGB order event.frame # byte[] PNG image event.image # current metadata dictionary that includes the state of the scene event.metadata
Unity DevelopmentUnity Development
If you wish to make changes to the Unity scenes/assets you will need to install Unity Editor version 2018.3.6 for OSX (Linux Editor is currently in Beta) from Unity Download Archive. After making your desired changes using the Unity Editor you will need to build. To do this you must first exit the editor, then run the following commands from the ai2thor base directory. Individual scenes (the 3D models) can be found beneath the unity/Assets/Scenes directory - scenes are named FloorPlan###.
pip install invoke invoke local-build
This will create a build beneath the directory 'unity/builds/local-build/thor-local-OSXIntel64.app'. To use this build in your code, make the following change:
controller = ai2thor.controller.Controller() controller.local_executable_path = "<BASE_DIR>/unity/builds/local-build/thor-local-OSXIntel64.app/Contents/MacOS/thor-local-OSXIntel64" controller.start()
CitationCitation
} }
SupportSupport
We have done our best to fix all bugs and issues. However, you might still encounter some bugs during navigation and interaction. We will be glad to fix the bugs. Please open issues for these and include the scene name as well as the event.metadata from the moment that the bug can be identified.
TeamTeam
AI2-THOR is an open-source project backed by the Allen Institute for Artificial Intelligence (AI2). AI2 is a non-profit institute with the mission to contribute to humanity through high-impact AI research and engineering. | https://libraries.io/pypi/ai2thor | CC-MAIN-2020-29 | refinedweb | 837 | 50.02 |
Beekeeping/Editing Guide< Beekeeping
Contents
Request for HelpEdit
Beekeeping is designed as a collaborative book based on beekeeping and apiary practices. It exists as a guide to both beginners and experts alike. However if there are any experts in the audience we ask that you donate some of your time to help this project out by submitting some text or media. Every additional amount of text is helpful, whether it be a simply adding missing punctuation or the addition of great body of text. This book cannot evolve on its own; it requires your help. Please don’t be discouraged even if you are not an expert; if you have something to add then please do so. Any help is appreciated.
Submitting TextEdit
Articles can be submitted in the same manner as any other Wiki submission, with one minor difference. Article links must be formed with a prefix of “Beekeeping” followed by a slash “/”. In example to submit a link about beekeeping fashion you must do the following
[[Beekeeping/Fashion|]]
Linking is done similarly to that of Namespace linking, in essence Beekeeping functions similarly to a namespace while not actually being one.
For a general reference guide of editing Wiki pages visit the How_to_edit_a_page page.
New BookEdit
Beekeeping is a new book. Because of this you will see a rather copious amount of red text, please help us by adding a missing article.
If It’s Missing Add ItEdit
If at any time you see that an article is missing, feel free to add it or add a request for it. Occasionally subjects can be overlooked and may not be added, other times no one has simply taken the time to add one, take the initiative and do so.
Stand Back and Take a BowEdit
If you have submitted anything to Beekeeping please add your name and any comments you might have to the Contributors list. Any added info you can relay in regards to your experience or background with bees would be an added plus. | https://en.m.wikibooks.org/wiki/Beekeeping/Editing_Guide | CC-MAIN-2016-44 | refinedweb | 336 | 60.14 |
Paul Eggert <address@hidden> writes: > On 11/29/11 09:30, Eli Zaretskii wrote: >> I wonder if we could have a much smaller change that >> fixes just that single problem. > > Yes we could, though it would involve more of the patch > than the part that you've identified, and it would involve > some other stuff done by hand. The simplest way to think > about it is, I expect, is that it would be a fork of gnulib. > I could look into preparing such a patch but it would take > some time and would introduce other reliability concerns, > so I hope I don't have to do that.... OK, then let's go with the ifdef conditioning directly in the Emacs sources. But is conditioning on OS X and FreeBSD the right thing? We don't know if it fails on other BSDs. Since revno 106533 was intended to fix the MS-WINDOWS build, I think it's better to condition it for WINDOWSNT for now, as below: Eli, WDYT? === modified file 'lib-src/emacsclient.c' *** lib-src/emacsclient.c 2011-11-27 18:52:53 +0000 --- lib-src/emacsclient.c 2011-11-30 02:44:47 +0000 *************** *** 1635,1640 **** --- 1635,1645 ---- /* Send over our environment and current directory. */ if (!current_frame) { + #ifndef WINDOWSNT + /* This is defined in stdlib.h on MS-Windows. It's defined in + unistd.h on some POSIX hosts, but not all (Bug#10155). */ + extern char **environ; + #endif int i; for (i = 0; environ[i]; i++) { | http://lists.gnu.org/archive/html/bug-gnu-emacs/2011-11/msg01068.html | CC-MAIN-2016-40 | refinedweb | 248 | 74.9 |
Python Basics
Quick Links
-
Python Beginner's Help (PDF)
-
Learning Python - 5th Edition (2014) (PDF)
Python Crash Course - 2nd Edition (2019) (PDF)
Python Crash Course - Basics
Introduction
Python is a powerful multiparadigm computer programming language, optimized for programmer productivity, code readability, and software quality.
Python is a popular open source programming language used for both standalone programs and scripting applications in a wide variety of domains
Python is an excellent and versatile language choice for making complex C operations much simpler:
String manipulation
Networking
Python Syntax
To start writing Python, open up a file with the .py file extension.
Unlike a C program, which typically has to be compiled before you run it, a Python program can be run without explicitly compiling it first.
Variables
Python variables have three big differences from C:
No type specifier
Declared by initialization only
Python statements do not need to be ended with semicolons
Conditionals
All of the old favorites from C are still available for you to use:
elif - else if
True / False (bool)
input() - collects user input
Loops
Two varieties: while and for
Arrays Lists
Here is where things really start to get a lot better than C.
Python arrays (more appropriately known as lists) are not fixed in size; they can grow or shrink as needed, and you can always tack extra elements onto your array and splce things in and out easily.Instead of square bracket syntax, you can also simply use a function to create a list:
Tuples
Tuples are ordered, immutable sets of data; they are great for associating collections of data, sort of like a
struct in C, but where those values are unlikely to change.
Here is a list of tuples:This list is iterable as well:
Dictionaries
Python also has built in support for dictionaries, allowing you to specifiy list indices with words or phrases (keys).
Functions
Python has support fr functions as well. Like variables, we don't need to specifiy the return type of the function (because it doesn't matter), nor the data types of any parameters.
All functions are introduced with the
def keyword.
Objects
Python is an object-oriented programming language.
Objects have properties and methods, or functions that are inherent to the object, and mean nothing outside of it. You must also define methods inside the object.
You define a type of object using the
class keyword in Python.
Classes require an initialization function, also more-generally known as a constructor, which sets the starting values of the properties of the object.
In defining each method of an object,
self should be its first parameter, which stipulates on what object the method is called.
Style
If you haven't noticed by now, good style is crucial in Python.
Tabs and indentation actually matter in this language, and things will not work the way you intend for them to if you disregard styling!
First Program
If you compare this to C's first code, you will notice that we no longer need to create a
main function or import the
<stdio.h> library.
Troubleshooting in Python
When a program contains a significant error, Python displays a trace-back, which is an error report. Python looks through the file and tries to identify the problem. Check the traceback; it might give you a clue as to what the issue is preventing the program from running.
Remember how important syntax is in Python, and every other programming language, and review your code. | https://docs.nicklyss.com/py/ | CC-MAIN-2022-40 | refinedweb | 580 | 55.88 |
Tech Ads
Back to Article List
Originally published February 2004 [ Publisher Link ]
XML to PDF conversion through FOP
Even though XML is in wide use in a vast array of applications today, it is often criticized for its lack of presentation and aesthetic features -- with good reason, since these were not its designers primary purposes. Sometimes it's useful to convert XML information into a more user-friendly format like PDF. In this article we will describe how to go about this process using Formatting Objects Processor (FOP), an Apache Software Foundation project.
FOP is not in itself a PDF conversion tool exclusively, but a broader project that takes a W3C standard XSL-FO tree and renders its content to another format, such as PCL, PS, SVG, and of course PDF, among others.
We will also be using Ant, another Apache project, to ease our conversion process by expressing it in a simple configuration script. Download FOP and Ant in their binary editions and let's get started.
We will begin by illustrating an XML document to be converted into PDF:
To begin, we need to transform this XML fragment into an XSL-FO tree. The natural choice for this step is an XSL stylesheet, since it allows us to define specific conversion instructions for each XML element. Here is the XSL stylesheet for this task:
For those of you who have never used an XSL stylesheet, each
<xsl:template> defines the output which is to be generated for each XML element. For example, when a
<linuxdistros> element is encountered it is supplanted with the contents of its template. This process occurs recursively for each XML element, and it's from the contents of these templates that another document is constructed that will represent our XSL-FO tree.
The XSL-FO elements used to construct our tree are the most basic in nature. Although FOP does support a wide range of XSL-FO elements, it does not support all of them as defined in the W3C's specification. This is one of the reasons FOP is still in its x.2 release. Some of the XSL-FO declarations which are used on our conversion process include:
fo:root: Indicates the start of the XSL-FO tree as well as the XML namespace.
fo:layout-master-set: Used to define the general characteristics of all PDF pages, its attributes are self-explanatory and include margins and page width and height, among others.
fo:flow: Defines the beginning of the document body.
fo:block: A
fo:blockis used to define content. It can take various attributes, such as font type, alignment properties, or font colors. It is similar to a
<p>element in HTML / XHTML.
fo:table: Declares the start of a table.
fo:table-column: Indicates the sizes of columns in a given table.
fo:table-row: Declares the start of a row in a given table, similar to the
<tr>element in HTML / XHTML.
fo:table-cell: Defines a cell for a given table, similar to the
<td>element in HTML / XHTML.
FOP does offer fancier formatting elements, but for simplicity's sake we do not address them here. Consult FOP's documentation to discover its additional formatting capabilities.
Next, we need to prepare the Ant script in charge of the actual conversion. Delving into the finer details of Ant goes beyond the scope of this article; if you have never used it before you can read First contact with planet Ant to get up to speed. Our build script looks like:
Wherever you place your build.xml file, you also need to create a directory named
lib to hold FOP's libraries: The
fop.jar file and its other ancillary JARs. These files are included in the FOP download and are located in the
build and
lib directories respectively.
Our Ant script first defines a
path instruction to load all of FOP's libraries, which are located under the
lib directory. We then define our main target, named
fop on the
org.apache.fop.tools.anttasks.Fop class. This class contains the actual logic for converting the XSL-FO tree into PDF.
Immediately after, we declare an
xslt task, which takes two input parameters:
in=linuxdistros.xml, where
linuxdistros.xml corresponds to our XML file, and
style="linuxdistros2pdf.xsl", where
linuxdistros2pdf.xsl is our XSL stylesheet. The output for this task, declared as
out=linuxdistros.fo, indicates that the generated output be placed in a file named
linuxdistros.fo, which represents our XSL-FO tree.
The last line defines the
fop task that takes the XSL-FO tree
linuxdistros.fo and generates the PDF file named
linuxdistros.pdf.
Finally, to generate the PDF document, simply execute the
ant pdf command from your shell prompt.
You can now streamline the process of creating PDF documents directly from XML, with the help of these open source-based tools. | https://www.webforefront.com/about/danielrubio/articles/ostg/xmltopdf.html | CC-MAIN-2021-31 | refinedweb | 817 | 63.59 |
Is Network Hacking Promotion Or Destruction Computer Science Essay
Published: Last Edited:
This essay has been submitted by a student. This is not an example of the work written by our professional essay writers.
On 12 January 2010, the most popular search engine in China, Baidu, was unusable for about 4 hours. This is because Baidus DNS records were hijacked by a group known as the Iranian Cyber Army. Later, a well known Chinese hacktivist group, the Honker Union of China, responded by attacking Iran websites and leaving messages.
During these several years, time and again we hear news about network hacking. But what is hacking? As a matter of fact, it is not easy to give a simple definition of hacking.
Hacking.[1]
The original meaning of hack was born at Massachusetts Institute of Technology. It was used by mathematician John Nash as a putdown which originally meant an elegant, witty or inspired way of doing almost anything. Now the meaning has changed to become something of a portmanteau term associated with the breaking into or harming of any kind of computer or telecommunications system.
According to Wikipedia, there is a distinction between security breaking and hacking. Cracking would be a better term for security breaking. However, here I prefer to discuss the effects of hacking events rather than doing research to the meaning of these terms.
This paper will begin with the history of hacking.
2. History
When it comes to the history of network hacking, the birth of internet has to be mentioned. In 1969, Arpanet, the forerunner of the internet, was founded. At this time, there were only four nodes in Arpanet which consisted of the University of California Los Angeles, University of California Santa Barbara, the Stanford Research Institute and University of Utah.
In the 1970s, hacking was all about exploring and figuring out how the wired world worked.[2] In this period, an early hacker, John Draper, discovered a way to make free long-distance call. He blew a precise tone into a telephone to make the phone system to connect with others. Later he earned the handle Captain Crunch. Throughout the 1970s, he was arrested repeatedly for phone tampering.
At the same time, computer virus appeared. For the first time, the Creeper virus was detected on Arpanet. Creeper was an experimental self-replicating program written by Bob Thomas at BBN Technologies in 1971.[3] In October 1980, Arpanet came to a crashing halt because of the accidental distribution of a virus.[2]
First National Bank of Chicago was the victim of a $70-million computer heist in 1988. Seven criminals carried out embezzlement in the First National Bank of Chicago. They transferred 70 million dollars to an account in a bank of New York, then, from there, to two banks in Vienna.[4] They ordered these transfers by telephone. When the bank tried to call the customers to confirm the transfers, all the calls were diverted towards the residence of one of the criminals.
In 1988, Robert Morris set off an internet worm program that quickly replicates itself to over 6,000 hosts bringing almost the whole network to a halt.[5]
In 1993, Kevin Poulsen, Ronald Austin and Justin Peterson conspired to rig a radio phone-in competition to win prizes. The trio seized control of phone lines to the radio station ensuring only their calls got through.[5]
In 2000, there were several serious hacker attacks caused by some infamous viruses, such as Y2K bug, I Love You virus, Melissa virus, etc. These kinds of viruses were well-documented by the media and experienced directly through the rapidly growing number of casual web surfers. Some of the most popular Internet sites, like CNN, Yahoo, E-Bay and Datek, were their victims at that time.
Since 2000, viruses and attacks have become increasingly commonplace �C too many to mention. At the same time, techniques of attacks and defense developed rapidly.
3. Technology
Network hacking could be done by using different techniques and different ways. As to Baidu, how was it hacked? The news said that Baidu.coms DNS was hijacked. Then what is DNS hijacking?
DNS Hijacking
The Domain Name System (DNS) is a hierarchical naming system for computers, services, or any resource connected to the Internet or a private network. The Internet maintains two principal namespaces, the domain name hierarchy and the Internet Protocol (IP) address system. The Domain Name System maintains the domain namespace and provides translation services between these two namespaces.[7]
DNS hijacking or DNS redirection is the practice of redirecting the resolution of Domain Name System (DNS) names to rogue DNS servers, particularly for the practice of phishing, or to direct users to the ISP's own servers.[8]
Now I want explain the difference between normal DNS request and hijacked DNS request by using Baidu as example.
The process of handling a normal DNS request is as follows
(1) Enter in the navigation bar of browser;
(2) Computer sends DNS request to DNS Server;
(3) DNS Server translates to IP address 119.xxx.209.xxx;
(4) DNS sends IP address 119.xxx.209.xxx back to the request computer;
(5) The user accesses the website normally.
If DNS is hijacked, the process is same as the one above. But the address records of Baidu in DNS record caching of Register.com has been modified by the hacker. Now in step (3) above, the IP address of Baidu is not translated to 119.xxx.209.xxx but the one which is appointed by the hacker. Consequently, the user accesses the website appointed by the hacker instead of Baidu.
We can see that in order to hijack Baidus DNS, the hacker need to crack into the system of Register.com first. To some extends, Register.com was hacked as well. In fact, Register.com suffered a major DDoS attack on April 1st, 2009, downing thousands of web sites. What is DDoS attack?
DDoS
Distributed Denial-of-server (DDoS) attack aims at making computer or server resource unavailable to its intended users. There are another two similar kinds of attacks, DoS (denial-of-server) attack and DRDoS (Distributed Reflection Denial of Service) attack. They are implemented by either forcing the targeted computer(s) to reset, or consuming its resources so that it can no longer provide its intended service or obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.[10]
All of them launch attacks by using the loophole of TCP three-way handshake. The attacks do not require completion of the TCP three-way handshake and attempt to exhaust the destination SYN queue or the server bandwidth. Since the source IP addresses can be trivially spoofed, an attack could come from a limited set of sources, or may even originate from a single host.
But these three attacks are different. DoS attack is like fight one on one. Hacker uses his own machine to consume targeted machines resources. But if the target machine is too powerful, the attack would fail.
Compared to DoS, DDoS is more like mass brawl which means several computers consume the resources of the victim machine at the same time. But how can hacker make several even lots of computers to do this? DDoS occurs when multiple systems flood the bandwidth or resources of a targeted system, usually one or more web servers. These systems are compromised by attackers using a variety of methods. Attacker may use Trojan to comprise others systems. Attackers can also break into systems using automated tools that exploit flaws in programs that listen for connections from remote hosts. One of the classic examples of DDoS tool is Stacheldraht. It detects and enables source address forgery automatically. It combines features of Trinoo with TFN (Tribe Flood Network), and adds encryption.
4. Promotion?
There is an interesting saying that hacking is a kind of promotion. Someone hold this opinion because hacking makes difference in some aspects.
Hacking promotes the development of information technology. Techniques of hacking have developed rapidly during these several years. In 2009, Kingsoft Internet Security detected 20,684,223 new viruses and Trojans in China. Someone has summarized 300 network attack methods of different kinds appeared between 2006 and 2009 (see reference [11]). From that article, it could be found that the hacking techniques is becoming more and more complicated, the speed of attacks is becoming faster and faster and the effects of attacks is becoming more and more destructive. At the same time, the defense techniques develop quickly as well. One of the convictive evidence is Cloud Security technique. Almost all the famous IT security corporations have products using Cloud Security.
Thanks to network hacking, a new industry came into being during these 20 years. Yes, it is IT Security. The firewall was invented in 1980s. The first paper about firewall was published in 1988.[12] As to antivirus software, the first publicly documented removal of a computer virus in the wild was performed by Bernt Fix in 1987.[13] But today, there are thousands of IT security corporations all over the world. According to Gartner, a world's famous information technology research and advisory company, the sales revenue of IT security software in the whole world in 2008 is more than $14.5 billion. Besides, this number will keep increasing by 9.1% in the next several years.
Iranian Cyber Army hacked Twitter and Baidu in order to pursuit their political views. As to this kind of hackers, they consider network hacking a way to promotes their political idea. They always leave some political messages while they are hacking some famous websites.
5. Destruction?
However, many other people regard network hacking as destruction.
First of all, some hacking events make great economy cost. In 2000, the notorious I Love You virus was estimated to have cost the global economy close to $9 billion, which made it as the most harmful hacker-created virus to date. In 2009, according to a report filed by the Internet Crime Complaint Center (IC3), online scams and other types of cybercrime cost computer users more than $559 million in losses in US. As to Baidu, the DNS hijacking made it lose more than $100 million directly within 7 hours.
Most hacking events infringe others privacy right. If a hacker breaks security of the system in a machine, then he could use this machine to do anything he wants. In this situation, the machine owner could not protect his privacy. The hacker can get all data in this machine, such as photos, personal information, etc. The hacker can also use this machine to monitor what the owner is doing or attack others machine.
Some international network attacks taint foreign relations. After Baidu was hacked, the Honker Union of China attacked Iran websites as revenge. This event causes the tension between two governments.
6. Conclusion
Different hacking events have different effects. And there are different kinds of hackers. Some are profit-driven hackers which launch attacks in order to get profits. In the eyes of law, this is cybercrime. The hacker may get profit directly or be hired to do hacking. Another kind of hackers is frame-driven hackers. They want to be famous or have other attempts. No matter which kind of hackers they are, I cannot agree with their behaviors.
But on the other hand, as a student of computer science, I can understand the excitement and sense of achievement to hack a system. It is said that hacking is an art of exploitation. To some extent, hacking is a creative problem solving. It exploits holes in sloppy programming that most programmers cannot find. In the worlds of Jon Erickson, Hackers are always pushing the boundaries, investigating the unknown, and evolving their art.
In conclusion, hacking as a kind of study or research is promotion. But it is destruction when it is abused. | https://www.ukessays.com/essays/computer-science/is-network-hacking-promotion-or-destruction-computer-science-essay.php | CC-MAIN-2017-17 | refinedweb | 1,993 | 56.76 |
0 Members and 1 Guest are viewing this topic.
BTW what do you think is Linux on the N64 possible I mean text based?
#include <studio.h>main(){printf("hello, world\n");}
I've found a book called "The C Programming Language Second Edition", it seems to be ok. First thing to do is:Code: [Select]#include <studio.h>main(){printf("hello, world\n");}I also downloaded xubuntu-9.04 and installed it on VMWare. Then I placed your toolchain in my Home directory and typed the envvars into the commandline.I saved above code to hello.c and typed: gcc hello.cIt made a file called a.out which I can run in the commandline via ./a.outIt doesn't run on my N64. I have to somehow convert it to a rom that has a header and so on. Does anybody know how to do this?
I found everything I needed in the test.v64 demo app for libdragon. | https://www.neoflash.com/forum/index.php?topic=5959.msg45253 | CC-MAIN-2021-04 | refinedweb | 161 | 79.67 |
Apr 27 2020 01:27 AM - edited Apr 27 2020 01:30 AM
I've looked for this answer online and have come across the "systemreset -factoryreset" command which works, but it comes up with the prompt asking if I want to keep my files or remove everything, I want to remove everything, but without the prompt.
We are not doing this from any pre-exiting images, and our laptops are running the pre-loaded Windows 10 Pro install, we are just using the in-built Windows 10 "reset this PC" feature as we have no MDM configured. We just want the laptops to be totally reset so they don't contain any company information, we're not bothered about completing the OOBE once they are wiped.
We are trying to accomplish this remotely as our users are all at home, so I need to automate it and have no user involvement in the process, I just want it to factory reset, and bring the laptop up to the off-the-shelf state configuration. We have the facility to push commands and scripts to the laptops so was hoping to do this via powershell.
Does anyone know if this is possible?
Thanks
Apr 27 2020 07:27 AM - edited Apr 27 2020 07:29 AM
Apr 27 2020 07:27 AM - edited Apr 27 2020 07:29 AM
The systemreset command will show interface to user and it is behavior by design , however if you are able to manage devices using Configuration Manager, you could do it using Full Wipe, take a look at:
You could remotely wipe device using Windows Intune too:
Apr 27 2020 07:57 AM
Apr 27 2020 07:57 AM
@Reza_Ameri-Archived Thanks for your reply.
Unfortunately we do not use configuration manager, nor do we have capacity to register devices on InTune currently.
We can run exe's/powershell scripts, that sort of thing on the laptops so we're hoping to use something like that to achieve this.
Apr 28 2020 10:04 AM
Apr 28 2020 10:04 AM
From what I know there is no script to run it in silence mode and wipe system and it is behavior by design, so let say if there is possibility to do so, cybercriminals might run that script and user will lose Windows but it is available in Configuration Manager or Intune, it means PC is being managed by trusted administrator.
Apr 29 2020 08:27 PM
If you have the ability to pull down content, you can pull down Windows 1909 Installer, then run the command to upgrade and clean the system. The entire thing can be scripted.
Apr 30 2020 12:37 AM - edited Apr 30 2020 12:46 AM
You can use the MDM WMI Bridge Provider to do what you want. This way you do exactly the same as intune would do.
You have to execute the following PowerShell script as SYSTEM. Administrator ist not enough!
To accomplish this, you can either execute the script with task scheduler or use psexec.exe to run powershell as system (psexec -s powershell.exe -file c:\pathtoscript\script.ps1).
$namespaceName = "root\cimv2\mdm\dmmap" $className = "MDM_RemoteWipe" $methodName = "doWipeMethod" $session = New-CimSession $params = New-Object Microsoft.Management.Infrastructure.CimMethodParametersCollection $param = [Microsoft.Management.Infrastructure.CimMethodParameter]::Create("param", "", "String", "In") $params.Add($param) $instance = Get-CimInstance -Namespace $namespaceName -ClassName $className -Filter "ParentID='./Vendor/MSFT' and InstanceID='RemoteWipe'" $session.InvokeMethod($namespaceName, $instance, $methodName, $params)
$methodname can bei either "doWipeMethod" or "doWipeProtectedMethod". The later one will also wipe all data from the disks, especially if you want to refurbish the devices. The downside is that "doWipeProtectedMethod" can leave some clients (depending on configuration and hardware) in an unbootable state.
Additionally "doWipeMethod" can be canceled by the user (power cycle for example), "doWipeProtectedMethod" cannot be canceled. It automatically resumes after a reboot until done. The higher risk ist worth it most of the time. If you want to be sure that the devices will be in a usable state after the wipe, use "doWipeMethod" instead.
Nov 17 2020 08:38 AM
Nov 17 2020 08:38 AM
Nov 18 2020 02:37 AM
Nov 18 2020 02:37 AM
The MDM wipe method above wipes all fixed disks, no modification necessary. I'm not sure about removable disks, but all fixed disks (C:, D:, ...) will be cleaned.
If it is important to fully wipe the data from the disks (i.e. non-recoverable) you should make sure that all disks are bitlocker encrypted. Only with encryption you can be sure that no data is recoverable with this method.
Nov 19 2020 01:58 PM
Nov 19 2020 01:58 PM
Feb 03 2021 02:39 PM - edited Feb 03 2021 04:51 PM
@dretzer
Hi,
I'm trying to use the script you referred to above (and also seemed to have wrote) using the following Kaseya Agent Procedure:
It seems to go through Kaseya correctly, first image, but when I run the script through powershell directly, I receive the error in 2nd image.
Would you be able to help me with this? We are trying to wipe a bunch of computers as quickly as possible and this was the most promising option we saw.
Thanks for the help and the work!
Feb 04 2021 02:50 AM
Hi.
You are trying to run the script with not enough privileges. The needed WMI methods can only be invoked with SYSTEM privileges. Membership in "Administrators" is not enough.
To execute a PowerShell script manually with SYSTEM privileges, you can, for example, use psexec.exe from Microsoft Sysinternals:
PsExec - Windows Sysinternals | Microsoft Docs
Place the .exe file and the .ps1 file in the same directory and execute psexec.exe with administrative privileges the following way (replace the paths as necessary):
C:\Scripts\psexec.exe -accepteula -S powershell.exe -command C:\Scripts\wipe.ps1
Another way, which you can do remotely and without psexec (group policy for example), would be to create a scheduled task running as SYSTEM and executing the script. You can then execute the task on demand or with a time/date schedule.
Feb 09 2021 03:36 AM - edited Feb 09 2021 03:40 AM
Feb 09 2021 06:31 AM
how annoying. all reset functions I've tried, including the powershell on this thread, resets to include the OEM stuff I want rid of. If you Fresh Start from intune, theyre not present.
I'm trying to avoid having to enrol a load of devices only to fresh start them. If I can avoid the initial enrolment and kick off a total fresh start from the beginning, that would be good.
Feb 09 2021 06:47 AM
The "OEM stuff" is found in C:\Recovery\*. If you remove all contents in this folder before you initiate the device reset, it should restore a clean windows installation without any "OEM stuff". Keep in mind though, that certain driver packages will be migrated to the new installation. Sometimes these can contain additional software packages included in the device driver package (for example audio control panels from the audio driver).
Feb 09 2021 06:55 AM
@dretzer I realized the computer I was running it on didn't have a recovery partition so even running the "systemreset -cleanpc" command wasn't working.
Kaseya allows you to run scripts as System - so even though I was running locally in picture - I was trying as System most of the time.
Thanks for the help either way.
Feb 09 2021 10:46 AM
Feb 10 2021 01:34 AM
I think I'm wrong. A fresh start from intune still brings back some HP stuff. Which would make sense if there's some stuff HP have embedded in the image, and some stuff is in the recovery folder.
Might have to look into manual cloud reinstall at shift-f10 on first boot on each machine or a bootable USB with an unattended xml to just blow the hard drive away and start again without user interaction.
sigh
Feb 10 2021 03:20 AM
May 18 2021 07:05 AM
May 18 2021 07:05 AM
Dec 20 2021 12:47 PM | https://techcommunity.microsoft.com/t5/windows-deployment/factory-reset-windows-10-without-user-intervention/m-p/1339823 | CC-MAIN-2022-21 | refinedweb | 1,368 | 61.67 |
Asked by:
debug does not see a template member
It is Visual Studio 2017 Community 15.8.1 under Windows 7 Pro SP1, The project is MFC project but the problem is with C++ native debug session.
Code:
// My Header template <class T> struct MyStruct { ... static vector<T> m_vT; .... }; // initialization,any vector<t> MyStruct::m_vT(128); using MyStructWithInt = MyStruct<int>: // Source file Mysource.cpp #include "MyHeader // Other includes int main() { ........................ vector<int> vI = MyStructInt::m_vT; .............................. }
In Debug session I can see vI in all details, but MyStructWithInt::m_vT sais 'no access' to this member.
I understand that m_vT is compiled and placed into other section of the memory, before app entered main.
Is this behavior of VS debugger legitimate?
Question
All replies
Thank for reply.
Below is the simplest Console VS app:
// Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file // Header pch.h #ifndef PCH_H #define PCH_H // TODO: add headers that you want to pre-compile here #endif //PCH_H
// Source pch.cpp // pch.cpp: source file corresponding to pre-compiled header; necessary for compilation to succeed #include "pch.h" // In general, ignore this file, but keep it around if you are using pre-compiled headers.
// DebugTest.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> #include <vector> using namespace std; template <typename T> struct DebugStruct { static vector<T> m_vT; }; using MyDStruct = DebugStruct<int>; vector<int> MyDStruct::m_vT(128); int main() { vector<int> vI = MyDStruct::m_vT; std::cout << "Hello World!\n"; }
In Quick Watch:
By a way, pch is for precompiled header; VS refuses to build if you delete it from the project and from project properties. It happy with empty files. Strange!
Also, 'Hello...' is added by VS, I did not ask for it.
Thanks for that.
It would appear to me to be due to use of using here:
using MyDStruct = DebugStruct<int>;
since the long form: DebugStruct<int>::m_vT
can be shown OK by the debugger.
This reproduces in both 15.8.2 and 15.9 preview 1 for me, so please go ahead and report it to MS using the Report a Problem facility
from the VS IDE. Be sure to supply your repro project and clear instructions on what to do to reproduce it, that way it should get
past the first hurdle.
When you have a link to the bug report, please post it here and I'll add a vote and comment to your report.
Dave | https://social.microsoft.com/Forums/en-US/63db52dc-40ce-4174-be50-c56f38d1a216/debug-does-not-see-a-template-member?forum=vsdebug | CC-MAIN-2018-47 | refinedweb | 493 | 75.2 |
Web 2.01, a Rich Internet Application Example
Learn about what I call "Web 2.01," a fusion of "Web 2.0" style application content with a "Rich Internet Application" client, which is not subject to many of the limitations of a web browser.
Summary:
Learn about what I call "Web 2.01," a fusion of "Web 2.0" style application content with a "Rich Internet Application" client, which is not subject to many of the limitations of a web browser.
What does a Web 2.01 application look like? Well, here's a screenshot:
Notice that it's a Rich Internet Application. It includes a favorite feeds list, Friend of a Friend functionality, and a way to select favorite authors.
Once you set up your favorites, you can get an XML feed of the favorites via web services.
Visioning:
Back in September of 2005, Tim O'Reilly offered his vision of what distinguishes "Web 2.0" from what went before (which we're left retroactively to call "Web 1.0"). He described a list of correspondences (with a distinctly "what's hot/what's not" flavor to it), some examples being:
I want to show you my vison for the fusion of Web 2.0 with Rich Internet Applications (RiA), which I'm going to call "Web 2.01".
Web 1.0 was dominated by PHP-based applications like vBulletin and Drupal. These frameworks were aimed at the lowest common denominator: a cross platform browser-based user interface(UI) that accessed a single, central server through a dial-up MODEM. Many sites had only the flattest forms of user feedback.
Web 2.0 lives on a services-based ecosystem with a richer UI, enabled by the higher prevalance of users with broadband connections. Appplications are driven by richer, more interwoven data, and include features such as friend of a friend (FOAF) and tagging.
The value proposition isn't dominated by delivering the party line of the central site management, but is more about user input and participation; in short: social networking. The web service approach, having less direct control of the final presentation, also results in the injection of less parasitic content (such as spam and pop-up, pop-over and pop-under advertising).
In short, in Web 2.0 we will see websites and applications (that communicate via service calls) merging into right Internet applications, blurring the distinctions between desktop apps and internet apps, almost re-defining the word webapp to mean any application that talks to the Internet.
When we talk of "rich content", most people think of technologies like:
- Adobe Flash/Flex
- MS ClickOnce
- DHTML/Ajax
- Sun/Google Java Network Launcher (JNLP)
DHTML/Ajax runs only in a browser, and the weaknesses are well-known: the difficulty of obfuscating or otherwise protecting the implementation details of the interface, security issues, injection of parasitic content, maintainability, and scalability. Many experienced developers are dogged by the persistant feeling that AJAX may be just a fad.
For an example AJAX app, look at the Yahoo Mail beta (that only runs on a single platform). Longhorn Clickonce is a 6 months away, and an example done with Flash is Goovy.com.
Java Desktop (JDNC), on the other hand, is cross platform, allows you html edits, and embedding of a browser. For more on the future read re: Google and Java.
Adding FOAF and Tagging to Web 1.0 websites is not enough to make them Web 2.0. You also need services, and adding RiA takes you to my "Web 2.01" . I disagree with Tim O'Reilly that Web 2.0 will be an incremental upgrade; I think it's revolutionary rather than evolutionary.
Table:
But enough preaching; let's write a Web 2.01 app. It will use services, FOAF, tagging, and have a rich user interface that is as easy to use as a website.
I wrote an early article some time back with examples for Network Launcher that you should review ( , and you can also read- ) if RiA is new for you. (Also note that NetBeans 5.0 IDE can now automatically generate a JNLP Network Launch's file for you.)
Step 1:
In order to display FOAF and favorite communities in our sample application, we need a FOAF/favorites feeds from someplace. (remember, social networking and RiA are a must for Web 2.01!).
You can get feeds by joining Roomity.com, and selecting "favorite communities" and "favorite authors" for your account. Roomity can aggregate the same clubs you are currently subscribed to, while concealing your email address from spammers. Roomity also lets you access Usenet newsgroups and your favorite blogs while sitting behind a firewall and can categorize content . In your favorite clubs, you may have favorite authors that you like to follow. You can search by content, people or places, as well as play streaming audio and video, all in a cross-platform environment. Whatever feeds and topics you select are the ones that we will display.
You should be able to see the favorites you selected via a hyperlink, for example you would use to see your favorites. (You can also use to see a specific club and to see a specific author.)
Once you have confirmed your favorites with the url, we are ready to move to Step 2, where we begin writing code.
Step 2:
Paste the following code in your favorite editor.
View:
public class Web2ExampleView { private JButton button = new JButton("Get Feed"); private JEditorPane pane = new JEditorPane(); private JTextField user = new JTextField(10); private JPasswordField passwd = new JPasswordField(10); public JPanel exec() { JPanel pan = new JPanel(new BorderLayout()); pan.add(new JScrollPane(pane), BorderLayout.CENTER); pan.add(button, BorderLayout.SOUTH); pan.add(getTopPanel(), BorderLayout.NORTH); pane.setEditable(false); activate(); return pan; } private JPanel getTopPanel() { JPanel pan = new JPanel(new FlowLayout()); pan.add(new JLabel("User : ")); pan.add(user); pan.add(new JLabel("Password : ")); pan.add(passwd); return pan; } private void activate() { GetXMLAction action = new GetXMLAction(); button.addActionListener(action); action.addSource("user", user); action.addSource("passwd", passwd); action.setTarget(pane); } }
And Action:
public class GetXMLAction implements ActionListener { private static final String U_R_L = "?"; private JEditorPane pane = null; private HashMap source = new HashMap(); public void actionPerformed(ActionEvent e) { String url = constructURL(); if(url != null) { pane.setPage(url); } } private String constructURL() { String url = null; String user = ((JTextField)source.get("user")).getText(); String passwd = ((JTextField)source.get("passwd")).getText(); if(user != null && passwd != null) { url = U_R_L + "user=" + user + "&password=" + passwd; } return url; } public void setTarget(JEditorPane pane) { this.pane = pane; } public void addSource(String key, JTextField field) { source.put(key, field); } }
This code (combined with Part I) will give you a simple, easy to launch Web 2.0/RiA webapp. demonstrating the rich UI meant for broadband with FOAF and "mashing".
The code only displays a XML document view of a user's recent posts, and his favorite feeds and authors in XML. It does not bind the XML (although XML binding is easy in Java 5.0).
The output of your personal Web 2.0 RiA should look a bit like this:
You can bind this to any UI control you'd like; a TreeTableModel, for example. The XML displays a user's tagged favorite feeds, favorite authors, as well as any posts the user placed.
If you don't know how to pull a screen, use:
public class RoomityXMLClient { public static void main(String[] ar) { JXFrame frame = new JXFrame("Roomity Sample Client"); frame.getContentPane().add(new ClientView().exec(), BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(100, 100, 900, 700); frame.setVisible(true); }
Can you see your feeds in your application with the code provided?
If you have the code working, great! If not, you can see a video of the coded solution at
In the upcoming Java 5.06 patch, the Network Launcher "Scary User Screen" (displayed even for deployment of properly signed JARs) will be fixed. JDNC is a great platform for huge applications with professional developers, and JDNC's A. Folwer is working on making it more compliant with an MVC model, as a result of user feedback.
Conclusion
LimeWire, Azuareus and Roomity have a combined 30 million users using Java technology with internet services. Google is denying that it will offer Java based applications to store content in Google. It seems that Sun middle management realizes that in order for them to have a services market, they have to have desktop applications deployed to use those services.
The battle for control of services architecture is going to depend on the battle for mindshare among service consumers (applications requesting the service), And the technology (be it .NET, Flash, Java or DHTML/Ajax) that works best for Web 2.0 has yet to be decided. J2EE was one of weakest technology stacks on the server, thanks to ORM, EJB and JSF, even though it has power on the desktop because it's easy to deploy. Many veterans suspect that Ajax/DHTML is going to fade away.
This example illustrates the simple steps you need to take to rapidly create a "Web 2.01" (Web 2.0/RiA) application for yourself, and participate in social networking's evolution as a "play it forward" ecosystem.
Roomity.com at that has TV-like video streams as well as music streams. Explaining Roomity is like trying to explain what a spreadsheet is to someone who does not know what a spreadsheet is ("it's like a calculator but …."). Roomity is a Web 2.01 RiA application. Roomity itself is built using NetBeans, Looking Glass, Groovy (anyplace where one would use J2EE frameworks, we used Java-based Groovy for all the back end stuff), JMF, etc.
More 2.01 links:
- Amazon:
- EBay:
- J2EE
About the Author
Vic Cekvenich has been leading large scale development and deployments for two decades, and is a published author. Sandy (Rex), Erick (WhatHmm), Asha (AvRootShell) and Gana (JavaBuddy) helped with this article.
Start the conversation | https://www.theserverside.com/news/1365070/Web-201-a-Rich-Internet-Application-Example | CC-MAIN-2020-24 | refinedweb | 1,656 | 56.25 |
22918/how-to-catch-boto3-errors
I am developing a django app which communicates with several Amazon Web Services.
So far I am having trouble dealing with and catching exceptions thrown by the boto3 client. What I am doing seems unnecessarily tedious:
Example:
client = boto3.client('sns')
client.create_platform_endpoint(PlatformApplicationArn=SNS_APP_ARN, Token=token)
this might throw an botocore.errorfactory.InvalidParameterException if e.g. the token is bad.
client.get_endpoint_attributes(EndpointArn=endpoint_arn)
might throw an botocore.errorfactory.NotFoundException.
First, I can't find these Errors anywhere in code, so they are probably generated somewhere. Bottom line: I can't import it and catch it as usual.
Second, I found one way to catch the error here using:
try:
# boto3 stuff
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NotFound':
# handle exception
else:
raise e
But I have to remove the Exception part of the error name. Seems very random and I have no clue whether I would remove the Error in botocore.exceptions.ParamValidationError if I wanted to catch that one. So it's hard to generalize.
Another way to catch the error is using the boto3 client object I got:
try:
# boto3 stuff
except client.exceptions.NotFoundException as e:
# handle exception
This seems the cleanest way so far. But I don't always have the boto3 client object at hand where I want to catch the error. Also I am still only trying things out, so it's mostly guess work.
Does anybody know how boto3 errors are supposed to be handled?
Or can point me towards some coherent documentation which mentions the errors above? Thanks
You've summarized the situation well. The old boto had a simple hardcoded approach to supporting AWS APIs. boto3, in what appears to be an attempt to reduce the overhead of keeping Python client synced with evolving features on the various apis, has been more squishy around exceptions, so the ClientError approach you outlined above used to be the canonical way.
In 2017 they introduced the second mechanism you highlight: 'modeled' exceptions available on the client.
I am not familiar with SNS but in my experience with other AWS products, the ClientError naming matches up with the HTTP apis, which tend to be well documented. So I would start here:
It looks like the new-style modeled exceptions are generated from service definition files that live in botocore module. I can't find any documentation about it, but go browse around the AWS service models in.
Also, it's good to know that if you are not (in contrast to OP's code) dealing directly with the low-level client, but instead are using a high-level AWS ServiceResource object, a low-level client is still easily available at my_service_resource.meta.client so you can handle exceptions like this:
try:
my_service_resource.do_stuff()
except my_service_resource.meta.client.exceptions.NotFoundException as e:
# handle exception
You can use method of creating object ...READ MORE
Using Client versioning you can create folders ...READ MORE
You can delete the file from S3 ...READ MORE
You can delete the folder by using ...READ MORE
Grep your project for boto or boto3 if you're using AWS ..
The recommended way of managing credentials used ...READ MORE
import boto3
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/22918/how-to-catch-boto3-errors?show=22919 | CC-MAIN-2019-47 | refinedweb | 556 | 58.69 |
I used:
#include <MIDI.h>
void setup() {
MIDI.begin(); // Launch MIDI with default options
}
void loop() {
MIDI.sendNoteOn(42,127,1); // Send a Note (pitch 42, velo 127 on channel 1)
delay(600); // Wait for a second
MIDI.sendNoteOff(42,0,1); // Stop the note
delay(600); // Wait for a second
}
I use the MidiWatcher ap from software CSharpMidiToolkitV5_demo
The a Midi Controller Behringer BCR2000 sends messages that are reported in MidiWatcher.
Windows detects the Teensy as a MIDI device.
The software MidiWatcher software recognizes that a MIDI device is present,
but does not report receiving the notes sent by Teensy.
I note that Channel 1 is declared and Setup() has no parameters for default.
Do these need to change and to what?
Any ideas?
thanks,
Richard | https://forum.pjrc.com/threads/27495-Teensy-3-1-MIDI-sendNoteOn-not-received?s=4228ede2c70a1eae8aca98c6a4dffbd4&p=61651 | CC-MAIN-2019-30 | refinedweb | 127 | 66.94 |
Web Hosting using PHP and MySQL on AWS
It’s was a Sunday and I was bored. Then I came across a custom URL shortener service, YOURLS that I had previously used in my college days. It was very simple to set it up with my GoDaddy shared web hosting. I no longer have a web hosting package on GoDaddy so I decided to try out AWS cloud instead.
AWS is cheap and easy to get started. Our goal is to get our own custom URL shortener service up and running on.
Before we deep dive into the details of setting up everything, here are our broader goals.
- Setup an EC2 instance for cloud hosting
- Setup a hosting zone and configure DNS
- Setup a load balancer for the EC2 instance.
- Install a LAMP web server on the EC2 instance.
- Configure YOURLS on the web server.
This article will cover everything up to setting up the LAMP web server.
Create an EC2 instance
An EC2 instance is a virtual server in Amazon’s Elastic Compute Cloud (EC2) for running applications on the Amazon Web Services (AWS) infrastructure.
Launch an EC2 instance
Click on Launch Instance to create a new instance.
Run a Linux machine
Choose Amazon Linux from the listed options for machine images.
Choose an Instance Type
We will go for a
t2.micro free instance for the purpose of this example.
Review your EC2 instance
All done! Review your settings.
Create Key Pair
Create a public-private key pair if you desire. This is an optional step but we recommend that you create a key pair and download it. We will be using it later on in the article to SSH into our EC2 instance.
View Launch Status
Good Going! Your instance is up and running.
Edit Security Group
Edit security group settings to allow SSH inbound traffic from your IP address.
Add a custom rule
Take a look at this post if you want to SSH into your EC2 instance programmatically.
How to SSH into an EC2 instance using Boto3
The simplest way to programmatically SSH into an EC2 instance is to using the Paramiko package. In this post, I will…
medium.com
Domain Mapping
Next, you need to create a Hosting Zone where you would configure your DNS settings for the domain name. Here are the steps.
Create a Hosting zone
Click on Create Hosting Zone to get started.
Setup Your Domain
Fill in your Domain Name to create a new hosted zone.
Edit Namespace for your Domain
Once you have created a Hosted zone, you will be able to see associated namespace records for it. Edit these NS records for your domain. I purchased the domain from GoDaddy, so I had to go and edit these records in DNS settings for the domain on GoDaddy’s admin panel.
Add a A Record
Coming back to your Hosted Zone, create a new A record. Leave the Name field empty if you don’t want to configure just for a particular subdomain.
That’s it. Your Hosted Zone is now set up. You can also set up a subdomain in 4 easy steps by following this step by step guide.
How to Create a Subdomain in Amazon Route 53?
Step 1: Make a hosted zone for your original domain
medium.com
Create a Load Balancer
Next, you need to create a Load Balancer for your EC2 instance. As described by Wikipedia,
In computing, load balancing improves the distribution of workloads across multiple computing resources, such as computers, a computer cluster, network links, central processing units, or disk drives.
Create a Classic Load Balancer
Choose a Classic Load balancer which is used for HTTP, HTTPS and TCP traffic.
Follow the wizard to complete the Load Balancer settings.
Define Load Balancer Properties
Define its name and protocol as depicted in the section below.
Assign Security Groups
Assign security groups to the load balancer. Create a new security group for your load balancer that allows traffic from any IP address.
Set Load balancer’s security group to the newly created one.
Setup Health Checks
Setup health checks. Again you and go ahead with the default options as of now. We can revisit these settings later.
Map with an EC2 instance
Choose the EC2 instance that you created earlier for the load balancer.
Create tags
Tags are optional and help to identify your resources.
All done! Your load balancer is now set up.
Edit Inbound Rules for EC2 instance
Go back to your EC2 instance and add a new inbound rule for it. This will allow all traffic from the load balancer.
Now your EC2 instance, hosting zone, and load balancer are all setup. We will go ahead and install a LAMP web server on our EC2 instance.
Connect to your Instance
- Open an SSH client
- Locate your private key file and provide permissions
chmod 400 amazon_ec2_key.pem
- Connect to your EC2 instance
ssh -i "amazon_ec2_key.pem" ec2-user@ec2-13-127-42-0.ap-south-1.compute.amazonaws.com
Install a LAMP webserver
- Check if software packages are up to date.
sudo yum update -y
- Install the packages for php and mysql.
sudo yum install -y httpd24 php70 mysql56-server php70-mysqlnd
- Start the http server
sudo service httpd start
- Create a
health.htmlfile in
cd/var/www/html. Put any content in the file and save it.
nano health.html
- Edit health check settings for your load balancer.
Now you should be able to see the test page when you hit the domain.
Set File Permissions for your User
Run the following commands to set file permissions.
sudo usermod -a -G apache ec2-user
sudo chown -R ec2-user:apache /var/www
sudo chmod 2775 /var/www
find /var/www -type d -exec sudo chmod 2775 {} \;
find /var/www -type f -exec sudo chmod 0664 {} \;
Test your LAMP server
Create a PHP file in Apache document root.
echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
Secure the MySQL server
- Start MySQL server.
sudo service mysqld start
- Run
mysql_secure_installationand set root password, remove anonymous user accounts, disable remote root login, remove the test database, reload the privilege tables.
sudo mysql_secure_installation
Install phpMyAdmin
Run the following commands to setup phpMyAdmin.
sudo yum install php70-mbstring.x86_64 php70-zip.x86_64 -ysudo service httpd restartcd /var/www/htmlwget -xvzf phpMyAdmin-latest-all-languages.tar.gzmv phpMyAdmin-4.7.6-all-languages phpMyAdminsudo service mysqld start
Special thanks to Chetan Gulati who helped me set it up.
All done! Now your web server is up and running. We will cover the configuration of YOURLS on this web server in the next story. | https://maskaravivek.medium.com/web-hosting-using-php-and-mysql-on-aws-95bd5df0bd75 | CC-MAIN-2021-04 | refinedweb | 1,107 | 66.13 |
So this is kind of repost as I had already posted this at StackOverflow but I thought it might have some merit here. Whatever. Charts are hot right now so I’m going to push the damned bandwagon. You don’t like it? Well then go do something to yourself that you would consider rude for me to suggest it. Anyways, this might have been overkill but hey, that’s me.
protected void Page_Load(object sender, EventArgs e) { Bench benchList; FoodIntake foodIntakeList; Panel panelChartHolder; panelChartHolder = new Panel(); Controls.Add(panelChartHolder); benchList = Bench.GetAll(); AddNewCharts(benchList, panelChartHolder, GetBenchXValue, GetBenchYValue); foodIntakeList = FoodIntake.GetAll(); AddNewCharts(foodIntakeList, panelChartHolder, GetFoodIntakeXValue, GetFoodIntakeYValue); }
Ok so this first part is simple. Create a panel to hold the charts you are adding, get the lists you want represented by the charts and call the method to create the charts.
private void AddNewCharts(T[] listToAdd, Panel panelToAddTo, Func<T, DateTime> xMethod, Func<T, Int32>) { ChartArea mainArea; Chart mainChart; Series mainSeries; mainChart = new Chart(); mainSeries = new Series("MainSeries"); for (Int32 loopCounter = 0; loopCounter < listToAdd.Length; loopCounter++) { mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]), yMethod(listToAdd[loopCounter])); } mainChart.Series.Add(mainSeries); mainArea = new ChartArea("MainArea"); mainChart.ChartAreas.Add(mainArea); panelToAddTo.Controls.Add(mainChart); }
As you can see, I just created a new chart, added a series to it, and added a ChartArea to it. Next part is pretty much just looping through the collection and adding each item in it to the list itself. It uses the passed in delegate methods (Func) to get the X and Y values.
Last part holds the four methods responsible for getting the X and Y values from the two lists. Basically I did this to allow the chart creating method to be a generic as possible. Might be overkill.
private DateTime GetBenchXValue(Bench currentBench) { return currentBench.DateLifted; } private Int32 GetBenchYValue(Bench currentBench) { return currentBench.BenchAmount; } private DateTime GetFoodIntakeXValue(FoodIntake currentIntake) { return currentIntake.DateEaten; } private Int32 GetFoodIntakeYValue(FoodIntake currentIntake) { return currentIntake.Calories; }
And so when you run this, you will get two graphs side by side. Mind you, they will be very plain as there are million different properties that can be set to improve the look. I guess the main point of this was to show that it’s pretty easy to create graphs dynamically using any kind of object list. You know what? Screw you. This is my blog and I’ll post whatever I want to. If you don’t like that then you can just come back at a later time and read something else I post. Yeah so there.
using System; using System.Web.UI.DataVisualization.Charting; using System.Web.UI.WebControls; | http://byatool.com/tag/charting/ | CC-MAIN-2019-47 | refinedweb | 440 | 59.5 |
Platform Invocation Services.
An important and unique feature of Managed Extensions for C++ is that you can use unmanaged APIs directly. Data marshaling is handled automatically. If you do not require customized data marshaling, you do not need to use PInvoke.
The Managed Extensions for C++ program. The native function
puts is defined in
msvcrt.dll. The
DllImport attribute is used for the declaration of
puts.
Example
Output
The following version of the same example shows IJW in action.
Example
Output
The example illustrates some of the advantages and disadvantages of both methods.
Advantages of IJW
- There is no need to write
DLLImportattribute since that is done explicitly by the developer).
- It clearly illustrates performance issues. In this case, the fact that you are translating from a Unicode string to an ANSI string and that you have an attendant memory allocation and deallocation. For example, in this case, a developer writing the code using IJW would realize that calling
_putwsand using
PtrToStringCharswould be better for performance.
- If you need to call many unmanaged APIs using the same data, marshaling it once up front and passing the marshaled copy around is much more efficient than re-marshaling every time.
Disadvantages of IJW
- Marshaling needs to be specified explicitly in code rather than by attributes (which in many cases like this one have suitable defaults).
- The marshaling code is inline, where it is more invasive in the flow of the application logic.
- Since the explicit marshaling APIs return
IntPtrtypes for 32-bit to 64-bit portability, extra
ToPointercalls need to be used.
Like many places in Managed Extensions, the specific method exposed by Managed Extensions is the more efficient, explicit method, at the cost of some additional complexity.
If the application uses mainly unmanaged data types or if it calls more unmanaged APIs than .NET Framework APIs, using the IJW feature will generally be preferable. To call an occasional unmanaged API in a mostly managed application, the choice is more subtle.
Marshaling Arguments
With PInvoke, no marshaling is required between managed and C++ native primitive types with the same form. For example, no marshaling is required between
Int32 and
int, and
Double and
double.
Marshaling is required.
Marshaling information for individual arguments of a native function can be specified using the
MarshalAs attribute. There are several choices for marshaling a
String * argument:
BStr,
ANSIBStr,
TBStr,
LPStr,
LPWStr, and
LPTStr. The default is
LPStr.
Example
Output
In this example, the string is marshaled as a double-byte Unicode character string,
LPWStr. The output is just the first letter of
Hello World! because the second byte of the marshaled string is null, and
puts interprets this as the end-of-string marker.
The
MarshalAs attribute is in the
System::Runtime::InteropServices namespace. The attribute can be used with other data types such as arrays.
PInvoke with Windows APIs
PInvoke is also convenient for calling functions in Windows.
In this example, a Managed Extensions program interoperates with the
MessageBox function that is part of the Win32 API.
Example
#using <mscorlib.d = S"Hello World! "; String * pCaption = S"PInvoke Test"; MessageBox(0, pText, pCaption, 0); }
The output is a message box with the title
PInvoke Test and the text
Hello World! in it., using Unicode versions of unmanaged APIs should be preferred because that eliminates the translation overhead from the native Unicode format of .NET Framework string objects to ANSI.
When Not to Use PInvoke
Using PInvoke is not suitable for all C-style functions in DLLs. For example, suppose there is a function
MakeSpecial in
mylib.dll declared as follows.
If we use PInvoke in a Managed Extensions application, we might write something similar to:
The difficulty here is that we cannot delete the memory for the unmanaged string returned by
MakeSpecial. Other functions called via PInvoke return a pointer to an internal buffer that does not need to be deallocated by the user. In this case, using the IJW feature is the obvious choice.
Performance Considerations higher performance, it may be necessary to have fewer PInvoke calls that marshal as much data as possible, rather than have more calls that marshal less data per call. Or somewhat more memorably: prefer a chunky over a chatty API. | https://msdn.microsoft.com/en-us/library/aa712982(v=vs.71).aspx | CC-MAIN-2015-11 | refinedweb | 702 | 56.66 |
Opened 4 years ago
Closed 4 years ago
#16853 closed Bug (duplicate)
Slugify removes dotless "i"
Description
Hi,
As a Turkish Django user, I need to use slugify with strings containing Turkish dotless i. As most Turkish developers, I also expect it to convert that character to ascii "i", however, It just disappears in resulting string. As for now, I am using a workaround I have found in here:
Here is the workaround I currently use:
def slugify_unicode(value): value = value.replace(u'\u0131', 'i') value = normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(sub('[^\w\s-]', '', value).strip().lower()) return sub('[-\s]+', '-', value)
Change History (1)
comment:1 Changed 4 years ago by ptone
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Resolution set to duplicate
- Status changed from new to closed
Note: See TracTickets for help on using tickets.
This seems more of a specific case of #8391, it would be worth adding your notes to that ticket. There are several approaches on that ticket that try to solve this problem more generally | https://code.djangoproject.com/ticket/16853 | CC-MAIN-2015-48 | refinedweb | 177 | 50.77 |
With much of the drilling to be done in deep-water blocks, senior RIL officials say the costs are high and add that it is risky to make additional spends till there is more certainty on gas pricing. To find substantial gas reserves, deep-water drilling is the only option, an RIL official said. RILs apprehensions stem from the fact that the formula for arriving at the price of gas, as proposed by the Rangarajan Committee, will not result in a market-related price. The committee has suggested a formula that takes into account the average of the imported price of LNG into India and the weighted average benchmark prices in North America, Europe and Japan. RIL officials say it costs R700 crore to develop one deep-water well.
Cairn India Indias biggest private sector crude oil explorer and ONGC are, however, keen to participate. P Elango, CEO, Cairn India said: For us, the policy has been conducive and we will keenly look at the NELP X round. Sudhir Vasudeva, chairman, ONGC, is confident that the government will resolve any issues relating to policy uncertainty. It is not mandatory for us to participate in NELP and we will do so only if the blocks on offer have good prospects, Vasudeva told FE.
Going by current price trends, globally, the Rangarajan formula would throw up a price of $8.4 mmBtu (million metric British thermal units). However, RIL believes a market-linked price should be arrived at by the producer floating tenders and calling for bids. RIL is non-committal on whether whether a price of $8.4 mmBtu would be remunerative enough for it to invest.
Analysts estimate a minimum price of $10 mmBtu might be needed to ensure an assured internal rate of return (IRR) of 30%. A presentation by IHS CERA, a US-based independent energy research firm, says 91 trillion cubic feet (tcf) of reserves remain unexplored across12 main sedimentary basins in India. Of this, 53 tcf is in deep-water and ultra deep-water, 85% of which can only be viable at over $10 per mmBtu.
How much participation there will be in NELP X from overseas players is hard to gauge. Foreign explorers were absent in NELP IX while NELP VIII saw Cairn, BG and BHP Billiton putting in bids. Foreign players have been bidding for blocks in India since NELP II although they skipped NELP III.
Under NELP X, the government is expected to auction 86 hydrocarbon-bearing acreages; 58 have received clearances environment and clearances. On a visit to Mumbai last month to woo foreign explorers, petroleum minister M Veerappa Moily conceded several of them had raised some short term concerns which he said would be addressed in two months. Petroleum secretary Vivek Rae had indicated that investors were apprehensive about the stability of the terms of production sharing contracts (PSC). Moreover, explorers, Rae said, had requested that gas be classified as a mineral oil in order that it attracted the same levies as crude oil. Explorers also want that the PSC should be based on the cost recovery model rather than the government-proposed revenue sharing model.. | http://www.financialexpress.com/archive/cagey-after-kg-ril-to-skip-next-nelp-cairn-ongc-keen/1209285/ | CC-MAIN-2016-30 | refinedweb | 525 | 59.13 |
NuGet - Manage Project Libraries with NuGet
By Phil Haack | November 2011
Try as it might, Microsoft can’t supply every possible library developers need. Though Microsoft employs close to 90,000 people worldwide, the world has millions of developers. It doesn’t make sense for Microsoft to attempt to fill every niche, nor does it scale. Developers, therefore, frequently take it upon themselves to “scratch their own itch,” and they’ve written thousands upon thousands of useful libraries that are distributed all over the Web.
The problem with so many libraries out there is sharing them. Sharing and reusing code is a big challenge. Don’t believe me? Walk into any midsize to large shop and ask them how many logging libraries they have. Visit enough companies and you’ll find a high percentage of in-house logging libraries when good ones—Log4Net, NLog and Error Logging Modules and Handlers, or ELMAH—already exist.
When a developer starts a new project, he faces the empty canvas problem. How can he find these useful libraries? How does he incorporate a library into his current project and manage its dependencies and updates?
ELMAH is a great example of a useful library that developers took upon themselves to write. ELMAH logs all unhandled exceptions within a Web application along with all the request information, such as headers, server variables and so on, when the exception is thrown. Suppose you’ve just heard about ELMAH and want to use it in your next project.
These are the steps you might take:
- Find ELMAH. Due to its unique name, a Bing search locates the ELMAH Google code page as the first result.
- Download the correct zip package. The download page for the site has multiple zip packages. You have to think about it and pick the correct one. Sometimes the correct choice isn’t intuitive.
- “Unblock” the package. Once you’ve downloaded the package from the Web, you need to right-click the file, bring up the Properties dialog and click the Unblock button to remove the “mark of the Web” from the file.
- Verify its hash against the one provided by the hosting environment. The Google code site displays a QR code representing the zip file. How many developers do you know who take the time to verify the file against the QR code?
- Unzip the package contents into a specific location in the solution. Most developers avoid unpacking assemblies into the bin directory, because the directory is meant for output from the build, not for input, and isn’t tracked by version control. Instead, it’s important to add the dependency to a folder that’s committed to version control and reference the assembly from that location.
- Add an assembly reference to the project.The assembly isn’t usable until you add a reference to it from within the Visual Studio project.
- Update web.config with the correct settings.This may mean more searching around using Bing or Google while you try to find the correct settings needed for your config file.
What a pain! Now suppose you have to do this for 10 to 15 dependencies. When it comes time to release the next version of your application, you spend significant time searching for updates to your application’s dependencies.
That often-maligned notion, “not invented here” (NIH), begins to sound like a good idea.
NuGet to the Rescue.
OPC is just a fancy acronym for a zip file with some metadata. In fact, you’re probably already familiar with OPC, as it’s the format used by Word and Excel documents. If you’ve ever taken a .docx file and changed the file extension to .zip, you know you can open it up and poke around its internals. The same goes for .nupkg files.
The NuGet product also comes with utilities to easily create and publish packages. For now, I’ll focus on using NuGet to discover and install packages. Later I’ll cover how to create and publish packages.
Installing NuGet
To install NuGet, launch the Visual Studio Extension Manager via the Tools | Extension Manager menu option. Click the Online Gallery tab to view available Visual Studio extensions, as shown in Figure 1. As you can see, NuGet is the highest-ranked package, which puts it on the first screen. If that ever changes, you can use the search box on the top right to find it. Click the Download button to install NuGet.
Figure 1 Visual Studio Extension Manager
If you’ve installed ASP.NET MVC 3, you already have NuGet installed. ASP.NET MVC 3 includes NuGet, and Microsoft plans to include NuGet in the next version of Visual Studio.
Installing a Package
Let’s start with NuGet’s user-friendly dialog to install packages. NuGet also comes with a Windows PowerShell-based console geared toward power users that I’ll cover later.
To launch NuGet, right-click on the project’s references node and select the Manage NuGet Packages option (this option had a different label prior to NuGet 1.4). This launches the Manage NuGet Packages dialog shown in Figure 2.
Figure 2 NuGet Package Manager Dialog
Make sure the Online tab is selected and type in a search term in the top right (for example, search for MiniProfiler, a useful library from the StackOverflow.com folks).
Once you locate a package, click the Install button to install the package. NuGet then downloads the package and its dependencies and applies any necessary changes to your project specified by the packages.
NuGet performs the following steps to install a package:
- Downloads the package file and all its dependencies. Some packages require explicit license acceptance and prompt the user to accept the license terms for the package. Most packages are fine with implicit license acceptance and do not prompt. If the package already exists in the solution or in the local machine cache, NuGet skips downloading the package.
- Extracts the package’s contents. NuGet extracts the contents into the packages folder, creating the folder if necessary. The packages folder is located next to your solution (.sln) file. If the same package is installed into multiple projects within a solution, the package is only extracted once and is shared by each project.
- References assemblies in the package. By convention, NuGet updates the project to reference the appropriate assembly (or assemblies) within the packages lib folder. For example, when installing a package into a project targeting the Microsoft .NET Framework 4, NuGet will add references to assemblies within the lib/net40 folder.
- Copies content into the project. By convention, NuGet copies the package’s content folder’s contents into the project. This is useful for packages containing JavaScript files or images.
- Applies package transformations. If any package contains transform files, such as app.config.transform or web.config.transform for config, NuGet applies those transformations before it copies the content. Some packages may contain source code that can be transformed to include the current project’s namespace in the source file. NuGet transforms those files as well.
- Runs associated Windows PowerShell scripts in the package. Some packages may contain Windows PowerShell scripts that automate Visual Studio using the Design Time Environment (DTE) to handle tasks NuGet isn’t designed for.
After NuGet performs all these steps, the library is ready for use. Many packages wire themselves up using the WebActivator package to minimize any configuration necessary after installation.
A package can be uninstalled, which returns your project to the state it was in before installing the package.
Updating Packages
In his book, “Facts and Fallacies of Software Engineering” (Addison-Wesley Professional, 2002), Robert L. Glass states: “Maintenance typically consumes about 40 to 80 percent (60percent average) of software costs. Therefore, it is probably the most important lifecycle phase.”
Installing a package is only the beginning of the story. Over time, as these libraries are maintained, it becomes important to keep your application up-to-date with the latest bug fixes for the libraries. This requires you to answer the question, “Which dependencies in this project have new updates available?”
As mentioned before, answering this question has always been a time-consuming endeavor. With NuGet, however, you simply launch the dialog and click on the Updates tab to see a list of packages with available updates, as shown in Figure 3. Click the Update button to update the package to the latest version.
Figure 3 Updates Available for the Current Project
The update command uninstalls the old package and then installs the new one, ensuring all dependencies are updated appropriately if needed.
NuGet provides commands in the Package Manager Console to better control updates—such as to update all packages in the solution or to perform a “safe” update, for example.
NuGet for Power Users
While I’m a big fan of nice GUI dialogs, I know many developers who disdain mouse-dragging people like me. Those folks prefer a command-line shell as the UI for its ability to compose sets of commands together.
NuGet fills this need with a Windows PowerShell-based console window called the Package Manager Console, as well as a set of Windows PowerShell commands for interacting with NuGet. Windows PowerShell, a .NET-based scripting language and command-line shell, is well-suited for composing command sets and working with objects.
To launch the Package Manager Console, navigate to the Tools | Library Package Manager | Package Manager Console menu option.
Listing and Installing Packages
To list and search for packages, use the Get-Package command. By default, the command lists installed packages in the current project. You can search for packages online by specifying the ListAvailable flag combined with the Filter flag. The following command searches for all packages mentioning “MVC”:
Get-Package -ListAvailable -Filter Mvc
Once you find a package to install, use the Install-Package command. For example, to install ELMAH into the current project:
Install-Package Elmah
Because Windows PowerShell is a dynamic language, it can provide tab expansions to help you correctly enter command arguments. Tab expansions are equivalent to IntelliSense for C# but, unlike IntelliSense, which is based on compile-time information, tab expansions can be populated at run time.
For example, if you type in Install-Package Mvc{tab}, you’ll see a list of possible package names from the package source, as shown in Figure 4.
Figure 4 A Tab-Expanded List of Packages
Updating Packages
The Package Manager Console also includes a command that provides more control over updates than the dialog. For example, call this command with no arguments to update every package in every project of the solution:
Update-Package
This command attempts to update each package to the latest version. Thus, if you have version 1.0 of a package and versions 1.1 and 2.0 are available in the package source, this command will update the package to version 2.0, because it’s the latest.
This can be a drastic action if any package contains breaking changes. In many cases, you’ll just want to update every package to the latest bug fix release. This is called a “safe” update and assumes that packages with a larger build or revision number (but with the same major and minor numbers) are backward-compatible. Just add the Safe flag to perform a safe update, like so:
Update-Package -Safe
In this case, if you have version 1.0.0 of a package installed, and both 1.0.1 and 1.1 are available in the package source, the package is safely upgraded to 1.0.1 and not 1.1.
The Update-Package command also provides more granularity, such as updating a package to a specific version of the package rather than the latest version.
Extending Visual Studio with New Commands
While the ability to use Windows PowerShell to install packages is nice, it’s not the most compelling reason to choose Windows PowerShell. One of the most compelling reasons is that packages can add new commands to the Package Manager Console. These commands can interact with the Visual Studio DTE in order to perform various tasks.
For example, install the MvcScaffolding package and it adds a new Scaffold Controller command to the console. Given an Entity Framework (EF) Code First object, this command generates a controller, controller actions and views corresponding to the basic Create, Read, Update and Delete (CRUD) operations for the EF object, as seen in Figure 5.
Figure 5 MvcScaffolding Custom Scaffold Command in Action
NuGet in Your Organization
With all this focus on how NuGet makes it easy to share libraries with the public developer community, NuGet’s usefulness within the enterprise is easy to miss.
After all, there’s nothing special about businesses that make them immune to the same challenges the software community as a whole faces when sharing code. As a company grows over time, entropy sets in. Different groups within the same company use their own private versions of company “standard” libraries. Some groups may go so far as to completely ignore these libraries and write their own from scratch.
Often, the problem is not the libraries themselves but the hassle in sharing these libraries with other teams and keeping them notified of changes. Sound familiar?
Package Sources
So far, I’ve covered how to install packages, but haven’t answered the obvious question: Where are those packages located? They’re located in the official NuGet package gallery at nuget.org. This gallery exposes an OData feed: packages.nuget.org/v1/FeedService.svc.
The OData format allows the NuGet client to generate ad hoc queries to search the package source on the client, but have them executed on the server.
To add more package sources to NuGet, navigate to the Tools | Library Package Manager | Package Manager Settings menu option and click on the Package Sources node, as seen in Figure 6.
Figure 6 Package Manager Settings
The default package source is an OData endpoint on the Web, but the example screenshot also shows a local folder as a package source. NuGet treats folders (whether local or on a network share) as a package source and lists each package within the folder in the Online pane. This makes sharing code with others as easy as putting it in a folder, and is also helpful when you test packages you create yourself.
Hosting Your Own NuGet Server
In addition to hosting packages on a network share, you can also set up a Web site as a package source and use it to share packages with others across your organization.
As with many tasks, there’s a package that helps here. First, create an empty ASP.NET Web Application in Visual Studio (targeting ASP.NET 4). Use NuGet to install the package NuGet.Server. This package adds a simple OData endpoint to the empty Web application.
Next, add package files to the Web application’s Packages folder to publish them and deploy the Web site. For more details on how to set this up, refer to the NuGet documentation site, bit.ly/jirmLO.
For those who want to deploy a full gallery experience like nuget.org, the NuGet gallery code is also available as an open source project via the nugetgallery.codeplex.com project.
Hosting a private NuGet server or gallery implementation is an easy way to share proprietary code within a company without having to publish it to the public.
Creating a Package
NuGet wouldn’t be useful without any packages to install in the first place. The more useful packages available in NuGet, the more valuable NuGet becomes to every developer. That’s why the NuGet team has gone to great lengths to make creating packages as simple and painless as possible. While it’s easy to create a package, the NuGet team continues to invest in features to make it even simpler. They’ve built several tools for creating NuGet packages. For example, Package Explorer is a ClickOnce application written by a developer on the NuGet team that provides a visual way to build or examine a package. It’s available at npe.codeplex.com.
NuGet.exe
Because most package authors want to integrate package creation into their build processes, let’s look at another approach that uses the NuGet command-line utility. You’ll need to download the utility just once from bit.ly/gmw54b. After you download NuGet.exe, make sure to put it in a folder that’s added to your PATH environment variable. I have a folder named “utils” for utilities like this.
The reason I say you only need to download NuGet.exe once (well, once per machine) is because it’s a self-updating executable. Just run the following command to have NuGet check online and update itself to the latest version if a newer one is available:
nuget update –self
The command-line tool can query the online feed like the Package Manager Console. For example, to search for all packages with “MVC,” use the following command:
nuget list Mvc
NuGet.exe can even download a package and dependencies and unpack them, but it can’t modify a project to reference the downloaded package assemblies or run any Windows PowerShell scripts included in a package.
Creating a Package from a Project
Packages contain a single assembly 90 percent of the time (a statistic I made up). This section covers a simple workflow to create such packages using NuGet.exe against a project file (such as a .csproj or .vbproj file).
For details on creating more complex packages, such as a single package that targets different .NET Framework versions, refer to the NuGet documentation Web site at docs.nuget.org.
The basic steps for creating a package are:
- Create a class library project.
- Generate a NuSpec manifest from the project.
- Update the project’s assembly metadata.
- Use NuGet.exe to create the package.
Create a Class Library Project To share an assembly, start with a class library project. NuGet can pack multiple project types, but the most common case when sharing code is to use a class library. After you create the package, make sure to open the AssemblyInfo.cs file to update the assembly’s metadata.
Create a NuSpec Manifest The NuSpec file is a package manifest with important metadata about the package, such as the author, description and the package dependencies. The NuSpec format is simple to create by hand, but it’s more convenient to let the spec command generate the file for you. Make sure to run the command in the same directory as the project file:
nuget spec
In this particular case, because the spec command generated the NuSpec from a project file, it contains placeholders for some metadata, as shown in Figure 7.
<?xml version="1.0"?> <package xmlns= ""> <metadata> <id>$id$</id> <version>$version$</version> <title>$title$</title> <authors>$author$</authors> <owners>$author$</owners> <licenseUrl></licenseUrl> <projectUrl></projectUrl> <iconUrl></iconUrl> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>$description$</description> <copyright>Copyright 2011</copyright> <tags>Tag1 Tag2</tags> </metadata> </package>
Don’t edit the fields with the placeholders, but do fill in the correct values for the other fields such as licenseUrl, projectUrl, iconUrl and tags.
Update the Project’s Assembly Metadata Every assembly has metadata related to the assembly. NuGet can read this assembly metadata and merge it into the NuSpec manifest when it creates a package, which ensures this information is never out of sync between your package and your assembly.
As mentioned earlier, this information is usually located in a file named AssemblyInfo.cs. The table in Figure 8 shows the mappings between the assembly metadata and the NuSpec placeholder values.
Figure 8 Assembly Metadata Mapped to NuSpec
Unlike the other fields, the $id$ field is not extracted from an assembly attribute, but is set to the assembly name.
Create the Package In the same directory as the project file and NuSpec file, run the following command to create a package:
nuget pack ProjectName.csproj
If you have one project file in the same directory, you can omit the project file name when you run the command.
If you haven’t compiled the project yet, you can use the Build flag to compile the project first, before packing it. This will compile the project first before running the pack command:
nuget pack ProjectName.csproj -Build
This command results in a file named ProjectName.{version}.nupkg, where {version} is the same value specified in the AssemblyVersionAttribute. For example, if the version is 1.0.0, your package will be named ProjectName.1.0.0.nupkg. You can use the Package Explorer to examine the package after the fact to ensure it’s been created correctly.
As a courtesy to developers who will install your package, consider using the Symbols flag to create a package with debugger symbols:
nuget pack ProjectName.csproj -Build -Symbols
This command creates a symbols package in addition to the main package. This allows others who install your package to step into the package code when they debug their application.
Publishing a Package
After you create a package, you’ll probably want to share it with the world. NuGet.exe has a publish command for just this purpose. Before you publish, you’ll need to create an account on nuget.org.
When you’ve registered for an account, click on the link to your account to see your access key. This key is important as it identifies the nuget.exe command to the gallery and is a revocable password.
Once you have your key, store it in a secure location using the following command:
nuget setApiKey b688a925-0956-40a0-8327-ff2251cf5f9a
With this in place, use the push command to publish your package to the gallery:
nuget push ProjectName.1.0.0.nupkg
The command validates your API key with the gallery before it uploads the package. If you created a symbols package as we discussed earlier, you should specify the Symbols flag when you push your package:
nuget push ProjectName.1.0.0.nupkg -Symbols
Be sure to specify the main package name and not the symbols package name. The command finds the appropriate symbols package by convention. The command pushes the main package to the NuGet gallery and the symbols package to the partner symbolsource.org repository.
What’s Next
In this article, I demonstrated how NuGet pulls in useful libraries from the NuGet gallery to jump-start new project development. Within enterprises, NuGet is useful for sharing code among various developers in an organization.
But there’s one persistent misperception about NuGet I need to address—that NuGet is only for Web developers. This misperception is probably due to its inclusion with the ASP.NET MVC 3 release, but it’s simply not true. NuGet is not just for Web developers—it’s for all developers. NuGet supports Windows Phone, Silverlight and Windows Presentation Foundation, among other project types, and will support new project types in the future.
NuGet is a community-driven open source project licensed under the Apache 2 license. The project belongs to the Outercurve Foundation but is incorporated into Microsoft products and counts several Microsoft developers as core contributors.
To help in NuGet’s development, visit nuget.codeplex.com to learn about how to get involved and maybe even contribute to NuGet.
This article only scratches the surface of what’s possible with NuGet. To learn more, visit the NuGet documentation Web site at docs.nuget.org (the team works hard to maintain this and accepts contributions to its documentation). The team is active in the CodePlex discussions forum for the NuGet project and welcomes your questions.
Phil Haack works for Microsoft as a senior program manager on the ASP.NET team aiming to build great products for developers. While he delves into many areas of ASP.NET, his primary projects are ASP.NET MVC and NuGet Package Manager, both released under an OSS license. In his spare time, he writes about software on his blog, haacked.com, and works on the Subtext open source blog engine.
Thanks to the following technical expert for reviewing this article: David Fowler
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus. | https://msdn.microsoft.com/en-gb/magazine/hh547106.aspx | CC-MAIN-2019-35 | refinedweb | 4,046 | 55.54 |
ASP.NET has a little-known feature that allows you to easily implement what is known as an HTTP Handler. Basically, when a request for a page comes into ASP.NET, eventually that request is handled by an object that implements the IHttpHandler interface. This interface includes a method called "ProcessRequest" that is responsible for writing all of the page content to the HttpContext.Response.Output stream. ASHX files allow you to easily write the IHttpHandler class without even having to pre-compile it. I used ASHX files in a recent project (coming soon) to retrieve images out of a SQL database. Here's how I did it.
You need to create a file in your project with an ASHX extension. I'm retrieving data from the Employees table of the Northwind sample database, so I called my page NWEmpPhoto.ashx. The contents of the ASHX file are as follows:
<%@ webhandler language="C#" class="NWEmpPhotoHandler" %> using System; using System.Web; using System.Data; using System.Data.SqlClient; public class NWEmpPhotoHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext ctx) { string id = ctx.Request.QueryString["id"]; SqlConnection con = new SqlConnection(<<INSERT CONNECTION STRING HERE>>); SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @EmpID", con); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@EmpID", id); con.Open(); byte[] pict = (byte[])cmd.ExecuteScalar(); con.Close(); ctx.Response.ContentType = "image/bmp"; ctx.Response.OutputStream.Write(pict, 78, pict.Length - 78); } }
As you can see, it's basically source code with the special <% webhandler %> tag at the top. The class implements two methods - IsReusable and ProcessRequest. IsReusable is for handler pooling, and as far as I can tell can be safely hard coded to return true, at least in this scenario. The ProcessRequest method implements the database access. It does some fairly straight forward ADO.NET to retrieve the image from the DB as a byte array. The primary key to the query is passed in on the query string. I'm using ExecuteScalar since I'm retrieving a single column from a single row. The photo column is returned as a byte array. We set the Response's correct content type (image/bmp in this case) and write the byte array containing the picture to the Response.OutputStream. By the way, the 78 byte offset is Northwind database specific. I'm not sure why the bitmap starts 78 bytes into the blob, but I was clued into the fact by an article by Dino Esposito .
To use the NW Photo Handler, you simply use an HTML image tag. Since the primary key is passed in on the query string, you need to include it as the src attribute of the image tag. Here's an example of the image tag:
<img src="NWEmpPhoto.ashx?id=1" /> | https://www.developerfusion.com/code/5223/using-ashx-files-to-retrieve-db-images/ | CC-MAIN-2019-22 | refinedweb | 466 | 58.69 |
I am not a heavy SOAP user, but as a programmer when my program is acting as
a client, I would perhaps like it to use SOAP in 3 different ways --
1. Make an SOAP RPC call from an XSP, preferrably with a syntax like:
...
...
I should be able to use arbitrary objects as arguments and return values.
Also, I would expect information about encoding style, namespaces, transport
binding etc. to be taken from configuration files or supplied by the
logicsheet.
2. Send a SOAP message and receive a response ( synchronous send ),
preferrably
with a syntax like:
... |
...
It may be possible to provide convenience tags to construct a SOAP
envelop, header fields and the body, but the programmer should have the
flexibility to build the packet in any other way possible well. Same goes
for response message ( though the convenience tags here would extract fields
from a response ).
3. Send a SOAP message asynchronously, preferrably with a syntax like:
... |
Should this functionality be available as logicsheet or a transformer?
Probably both. Logicsheet will work fine as long as I am writing an XSP that
gets compiled during generation phase but what if I inject these tags as a
result of an XSLT transformation in the middle of the Cocoon processing
pipeline? ( should that be allowed at all ? )
Haven't thought about how should a server receive a SOAP message. A straight
forward answer would seem to be a SOAP generator, but may be there is a
better way with actions ( need to understand this !! ). How about hooking up
with a SOAP server for processing SOAP message in the generator the same way
as the JSP generator hooks up with Jasper for document generation !!
Pankaj.
> -----Original Message-----
> From: Michael Homeijer [mailto:M.Homeijer@devote.nl]
> Sent: Sunday, June 03, 2001 3:23 AM
> To: 'CARLTON,NADINE (HP-Cupertino,ex1) '
> Cc: ''cocoon-dev@xml.apache.org' '
> Subject: RE: SOAP client and server
>
>
> Hi,
>
> The implementation I sent to the list was meant to get some
> comment on how
> soap should be implemented in C2.
>
> I think my prototype gives a basic understanding about what
> should be done
> to implement a soap client and a soap server in C2. I think
> you'r right that
> some design decisions have to be made.
>
> One of them is what components have to be implemented, you
> talk about a SAX
> state machine, Giacomo talks about Avalon components (or
> could these be the
> same?). My understanding of C2 or Avalon doesn't go that far
> that I can make
> such a decision.
>
> The other is weather to use the C1 soap syntax from Uli. My
> reason not to
> was that the syntax should be used for both the client and
> the server and
> imho Uli's syntax was aimed at the client. Another reason is
> that at the
> basis of SOAP, there are response and request envelopes that
> you sent to a
> client or server, you can just copy those envelopes from
> xmethods.com and
> implement, replace or call a soap service.
>
> Michael Homeij | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200106.mbox/raw/%3CA5374D237E78D41195810090279CC91A026D2886@xcup04.cup.hp.com%3E/ | CC-MAIN-2014-10 | refinedweb | 507 | 69.31 |
I'm interested in implementing coverage support for my plugin, but I'm not sure what the best way to proceed is. I've read the mega-thread here:, but I'm hoping to avoid implementing everything since my language (Clojure) is a JVM language. I looked at what Kotlin does, and it seems that they only need to register a JavaCoverageEngineExtension. I tried that and have breakpoints in my code and in JavaCoverageEngine, but they're not being hit. My extension is deemed applicable since my run configuration implements CommonJavaRunConfigurationParameters, and for example isSourceMapNeeded() is called.
I suspect that this problem is because Clojure is an unusual JVM language. It's not class-based, although obviously everything compiles to class files in the end. So my files don't implement PsiClassOwner, and my elements don't implement PsiClass. The names of the classes are also not deterministic from a particular source file, so I can't figure out for a particular PsiFile what the classes that will be produced are. It seems like the Java coverage stuff is all built around these assumptions. Many Clojure projects include code in Java or other JVM languages, so I'd like a coverage run to be able to annotate coverage from both Clojure and e.g. Java, so I don't want to reimplement all the coverage infrastructure as if it were a totally new language. Is there a way I can integrate Clojure without doing that?
Hi Colin,
as Clojure is JVM based language you can reuse existing instrumenters which collect line coverage for the jvm classes. Can you get that work through existing JavaCoverageEngine? I guess you would need custom `com.intellij.coverage.JavaCoverageEngine#createCoverageViewExtension` as it shows package/class structure which is not applicable and you would need to override methods to get source/class mappings (I think, it must be possible as you have debugger, don't you?). Then if you register your inheritor of JavaCoverageEngine before default one, it should be used for your configurations.
I am sure there would be a lot of small problems here and there though in general it should somehow work
Anna
Thanks for the prompt response, Anna. I gave this a try - I created a ClojureCoverageEngine inheriting from JavaCoverageEngine, and a ClojureCoverageViewExension inheriting from JavaCoverageViewExtension. My plan with all these classes was to intercept the methods, check if it looks like the call is relevant to the Clojure portion of the user's code, and if not then delegate to the superclass so that the coverage will also work for their Java code. However I can't do this for the annotator - I tried to create a ClojureCoverageAnnotator extending JavaCoverageAnnotator, but that class is final. I then tried to use delegation, but that doesn't work because JavaCoverageAnnotator.createRenewRequest() is protected and also because I need a JavaCoverageAnnotator to pass to the JavaCoverageViewExtension constructor. I handled the second problem by passing the delegate to the constructor instead of my annotator, but that starts feeling pretty risky and I'm unsure of the implications. I also can't seem to fix the first problem - I can't just copy the code because it updates private data structures, and there's no good way for me to call it. Do you have any suggestions here?
I don't think you can get much useful stuff from `JavaCoverageViewExtension` or `JavaCoverageAnnotator` because they are connected to `PsiClass` too closely. So I'd use base classes instead. From the first glance there should be no problems with that.
Anna
The main thing I wanted to achieve with that was to be able to provide coverage info for Clojure and Java from the same run configuration, since Clojure projects are often polyglot JVM projects. If I don't use those classes at all then users will not see coverage for Java, correct?
Complicated. But generally that's true. What entries do you expect in coverage view?
In the coverage view I think users would expect to see namespace coverage (namespaces are also shown in the project view and would probably have coverage against them), and possibly function coverage too - these are roughly analogous to package and class coverage. My plan was to create my own classes but delegate to the Java ones if I can identify that the information doesn't relate to Clojure code. I'm not sure how what information comes back from the coverage agent yet, so perhaps my first step is to implement the Clojure-only coverage as you suggest and then to think about how to mix that presentation with the Java coverage, if that's even possible. It seems like the best thing would be to separate the class-based coverage info from e.g. Java and the namespace-based coverage from Clojure, perhaps into separate trees in the toolwindow. I have no idea if that's possible though.
From coverage agent you'll get ClassData objects which represent jvm classes with information about covered lines. If you are going to implement class wrappers, then probably inheritance would be your good choice indeed. As for JavaCoverageAnnotator: looks like you'll need it as is if you'll be able to map jvm classes to your wrappers. | https://intellij-support.jetbrains.com/hc/en-us/community/posts/360009995240-Coverage-integration-for-unusual-JVM-language | CC-MAIN-2021-39 | refinedweb | 875 | 51.89 |
I am trying to pass in a JSON file and convert the data into a dictionary.
So far, this is what I have done:
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)
json1_data
dict
list
type(json1_data)
Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:
json1_data = json.loads(json1_str)[0]
Now you can access the data stored in datapoints just as you were expecting:
datapoints = json1_data['datapoints']
I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?
datapoints[0:5][0] doesn't do what you're expecting.
datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding
[0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:
[p[0] for p in datapoints[0:5]]
Here's a simple way to calculate the mean:
sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8
If you're willing to install NumPy, then it's even easier:
import numpy json1_file = open('json1') json1_str = json1_file.read() json1_data = json.loads(json1_str)[0] datapoints = numpy.array(json1_data['datapoints']) avg = datapoints[0:5,0].mean() # avg is now 35.8
Using the
, operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices. | https://codedump.io/share/UrbKwCU85wHo/1/converting-json-string-to-dictionary-not-list | CC-MAIN-2017-43 | refinedweb | 326 | 64.3 |
Circus can bind network sockets and manage them as it does for processes.
The main idea is that a child process that’s created by Circus to run one of the watcher’s command can inherit from all the opened file descriptors.
That’s how Apache or Unicorn works, and many other tools out there.
The goal of having sockets managed by Circus is to be able to manage network applications in Circus exactly like other applications.
For example, if you use Circus with Chaussette – a WGSI server, you can get a very fast web server running and manage “Web Workers” in Circus as you would do for any other process.
Splitting the socket managment from the network application itself offers a lot of opportunities to scale and manage your stack.
The gist of the feature is done by binding the socket and start listening to it in circusd:
import socket sock = socket.socket(FAMILY, TYPE) sock.bind((HOST, PORT)) sock.listen(BACKLOG) fd = sock.fileno()
Circus then keeps track of all the opened fds, and let the processes it runs as children have access to them if they want.
If you create a small Python network script that you intend to run in Circus, it could look like this:
import socket import sys fd = int(sys.argv[1]) # getting the FD from circus sock = socket.fromfd(fd, FAMILY, TYPE) # dealing with one request at a time while True: conn, addr = sock.accept() request = conn.recv(1024) .. do something .. conn.sendall(response) conn.close()
Then Circus could run like this:
[circus] check_delay = 5 endpoint = tcp://127.0.0.1:5555 pubsub_endpoint = tcp://127.0.0.1:5556 stats_endpoint = tcp://127.0.0.1:5557 [watcher:dummy] cmd = mycoolscript $(circus.sockets.foo) use_sockets = True warmup_delay = 0 numprocesses = 5 [socket:foo] host = 127.0.0.1 port = 8888
$(circus.sockets.foo) will be replaced by the FD value once the socket is created and bound on the 8888 port.
Chaussette is the perfect Circus companion if you want to run your WSGI application.
Once it’s installed, running 5 meinheld workers can be done by creating a socket and calling the chaussette command in a worker, like this:
[circus] endpoint = tcp://127.0.0.1:5555 pubsub_endpoint = tcp://127.0.0.1:5556 stats_endpoint = tcp://127.0.0.1:5557 [watcher:web] cmd = chaussette --fd $(circus.sockets.web) --backend meinheld mycool.app use_sockets = True numprocesses = 5 [socket:web] host = 0.0.0.0 port = 8000
We did not publish benchmarks yet, but a Web cluster managed by Circus with a Gevent or Meinheld backend is as fast as any pre-fork WSGI server out there.
In a classical WSGI stack, you have a server like Gunicorn that serves on a port or an unix socket and is usually deployed behind a web server like Nginx:
Clients call Nginx, which reverse proxies all the calls to Gunicorn.
If you want to make sure the Gunicorn process stays up and running, you have to use a program like Supervisord or upstart.
Gunicorn in turn watches for its processes (“workers”).
In other words you are using two levels of process managment. One that you manage and control (supervisord), and a second one that you have to manage in a different UI, with a different philosophy and less control over what’s going on (the wsgi server’s one)
This is true for Gunicorn and most multi-processes WSGI servers out there I know about. uWsgi is a bit different as it offers plethoras of options.
But if you want to add a Redis server in your stack, you will end up with managing your stack processes in two different places.
Circus’ approach on this is to manage processes and sockets.
A Circus stack can look like this:
So, like Gunicorn, Circus is able to bind a socket that will be proxied by Nginx. Circus don’t deal with the requests but simply binds the socket. It’s then up to a web worker process to accept connections on the socket and do the work.
It provides equivalent features than Supervisord but will also let you manage all processes at the same level, wether they are web workers or Redis or whatever. Adding a new web worker is done exactly like adding a new Redis process.
We did a few benches to compare Circus & Chaussette with Gunicorn. To summarize, Circus is not adding any overhead and you can pick up many different backends for your web workers.
See: | http://circus.readthedocs.org/en/0.6/sockets/ | CC-MAIN-2014-42 | refinedweb | 752 | 64.71 |
Name a tech company, any tech company, and they're investing in containers. Google, of course. IBM, yes. Microsoft, check. But, just because containers are extremely popular, doesn't mean virtual machines are out of date. They're not.
Yes, containers can enable your company to pack a lot more applications into a single physical server than a virtual machine (VM) can. Container technologies, such as Docker, beat VMs at this part of the cloud or data-center. That's a winning trifecta.
If that's all there was to containers vs. virtual machines then I'd be writing an obituary for VMs. But, there's a lot more to it than just how many apps you can put in a box.
Container problem #1: Security
The top problem, which often gets overlooked in today's excitement about containers, is security. As Daniel Walsh, a security engineer at Red Hat who works mainly on Docker and containers puts it: Containers do not contain. Take Docker, for example, which uses libcontainers as its container technology. Libcontainers accesses five namespaces -- Process, Network, Mount, Hostname, and Shared Memory -- to work with Linux. That's great as far as it goes, but there's a lot of important Linux kernel subsystems outside the container.
These include all devices, SELinux, Cgroups and all file systems under /sys. This means if a user or application has superuser privileges within the container, the underlying operating system could, in theory, be cracked.
That's a bad thing.
Now, there are many ways to secure Docker and other container technologies. For example, you can mount a /sys file system as read-only, force container processes to write only to container-specific file systems, and set up the network namespace so it only connects with a specified private intranet and so on. But, none of this is built in by default. It takes sweat to secure containers.
The basic rule is that you'll need to treat containers the same way you would any server application. That is, as Walsh spells out:
- Drop privileges as quickly as possible
- Run your services as non-root whenever possible
- Treat root within a container as if it is root outside of the container
Another security issue is that many people are releasing containerized applications. Now, some of those are worse than others. If, for example, you or your staff are inclined to be, shall we say, a little bit lazy, and install the first container that comes to hand, you may have brought a Trojan Horse into your server. You need to make your people understand they cannot simply download apps from the Internet like they do games for their smartphone.
Mind you they shouldn't be downloading games willy-nilly either, but that's a different kind of security problem!)."
The hit list!
This story, "Containers vs. virtual machines: How to tell which is the right choice for your enterprise" was originally published by Network World. | https://www.infoworld.com/article/3068183/containers-vs-virtual-machines-how-to-tell-which-is-the-right-choice-for-your-enterprise.html | CC-MAIN-2021-21 | refinedweb | 494 | 63.9 |
I am a beginner in python, and I am trying to do the following exercise:
"Write a function that takes a string as a parameter and returns True if the string is a palindrome " (recursively)
Here's what I've written:
- Code: Select all
def palindrom(str):
pal=""
while len(pal) != len(str):
pal = str[-1] + reverse(str[:-1])
This gives me the string backwards. However, when I am trying to compare them, I keep getting errors. I have tried using == and is, but they don't seem to work. Why can't i use these boolean operators in a recursive function and how can I solve it? | http://www.python-forum.org/viewtopic.php?f=6&t=8421&p=11075 | CC-MAIN-2015-40 | refinedweb | 108 | 68.5 |
Let's start with our header file for the Window, we'll call it window1.h
#ifndef WINDOW_1_DEF_H
#define WINDOW_1_DEF_H
#include<gtkmm/window.h>
#include<gtkmm/button.h>
#include<gtkmm/entry.h>
#include<gtkmm/box.h>
class Window1 : public Gtk::Window {
public:
Window1();
virtual ~Window1();
protected:
void on_button1_clicked();
private:
Gtk::Button button1, button2;
Gtk::Entry entry1;
Gtk::VBox vbox1;
};
#endif
All of that should explain itself. Basically the object is a Gtk::Window, which is the top level container (widget, whatever you want to call it). We are adding two Gtk::Button, a Gtk::Entry (text entry widget), and a Gtk::VBox which is the layout container.
Now the fun thing about Gtkmm is that you don't have to "new" objects into existence. Instead Gtkmm will handle the memory allocation for you in most cases!! However, if you need to dynamically allocate objects or you need them outside of the class scope then your own your own, unless you use the Gtkmm smart pointer Glib::RefPtr<>, which is basically the same as the std::auto_ptr<> for those of you who have studied standard C++.
Okay let's implement the window, this will be in most logically window1.cc
#include "window1.h"
#include <iostream>
#include<gtkmm/main.h>
Window1::Window1() : button1("Print"), button2("Ouit") {
set_size_request(200,100);
set_title("Text Entry Demo");
add(vbox1);
entry1.set_max_length(25);
entry1.set_text("Enter something");
entry1.select_region(0,entry1.get_text_length());
vbox1.add(entry1);
button1.signal_clicked().connect(sigc::mem_fun(*this,&Window1::on_button1_clicked));
button2.signal_clicked().connect(sigc::ptr_fun(&Gtk::Main::quit));
vbox1.add(button1);
vbox1.add(button2);
show_all();
}
Window1::~Window1() {
using namespace std;
cout << "Say goodbye" << endl;
}
void Window1::on_button1_clicked() {
std::cout << "You have entered: " << entry1.get_text() << std::endl;
}
Okay this one has a couple of things to cover. Like what the heck is the sigc namespace?!
sigc is the library that Gtkmm uses to implement callbacks. A callback is a function or method that is called from another function. Basically the on_click method of your buttons gets called when you click on them. The method basically says, when I'm clicked run ________(insert blank line)________. The callback fills in the blank line.
Now historically there is basically one way to do this in C, but in C++ there must be at least a dozen libraries that do this. I won't get into why this is because that's a much bigger topic.
At anyrate, sigc is the tool that Gtkmm has chosen to implement callbacks. sigc has two ways to add callbacks. mem_fun and ptr_fun, both used here. mem_fun, allows you to call a method and ptr_fun allows you to call a function. Pretty clear cut there. As you can see I've connected the button2's click to the Gtk::Main::quit, which of course does what it says. Quits.
The other button, button1, I've connected to the on_button1_clicked method. This method simply uses standard C++ cout to write information to standard out. You may notice that I use the entry1.get_text() method within the on_button1_clicked() method and that I don't cast it's result to std::string. That's the neatest part of Gtkmm is that it was made to work with the C++ STL so well. Gtkmm already implements the logic needed to cast Glib::ustring (which is what the get_text() wethod returns) to std::string.
The rest of the code is pretty simple to follow.
So now that we have implemented our window we need an application that actually uses it.
I present main.cc
#include<gtkmm/main.h>
#include"window1.h"
int main(int argc, char *argv[]){
Gtk::Main kit(argc, argv);
Window1 w;
Gtk::Main::run(w);
return 0;
}
This is as basic as you can make an application that uses our window.
The results are here.
Clicking on the Print button outputs the text box on standard out and clicking quit, well quits. As you can see Gtkmm is very much like most other Toolkits, semantics are a little different here and there and you'll use some of the core tools of Gtkmm a little differently but overall you'll easily see how Gtkmm compares to things like SWT, Swing, and QT.
And since I said something about QT, it's worth saying something about it. If you have ever used QT then you know about it's signal/slot system and moc. Well Gtkmm takes the "high road" on this one and uses sigc to implement callbacks in a C++ standard-ish kind of way. The downfall of this, however, is that every callback must be statically typed. This amounts to a lot of double work. If you implement a signal connection in Glade, you must also implement that connection in Gtkmm by importing the widget and then using sigc.
I know this is one of the downfalls of C++'s strong type safety system and name mangling system. QT gets around this with moc but then using moc makes your code non-C++ standard compliant, which I don't think anybody really has a problem with except the people behind Gtkmm.
At anyrate, at risk for getting way off topic, Gtkmm is a neat little wrapper around Gtk+ and you should give it a whirl. You'll be making Gtk+ applications in no time, and best of all is the Gtkmm library works on Windows, Mac, Linux, BSD, and other Unix systems.
Link to Gtkmm | http://ramenboy.blogspot.com/2010/08/quick-try-of-gtkmm_2062.html | CC-MAIN-2018-13 | refinedweb | 904 | 64.71 |
Building Aurelia's Focus Attribute
This week we are really excited to have our first community member highlight post! Manuel Guilbault is a Canadian-born, Paris-based developer, where he works as a consultant in the financial sector. Passionate about software craftsmanship, agility and lean principles, he loves to learn and debate about how we do things, why we do them this way and how they can be improved. This week we've invited Manuel to guest blog with us and share the work he did implementing a new custom attribute that's shipping in the next Aurelia update.
Take it away Manuel....
Introduction
I've been a huge fan of Durandal and Knockout JS for many years now, and I've been closely following Aurelia since I first heard about it. After playing with it for a while, I noticed that one of the features I used with Knockout was missing from Aurelia: a
focusbinding. I decided to take advantage of the Custom Attribute API to develop a
focus custom attribute for Aurelia.
Requirements
The custom attribute I have in mind would be used this way:
export class ViewModel { hasFocus = false; }
<input focus.
The requirements are as follows:
- When
hasFocusis set to
true, the input gets focus;
- When
hasFocusis set to
false, the input loses focus;
- When input gains focus following a user action,
hasFocusis set to
true;
- When input loses focus following a user action,
hasFocusis set to
false.
So, what I want is basically a two-way binding between the bound property and the focus state of the input. You might think that this kind of two-way binding will trigger an infinite loop, but rest assured: Aurelia's binding module will take care of that.
Getting Started
First, let's follow the documentation and create an empty custom attribute:
import {customAttribute, inject, bindingMode} from 'aurelia-framework'; @customAttribute('focus', bindingMode.twoWay) @inject(Element) export class Focus { constructor(element) { this.element = element; } valueChanged(newValue) { } }
The first and easiest step is to listen for changes of the
value property, and to react accordingly, by focusing or bluring the target element. This is done inside the
valueChanged method:
valueChanged(newValue) { if (newValue) { this.element.focus(); } else { this.element.blur(); } }
Pretty simple! Now, when our view model's
hasFocus property changes, the input is properly focused or blured.
Next, the attribute's
value property needs to be updated when the input receives or loses focus after a user action. To do this, we need to register event listeners on the element. As mentioned in the documentation, this should be done in the
attached() method:
attached() { this.element.addEventListener('focus', e => this.value = true); this.element.addEventListener('blur', e => this.value = false); }
Still pretty straight forward, right? Yet, something's still missing: the event listeners need to be removed when the element is
detached() from the document:
detached() { this.element.removeEventListener('focus', e => this.value = true); this.element.removeEventListener('blur', e => this.value = false); }
Now if you go and test what we have so far, and you are running this on a setup that doesn't fully support ECMAScript 6 and uses a transpiler (like Babel), you will see the
removeEventListener calls don't work. This is because the
attached() and
detached() methods get transpiled this way:
function attached() { var _this2 = this; this.element.addEventListener('focus', function(e) { _this2.value = true; }); this.element.addEventListener('blur', function(e) { _this2.value = false; }); } function detached() { var _this3 = this; this.element.removeEventListener('focus', function(e) { _this3.value = true; }); this.element.removeEventListener('blur', function(e) { _this3.value = false; }); }
As you can see, the removed listeners are are not the same as the added ones. Let's try and make them methods, to see if it works:
onFocus(e) { this.value = true; } onBlur(e) { this.value = false; } attached() { this.element.addEventListener('focus', this.onFocus); this.element.addEventListener('blur', this.onBlur); } detached() { this.element.removeEventListener('focus', this.onFocus); this.element.removeEventListener('blur', this.onBlur); }
It still doesn't work: when the
onFocus and
onBlur listeners are called by the browser,
this doesn't contain the
Focus instance but the element that fired the event. That's actually a common mistake; I should have known better. Let's solve this issue by creating instance functions that capture
this in their scope:
constructor(element) { this.element = element; this.focusListener = e => this.value = true; this.blurListener = e => this.value = false; } attached() { this.element.addEventListener('focus', this.focusListener); this.element.addEventListener('blur', this.blurListener); } detached() { this.element.removeEventListener('focus', this.focusListener); this.element.removeEventListener('blur', this.blurListener); }
That works fine now.
Fine-tuning
We now have a
Focus custom attribute that answers to all of our initial requirements. But if you play a little bit with it, you will see that there are still some edge cases that are not yet covered.
Interaction With Other Attributes
By definition, a custom attribute is used to decorate an element, so it has to work along fine with other custom attributes that can be on the same element.
What if the view model property bound to our
focus attribute is also bound to the
show attribute? This will be problematic, because depending on the order of evaluation when the bound property turns to
true, the target element may not be visible yet when our attribute tries to give it focus. We can solve this problem by using another part of Aurelia's API: the
TaskQueue class.
import {customAttribute, inject, bindingMode, TaskQueue} from 'aurelia-framework'; @customAttribute('focus', bindingMode.twoWay) @inject(Element, TaskQueue) export class Focus { constructor(element, taskQueue) { this.element = element; this.taskQueue = taskQueue; } giveFocus() { this.taskQueue.queueMicroTask(() => { if (this.value) { this.element.focus(); } }); } valueChanged(newValue) { if (newValue) { this.giveFocus(); } else { this.element.blur(); } } }
In the above snippet, I first added injection of the
TaskQueue instance into the
Focus constructor. I also added a
giveFocus() method, which will enqueue a microtask responsible for giving focus to the element. This will actually delay the
focus() call by pushing it to the end of the binding queue. This will ensure that all queued events, including the bound property's value change, are processed before the focus is given.
Handling Window Change
You may have noticed that our
Focus custom attribute does not react correctly when the element is focused and you change browser tabs. How can we fix that?
constructor(element) { this.element = element; this.focusListener = e => this.value = true; this.blurListener = e => { if (document.activeElement !== this.element) { this.value = false; } }; }
In the above code snippet, I changed the
blurListener function, so that, when a
blur event is triggered, the
value is set to
false only if the element is not the document's active element. This scenario occurs typically when you change tabs in the browser (or change window in the OS). By preventing setting
value to
false, we prevent
valueChanged(false) from being called, which would call
element.blur() and would make the document's active element to become the body, and therefore cause the element to have lost focus when you go back to the browser tab.
Summary
As you can see, it is pretty easy to create new features for Aurelia. We were able to quickly come up with a new
focus attribute, thanks to Aurelia's modular and extensible design.
| http://blog.aurelia.io/2015/06/05/building-aurelias-focus-attribute/ | CC-MAIN-2017-17 | refinedweb | 1,206 | 50.02 |
Preprocessor macro definitions for the screen.h header file in the libscreen library
#include <screen/screen.h>
#define _SCREEN_MAKE_VERSION (((major) * 10000) + ((minor) * 100) + (patch))
Convenience macro to facilitate comparison of Screen versions.
All versions of Screen prior to 2.0.0 are considered to be Screen version 0.0.0.
#define _SCREEN_VERSION_MAJOR 2
The major version number.
A difference the major version number implies that the Screen API isn't backwards compatible (e.g., A Screen application that's developed using Screen version 2.0.0 can't run on a target that's running Screen version 0.0.0.).
#define _SCREEN_VERSION_MINOR 0
The minor version number.
A difference the minor version number implies that there may be differences in the Screen API, but the changes are backwards compatible (e.g., A Screen application that's developed using Screen version 2.0.0 can run on a target that's running Screen version 2.1.0.).
#define _SCREEN_VERSION_PATCH 0
The patch version number.
A difference the patch version number implies no differences in the Screen API; the changes are implementation updates only(e.g., A Screen application that's developed using Screen version 2.1.0 uses the same Screen API as one from Screen version 2.1.1.).
#define _SCREEN_VERSION _SCREEN_MAKE_VERSION(_SCREEN_VERSION_MAJOR, _SCREEN_VERSION_MINOR, _SCREEN_VERSION_PATCH)
The current version of Screen.
#define SCREEN_MODE_PREFERRED_INDEX (-1)
Defines the mode preferred index.
Used as a convenience value to pass when setting SCREEN_PROPERTY_MODE. When this value is passed in setting SCREEN_PROPERTY_MODE, Screen uses the default video mode without having to first determine all the modes supported by the display to find the one with SCREEN_MODE_PREFERRED set in flags. | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.screen/topic/screen_h_defines.html | CC-MAIN-2017-51 | refinedweb | 273 | 59.8 |
David Isaac wrote: > > Michael Spencer wrote: > > > This can be written more concisely as a generator: > > > <bonono at gmail.com> wrote in message > news:1132708265.941224.186550 at g44g2000cwa.googlegroups.com... > > If iterable has no elements, I believe the behaviour should be [init], > > there is also the case of init=None that needs to be handled. > > Right. So it is "more concise" only by being incomplete, right? > What other advantages might it have? > > > otherwise, that is more or less what I wrote for my scanl/scanl1. > > I didn't see a post with that code. > > Alan Isaac def scanl1(func, seq): def my_func(x): my_func.init = func(my_func.init, x) return my_func.init i = iter(seq) try: my_func.init = i.next() except StopIteration: return [] return (chain([my_func.init], (my_func(y) for y in i))) def scanl(func, seq, init): def my_func(x): my_func.init = func(my_func.init, x) return my_func.init my_func.init = init return (chain([my_func.init], (my_func(y) for y in seq))) | http://mail.python.org/pipermail/python-list/2005-November/321132.html | CC-MAIN-2013-20 | refinedweb | 163 | 71.51 |
Stephan Richter wrote: > - You do not argue how the decision-making process is "highly inconsistent".
Advertising
Fair enough. I will update the proposal later. Supper first :). > -. Sure, it's easy to write ZCML directives. It's also possible to write ZCML directives that are easy to use, but just as well to write ones that are hard to use. So your generalization above is a bit too, well, general :). The problem is uncontrolled ZCML directive proliferation. It's "bad" enough that you have to familiarize yourself with a new API when dealing with a 3rd party Zope package. But having to learn a new set of ZCML directives?!? I think many people would be skeptical. Me included. As we have learned that we can reduce nearly all component tasks to adapters and utilities, many tasks revolving around registration and configuration of policy also only involve adapters and utilities. By using those "elementary" directives we can stimulate the learning process for developers ("there should only be one way of doing things"). Yes, you might have to use two or three directives instead of just one new one, but you'll know what you're doing... And you'll remember it in 2 months. I think that's more valuable than saving a couple of lines today. That said, there might still be a small percentage of cases where custom directives are a valid tool. I can accept their being on the same namespace as others. In fact, I would like it to be that way, reducing the amount of dead chickens (namespace declarations). Philipp ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg04024.html | CC-MAIN-2018-05 | refinedweb | 283 | 66.13 |
The QtopiaServiceRequest class allows applications to request services from other applications. More...
#include <QtopiaServiceRequest>
The QtopiaServiceRequest class allows applications to request services from other applications.
A QtopiaServiceRequest encapsulates a Qt Extended service name and the message to be sent to that service. It is similar to QtopiaIpcEnvelope, but uses service names rather than direct channel names. The following example sends the editTime() request to the Time service:
QtopiaServiceRequest req("Time", "editTime()"); req.send();
Parameter data may be written to the request prior to sending it with send(). The following example requests that the WebAccess service open a specific URL:
QtopiaServiceRequest req("WebAccess", "openURL(QString)"); req << ""; req.send();
Applications that implement services can use QtopiaAbstractService to process incoming service messages. See also {Services} for more information on implementing and configuring services.
See also Services, QtopiaService, and QtopiaAbstractService.
Construct a null service request. setService() and setMessage() must be called before send(), but the service may be written prior to the calls.
Construct a service request that will send message to a service when send() is called. The service may be written prior to the calls.
Copy constructor. Any data previously written to the orig service will be in the copy.
Destructs the service request. Unlike QtopiaIpcEnvelope, the request is not automatically sent.
Adds the variant var to the list of arguments, so that the variant's value is serialized in send() rather than the variant itself.
Returns the complete list of arguments for this service request.
See also setArguments().
Returns true if either the service() or message() is not set.
See also service() and message().
Returns the message of the request.
See also setMessage().
Sends the request. Returns false if there was no application that could service the request.
Returns the service to which this request will be sent.
See also setService().
Sets the complete list of arguments for this service request.
See also arguments().
Sets the message to be sent to the service.
See also message().
Sets the service to which the request will be sent.
See also service().
Adds var to the list of arguments for this service request.
This is an overloaded member function, provided for convenience.
Adds var to the list of arguments for this service request.
Assignment operator. Any data previously written to the orig service will be in the copy. | https://doc.qt.io/archives/qtextended4.4/qtopiaservicerequest.html | CC-MAIN-2019-26 | refinedweb | 384 | 52.97 |
"D. Goel" <deego@gnufans.org> writes: > While that is supposed to be true, it has been very untrue in > practice, IME. Here are some examples of the top of my head: > > * Installing maxima makes my emacs N new functinos with ~ N namespaces > * Installing ilisp makes emacs bind C-c <letter> which broke my .emacs. > * Installing remem makes emacs bind C-c <letter> which broke my .emacs. > * Installing html-helper-mode luckily did not break my .emacs but it > did override some of my C-c <letter> bindings ... > > thus, these packages, instead of being mere additions to site-lisp, > placed files in site-init which breaks emacs conventions. > > It would be nice if debian would require each emacs package which > seeks to "modify the default emacs" to please follow emacs conventions > as well. Moreover, they should not break emacs conventions even if > they "merely add themselves to site-lisp" and leave the site-init > alone. Agreed. A typical package should not do anything more than add some autoloads to site-lisp and perhaps munge auto-mode-alist. > Of course, similar to Faheem, it remains a wishlist of mine (and i am > foggy on how it can be implemented) to recognize that since in > practice, many packages will err about following emacs conventions, > they should somehwo be "disabled" unless a user requests. This sounds like it could cause inconvience as well though; I presume that _most_ debian emacs users have their own machine, and when they install an emacs add-on package, they expect it to just start working. Anyway, a good start would be to just report bugs against emacs add-on packages that do something stupid (like those you mentioned). Fixing those problems will help, regardless of whether some additional mechanism is later added... -Miles -- Occam's razor split hairs so well, I bought the whole argument! | https://lists.debian.org/debian-emacsen/2002/11/msg00036.html | CC-MAIN-2016-30 | refinedweb | 307 | 67.38 |
Content count4822
Joined
Last visited
Days Won2
Community Reputation12116 Excellent
About Nypyren
- RankContributor
Personal Information
- InterestsProgramming
- You could definitely control "inline" vs "use reference id" with attributes. If it makes the most sense, you could even have inline be the default. You could automatically switch to reference ids only if a cycle is detected. Things like that.
- I don't know if JSON.NET intrinsically can handle object->object references. I have implemented my own reflection-based serializer before and it handles arbitrary objects, including cyclic object references (what I assume you meant by recursion). The way it works is fairly simple: Do two passes. On the first pass, traverse all reference types and make a unique ID each time you run into a new one. Skip any you've already seen. On the second pass, actually serialize data: the number of reference types, followed by the Type of each reference type (so you can support polymorphism), and finally followed by the values for all of the fields in each object. When a field is a reference type, serialize the ID (reserve a number like 0 or -1 for null). When a field is a value type, serialize its entire contents directly. Deserialization then uses FormatterServices.GetUninitializedObject (or equivalent if you're not using .Net) to create all of the reference types first, then when fields are being deserialized, references to other objects can be assigned immediately. This supports polymorphism and arbitrary graphs of objects, which as far as I know is everything that can be represented in any data structure. The underlying data can be binary, JSON, XML, or whatever you want. You can optimize each of the individual pieces of data as much as you feel like: well-known type IDs instead of names, zigzag integer encoding and field IDs/sizes like protobuf has for versioning compatibility, etc.
- But how would that change how they make money (or are unable to make money, in many cases)? My 2018 prediction is that plain old news sites will begin adding cryptominers to their own pages to increase revenue.
SAT not working properly
Nypyren replied to Bob Dylan's topic in Math and PhysicsWhat have you tried? Did you use a debugger to investigate what the values are which lead to the problem? It should be pretty easy to identify the issue if you have a repro case.
C# To Callback or not to callback
Nypyren replied to Munchkin9's topic in General and Gameplay ProgrammingCommands are functions, right? If they already perform work then why does anything need to be refactored? Perform the callback within the normal work of the command's function, or wrap the command with a command which calls the original command THEN the callback, if that makes more sense. Imagine this pattern, but adapted to whatever additional complexities you require (IPC, RPC, etc). Action WrapAction(Action command, Action callback) { return () => { command(); callback(); }; } If you're dealing with IPC then you will definitely need some way of handling responses and completion which can deal with the callback. It's not overkill. If you're NOT dealing with IPC then do you really need all those intermediate objects and queues?
- That's literally an empty document. Are you trolling or what? Are you a chatbot? Your name would make sense in that case.
C++ Linker problem.
Nypyren replied to Mr_Mauve's topic in General and Gameplay ProgrammingTemplates behave differently than the standard header/cpp file dichotomy. There are lots of references online; you should be able to find comprehensive info that explains why you need to have the implementation #included.
C++ Unique identifier for functions? (c++)
Nypyren replied to suliman's topic in General and Gameplay ProgrammingUse callbacks/anonymous methods/lambdas/whatever C++'s modern equivalent is. C# example since it's easier to demonstrate: Popup("What to eat?", new string[]{"Cake", "Cookies!"}, x => { switch (x) { case 0: eatCake(); break; case 1: eatCookiesDammit(); break; } });
- You say you have done some of the planning already, but then you posted two meaningless pictures. Try posting things that have meaning first.
Does u,v,w texture mapping exist?
Nypyren replied to lucky6969b's topic in Graphics and GPU ProgrammingI stand corrected. It looks like the vector-to-sampler-address step is done for us. Using Hodgman's hints, I found this which seems relevant:
Does u,v,w texture mapping exist?
Nypyren replied to lucky6969b's topic in Graphics and GPU ProgrammingIf you mean volume textures, then you need a W. If you mean a cubemap, then no, the cube texture itself is flat and you only need U and V.
- My experience with GUIs is that they have a whole lot of state which can be preserved between updates. If you resize your window, the layout needs to change. If you move your mouse over a button, there might be a mouse-over highlight. But if you're not constantly resizing the window, you don't need to redo the layout. If you're not constantly moving the mouse, you don't need to collision check every button or other clickable element. Keeping the UI state stored somewhere between updates so that it can be reused is called "retained mode". Usually there is no choice: Immediate mode is typically built on top of retained mode, and the code to actually render the GUI is inevitably draw calls. You can implement a pure immediate mode render-only GUI by just making draw calls, but if you discard layout and input state you end up having to redo all of your layout computations every time you want to render. The issues I've experienced with immediate mode is that the additional wrapper on top of retained mode is inefficient. If the immediate mode API doesn't include control identifiers, the wrapper layer has to spend time looking these up on each call. Retained mode GUIs have SEPARATE functions which update just what is actually needed at the moment (layout, mouse rect tests, keyboard input goes directly to whatever control has focus, etc). And those functions are only called when a change occurs. Immediate mode GUIs often jam literally everything into one function hierarchy representing the GUI hierarchy, and each individual control's function switches on what is happening (layout, input handling) and adjusts its internal retained mode state. The problem is that these APIs typically traverse the entire call hierarchy even if you don't need to, because they use the call order to determine which retained mode control ID is being referenced by the immediate mode function. If you skip calling a "Button" function in one case your entire GUI stops working. Particularly egregious examples of immediate mode GUI are Unity's OnGUI mehod, GUI and GUILayout classes. Unity basically calls your OnGUI method once per "event" (layout, paint, input handling, that kind of thing). Since much of the code in your OnGUI method may only be relevant to one or two of the event types, if you do anything other than GUI.* calls you're wasting time calculating things that will be discarded. Trying to do anything complicated with them can very quickly wreck performance. The hoops you can optionally jump through to increase performance (by avoiding irrelevant calculations in specific 'event' phases) are like writing a retained-mode interface wrapper on top of that. Unnecessary additional layers of abstraction when ideally you could just control the retained mode GUI under the hood. I haven't personally used any of the web-specific UI frameworks since I avoid web development like the plague, but my understanding is: The HTML elements are a 'retained mode' equivalent. The browser handles their layout and rendering. Why anyone would want to build immediate mode on top of that is beyond me.
- When have web developers *ever* made good decisions about technology choices? Someone decides they want something easy and minimal now, they make it available for the unwashed masses, and it spirals out of control for years. Wash, rinse, repeat.
Manual syntax trees
Nypyren replied to TheComet's topic in Coding HorrorsMaybe overload the operators on the Expression type itself (or a type specific to performing AST generation) to make the combined expression. Then the C++ parser itself will construct your AST creation calls properly due to operator precedence rules. Also it might be worth investing time in seeing whether your 'entries' can be immutable. If so, you won't need to clone() them.
Token representation
Nypyren replied to matt77hias's topic in General and Gameplay ProgrammingYour lexer should be a DFA built out of switch-on-character statements and state variable(s), so your tokens should be "stored" spread out across case statement character constants in certain states. Each token you recognize should have two parts - the token type ID (integer) and possibly the substring that you parsed which resulted in this token type which you then use as a value (string, enum, integer, etc). Your lexer should then pass those tokens to your parsing engine (SLR/LR/whatever) - or the parsing engine can have a loop that calls "GetNextToken". The parsing engine should primarily be dealing with the token type IDs to guide its state(s), but if you have something like a math expression evaluator you can immediately evaluate subexpressions in the middle of the parse instead of generating an AST if you want to. But if you're not writing a high performance parser it really doesn't matter what you do. Since you're even asking this question at all implies you do care, though. | https://www.gamedev.net/profile/35207-nypyren/?tab=smrep | CC-MAIN-2018-05 | refinedweb | 1,596 | 53.81 |
This quick lesson covers Javadoc, a helpful tool for generating documentation from your Java source files. This lesson is part of an ongoing series of tutorials for developers learning Java in order to develop Android applications.
What is Javadoc?
Javadoc is a utility provided with the Java SDK that allows developers to generate code documentation from Java source files. Development environments like Eclipse have built-in support for Javadoc and can generate searchable HTML reference materials from Javadoc-style comments. In fact, the Android SDK reference is a form of Javadoc documentation.
How Does Javadoc Work?
Javadoc documentation uses a combination of processing the source code (and inspecting types, parameters, etc.) and reading special comment tags that the developer provides as metadata associated with a section of code.
A Javadoc-style comment must come just before the code it is associated with. For example, a Javadoc comment for a class should be just above the class declaration and a comment for a method should be just above the method declaration. Each comment should begin with a short description, followed by an option longer description. Then you can include an number of different metadata tags, which must be supplied in a specific order. Some important tags include:
- @author – who wrote this code
- @version – when was it changed
- @param – describe method parameters
- @return – describe method return values
- @throws – describe exceptions thrown
- @see – link to other, related items (e.g. “See also…”)
- @since – describe when code was introduced (e.g. API Level)
- @deprecated - describe deprecated item and what alternative to use instead
You can also create your own custom tags for use in documentation.
Generate Javadoc-style Comments in Eclipse
While you are writing code in Eclipse, you can generate a Javadoc –style comment by selecting the item you want to comment (a class name, method name, etc.) and pressing Alt-Shift-J (Cmd-Shift-J on a Mac). This will create a basic Javadoc-style comment for you to fill in the details.
Simple Javadoc Class Comments
Let’s look at an example. Here’s a simple Javadoc comment that describes a class:
/** * Activity for loading layout resources * * This activity is used to display different layout resources for a tutorial on user interface design. * * @author LED * @version 2010.1105 * @since 1.0 */ public class LayoutActivity extends Activity {
Here’s what it will look like when you generate the Javadoc documentation:
Simple Javadoc Field Comments
Let’s look at an example. Here’s a simple Javadoc comment that describes a field within a class:
/** * Debug Tag for use logging debug output to LogCat */ private static final String DEBUG_TAG = "MyActivityDebugTag";
Here’s what it will look like when you generate the Javadoc documentation:
Simple Javadoc Method Comments
Now let’s look at two examples of method comments. Here’s a simple Javadoc comment that describes a method within a class:
/** * Method that adds two integers together * * @param a The first integer to add * @param b The second integer to add * @return The resulting sum of a and b */ public int addIntegers(int a, int b) { return (a+b); }
Now let’s look at a method that returns void, but throws an exception:
/** * This method simply throws an Exception if the incoming parameter a is not a positive number, just for fun. * * @param a Whether or not to throw an exception * @throws Exception */ public void throwException(boolean shouldThrow) throws Exception { if(shouldThrow == true) { throw new Exception(); } }
Here’s what it will look like when you generate the Javadoc documentation for these two methods:
Generating Javadoc Documentation in Eclipse
To generate Javadoc code documentation in Eclipse, go to the Project menu and choose the “Generate Javadoc…” option. This will launch a wizard that allows you to choose the projects to generate documentation for.
From this wizard, you should point Eclipse at the appropriate javadoc.exe command line tool (you’ll find it in your JDK’s /bin directory). You can also configure some documentation settings, such as whether to document all code, or only visible classes, members, etc. Finally, choose a destination for your documentation files.
Even without generating the Javadoc files, Eclipse will show the Javadoc-style documentation when you hover over your methods and such, as shown in the figure below.
Learning More about Javadoc
You can find out more from the Javadoc reference at the Oracle website. There is also a helpful Javadoc FAQ available.
Conclusion
In this quick lesson you have learned about Javadoc, a powerful tool used by Java developers to document source code thoroughly for reference and maintenance purposes. Eclipse, the development environment used by many Android developers, has built-in support for Javadoc.<< | https://code.tutsplus.com/tutorials/learn-java-for-android-development-javadoc-code-documentation--mobile-3674 | CC-MAIN-2021-43 | refinedweb | 774 | 51.07 |
The world's most popular open source database
In the previous sections, you used mysql interactively to enter queries and view the results. You can also run mysql in batch mode. To do this, put the commands allows you to avoid retyping it each time you execute it.
You can generate new queries from existing ones that are similar by copying and editing script files.
Batch mode can also be useful while you're developing a query, particularly for multiple-line commands or multiple-statement sequences of commands. commands.
commands that are executed, use
mysql -vvv.
You can also use scripts from the mysql prompt
by using the
source command or
\. command:
mysql>
sourcemysql>
filename;
\.
filename
See Section 4.5.1.4, “Executing SQL Statements from a Text File”, for more information.
How to measure total batch running time for several SQLs:
# at start of your script file
SET @start=UNIX_TIMESTAMP();
# great job
...
...
...
# at bottom of your script file
SET
@s=@seconds:=UNIX_TIMESTAMP()-@start,
@d=TRUNCATE(@s/86400,0), @s=MOD(@s,86400),
@h=TRUNCATE(@s/3600,0), @s=MOD(@s,3600),
@m=TRUNCATE(@s/60,0), @s=MOD(@s,60),
@day=IF(@d>0,CONCAT(@d,' day'),''),
@hour=IF(@d+@h>0,CONCAT(IF(@d>0,LPAD(@h,2,'0'),@h),' hour'),''),
@min=IF(@d+@h+@m>0,CONCAT(IF(@d+@h>0,LPAD(@m,2,'0'),@m),' min.'),''),
@sec=CONCAT(IF(@d+@h+@m>0,LPAD(@s,2,'0'),@s),' sec.');
CONCAT(@seconds,' sec.') AS seconds,
CONCAT_WS(' ',@day,@hour,@min,@sec) AS elapsed;
# enjoy :)
p.s. Tested & works
p.p.s. No fractions of seconds :(
jz
Example of a Korn Shell Script
#!/bin/ksh
mysql --user=<user> --password=<password> -h <host> <<!!
SELECT VERSION(), CURRENT_DATE;
quit
!!
When using mysql in batch mode there is an odd requirement that cost me hours. Your .sql file cannot contain any #comment lines. Delete them and importing will be a breeze. There is no indication that this is the problem. However, experimentation revealed this to be the cause.
Lines beginning with two dashes are comment lines. Inside a shell script you will use #comment lines in the shell part and if you use a here-document you must use --comment lines inside the here document. Example:
===file petquery.sh===
#!/bin/sh
# This is a comment
mysql -t <<STOP
-- This is a comment inside an sql-command-stream.
use menagerie
select * from pet ;
\q
STOP
test $? = 0 && echo "Your batch job terminated gracefully"
===end-of-file petquery.sh===
DO NOT cut/paste the === lines.
I don't know how to make source listings inside the example.
donald_j_axel(at)get2net.dk
A more secure way to use the shell.
So that passwords are not embedded in the shell source file create a password file:
echo "batchpassword" > /etc/security/mysqlpassword
chmod 200 /etc/security/mysqlpassword
Then in your script:
echo "update tablex set x=1 where a=2;" | mysql mydb --user=batchdb --password=`cat /etc/security/mysqlpassword`
This assumes you have created a user called "batchdb" with that password and the correct access rights to the database called "mydb".
tc
When using mysql in batch mode you can use pipes to write an interactive but pre-scripted shell script. Be aware that you need to use the "-n" command line option to flush the buffer otherwise your read will hang. Here is a code sample in ksh:
-------------------------------------------------
#!/bin/ksh
mysql -u username -ppassword -D dbname -ss -n -q |&
print -p -- "select count(*) from some_table;"
read -p get_row_count1
print -p -- "select count(*) from some_other_table;"
read -p get_row_count2
print -p exit ;
#
echo $get_row_count1
echo $get_row_count2
#
exit
-------------------------------------------------
(The -q option is optional)
Note: If you dislike using "-n" then make sure all your read statements are after the exit.
N.B. On most Unix systems, by placing the password in the command line with --password (even the above method for using a password file) you are making the password visible to local users, who can see the command string with a "ps" or "w" command.
Whilst some systems can be set to block this, and others would let you wrap the command in something that would overwrite what users could see as your command, the best way to do any automations like this is to create a specific unix user for the job (or use a user that is already secure) and place the password in the .my.cnf file for that user - making sure the permissions are set so that only the owner can read it
For newbies like me: This exact command allowed me to run a script from outside MySQL (using the DOS command line in Win98):
C:\WINDOWS\Desktop>c:\mysql\bin\mysql -u root -p < "c:\mysql\scripts\20060416_ShowInnodbstatusscript.txt" | more
Note: My text file had two commands:
Use db_name;
Show InnoDB Status;
FYI: I had been plagued by a foreign key error, but was unable figure out how to see the result of my Show Innodb Status command due to my 50-line DOS screen limitation. To get around this problem I
a) created the simple script shown above
b) created a foreign key error while logged into my MySQL user account, then
c) opened an additional DOS window to execute the command shown above.
Running the command outside of MySQL essentially creates a way to view command results one page at a time for folks administering MySQL at the command line (using Windows).
Alternatively, by default, mysql.exe assumes that the script is inside the same folder.
cd C:\Program Files\MySQL\MySQL Server 5.0\bin
mysql -u root -p < testing.txt
Done!
Hello!P.S.
Suppose you want to run script `test.sql' in batch mode.
The most straightforward way, as mentioned at the very
beginning, is to say:
shell> mysql < test.sql
In order to further reduce typing, one wish to invoke
shell> chmod a+x test.sql
and then run `test.sql' as a usual Unix script.
But it doesn`t work.
It is well known that so-called Sha-Bang (#!) symbol
is used in Unix world to specify where actual interpreter
lives. For example, #!/bin/bash
My objective is to create small and convenient wrapper
to run MySQL scripts in the same way as I run other scripts:
just typing `test.sql'.
Here is the program:
=[sql.c]===8<========================================================
/*
* MySQL Sha-Bang wrapper. Public domain.
* Alexander Simakov
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char buf[512];
int i;
buf[0] = 0;
for (i = 1; i < argc; i++) {
if (i == 1) {
strncat(buf, "mysql ", sizeof(buf) - strlen(buf) - 1);
}
if (i == argc - 1) {
strncat(buf, "< ", sizeof(buf) - strlen(buf) - 1);
}
strncat(buf, argv[i], sizeof(buf) - strlen(buf) - 1);
if (i != argc - 1) {
strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
}
}
return system(buf);
}
===========8<========================================================
Compile the program
shell> gcc -o sql sql.c
Copy program into the usual location
shell> cp sql /usr/bin/sql
Set execution flag on the script
shell> chmod 755 test.sql
Show script contents
shell> cat test.sql
#!/usr/bin/sql -t
use mysql;
select User,Host from user;
Enjoy!
shell> ./test.sql
Note that in order to use batch mode efficiently you need
non-interactive authentification. The best way is per-user
configuration file: ~/.my.cnf
Create file and put a couple of strings:
[client]
password = yourpasswd
NB! Don`t forget to set proper permissions!
shell> chmod 400 ~/.my.cnf
Now mysql will use this password as you default password.
P.S.S.
You can also pass any mysql parmeters in the sha-bang line.
For example:
#!/usr/bin/sql -t
or
#!/usr/bin/sql -X
or even
#!/usr/bin/sql -u someuser -ppassword
That`s it!
---
There are 10 kinds of people: those who understand binary and those who don`t.
re:Using mysql in Batch Mode - Windows XP - Vista:
If you need to specify connection parameters on the command line for using a text file use forward slashes
and print the word source, not the url of your file.
Example:mysql> source C:/inetpub/wwwroot/your folder/sql.txt; unfortunately the reference manual does
not allude to this.
rich: comrefhvac.com
Batches in Linux are ok but, running batches in Windows via a DOS box (cmd line) causes a lot of problems if other tasks are running.
I have a large file of SQL (1000 lines, 38Kb) that is generated nightly and run as a batch. For about 10 minutes the CPU utilisation is 100% and other programs slow to a crawl.
Sadly we have no nice for cmd.exe so cannot change it. We fixed the problem by using another program to execute the file as a series of SQL statements. As the program is a proper windows program (Delphi) then it yields from time to time and the CPU utilisation drops back. Ok, the SQL takes longer to run, but it run at 2am, so no one is waiting for it.
on windows, there's difference in batch mode(see example):
C:\Documents and Settings\Administrator>mysql -u me -p enagerie < batch.sql
species
cat
dog
bird
snake
hamster
C:\Documents and Settings\Administrator>mysql -u me -p enagerie -e "source batch.sql"
C:\Documents and Settings\Administrator>more batch.sql
select distinct species from pet;
C:\Documents and Settings\Administrator>mysql -u me -p -e "select version()"
The documentation on this page that says: "To echo to the output the commands that are executed, use mysql -vvv." does not work for my version of mysql.exe, I used mysql -v -v -v instead
Add your own comment. | http://dev.mysql.com/doc/refman/5.1/en/batch-mode.html | crawl-002 | refinedweb | 1,599 | 65.01 |
Hello,
perhaps there are other people interested in disabling and later enabling
Toolbar Buttons.
Now I have found a solution:
Send with SendMessage the message TB_ENABLEBUTTON (0x0401) and 0 or 1
Example:
# TB_ENABLEBUTTON, button number (the same that will be passed to the _Click
event), 0/1
$win->tbToolbar->SendMessage(0x0401, 1, 0)
I am still looking for making a toolbar with hot and cold images. Any
suggestions?
Have fun,
Peter
In my application, clicking on a row in a listview displays information in
another window. I have a separate button that clears the display window.
However, I noticed that if I click on the same row again, the display is not
reset. What happens is that the listview does not detect multiple clicks on
the same row; it gets "fatigued". Is there a way to reset this behavior?
_______________________________________________________
Stephan Gross Loral Skynet 908-470-2388 sg@...
<mailto:sg@...>
Try using the CDO.dll. It provides pretty much the
same interface to Exchange e-mail as Outlook does, but
it doesn't require Outlook to be running.
If you have ActivePerl installed you can look at the
Win32 OLE Browser and it will list the available
methods & options. You'll probably want to keep MSDN
or TechNet handy, as their are certain snafus that CDO
has.
Jeremy Blonde
--- Peter_Köller <pkoeller@...> wrote:
>
>
>
>
> _______________________________________________
> Perl-Win32-GUI-Users mailing list
> Perl-Win32-GUI-Users@...
>
__________________________________________________
Do You Yahoo!?
Make international calls for as low as $.04/minute with Yahoo! Messenger
Hello!
When using Win32::OLE and a Win32::GUI RichEdit, I get an "Can't locate
auto/....al" error.
I have searched through the mailing list and found the following:
------
Kevin.ADM-Gibbs@... wrote:
> Has anyone tried using the GUI module with imported
> OLE contants? I'm finding that if I try to use
> something like
>
> use Win32::GUI;
> use Win32::OLE::Const ('Microsoft Excel');
>
> some of my controls aren't defined. I've only noticed
> it with RichEdit fields but it may affect other things
> as well. there was a discussion about this on Perl-Win32-Users
some times ago; you can search for 'RichEdit' in the
mailing list archives. one workaround is to load the
OLE constants in an hash rather than in the main
namespace, something like:
use Win32::OLE::Const;
my $EX = Win32::OLE::Const->Load('Microsoft Excel');
print $EX->{xlMarkerStyleDot};
---
This did work for me sometimes, but don't work anymore. I then declared my
OLE constants by myself like $constant = 34, etc... I removed all
Win32::OLE::Const lines and that worked for a few times.
I reviewd my program, restructered some lines and that don't work anymore,
too!!!
Even if try something like my $riched = $win->AddRichEdit(-name =>
'riched'...) and use $riched->Text() instead if $win->riched->Text();
Please help,
Peter | http://sourceforge.net/p/perl-win32-gui/mailman/message/7578969/ | CC-MAIN-2014-41 | refinedweb | 468 | 73.68 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
dynamic selection for year [Closed]
The Question has been closedby
Hi,
i have written functional field for date
def _get_year(self, cr, uid, context=None): year = int(time.strftime('%Y')) return [((year+r), (year+r)) for r in range(2)]
this is showing the values in selection field , if i try to save and edit the record,the value is not showing.
Thanks.
Value of selection fields are store as
char in database. So problem is that you are returning year as
int. You have to return value in char form.
Try this:
return [(str((year+r)), str((year+r))) for r in range(2)]
This will solve your problem for sure.
year = 2000 #assign starting year year_range = int(time.strftime('%Y')[-2:]) #this will give current year (like 13 for 2013) [((str(year+r)), (str(year+r))) for r in range(year_range+1)]
If you want list from 2000 to 2013 + next 10 years, increment range value by 11 because loop starts from
0:
[((str(year+r)), (str(year+r))) for r in range(year_range+11)]
I have a doubt here, if the current year is 2013 , this will return 2013 and 2014 , and if year is 2014 then i will get 2014 and 2015 , in this 2013 is deleted how to avoid this
That is because of your code. Method will return current year and next coming year only. So previous value will be overwritten by them and you won't be able to see old year's value.
how to make modification for my function so that i can be able to see the previous years
You can set starting year as static and then can generate year's record till current year.
ok ,and it is not possible to store value as integer in database rather than char
See my updated answer.
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/dynamic-selection-for-year-17630 | CC-MAIN-2017-22 | refinedweb | 361 | 76.45 |
MyShuttle.biz and Cross-platform Mobile Development of native apps for iOS, Android and Windows with .NET and Xamarin
Cesar
[**NEW!! – Updated on March 2015 – Compatible with VS 2015 CTP 6 **]
This blog post (focusing on native apps development) is the third post of a blog posts serie. (Current)
When developing mobile apps across different OS platforms (Windows, iOS, Android) in many cases you’d be targeting end customers or scenarios where you want to have the best UX especially tailored and visually designed according to their specific device platform style/guidelines and controls (Windows Phone vs. iOS vs. Android) and at the same time, you want to have the best performance.
You can achieve those goals by developing native apps, of course (like Java for Android or ObjectiveC/Swift for iOS), but Microsoft’s bet to achieve the same goals supported by native apps is a cross-platform approach based on C# and .NET plus Xamarin as the runtimes.
The following diagram summarizes how you can develop cross-platform mobile Apps with C#, .NET and Xamarin:
So, with Xamarin and .NET you can create 100% native apps but reusing around 80% of the C# client code between the different platforms, and code the other 20% in representational markup (like XAML, XML, etc.) or specific platform code, for a UI tailored experience per platform.
In the MyShuttle.biz scenario (see the diagram below) we created several native apps (for mobile and desktop) that I highlighted in there with a yellow star.
Basically, we developed a desktop WPF application, a Windows 8.1 Store app and a Windows Phone 8.1 app both developed as Universal Windows Apps with .NET. Then, an iOS app and an Android app developed with Visual Studio and Xamarin.
(NOTE: That diagram and photo show the mobile apps, so they are missing the WPF desktop app that is also sharing the same C# common code tan the mobile apps).
The important point here? All of those native apps are reusing the same C# code, shared between the .NET apps and the Xamarin apps.
This is true native cross-platform mobile based on C#!!
Setting up the MyShuttle.biz native apps solution in Visual Studio
The requirements in order to set these client apps up in Visual Studio are the following:
– 1. Visual Studio 2015 Preview (or Visual Studio 2013 with Update 4 but you’ll need VS 2015 when working with ASP.NET 5 Services)
Visual Studio 2015 Preview download
– 2. Xamarin (for Visual Studio 2015 Preview)
Xamarin for VS 2015 Preview – download and installation (Check this info from Kzu, Xamarin)
This is also a good post about current Xamarin’s installation on VS 2015 Preview (from Brian Lagunas)
See deeper details about setting Xamarin up in the ‘Xamarin Apps section’ within this blog post
– 3. Make sure you are referencing to nugget.org from VS Nuget Package Manager. You’ll need it in order to ba able to find and grab all the external dependencies we’re using, like MVVMCross, etc.
– 4. MyShuttle.biz ASP.NET 5 Web API Services deployed in Microsoft Azure or any central place/server. You could try to run the ASP.NET 5 services locally, in Visual Studio and its local Web Server and start the services up each time you are going to use the mobile apps, but usually that is harder than placing the services in a global, accessible and stable place, like Azure. When running the services locally (your dev machine) you might get issues trying to consume the services from mobile devices or emulators that might not be able to reach the local IP and services in the same laptop, etc. In any case, in my experience, it is much easier to have the services up and running in Azure and available for any mobile app.
– 5. MyShuttle.biz Azure Mobile Service project deployed in Microsoft Azure. This service is used to handle the push notifications between the different mobile apps, so if you want to have that functionality, you’ll need to have this Mobile Service project deployed into Azure.
– 6. Once you have all the mentioned requirements set up, if you are not used to work with Xamarin projects, I recommend to start by opening the SOLUTION that has no Xamarin projects called 01.1_Demos_NativeApps_Microsoft.sln. Other tan that, if you do know Xamarin and have it installed properly, open the solution called 01_Demos_NativeApps.sln which includes the Xamarin projects.
IMPORTANT: Be patient. The first time you open this solution, due to so many dependencies in NuGet and especially because of the Xamarin projects if you opened the full solution, it will take many seconds to open up, if not a few minutes. Next time you open the solution with most of the NuGet depenedencies already in place, it will be faster. 🙂
Sharing code between all your C# apps with PCL (Portable Class Libraries)
Let’s start in VS from the important point which is that we’re sharing C# code (about 80% of the UI logic, like ViewModels, Service Agents consuming remote services, etc.) between Universal Windows Apps and Xamarin apps thru a PCL (Portable Class Library) which is shared as a compiled library.
Open the PCL project called MyShuttle.Client.Core (Portable).
Setting up the PCL project
This PCL “MyShuttle.Client.Core (Portable)” project contains common configuration code to be re-used by the Windows 8.1 Store app, the Windows Phone 8.1 app, the Xamarin Android app and the Xamarin iOS app. Things like URLs of your deployed services to consume, your Bing Maps key and other settings. We placed this configuration settings in a single point, within the PCL, so we don’t need to place that info spread into the different client apps.
1. Expand the MyShuttle.Client.Core (Portable) project up.
2. Open the file called ApplicationSettingServiceSingleton.cs which is within the folder Infrastructure.
3. Change the value for the DefaultUrlPrefixValue constant to the URL where you must have your ASP.NET 5 Web API services, like deployed in Azure, for instance.
So, in your case it will be something like the following if your ASP.NET 5 Services are deployed to Azure:
private const string DefaultUrlPrefixValue = “”;
4. Change the value for the DefaultUrlPrefixValue constant to your Bing Maps key..
Once you have your key, update that into the code below within the ApplicationSettingServiceSingleton.cs file.
5. In the PCL Project, within the CommonAppSettings.cs file, change the value for the following static strings:
_MobileServiceUrl (Should point to your deployed Mobile Service)
_MobileServiceKey (Should have your Mobile Service key that you can see in Azure’s portal)
_SignalRUrl (Should point to your deployed ASP.NET 5 Service, the same URL than the ASP.NET 5 web app and Web API Services).
PCL code/assets
Now, you can take a look to the code. You’ll see the how we have implemented many ViewModels that are shared between the different C# apps:
For instance, it is not just that the VehicleDetailViewModel.cs code is being shared by the different apps, but it is also being shared in a consistent way thanks to the MVVMCross framework that we’re using across .NET and Xamarin apps.
If you go to the PCL project properties you can see how a PCL can support the different platforms:
You can see there, in the PCL properties, how you can target the different platforms with PCL libraries: Windows Desktop, Windows 8 Store apps, Windows Phone 8.1 apps and thanks to Xamarin support, Android and iOS, all C# code compiled as a PCL library/DLL.
But using a great feature in VS Ultimate, called Code Map, you can prove that we’re actually using this PCL from all the different clients in our scenario. Code Map allows you to research code that you might not be familiar with, like in this case.
Basically, Code Map allows you to map out the structure of your application by connecting your assemblies and methods to see what methods link to each other, so you visually see how your application flows.
In this case, I’m showing you in Visual Studio Code Map how the PCL MyShuttle.Client.Core (Portable) is being referenced from the different assemblies/apps:
Look at that!, we’re reusing C# code in this PCL from a WPF desktop app, a Windows Store 8.1 app, a Windows Phone 8.1 app, a Xamarin-Android app and a Xamarin-iOS app! All C# code reused between native apps!
Code Map also offers insights between classes, methods, and you can even debug in a visual way with Code Map! 🙂
The MyShuttle.biz WPF desktop application
Let’s start with a traditional WPF desktop application that we created for the MyShuttle.biz scenario.
WPF desktop applications are useful in cases where you want to target Windows desktop scenarios, for instance, if you require off-line applications or because of any other reason you want to have a Windows desktop application.
Setting up the WPF app
In order to set this WPF app up, you just need to configure the WPF app and “point to” the ASP.NET Web API Services, so it consumes the central services and data.
1. Expand the MyShuttle.Client.Desktop project up.
2. Open the App.config file and change the URLPREFIXKEY value to the URL where you must have your ASP.NET 5 Web API services, like deployed in Azure, for instance.
If you didn’t deployed the services to Azure, you still could run the services from a Visual Studio and put here the local URL you’d get. In that case, you’d just need to start the ASP.NET 5 application so the Web API Services also start running.
But, in my case, I deployed my services to Azure in this web site so it will be like this for me:
<add key=”URLPREFIXKEY” value=”” />
3. Just go ahead and run the WPF app by hitting F5. You should get something like the following WPF app:
MyShuttle.biz WPF app
This is the sample WPF application that Daniel Moth used for his IDE and performance demos, although he tweaked it so he could highlight a few issues he wanted to pop up and fix.
You can see Daniel’s demos about VS 2015 Preview IDE productivity and performance diagnostics here:
Visual Studio in a world of multiple devices (MINUTE 21:50 of that keynote).
WPF Roadmap
I’m not going to get into details about WPF since it is well know in the .NET community. But what I want to do is to highlight the last WPF news about its roadmap, coming from the WPF team:
The Roadmap for WPF (Nov. 12th 2014)
It seems many people are interested on this… just saying that based on the number of comments in that blog post.. 😉
The MyShuttle Universal Windows apps for Windows Store and Windows Phone
So, as part of the C# native apps, I want to show you the Universal Windows apps that we created for this “MyShuttle.biz” scenario, targeting Windows 8.1 Store apps and Windows Phone 8.1 apps.
These Universal Windows apps are built by re-using C# and reusing the PCL I just showed previously, also shared by the Xamarin apps.
But, since Windows apps have more similitude between them than compared with Xamarin apps, we’re also using a Shared project with additional code being shared just between the Windows Store and Windows Phone apps.
Shared projects share code just like linked projects. You could also use Share Projects to share C# code between Xamarin projects, but in this design we decided to use PCL as the most global and common code to share, then, a Shared Project to share code just between the Windows Store apps, since a Shared project is the typical common project for universal apps. But you could have a different approach, like I said.
Running the Universal Windows apps (Windows Store and Windows Phone) in the emulators
Sure, you could run the Windows apps in devices, but before deploying to devices that you might not have, you might want to test it on top of emulators.
First of all, if you want to see the Windows Store app within an emulator rather than running directly in your Windows 8.1 machine, you need to configure that in the Windows Store project properties, like below, where I’m setting the “Simulator” as target device:
By the way, the first time run the apps, you might need to deploy the apps one by one by right-clicking on the project and hitting on “Deploy”:
And:
But, after that, if you change the startup settings for the solution, you could run both Universal apps at the same time in the different emulators (Tablet and Phone).
Hit OK and then just hit Ctrl+F5, so you should get both apps running on the Windows Store and Windows Phone emulators at the same time!
The point here is that even when most of the C# code is being reused by the different Universal apps, you are still able to create a personalized UX depending on the form-factor, as you can see above, the layout and design guidelines for a Phone app is usually different tan for a Tablet app.
But if you need or simply want, you can also re-use exactly the same XAML views between Windows Phone apps and Windows Store apps.
For instance, open the XAML view About.xaml in the shared project “MyShuttle.Client.UniversalApp.Shared”, within the Views folder. In this case we’re reusing the “about Xaml page” between the two form factors. You could do so in any page/view that you´d like, as well.
I can visually edit the XAML view and see it how it looks like as a Tablet…
Or I can go ahead and change the selected form-factor in design mode by opening the combo-box on the bottom left side of the visual designer and change to a Windows Phone form factor.
If you cannot find the form factor selection combo (related Universal projects), you need to enable that from Tools—>Options—>XML—>General—>Navigation bar (It is not enabled by default in VS 2015 Preview..).
So I check how it would look like as a Phone, as you can Check below.
OK, so clearly, this XAML view could be shared between the two form-factors in a good way!
The MyShuttle.biz native Apps for iOS and Android powered by Xamarin, C# and VS
As you may know, Microsoft bets strong on .NET native apps development thru our partnership with Xamarin.
With Xamarin, you can develop full native iOS and Android apps by re-using your C# skills and right in the tools and development environment you are familiar with: Visual Studio.
Here you can see the “MyShuttle.biz” apps developed in C# with Xamarin and running in an iPhone and an Android smartphone, and sharing most of the C# client code that we were also using from the Universal Windows Apps and WPF app thanks to our common PCL.
Xamarin installation and Configuration
1. Install Xamarin on top of Visual Studio 2015 Preview.
Xamarin for VS 2015 Preview – download and installation (Check this info from Kzu, Xamarin)
This is also a good post about current Xamarin’s installation on VS 2015 Preview (from Brian Lagunas)
(UPDATE January 9th 2015): As of today, you still need to upgrade to the ALPHA channel either in Xamarin Studio in the MAC and in Xamarin within Visual Studio 2015 Preview in Windows. Other than that, I am not able to connect from VS 2015 Preview to the Xamarin iOS Build Host running in the MAC so I can build and debug.
2. Log in with you Xamarin account, from Visual Studio, before opening the MyShuttle SOLUTION. It is a good thing to login with your Xamarin account first, so you won´t get any warning from the iOS Project that could slow down the projects opening Process in VS. Although, you could do it later.
You can do so from VS –>Tools—> Xamarin Account
If you have a Xamarin’s Business account, you´ll have to see a similar secreen to the following, after logging in:
If your account is not Business, you´ll be able to work just with Android projects.
3. VS Solution with Xamarin projects
Have opened the 01_Demos_NativeApps.sln. When opening the SOLUTION with any Xamarin Project for iOS, you´ll get the following dialog requesting for your iOS build host (a Mac with Xamarin installed and running the Xamarin build host). If you Still don´t have that installed, just cancel that dialog, then you’ll be able to work just with the Android Project, though.
4. Set the apps custom configuration up (Within the Shared PCL)
In order to set up the Xamarin Apps to consume your own services, you need to configure the PCL. Make sure you did those steps explained within the PCL section in this blog post (section called “Setting up the PCL project”).
Xamarin templates for Visual Studio
Before drlling down into our projects, take a look to the project templates in Visual Studio that you can use to create iOS and Android apps.
iPhone and iOS Project templates based on C# within Visual Studio 2015 Preview, after installing Xamarin.
Android project templates based on C# within Visual Studio 2015 Preview, after installing Xamarin.
So, in the MyShuttle.biz solution we created two Xamarin projects. One for iOS and the second for Android, develop in C#.
Again, I want to highlight that both projects are reusing the same C# logic that we´re also using from the Windows apps, which was placed in the PCL library, with most of the operations like ViewModels based on MVVMCross framework and Service-Agents.
Intellisense in Xamarin projects
And of course, because you are using Visual Studio and C# you get what you expect from it. You can develop with all the richness in VS like using intellisense even with classes and code related to the mobile device, like in this case, the Android camera or any other hardware related feature in Android when you type that namespace within any C# file in the Xamarin Android Project.
Xamarin Designers in Visual Studio, for iOS and Android views
Xamarin extends Visual Studio not only at a runtime and programming level, but also with productivity tools like visual designers for iOS and Android apps views.
For instance, you can see here the Android Views designer or the iOS designer where I can very easily and visually design my iOS app’s storyboard.
1. iOS Storyboard view: Open the MyShuttle.Client.iOS project root –> Storyboard.storyboard file
The iOS Designer for StoryBoards is new since Xamarin 3. It is worth to highlight that the screens are rendered in the remote MAC thru the Xamarin build Agent, then VS gets it and shows it in a WYSIWYG way. Using the iOS designer you can drag and drop controls and get the best productivity for iOS development.
NOTE: Like mentioned, in order to render the iOS storyboard you need to have Visual Studio connected to a Mac which has to be running the Xamarin Build Host agent. Check this info in order to know how to work with Xamarin iOS projects:
Introduction to Xamarin.iOS for Visual Studio
iOS User Interface design in Visual Studio and Xamarin Studio
2. Android view: Open the Android project –> Resources –> Layout –> VehicleDetailView.axml
The Android views can be rendered and edited directly in Visual Studio with no connection to any other environment.
Microsoft Visual Studio Android Emulator
These designers are great, but the designers aren’t quite enough, you really need a rapid development and execution environment experience with a running app. This is why we are releasing a new Microsoft Visual Studio Android emulator, brand-new since Visual Studio 2015 Preview.
This is x-86 based image runs on Hyper-V and is optimized to run on Windows machines. So no more reboot to switch your focus from Windows to your Android app. You can run the app, debug it, etc. like if you were debugging in a real Android device.
Disable Fast Deployment of Android Project when deploying to VS Android Emulator
With current version of the Microsoft Android emulator and Xamarin (VS 2015 Preview timeframe, nov/Dec 2014), in order to get the Microsoft Android emulator working for Xamarin projects, you need to have the “Fast Deployment” disabled within the Xamarin-Android Project properties and Android Options tab:
After doing that, if you debug or deploy the Android Project by targeting the Microsoft Android emulator, it should work.
Wrap up about C# cross-platform development, .NET and Xamarin
Regarding native Apps with Xamarin, remember, whatever you can do in Objective-C or Swift for iOS or in Java for Android, you can do the same with Visual Studio, C#, and Xamarin.
So, as you saw in this post, C# provides a unique approach for Cross-platform Mobile development of native apps, either for Windows (Desktop, Windows Store or Windows Phone) when using .NET or for iOS and Android when using Xamarin. But the important point here is that you’re using C# and Visual Studio, you are re-using the same skills and even the same familiar development environment to build native apps across different OS platforms!
Download the code!
Download page from MSDN Samples | https://devblogs.microsoft.com/cesardelatorre/myshuttle-biz-and-cross-platform-mobile-development-of-native-apps-for-ios-android-and-windows-with-net-and-xamarin/ | CC-MAIN-2019-43 | refinedweb | 3,596 | 60.24 |
This is your resource to discuss support topics with your peers, and learn from each other.
04-17-2009 10:53 AM
Hi, I'm developing a CLDC Application on JDE 4.7, and I have a problem while I create a custom Field (any field, NullField, VertivalFieldManaher, LabalField, etc). I make an override from the getPreferredWidth() or getPreferredHeight() methods to set the new height and width of my field, but when a print a string to console in the method paint, I see that this method paint is executed in a cycle.
This an expmple of code:
public class ExpanderField extends VerticalFieldManager { public int getPreferredHeight() { return 200; } public int getPreferredWidth() { return 200; } protected void subpaint(Graphics graphics) { //super.paint(graphics); System.out.println("Paint Method Executed"); } protected void sublayout(int width, int height) { super.sublayout(getPreferredWidth(), getPreferredHeight()); super.setExtent(getPreferredWidth(), getPreferredHeight()); System.out.println("layout executed..."); } }// ExpanderField class
In this example, the string "Paint Method Executed" is printed constantly. I don't know why the paint method is executed all the time.
Anybody know what's happen?
Solved! Go to Solution.
04-17-2009 12:04 PM
I think that I found the answer. In other class of my project I put the sentence setPosition(); within the paint() method of a VerticalFieldManager and this sentence call the paint method again, so this make a cycle, and all the fields controlled for this VerticalFieldManager are painted again when is executed the paint method in the VerticalFieldManager.
But I have a question for the RIM Developers...
Why in the code example above, you're using the sentences setPosition(); and getManager().invalidate(); within Paint() method?, so this sentences call constantly the Paint method and don't stop never, it is not a efficient way to program an application.
04-18-2009 01:39 AM
Hi,
I did'nt find any setPostion() call in the program
.
And they have mentioned why they have used invalidate() just make changes in this program and notice the chnage in the behaviour.
You will be able to understand it more clearly. | https://supportforums.blackberry.com/t5/Java-Development/How-to-change-the-size-of-any-Field/m-p/214184 | CC-MAIN-2016-30 | refinedweb | 344 | 56.35 |
Shortcuts: Downloads Fedora Red Hat Network
Issue #19 May 2006
Lyceum is a blogging services system, based on WordPress. Lyceum was conceived, funded, and developed by ibiblio, an online digital library that has been around for more than a decade, was one of the original mirrors of Linux distributions, and is the home of Project Gutenberg, Groklaw, the Linux Documentation Project, iCommons, and more than 1500 other collections.
In 2004 and 2005, blogging was becoming a Big Deal, and the blogging software scene began to mature. Ibiblio saw how important blogging was as a new web-enabled medium. Through our experience providing services and support to our collections, and research of available solutions, we saw an obvious deficiency in the blog system market: software that could support multiple blogs from one installation..
Lyceum has evolved into a full-featured blogging services package, offering the following features:
The development of Lyceum has been an exciting journey, and it has only just begun. Below I offer a description of how we began the project, and the architectural features we have implemented so far.
Any software project requires proper infrastructure. No matter how big or small, no matter how few programmers, there are two things that every software project lasting more than a week should absolutely have: (1) source control, and (2) issue tracking. For these two things, we went the route that many open source projects are going these days: Subversion and Trac. These powerful free tools provide stellar infrastructure for an open source software project.
Subversion is considered by many to be the successor to the venerable CVS. Some of its immediately noticeable advantages over CVS are:
Trac is a project management system. It has three core functions:
One of the things that makes Trac so nice to work with is the ability to link between the objects of each system using simple syntax. For example, when writing a comment on a "ticket" (a bug report or a feature request), the string
changeset:101 will render as a link to a graphical view of that changeset (including a visualization of the changes made in each file). Similarly, in the comments of a Subversion commit, one may use the string
ticket:42, which will then render as a link to that ticket. Tickets, changesets, and wikipages may all link to one another arbitrarily.
To facilitate the growth of a Lyceum community, we also made sure that mailing lists were in place. We went with the standard trifecta: developer, user, and announcement. For those who want immediate answers and fascinating discussion, #lyceum on freenode is the coolest place to be.
Our incentive for using WordPress is to take advantage of its interface, plugins, and themes. Therefore staying parallel with its codebase is extremely important. When we began to work on Lyceum, WordPress 2 development had just begun to pick up steam. We felt it was important to merge in changes on a weekly basis, to avoid surprises down the road. We needed an easy way to regularly and reliably merge changes from the WordPress trunk.
Our initial solution, while a little hacky, was effective and (mostly) reliable. We found that Subversion is happy enough to merge changes from one repository into another. An example merge command, executed from /src/lyceum/:
svn merge -r2955:2958
This command results in the familiar update output, noting files that were added, deleted, or updated, those that caused a conflict, and those that were merged. Merges are manually documented in /dev/wordpress_patch_history.txt. I call this technique a "foreign merge."
Subversion-savvy readers are now thinking, a foreign merge will result in inconsistent, meaningless, and/or corrupt Subversion metadata, and is prohibited in Subversion version 1.3 and beyond. Both of these thoughts are correct. To my knowledge there is no documented or recommended way to use Subversion to perform a foreign merge. This method worked well for us through the last time we used it, when we synchronized with WordPress 2.01. After this point, Lyceum's file structure became significantly different from WordPress', as described below in the section on security. To help resolve this issue, it would ideal if Subversion could:
Lyceum has made significant changes to WordPress' file structure, and intends to merge in almost all of its changes for the indefinite future. I have coined a phrase for this type of project: "Benevolent Rogue Heterostructural Parallel Branch." Such projects are certainly few and far between, and therefore their needs will probably not be directly addressed with Subversion features in the near future. We have yet to come up with a perfect solution, but it will probably entail shell scripts hard-coded with file path information, command-line diff and patch, and manual documentation. If any readers have ideas as to how we may more easily manage merges, please contact us at lyceum AT ibiblio DOT org.
Lyceum multiblogifies WordPress and adds few other features. The Lyceum database schema, as one might expect, is very similar to the WordPress schema. The only added infrastructure is used to associate data with blogs. reference a row in the
blogs table:
And lastly, a few additional columns have been added:
The rest of the WordPress schema remains unchanged. Those who don't do much DB design may be wondering why there isn't a blog column in more (or all) of the tables. This is because some of the tables are associated with a blog through another.
The URL for each blog in a Lyceum installation includes a "slug," either as a subdomain () or a directory (), specifying which blog is being accessed. Using mod_rewrite (which is required to run Lyceum), this slug is transformed into a URL variable,
b (for "blog"). The magic of this architecture is that, in the development of Lyceum, the vast majority of business logic, including that which generates URLs, did not need to be modified.
Consider the following relative path in WordPress:
file.php?x=5&y=42
This represents the URL:
In Lyceum, the code which generates this URL is unchanged. But since the Lyceum URL already has the base:
The link will lead to:
The rewrite engine will then transform this to:
providing the
b variable that is used throughout the system.
Included in the collection of unmodified URLs are those generated by the WordPress permalink engine. URL design in WordPress is very flexible and powerful. Through the web interface, WordPress users can use a multitude of tags in many different combinations to create permalinks of their liking. Examples include:
Furthermore, searches can be done as such:<term1>+<term2>+...
And the RSS feed URL is simple and intuitive:
In Lyceum, all of these features remain usable and adjustable on a per-blog basis, and no URL logic needed to be modified to achieve this. Those familiar with the WordPress source code may be surprised to see the results of performing a diff on WordPress and Lyceum's respective classes.php files.
Although the business logic of WordPress happily lives within Lyceum's schema, it was still necessary to tweak a large portion of the SQL statements in order be relevant to the new schema. To assist in the modification of the SQL statements, Lyceum uses SQL generator functions for the two most frequent types of commands: those which perform selections on only the
posts table, and those which perform selections on only the
posts table:
function make_post_query($columns, $criteria){ global $blog; $sql = " SELECT DISTINCT $columns FROM posts INNER JOIN post2cat ON (post_id = ID) INNER JOIN categories ON (category_id = cat_ID) WHERE blog = '$blog' AND $criteria ;"; return $sql; }
This generator is used within a series of one-liner functions that wrap around existing WordPress database functions. For example, the wrapper for the function
get_results() is
get_post_results(). Here is an example of a call to the DB in WordPress:
get_results(" SELECT ID, post_title FROM posts WHERE post_status = 'draft' AND post_author IN ($editable) AND post_author != '$user_id' ");
And the equivalent action in Lyceum:
get_post_results( 'ID, post_title', "post_status = 'draft' AND post_author IN ($editable) AND post_author != '$user_id'" );
All of the columns in the join are unique and indexed (B-tree), providing unfettered logarithmic access time to the data location. So the worst-case time-complexity for the entire join is O(3xln(n)), where n is the cardinality of the
posts or
categories table, whichever is greater. It will take quite a large data-set for this query to become a significant problem, and even then the problem can be solved by scaling the hardware linearly with n. For applications where such large datasets may arise, a problem that can be solved by the linear scaling of hardware is not a problem.
Add to all of this the fact that systems with gobs of memory are rather affordable these days (a 1U 64 bit server with 16 GB of RAM can be had for just over $10k), and you end up with the MySQL query cache cutting down query overhead by orders of magnitude.
In the future we will be experimenting with the possibility of using views in MySQL 5 to further optimize these queries.
To support large installations, it is essential that Lyceum use InnoDB tables instead of the MyIsam tables typically used in WordPress installations. InnoDB supports row locking (vs. MyIsam's table locking) and other features designed for large, high-demand datasets. Unfortunately, InnoDB does not support full-text search in MySQL 4 (in MySQL 5, it does). It is important that Lyceum support MySQL 4. In order to support full-text searching, we have created a lone MyIsam table,
postsearch, for the purpose of storing redundant searchable content.
WordPress and Lyceum's security needs differ in two ways. The first is the dramatically increased cost associated with an intrusion on Lyceum. A single security breach on a Lyceum installation can affect thousands of blogs and compromise data and services for thousands of users. This makes a breach more devastating, and creates a more desirable target for attackers.
The second is the social circumstances under which the two systems are used. Though WordPress allows for unmoderated and arbitrary account registration, few installations exercise this option. The vast majority of WordPress installations have one or a handful of authors, all of whom know one another personally. Lyceum, on the other hand, will often be used in environments where account registration is either wide open, or isomorphically associated with some other user namespace (such as a university network). In these situations, there is no lower bar of trust that users can expect from one another. Thus, comprehensive security design is a must.
There are two main security enhancements that Lyceum brings to the WordPress codebase. The first is a simple Best Practices redesign of the file structure: all of the non-web-requestable files in the system have been moved out of the web server document root. For open source projects (where there is no security gained by hiding the source code), compromises involving this vulnerability are very rare. Even so, they can be devastating and this is a key part of a "defense in depth" security strategy.
For the reasons mentioned above, it is not as crucial for WordPress to be secured in this manner. In addition, it would also be impractical; many hosting facilities do not allow users to configure the document root of their websites. In these situations it would be very difficult or impossible to install a web application that used files outside of the document root. In fact, this was the #1 complaint when Lyceum was first released. In response, we designed a system that allows the lib, config, and installation directories to be moved into the document root at the user's discretion. See the installation instructions and the comments in src/lyceum/private.php for more information.
The second architectural security enhancement that Lyceum introduces is the comprehensive, system-wide use of security tokens, (a.k.a. "nonces") in all POST and mutational GET requests, to defeat cross-site scripting, cross-site request forgeries, and spoofed forms. These tokens are a one-use, per-user, per-action, and sometimes per-object sha1 hash. Whenever a page in the admin interface is requested, all of the controls within it that perform data-changing actions have a security token associated with them. Security tokens are included in a hidden field in all forms, and as an HTTP variable in all link URLs.
For example, in the Manage→Posts section of the admin interface there is a list of posts, each with a 'Delete' link to a URL that looks something like this:
The token has been generated randomly:
$token = sha1(uniqid(rand(), TRUE));
And placed into an array in the php session, indexed by another hash that has been generated like this:
$key = sha1($targetscript.$action.$id.$userdata->ID);
In this case $targetscript is 'post.php', $action is 'delete', $id is 1, and $userdata->ID is the user id of the current authenticated user. After
$token has been generated and placed in the session, the only way for Lyceum to access it is by first generating the proper
$key, which requires using the correct user id, which restricts usage of the token to the user who generated it in the first place. Therefore, the security token system is as secure as the authentication system.
Currently, the Lyceum authentication system is essentially identical to that of WordPress. It stores a local double-hashed password in a cookie, and authenticates on every request. This is problematic: if the cookie is stolen, it may be used by an attacker indefinitely, unless the user changes their password. It is also somewhat less efficient to pass a username and password back and forth instead of a single session key. The solution, which Lyceum aims to implement in a forthcoming release, is to store the authentication information in a session, which periodically times out and then refreshes itself automatically. Then, if a session key is stolen, it is only good until the true user logs in again (with a stale session key). The true user will be prompted to reauthenticate, therefore canceling the stolen session being used by the attacker.
There are various other security features in Lyceum that are part of a "defense in depth" security strategy. One is the storing of session information in a database table instead of in temporary system files. This dramatically reduces the vulnerability of session data files, particularly in a shared hosting environment running PHP as an Apache module, where access to session data in /tmp by other users on the machine is trivial. Another feature requires the system admin user (the 'root' user of a Lyceum installation) to authenticate from a fixed list of IP addresses.
Blog spam is an ever increasing problem for the Web. 87% of blog comments are spam ["Live Spam Zeitgeist," 8 May 2006]. Most single-blog systems available today include anti-spam tools, with varying degrees of effectiveness. For blogging services systems such as Lyceum, quality of service, resource availability, and consistency of user experience for hundreds or thousands of users are a primary concern. A comprehensive and evolving set of anti-spam tools is essential. The Lyceum anti-spam strategy encapsulates several standard anti-spam measures, and a few that are specific to the needs of a large-scale blogging services system. Some of the below features are already implemented, and all of them will be included in future releases:
If using the above strategies, including the Javascript components, these anti-spam measures will eliminate all spam originating from bots. For now. The spam arms race never ends.
Some administrators may not want to require that a user have Javascript enabled to post a comment. This will allow a portion of spam bots to penetrate the system. An even bigger problem is human spammers. For this kind of spam, other heuristic techniques need to be employed. There are a variety of stand-alone anti-spam plugins for WordPress that will work equally as well in Lyceum. Some may even be made more effective because the dataset of the entire Lyceum installation can be used to help identify spam.
An anti-spam solution that stands out above the others is Akismet, produced by Automattic, the people who develop WordPress. Akismet is an anti-spam system that consists of a WordPress plugin, and a centralized service, through which comments are filtered. The heuristics employed by Akismet are unpublished, but our blackbox evaluation has shown the system to be very effective.
We are excited to see the ways in which people use Lyceum. The feedback we have gotten so far has been very positive, and already we are benefiting significantly from bug reports and patches being submitted by our users, even so early in the project. A testament to the power of open source. If you would like to learn more about Lyceum, please explore the links below, or to discuss this article, visit this thread.
John Joseph Bachir is a computer science graduate of Rice University, and is the chief architect of Lyceum. He currently works at ibiblio.org, one of the nation's premier public domain resources and research labs. Ibiblio is located at the University of North Carolina at Chapel Hill and is a collaborative project of the School of Information and Library Science and the School of Journalism and Mass Communication. Ibiblio hosts the Lyceum project, among many others. | http://www.redhat.com/magazine/019may06/features/lyceum/ | crawl-002 | refinedweb | 2,907 | 51.58 |
In the previous article, we learned the very basics of custom control implementation. Today, we take a closer look at control painting. This topic is quite important because successful controls must look nice and they must fit into the Windows environment. This task is not as simple as it sounds, especially if you consider that most applications support more than one particular Windows version, and that in the last 10 years, almost every Windows version changes the default visual appearance of its controls.
Over time, Microsoft has provided many APIs for 2D graphics and painting. GDI (GDI32.DLL) is available since ancient times, and can be used everywhere. GDI+ (GDIPLUS.DLL) is part of Windows XP and newer (but a redistributable version of it can be downloaded from the Microsoft website). Direct2D is the newest and it is available only on Windows 7 and newer.
In general, the newer APIs are capable of better graphics (e.g., support for anti-aliasing, alpha channels, etc.) and have better performance characteristics (when used in the right way) as they can offload many tasks to the graphics card, while GDI operates mainly on the main system memory and on the CPU.
However, we will mainly stick with GDI, in this article as well as the following ones. For custom controls implementation it is usually sufficient, it works everywhere, and last but not least, the paint-related messages a control receives are GDI-centric due to historical reasons. Of course, using the newer painting APIs is possible but it is not the subject of our interest.
All that said, this article is not about GDI painting. There are plenty of resources on the net on that. On this site, the topic is quite thoroughly covered by Paul Watt:
The preceding article already provided a code for a trivial control which was, of course, also capable of painting itself. Let's take a look at the painting code from that example once again. When the control's window procedure gets the message WM_PAINT, it was just calling our function, CustomPaint():
WM_PAINT
CustomPaint()
static void
CustomPaint(HWND hwnd)
{
PAINTSTRUCT ps;
HDC hdc;
RECT rect;
GetClientRect(hwnd, &rect);
hdc = BeginPaint(hwnd, &ps);
SetTextColor(hdc, RGB(0,0,0));
SetBkMode(hdc, TRANSPARENT);
DrawText(hdc, _T("Hello World!"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
}
static LRESULT CALLBACK
CustomProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg) {
// ...
case WM_PAINT:
CustomPaint(hwnd);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
The code sample already presents the very basic principle: Whenever the control needs painting, the system sends message WM_PAINT. The handler (here the function CustomPaint()) gets the device context handle (BeginPaint()), then uses it to paint the control with GDI functions (here, it just draws the string "Hello world" to the middle of the control), and then releases all resources with EndPaint().
BeginPaint()
"Hello world"
EndPaint()
So far, there is no issue. However for good painting of complex controls, we simply need better understanding of how things really work. Otherwise, you will probably find yourselves on some web forum, searching for an answer to the omnipresent question "How to prevent control flickering when it is being resized?"
Also, complex controls may have a need to paint in other times then when WM_PAINT is received, or they may even have a need to paint outside its client area, either into the control's non-client area, or completely outside of the control's area.
So how are the things around WM_PAINT glued together? From a perspective of the control (or more generally, any window represented with a HWND handle), there are several important messages, not just the WM_PAINT, and also some other concepts tightly related to the control painting.
HWND
First of all, we have to answer the question which any attentive reader already asks: When does the system decide the control needs to be painted? For each HWND, the system manages its window update region (also known as dirty region). The region describes part of the window, whose content is invalid and needs repainting. When the region is not empty, the system knows the control (actually its part as defined by the region) needs repainting and it will eventually send the control the WM_PAINT when there is no other message in the message queue of the window's thread.
Normally, the system does not remember the contents of a window. For example, whenever a window is moved to the edge of the screen so part of it is behind the corner, or whenever it is obscured by another window, the actual contents of the window is lost. After the window becomes fully visible once again, the system adds the unveiled part of the window into the update region which then eventually leads to requesting its repainting.
The control may also need to repaint itself or its part because its state or the data it shows has changed. To do so, the control simply may call a Win32API function to expand the update region InvalidateRgn() or one of its more specific relatives. In most cases, the region to be invalidated has a rectangular shape, so in most cases, the function InvalidateRect() is used instead.
Win32API
InvalidateRgn()
InvalidateRect()
I already noted that the repainting itself is also more complex than just sending the message WM_PAINT:
First, the system asks the control to erase its background with the message WM_ERASEBKGND. This may be as soon as the region is invalidated. The parameter wParam is set to the window's device context, which can be used to paint something. However the painting, if used at all, should be very fast, and usually consists of only filling the area with some background brush, hence effectively erasing its background. If the control passes the message into DefWindowProc(), this is exactly what happens. DefWindowProc() simply gets the brush which was specified during window class registration (WNDCLASS::hbrBackground) and fills the control with it. Have you ever seen a grayish window on your screen when your machine is very busy with some very CPU-intensive tasks and you bring open a new window or bring a window to the top of the Z-order? Well, this is the reason. The grayish window has already received the WM_ERASEBKGND but not yet WM_PAINT. The return value is also important, the message should return non-zero if it performs the erase, or zero if it does not. (DefWindowProc() follows it and returns non-zero if it filled the control with the background brush, or zero if it did not because the WNDCLASS::hbrBackground was set to NULL.) We will see soon what it is good for.
WM_ERASEBKGND
wParam
DefWindowProc()
WNDCLASS::hbrBackground
NULL
If the update region also intersects the non-client area of the window, the system sends WM_NCPAINT. For top-level windows, this message is responsible for painting window caption, the minimize and maximize buttons, and also the menu if the window has any. For child windows (i.e., controls), it is often used for painting a border and also scrollbars if the control supports them in a similar way as, for examples, the standard list-view and tree-view controls do. If the control just passes the message into DefWindowProc(), it paints a border as specified by the window style WS_BORDER and/or extended style WS_EX_CLIENTEDGE and the scrollbars as set by SetScrollInfo(). For today, we leave the WM_NCPAINT aside and we will return to it in a future article.
WM_NCPAINT
WS_BORDER
WS_EX_CLIENTEDGE
SetScrollInfo()
Finally, the WM_PAINT is sent. However, note that the system treats this message specially and it comes only after all other messages from the message queue are handled and it is empty. If you think about it, it makes sense. As long as there are other messages in the queue, they may change the state of the control, resulting in a need for yet another repainting.
The system assumes that a control uses BeginPaint() and EndPaint() when handling WM_PAINT. Between the two calls, the application is expected to paint the whole invalid region of the control.
The first function, BeginPaint(), initializes the pointed structure PAINTSTRUCT and returns the device context (HDC) to be painted on (the same handle as stored in the structure). Two members are often very useful when handling the painting: the member fErase, which is set to TRUE if the window has not been erased with WM_ERASEBKGND (i.e., depending on the value that message has returned), and the member rcPaint, which is the smallest rectangle enclosing the invalid region which needs repainting.
PAINTSTRUCT
HDC
fErase
TRUE
rcPaint
The latter function, EndPaint(), frees any resources taken by BeginPaint() (e.g. the device context), and it also validates the invalid region, i.e., the invalid region of the control becomes empty after this call.
Often, when a non-experienced control developer creates his first custom control, he is quite happy with it until he uses it in an application which resizes it together with the main window it resides in. When running it, he is then surprised by its ugly flickering. It is a wide-spread problem, so we pay a special attention to it.
If you already understand how Windows manages the painting from the section above, you probably already can see the culprit:
WM_SIZE
CS_HREDRAW
CS_VREDRAW
If you understand the cause of the issue, it is quite easy to formulate hints for avoiding it. But let's list them here anyway for the sake of completeness. I tried to list the hints in the order of their importance (which, of course, is a subject of my personal preference to some degree).
If possible, do not rely on WM_ERASEBKGND, i.e., let it return non-zero without passing it into DefWindowProc(). Often, WM_PAINT can paint all the background of the dirty region and there is no need for such erasing.
If you need to handle erasing specially from the painting itself, it can often be optimized so that WM_ERASEBKGND still does nothing but returns non-zero, and the handler of WM_PAINT can do the "erasing" by also painting the areas not covered by the regular paint code when PAINTSTRUCT::fErase is set.
PAINTSTRUCT::fErase
To the reasonable degree, try hard to design the painting code so that it does not repaint the same pixels multiple times. E.g., to paint blue rect with red border, do not FillRect(red) followed with FillRect(blue) to repaint the inner contents from red to blue. Rather paint the red border as 4 smaller rectangle not overlapped with the blue contents.
FillRect(red)
FillRect(blue)
For complex controls, the paint code may be often optimized to skip a lot of painting outside the invalid rectangle as specified by PAINTSTRUCT::rcPaint, by proper organizing the control data.
PAINTSTRUCT::rcPaint
When changing the control state, invalidate only the minimal required region of the control.
When the flickering still happens during resizing, consider to not using CS_HREDRAW and CS_VREDRAW. Instead, invalidate the relevant parts of the control in handling the WM_SIZE manually. Often much smaller parts of the control may need repainting.
When the control supports scrollbars, and using them leads to flickering, make sure the scrolling code uses ScrollWindow() function instead of invalidating whole control area. (Note we will cover the topic of scrolling in one of the sequel articles.)
ScrollWindow()
Generally, the flickering effect is also reduced when the painting performs better. If your paint method does not rely on the system setting the clipping rectangle to the client rectangle of the control, you may use window class style CS_PARENTDC when registering the control window class, leading to less work for BeginPaint().
CS_PARENTDC
Note that although some of the points above may seem like a lot of work for a developer, it is very often a work which will be needed to be done anyway for a fully featured control which implements, for example, features like hit testing (WM_HITTEST). A lot of the code then may be reused. For example, consider a control which paints a table of some sort, each cell providing some interactive response when a user clicks in it. Then the code must be aware of the layout of the table, and the code computing the layout may be reused for the paint implementation and hit testing implementation.
WM_HITTEST
In case everything above fails, there is also a magic wand called double buffering which can solve the flickering in all cases (assuming the erasing via WM_ERASEBKGND is suppressed and delayed to WM_PAINT). But there is some price to pay for using it: higher resource consumption, especially memory. Even if your control still has the flickering problem after all you did in some situation, I recommend to use double-buffering only if the application explicitly requested for that (e.g., by specifying a style for it) because often the application never allows the situation when the flickering occurs (e.g., the application never resizes the control).
Double buffering is a painting technique based on the fact that you may paint the control into a memory-based bitmap instead of directly on the screen, and then, after all the complex painting is done, you may copy (blit) the whole bitmap on the screen in a brisk.
Let's present a sample code of how it may look like. We start with the trivial control implementation and from the previous part, add the double buffering code:
/* custom.h
* (custom control interface)
*/
// ...
/* Style to request using double buffering. */
#define XXS_DOUBLEBUFFER (0x0001)
// ...
/* custom.c
* (custom control implementation)
*/
#include "custom.h"
static void
CustomPaint(HWND hwnd, HDC hDC, RECT* rcDirty, BOOL bErase)
{
// ... Paint the control here.
}
static void
CustomDoubleBuffer(HWND hwnd, PAINTSTRUCT* pPaintStruct)
{
int cx = pPaintStruct->rcPaint.right - pPaintStruct->rcPaint.left;
int cy = pPaintStruct->rcPaint.bottom - pPaintStruct->rcPaint.top;
HDC hMemDC;
HBITMAP hBmp;
HBITMAP hOldBmp;
POINT ptOldOrigin;
// Create new bitmap-back device context, large as the dirty rectangle.
hMemDC = CreateCompatibleDC(pPaintStruct->hdc);
hBmp = CreateCompatibleBitmap(pPaintStruct->hdc, cx, cy);
hOldBmp = SelectObject(hMemDC, hBmp);
// Do the painting into the memory bitmap.
OffsetViewportOrgEx(hMemDC, -(pPaintStruct->rcPaint.left),
-(pPaintStruct->rcPaint.top), &ptOldOrigin);
CustomPaint(hwnd, hMemDC, &pPaintStruct->rcPaint, TRUE);
SetViewportOrgEx(hMemDC, ptOldOrigin.x, ptOldOrigin.y, NULL);
// Blit the bitmap into the screen. This is really fast operation and although
// the CustomPaint() can be complex and slow there will be no flicker any more.
BitBlt(pPaintStruct->hdc, pPaintStruct->rcPaint.left, pPaintStruct->rcPaint.top,
cx, cy, hMemDC, 0, 0, SRCCOPY);
// Clean up.
SelectObject(hMemDC, hOldBmp);
DeleteObject(hBmp);
DeleteDC(hMemDC);
}
static LRESULT CALLBACK
CustomProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg) {
// ...
case WM_ERASEBKGND:
return FALSE; // Defer erasing into WM_PAINT
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
if(GetWindowLong(hwnd, GWL_STYLE) & XXS_DOUBLEBUFFER)
CustomDoubleBuffer(hwnd, &ps);
else
CustomPaint(hwnd, ps.hdc, &ps.rcPaint, ps.fErase);
EndPaint(hwnd, &ps);
return 0;
}
// ...
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
As it can be seen, the prototype of the function CustomPaint() has changed: It is now capable of painting the current control state to any device context, not just on the screen. The BeginPaint() and EndPaint() machinery has moved directly to the WM_PAINT handler. When double buffering is enabled (the control has the style XXS_DOUBLEBUFFER), the function CustomDoubleBuffer() is called to paint the control onto a temporary bitmap, which is then copied on the device context retrieved by BeginPaint().
XXS_DOUBLEBUFFER
CustomDoubleBuffer()
A few other things are worthy of any note as the code is quite self-explanatory:
When using the double buffering, we always pass bErase as TRUE because, obviously, when double-buffered, the in-memory bitmap must be painted completely from scratch.
bErase
As a small optimization, instead of allocating a bitmap for the complete control's client area, we allocate only as small as needed for the dirty region. However then we need to compensate the change in coordinates between the control's top left corner and the dirty rect's top left corner by arranging the proper view-port origin temporarily. We use the function OffsetViewportOrgEx() for the purpose.
OffsetViewportOrgEx()
The control creates and destroys the bitmap each time WM_PAINT is received. It is a potentially costly operation so this could be further optimized by some appropriate caching strategy of the bitmap for reuse. However, as the bitmap is potentially quite large and memory-hungry, you should not hold it all the time. In the real world, the control gets many WM_PAINT messages in a short period of time when the user is using it, or none for longer periods of time when he is not (e.g., when the application window is minimized) so the cache should be a bit smart. Something like that would make the example much longer and I believe the reader can take this as an opportunity for a small exercise of his own creativity.
(Again, an example Visual Studio 2010 project is attached. It is a slightly enhanced and more complete version of the code presented here.)
There is yet another message worth mentioning, related to painting. The controls aspiring on a position of good citizen in the Windows environment should also support the message WM_PRINTCLIENT. In short, this message asks the control to paint itself into the provided device context (via WPARAM). Printing in Windows, for example, takes use of this. Various tools like screen zooming or thumbnailing utilities may use it. Some coding tricks like painting on a glass window border are possible by using this message (but that is out of our topic, at least for today).
WM_PRINTCLIENT
WPARAM
Note our new version of CustomPaint() is exactly suitable for such purpose so implementing this message is a very straightforward task:
static LRESULT CALLBACK
CustomProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg) {
// ...
case WM_PRINTCLIENT:
{
RECT rc;
GetClientRect(hwnd, &rc);
CustomPaint(hwnd, (HDC) wParam, &rc, TRUE);
return 0;
}
// ...
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
I omitted talking about one API closely related to painting of controls. It is an API which provides support for visual themes (implemented by UXTHEME.DLL). As it was introduced in Windows XP, it is sometimes also referred as XP theming. In these days, the controls simply must be theme-aware if they want to fit into the Windows look and feel.
Though, it is quite a complex topic of its own, so the next time a whole article will be dedicated to it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
HPEN hOldPen = (HPEN)SelectObject(hMemDC, pData->hP_Pressed);
HBRUSH hOldBrush = (HBRUSH)SelectObject(hMemDC, pData->hBr_Idle_Disabled);
HFONT hOldFont = (HFONT)SelectObject(hMemDC, pData->hFont);
CS_OWNERDC
HBRUSH
CS_xxxx
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
// We let application to choose whether to use double buffering or not by using the style CCS_DOUBLEBUFFER.
if(pData->style & XXS_DOUBLEBUFFER)
CustomDoubleBuffer(pData, &ps);
else
CustomPaint(pData, ps.hdc, &ps.rcPaint, ps.fErase);
EndPaint(hwnd, &ps);
return 0;
}
if(pData->style && XXS_DOUBLEBUFFER)
)
--------------------Configuration: ChartWrapper - Win32 Debug--------------------
Linking...
ChartWrapper.obj : error LNK2001: unresolved external symbol _mcChart_Terminate@0
ChartWrapper.obj : error LNK2001: unresolved external symbol _mcChart_Initialize@0
Debug/ChartWrapper.exe : fatal error LNK1120: 2 unresolved externals
Error executing link.exe.
ChartWrapper.exe - 3 error(s), 0 warning(s)
#ifdef __cplusplus ... extern "C" ...
Martin Mitáš wrote:But if it behaves the same way as MSVC2010 in this regard
Martin Mitáš wrote:You forgot to add the import lib (MCTRL.LIB) when linking your code. (much more likely)
Martin Mitáš wrote:You built MCTRL.DLL from sources in MSVC
dllexport/dllimport
MCTRL_API
.dan.g. wrote:ps. Did you ever specifically test the build system with MFC? Or do you know of anyone who did?
.dan.g. wrote:pps. I also notice that you don't use dllexport/dllimport anywhere... which for me is unusual
dllexport
GetProcAddress(hModule, "_func@8")
GetProcAddress(hModule, "func")
#ifdef
dllimport
.dan.g. wrote:I was able to fix it by removing the MCTRL_API from the function declaration.
__stdcall
mcChart_Initialize()
mcChart_Terminate()
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. | https://codeproject.freetls.fastly.net/Articles/617212/Custom-Controls-in-Win-API-The-Painting | CC-MAIN-2021-31 | refinedweb | 3,333 | 51.99 |
Results 1 to 4 of 4
- Join Date
- Nov 2012
- 4
- Thanks
- 0
- Thanked 0 Times in 0 Posts
C# MF need help with a program please
I have a program that works fine, its in C# MF
My problem is with Method_6() and 7
This line
while (anyinputfor6.Read() == true && method_state_6 == true)
I need to reverse the logic, I tried everything it sounds simple but I don't know how to do it.
Tried stuff like
while (anyinputfor6.Read() == false && method_state_6 == true)
But no, that wont work, so I need help as I'm just a newb to programing.
Thanks
Code:
namespace NetduinoApplication1 { public class Program { public const int SecondMs = 1000; public const int MinuteMs = 60 * SecondMs; public const int HourMs = 60 * MinuteMs; public const int DayMs = 24 * HourMs; public const int WeekMs = 7 * DayMs; static bool method_state_6, method_state_7; static InputPort anyinputfor6 = new InputPort(Pins.GPIO_PIN_D0, false, Port.ResistorMode.Disabled); static InputPort anyinputfor7 = new InputPort(Pins.GPIO_PIN_D1, false, Port.ResistorMode.Disabled); static OutputPort ph = new OutputPort(Pins.GPIO_PIN_D2, true); static OutputPort b = new OutputPort(Pins.GPIO_PIN_D3, true); static OutputPort a = new OutputPort(Pins.GPIO_PIN_D4, true); static OutputPort drain = new OutputPort(Pins.GPIO_PIN_D5, true); static OutputPort solenoid = new OutputPort(Pins.GPIO_PIN_D6, true); static OutputPort heater = new OutputPort(Pins.GPIO_PIN_D7, true); static OutputPort phcontroller = new OutputPort(Pins.GPIO_PIN_D8, true); static OutputPort tdscontrollerA = new OutputPort(Pins.GPIO_PIN_D9, true); static OutputPort tdscontrollerB = new OutputPort(Pins.GPIO_PIN_D10, true); static OutputPort led = new OutputPort(Pins.GPIO_PIN_D11, true); public static void Main() { try { Thread led_proc = new Thread(new ThreadStart(turn_led)); led_proc.Start(); while (true) { method_state_6 = method_state_7 = true; Method_1(); call2_5(); call6_8(); Method_10(); Thread.Sleep(10000); } } catch { //Something has gone wrong; reset to a safe condition } } static void turn_led() //turn led for 16 hr and off for 8hr in loop { while (true) { led.Write(false); Thread.Sleep(HourMs * 12); led.Write(true); Thread.Sleep(HourMs * 12); } } public static void call2_5() { Thread t2 = new Thread(new ThreadStart(Method_2)); t2.Start(); Thread t3 = new Thread(new ThreadStart(Method_3)); t3.Start(); Thread t4 = new Thread(new ThreadStart(Method_4)); t4.Start(); Thread t5 = new Thread(new ThreadStart(Method_5)); t5.Start(); #region Wait for finishing 2-5 methods t2.Join(); t3.Join(); t4.Join(); t5.Join(); #endregion } static void call6_8() { Thread t6 = new Thread(new ThreadStart(Method_6)); t6.Start(); Thread t7 = new Thread(new ThreadStart(Method_7)); t7.Start(); Thread t9 = new Thread(new ThreadStart(Method_9)); t9.Start(); // wait for Method_9 finishing t9.Join(); method_state_6 = method_state_7 = false; } public static void Method_1() { drain.Write(false); Thread.Sleep(16 * MinuteMs); drain.Write(true); } public static void Method_2() { solenoid.Write(false); Thread.Sleep(16 * MinuteMs); solenoid.Write(true); } public static void Method_3() { a.Write(false); Thread.Sleep(182 * SecondMs); a.Write(true); } public static void Method_4() { b.Write(false); Thread.Sleep(100 * SecondMs); b.Write(true); } public static void Method_5() { ph.Write(false); Thread.Sleep(5 * SecondMs); ph.Write(true); } public static void Method_6() { Thread.Sleep(5 * MinuteMs); while (anyinputfor6.Read() == true && method_state_6 == true) { phcontroller.Write(false); Thread.Sleep(1 * SecondMs); phcontroller.Write(true); Thread.Sleep(5 * MinuteMs); } } public static void Method_7() { Thread.Sleep(5 * MinuteMs); while (anyinputfor7.Read() == true && method_state_7 == true) { tdscontrollerA.Write(false); Thread.Sleep(5454); tdscontrollerA.Write(true); tdscontrollerB.Write(false); Thread.Sleep(3000); tdscontrollerB.Write(true); Thread.Sleep(5 * MinuteMs); } } public static void Method_9() { heater.Write(false); for (int i = 0; i < 14; i++) { Thread.Sleep(1 * DayMs); solenoid.Write(false); Thread.Sleep(20 * SecondMs); solenoid.Write(true); } heater.Write(true); // added this } public static void Method_10() { drain.Write(false); Thread.Sleep(16 * MinuteMs); drain.Write(true); solenoid.Write(false); Thread.Sleep(16 * MinuteMs); solenoid.Write(true); Thread.Sleep(1 * MinuteMs); } } }
- Join Date
- Nov 2012
- 4
- Thanks
- 0
- Thanked 0 Times in 0 Posts
no one
Wow, not even one reply, sounds like this site has shortages of programers lol
what are you trying to accomplish? I don't get what it is you're trying to do... how about something like
Code:
while(method_state_6 == true) { do { ... }while(!anyinputfor6.Read()); }
Edit: It looks like you're trying to snake a value off that pin being tripped.... I haven't worked with that PIC so idk the API or the pinouts, but what about tying it high and then invoking the .Read()? You need something to hold that status true until you .Read() it and then flip it off; I imagine the PIC has that functionality. But are you trying to read it on the .Read() being true or false? Also what does the circuit look like on the tail end of that input? If you have nothing filtering the VS and it is rippling it could be flicking true-false-true-false-true-false etc. There are a lot more pieces here than just the code in play.
Edit Edit: Also from my xp here there are little to no EE's so without knowing about this from EE background (self) the amount of ppl looking at this that would know what it is you're even attempting is minimal if not null (in short need a lot more detail
maybe post a pic of circuit as well)
- Join Date
- Jun 2002
- Location
- USA
- 9,074
- Thanks
- 1
- Thanked 328 Times in 324 Posts
Your code is incredibly obtuse and hard to follow. "Method_1"? Seriously, that gives no indication what the function is supposed to do. For someone to look at your code and understand what it is supposed to be doing is nearly impossible. I'm impressed that you are able to keep it straight. Easier to follow code is much easier for people to help you with it.
OracleGuy
AdSlot6 | http://www.codingforums.com/computer-programming/281828-c-mf-need-help-program-please.html?s=3afdae256ceac7f4791702bb3f77a9c1 | CC-MAIN-2015-40 | refinedweb | 929 | 60.82 |
Effortless REST with Flask, Part 2
In Part 1, we created the base scaffolding for a production-ready Flask API. But what’s an API without data, and if we’re serving sensitive data, how do we go about securing it? Effortless REST with Flask, Part 2 is all about data and security. Follow along step-by-step as we connect our API to a live database and secure our endpoints. As a reminder, You can access the code from the git repo here.
Let’s get started!
Connecting a Database
To make things simple, we’ll use Heroku to deploy a PostgreSQL database. Of course, your application can use any database connection string and is not tied to Heroku, but Heroku offers a free application offering along with a free PostgreSQL add-on. Follow these general steps to get set up on Heroku:
1. Sign up For Heroku / Log in to your Heroku account
2. Create a new app
3. Once created, Configure/Add the “Heroku Postgres” add on with the Hobby Dev Plan (free)
4. Add the Heroku CLI to your terminal
Once everything is configured, getting your Heroku database connection string is as easy as
heroku config:get DATABASE_URL -a {your_heroku_app_name}
The output of this command will be what we give our Flask SqlAlchemy plugin as our connection string. To make this easy, add the above command to the
tasks.py script so you’ll always fetch the DATABASE_URL before starting your Flask application. You’ll also need to add your
HEROKU_APP_NAME at the top of
tasks.py.
Connecting to the Database
Now that we can start our server let’s take a look at how we can connect our database in
chap-2/app/__init__.py.
We define a
db variable, and then within the factory function, we initialize the database with the application. Because we've already set up our config to include an "SQLALCHEMY_DATABASE_URI" variable, we can use this simple command to connect our app to the database.
Defining Models
What’s a database without entities and models? Let’s view the User model in
app/models/user.py.
"User Model"
# pylint: disable=no-member
from app import db
from sqlalchemy.sql import func
# A generic user model that might be used by an app powered by flask-praetorian
class User(db.Model):
__tablename__ = "users"
user_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
roles = db.Column(db.Text)
is_active = db.Column(db.Boolean, default=True, server_default="true")
created_datetime = db.Column(
db.DateTime(), nullable=False, server_default=func.now()
)
@property
def rolenames(self):
try:
return self.roles.split(",")
except Exception:
return []
@classmethod
def lookup(cls, username: str):
return cls.query.filter_by(username=username).one_or_none()
@classmethod
def identify(cls, user_id: int):
return cls.query.get(user_id)
@property
def identity(self):
return self.user_id
def is_valid(self):
return self.is_active
def __repr__(self):
return f"<User {self.user_id} - {self.username}>"
What makes SqlAlchemy so powerful is that you can define the database model right here in Python code. You can define the table name, properties, and even other SQL native elements such as defaults and uniqueness. This allows you to interact with the database models and entities with ease in Python. If you don’t define a method here on the model, you can still import it and build queries elsewhere in your code.
Seeding the Database
Now that we’ve defined our connection string and defined our User model let’s seed our database. Thankfully, SQLAlchemy provides powerful commands to help stand up the database. These commands have been wrapped behind invoke commands. To initialize the database and seed the database, run the two following commands.
invoke init-db
invoke seed-db
These two commands are defined in the
tasks.py file and create the tables in our database and seed them with two users.
Using SQLAlchemy Models to Query the Database
In the
chap-2/app/__init__.py file, there is a /uhoh route that's defined where our user model is used.
Notice how we can import our User model at the beginning of our
create_app function and then later use it within our route to construct a query that fetches all users. NOTE: If you're unfamiliar with the List[user] syntax, this is Python typing syntax with mypy.
Now that we’ve got a route defined and a model being queried let’s run a GET request by going to ‘'.
You should see a response that says: TypeError: Object of type user is not JSON serializable
The TypeError tells us that our SQLAlchemy model response is not JSON serializable. In other words, the user variable can’t be transformed into JSON so easily. Instead, we need to deserialize the user and convert it into JSON. We can do this by using the Marshmallow package. Marshmallow is a foundational package when doing the input validation, deserialization into app-level objects, and serialization of app-level objects into Python types. We highly recommend that you get familiar with this package as it can offer you “superpowers” for app-objects coming in and out of your API.
Below is an example route that deserializes the SQLAlchemy model into JSON. It uses a defined schema to know how to deserialize the SQLAlchemy model.
When calling the route with, we see that the SQLAlchemy models correctly get transformed into JSON and the web browser displays the JSON.
Congratulations! You’ve now connected to a database and have an API serving data from it!
Authentication and Authorization
With our API connected to a database and serving data from it, let’s make sure that we can authenticate users before we use any sensitive data. To do this, we’ll use Flask Praetorian. Flask Praetorian is considered a “batteries included” JWT library. In other words, once you install this package, you can add authentication and authorization with little adjustments to your application. Let’s walk through the few steps we need to do to add JWT authentication.
In the
chap-3/app/config.py file, add the JWT_ACCESS_LIFESPAN, and JWT_REFRESH_LIFESPAN config variable.
Then in the
chap-3/app/__init__.py file, we can initialize the Praetorian library, add the /login route, and protect the routes with special decorator @auth_required.
"Main Flask App"
...
# Application Factory
#
def create_app(config_name: str) -> Flask:
"""Create the Flask application
Args:
config_name (str): Config name mapping to Config Class
Returns:
[Flask]: Flask Application
"""
from app.config import config_by_name
from app.models import User
# Create the app
app = Flask(__name__)
# Log the current config name being used and setup app with the config
app.logger.debug(f"CONFIG NAME: {config_name}")
config = config_by_name[config_name]
app.config.from_object(config)
# Initialize the database
db.init_app(app)
# Initialize the flask-praetorian instance for the app
guard.init_app(app, User)
@app.route("/")
def hello_world() -> str: # pylint: disable=unused-variable
return "Hello World!"
@app.route("/login", methods=["POST"])
def login():
# Ignore the mimetype and always try to parse JSON.
req = request.get_json(force=True)
username = req.get("username", None)
password = req.get("password", None)
user = guard.authenticate(username, password)
ret = {"access_token": guard.encode_jwt_token(user)}
return (jsonify(ret), 200)
@app.route("/users", methods=["GET"])
@auth_required
def users():
users = User.query.all()
return jsonify(UserSchema(many=True).dump(users))
@app.route("/users/admin-only", methods=["GET"])
@roles_required("admin")
def users_admin():
users = User.query.all()
return jsonify(UserSchemaWithPassword(many=True).dump(users))
return app
We initialize the guard variable with our User SQLAlchemy model. This is the model that Flask Praetorian will use to authenticate users when doing guard.authenticate() in the /login route. When the user is authenticated, we can encode a JWT token from the user and send it back to the client. The client can then use that token when making requests to the backend, such as in /users route. The @auth_required decorated will check the request headers for an Authentication Bearer token. If the token is present, it’ll parse it and validate the user against the database. If the user is authenticated, then the route can proceed. When building production-ready applications, you should always consider what data will feed through the app. When we set up applications, we treat all data as if it’s sensitive, and users need to be authenticated. This is a great best practice to adopt.
Flask Praetorian also gives us authorization with the @roles_required decorator, as is demonstrated in the /users/admin-only route. This decorator authenticates the user and then verifies that the proper roles are present on the user before allowing the request to continue.
To see the above actions yourself, use the file called
effortless_rest_with_flask_postman.json that allows you to import Postman requests to work with your local API quickly.
Securing your application can be incredibly challenging, but Flask Praetorian makes it simple. With a few endpoint configurations, you can easily add authentication and authorization. You now have an API that’s connected to a database along with routes that have general authentication and optional authorization. It would be perfectly reasonable to start building your business logic into your application now, but we still have something missing. How will our API consumers know about our API interfaces and inputs? What documentation can they rely on to be in concordance with our API? In Part 3 of this series, we’ll answer those questions with auto-generated API documentation within our Flask app. Until next time! | https://americantiredistributors.medium.com/effortless-rest-with-flask-part-2-cd658d6e4cb9 | CC-MAIN-2021-10 | refinedweb | 1,575 | 58.79 |
Birthday Cake Candles Hackerrank problem solution -coderInme.
For example, if your niece is turning 4 years old, and the cake will have 4 candles of height 3, 2, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candle is of height 3 and there are 2 such candles.
Complete the function
birthdayCakeCandles that takes your niece’s age and an integer array containing height of each candle as input, and return the number of candles she can successfully blow out.
Input Format
The first line contains a single integer, n, denoting the number of candles on the cake.
The second line contains n space-separated integers, where each integer i describes the height of candle i.
1<=n<=105
1<=height i<=107
Output Format
Print the number of candles Colleen blows out.
Sample Input 0
4 3 2 1 3
Sample Output 0
2
Explanation 0
We have one candle of height 1, one candle of height 2, and two candles of height 3. Your niece only blows out the tallest candles, meaning the candles where height=3. Because there are 2 such candles, we print 2 on a new line.
C++
include <iostream> int main(){ int c, n, max = 0; std::cin.ignore(); while(std::cin >> n) max < n ? c = !!(max = n) : c += max == n; std::cout << c; return 0; }
more easy answer) } }
If you want to use function then
int birthdayCakeCandles(int n, vector <int> ar) { int count = 1; sort(ar.begin(), ar.end()); reverse(ar.begin(), ar.end()); for (int i = 0; i < n; i++){ if (ar[i] == ar[i+1]){ count++; } else break; } return count; }
Python solution
n = input() arr = map(int, raw_input().split()) print arr.count(max(arr))
python is always the best
return ar.count(max(ar))
Java
import java.util.*; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // the number of candles int n = scan.nextInt(); // store the current maximum height of any candle, initialize to the minimum possible height of any candle int maxHeight = 1; // count the number of candles having the maximum height int countMax = 0; for(int i = 0; i < n; i++) { int tmp = scan.nextInt(); // if you read in a value larger than maxHeight, set new maxHeight if(tmp > maxHeight) { maxHeight = tmp; countMax = 1; } // if you read a value equal to the current value of maxHeight else if(tmp == maxHeight) { // increment the count of candles having maximum height countMax++; } } scan.close(); System.out.println(countMax); } } | https://coderinme.com/birthday-cake-candles-hackerrank-problem-solution-coderinme/ | CC-MAIN-2018-39 | refinedweb | 420 | 60.75 |
i only added the println to the min and max because those are the only two that aren't working properly.
i only added the println to the min and max because those are the only two that aren't working properly.
it printed "The smallest value is 0" for the min and "The largest value is 0" for the max.
like this?
import java.awt.Graphics;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
public class drawRectangle extends JApplet
{
public int x;
even with the println call it still says the max and min are both 0.
how would i go about assigning the values for the rectangle in this particular instance?
yes it executes but it just says the min value is 0 and the max value is 0
allows for user input of the 4 values (x, y, width, height) but it wont draw the rectangle with those values.
import java.awt.Graphics;
import javax.swing.JApplet;
import...
Everything works exactly like its suppose to but when its suppose to show the max and min values out of the 3 numbers, it just returns 0.
//23.4
import java.awt.Graphics;
import... | http://www.javaprogrammingforums.com/search.php?s=4acbb94b779904a5425db9c0775c44da&searchid=1461178 | CC-MAIN-2015-14 | refinedweb | 195 | 71.75 |
The good news is that it looked like the code I posted would work if it picked up the data.
/*--- HT12E.cpp HT12E Support for Arduino Author: Marcelo Shiniti Uchimura Date : May '08---*/#include "Arduino.h"#include "HT12E.h"HT12E::HT12E(int pin, unsigned int addrMask){ _pin = pin; pinMode(_pin, INPUT); _data = 0; _mask = addrMask << 4; // the HT12E basic word is a stream with an 8-bit address // followed by 4-bit data. I left shift the // address mask 4 bits so I can match it to the entire word}int HT12E::read(){ byte ctr; // for general error handling _tries = 0; do { /* look for HT12E basic word's pilot stream */ for(ctr = 0; ctr < 13; ++ctr) { while(digitalRead(_pin) == LOW); // wait for the signal to go HIGH _dur = pulseIn(_pin, LOW); if(_dur > 9000 && _dur < 12000) break; // 36x(clock tick interval) } /* if error, skip everything */ if(ctr == 13) { _tries = 4; break; } /* now wait until sync bit is gone */ for(ctr = 0; ctr < 6; ++ctr) { if(digitalRead(_pin) == LOW) break; delayMicroseconds(80); } /* if error, skip everything */ if(ctr == 6) { _tries = 5; break; } /* let's get the address+data bits now */ for(_data = 0, ctr = 0; ctr < 12; ++ctr) { _dur = pulseIn(_pin, HIGH); if(_dur > 250 && _dur < 333) // if pulse width is between 1/4000 and 1/3000 secs { _data = (_data << 1) + 1; // attach a *1* to the rightmost end of the buffer } else if(_dur > 500 && _dur < 666) // if pulse width is between 2/4000 and 2/3000 secs { _data = (_data << 1); // attach a *0* to the rightmost end of the buffer } else { /* force loop termination */ _data = 0; break; } } // check if buffered data matches the address mask if((_data & _mask) < _mask) { /* data error */ _tries = 6; } else ++_tries; } while(_tries < 3); if(_tries > 3) { switch(_tries) { case 4: return 0xffff; case 5: return 0xfffe; case 6: return 0xfffd; } } return (_data ^ _mask);}
/*--- HT12E.h HT12E Support for Arduino Author: Marcelo Shiniti Uchimura Date : May '08 Note : make sure HT12E is operating at 3~4kHz clock range---*/#ifndef HT12E_h#define HT12E_h#include "Arduino.h"class HT12E { public: HT12E(int pin, unsigned int addrMask); // this is the constructor int read(); // this is the main method private: byte _pin; // this is Arduino input pin unsigned int _data; // this is data unsigned int _mask; // this is the address mask byte _tries; // this is how many times Arduino could find // valid HT12E words unsigned long _dur; // pulse duration};#endif
#include <HT12E.h>HT12E remote(7, B01111111); // pino 7, endereço 0111 1111bvoid setup(){ Serial.begin(9600);}void loop(){ unsigned int valor; valor = remote.read(); if(valor > 0xFFF0) Serial.println(valor, HEX); else { Serial.print("DATA "); Serial.println(valor, BIN); } delay(1000);}
This thread has really made me hopeful, but unfortunately I'm left with a lot of questions after reading through it. It appears this is one of the only threads that turns up in Google that matches the same project I'm working on. I have a 350MHz Hunter remote for the ceiling light and fan. I have one in each room in my house and my goal is to remotely control through the Arduino.Mysticle31, would you mind posting what your final code was to make this work? I've read up a lot on using a 315MHz or 434MHz receiver for obtaining the codes for various RF controls. My problem is, I've yet to find a sniffing solution that is working with my 315MHz receiver. I'm suspecting that there is a communication problem with the frequencies being different, but I've read that it should work by adjusting the 315MHz receiver. The back of my 315 shows three different frequencies: 315, 330, 433. I'm not sure what that means though. Did you need to get a 350MHz receiver to get the codes for your fan's remote?Thank you very much.
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=146953.msg1153977 | CC-MAIN-2017-09 | refinedweb | 673 | 64.04 |
I don't understand what does comma after variable lines, means:
line, = ax.plot(x, np.sin(x))
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
#Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()
ax.plot() returns a tuple with one element. By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn.
Most often, you see this being applied for functions with more than one return value:
base, ext = os.path.splitext(filename)
The left-hand side can, however, contain any number of elements, and provided it is a tuple of variables the unpacking will take place.
In Python, it's the comma that makes something a tuple:
>>> 1 1 >>> 1, (1,)
The parenthesis are optional in most locations. You could rewrite the original code with parenthesis without changing the meaning:
(line,) = ax.plot(x, np.sin(x))
Or, you could recast it to lines that do not use tuple unpacking:
line = ax.plot(x, np.sin(x))[0]
or
lines = ax.plot(x, np.sin(x)) def animate(i): lines[0].set_ydata(np.sin(x+i/10.0)) # update the data return lines #Init only required for blitting to give a clean slate. def init(): lines[0].set_ydata(np.ma.array(x, mask=True)) return lines
For full details on how assignments work with respect to unpacking, see the Assignment Statements documentation. | https://codedump.io/share/w9a6ijuCWtOG/1/python-code-is-it-comma-operator | CC-MAIN-2018-09 | refinedweb | 320 | 61.63 |
Javascript has its fair share of ‘wat’ moments. Even though most of them have a logical explanation once you dig in, they can still be surprising. But JavaScript doesn’t deserve all the indignant laughter. For example, you’ll sometimes see jokes like this:
In what language does 0.1 + 0.2 not equal 0.3?
console.log(0.1 + 0.2 === 0.3); // ⦘ false console.log(0.1 + 0.2); // ⦘ '0.30000000000000004'
In JavaScript! Hahahaha. What a stupid language.
In this case the criticism is entirely undeserved. JavaScript, like nearly every other popular programming language, represents numbers using a standard. To be precise, the IEEE 754 standard for double-precision 64-bit binary format numbers. Let’s try that same joke in some other languages:
How about Ruby?
In what language does 0.1 + 0.2 not equal 0.3?
$ irb irb(main):001:0> 0.1 + 0.2 == 0.3 => false irb(main):002:0> 0.1 + 0.2 => 0.30000000000000004
In Ruby! Hahahaha. What a stupid language.
Or Clojure?
In what language does 0.1 + 0.2 not equal 0.3?
$ clj Clojure 1.10.1 user=> (== (+ 0.1 0.2) 0.3) false user=> (+ 0.1 0.2) 0.30000000000000004
In Clojure! Hahahaha. What a stupid language.
Or how about the mighty Haskell?
In what language does 0.1 + 0.2 not equal 0.3?
$ ghci GHCi, version 8.10.1: :? for help Prelude> 0.1 + 0.2 == 0.3 False Prelude> 0.1 + 0.2 0.30000000000000004
In Haskell! Hahahaha. What a stupid language.
You get the idea. The issue here isn’t JavaScript. It’s the bigger problem of representing floating point numbers in binary. But I don’t want to get into the details of IEEE 754 for the moment. Because, if we need arbitrary precision numbers, JavaScript now makes that possible. Since October-ish 2019,
BigInt is officially part of the TC39 ECMAScript standard.
Why bother?
We’ve gotten by with IEEE 754 for ages. It doesn’t seem to be a problem most of the time. That’s true. It isn’t a problem most of the time. But on occasion, it is. And in those moments, it’s good to have options.
For example, I was working on a chart library earlier this year. I wanted to draw candlestick charts in SVG. And SVG has this neat feature called a
transform. You can apply it to a group of elements, and it will change the coordinate system for those elements. So, with a little care, you can simplify generating the chart area. Instead of calculating chart coordinates for each candlestick, you specify a single transform. And then specify each candlestick using raw data values. It’s neat. At least, in theory.
But in my property tests, I was running into problems. If the chart was small, and the data values were large, I’d get rounding errors. And most of the time, that’s OK. But in a chart, certain pixels have to line up. Otherwise it doesn’t look right. So I started to look into
BigInt. The outcome was a library I’ve called ‘Ratio’. And I’m going to show you how you could write it too.
The Ratio class
The problem with floating point numbers is binary representation. Computers do all their calculations in binary. And binary is fine for integers. The trouble comes when we want to represent decimal numbers. For example, in English-speaking countries like Australia, we write decimal numbers like this:
\(3.1415926\)
The bit to the left the dot ( \(.\) ) is the integer part. And the bit to the right of the dot is the fractional part. But the trouble is, some numbers have fractional parts that don’t divide easily into two. So they’re hard to represent in binary. But we even have the similar problems working in base 10. For example, consider. the fraction \(\frac{10}{9}\). You can try to write it something like this:
\(1.11111111111111111111111111111111111\)
That’s an approximation, though. To represent \(\frac{10}{9}\) with full accuracy, those ones have to go on forever. So we have to use some other notation to represent the repeated ones. Like the dot notation:
\(1.\dot{1}\)
That dot over the one indicates the ones keep on going. But we don’t have dot notation in most programming languages.
Notice though, that \(\frac{10}{9}\) has perfect accuracy. And all it takes is two pieces of information. That is a numerator and a denominator. With a single
BigInt value we can represent arbitrarily large integers. But if we create a pair of integers, we can represent arbitrarily large or small numbers.1
In JavaScript, that might look like this:
// file: ratio.js export default class Ratio { // We expect n and d to be BigInt values. constructor(n, d) { this.numerator = n; this.denominator = d; } }
And with that, we’ve done the trickiest bit. We’ve ‘invented’ a way to represent numbers with near-infinite accuracy. (We’re still limited by the amount of memory in our devices). All that remains is to apply some mathematics. Stuff you might have studied in school.
So let’s add some features.
Equals
The first thing we want to do is compare two ratios. Why? Because I like to write my code test-first. If I can compare two ratios for equality, then it’s much easier to write tests.
For the simple case, writing an equality method is pretty easy:
// file: ratio.js export default class Ratio { constructor(n, d) { this.numerator = n; this.denominator = d; } equals(other) { return ( this.numerator === other.numerator && this.denominator === other.denominator ); } }
That’s fine. But it would be nice if our library could tell if, say, \(\frac{1}{2}\) was equal to \(\frac{2}{4}\). To do that, we need to simplify our ratios. That is, before we test for equality, we want to reduce both ratios to the smallest possible integers. So, how do we do that?
A naïve approach is to run through all the numbers from 1 to \(\min(n,d)\) (where \(n\) and \(d\) are the numerator and denominator). And that’s what I tried first. It looked something like this:
function simplify(numerator, denominator) { const maxfac = Math.min(numerator, denominator); for (let i=2; i<=maxfac; i++) { if ((numerator % i === 0) && (denominator % i === 0)) { return simplify(numerator / i, denominator / i); } } return Ratio(numerator, denominator); }
And, as you’d expect, it’s ridiculously slow. My property tests took ages to run. So, we need a more efficient approach. Lucky for us, a Greek mathematician figured this one out a couple of millennia ago. The way to solve it is using Euclid’s algorithm. It’s a way of finding the largest common factor for two integers.
The recursive version of Euclid’s algorithm is beautiful and elegant:
function gcd(a, b) { return (b === 0) ? a : gcd(b, a % b); }
It can be memoized too, making it quite snappy. But alas, we don’t have tail call recursion in V8 or SpiderMonkey yet. (At least, not at the time of writing). This means that if we run it with large enough integers, we get stack overflow. And large integers are kind of the point here.
So, instead, we use the iterative version:
// file: ratio.js function gcd(a, b) { let t; while (b !== 0) { t = b; b = a % b; a = t; } return a; }
Not so elegant, but it does the job. And with that in place, we can write a function to simplify ratios. While we’re at it, we’ll make a small modification so that denominators are always positive. (That is, only the numerator changes sign for negative numbers).
// file: ratio.js function sign(x) { return x === BigInt(0) ? BigInt(0) : x > BigInt(0) ? BigInt(1) /* otherwise */ : BigInt(-1); } function abs(x) { return x < BigInt(0) ? x * BigInt(-1) : x; } function simplify(numerator, denominator) { const sgn = sign(numerator) * sign(denominator); const n = abs(numerator); const d = abs(denominator); const f = gcd(n, d); return new Ratio((sgn * n) / f, d / f); }
And with that it place, we can write our equality method:
// file: ratio.js -- inside the class declaration equals(other) { const a = simplify(this); const b = simplify(other); return ( a.numerator === b.numerator && a.denominator === b.denominator ); }
We’re now able to compare two ratios for equality. It might not seem like much, but it means we can write unit tests and make sure our library works as expected.
Converting to other types
Now, I won’t bore you by writing out all the unit tests for this library. But something that would be nice is to convert these ratios into other formats. For example, we might want to represent them as a string in debug messages. Or we might want to convert them to numbers. So let’s override the
.toString() and
.toValue() methods for our class.
The
.toString() method is easiest, so let’s start with that.
// file: ratio.js -- inside the class declaration toString() { return `${this.numerator}/${this.denominator}`; }
Easy enough. But how about converting back to a number? One way to do it is to just divide numerator by denominator:
// file: ratio.js -- inside the class declaration toValue() { return Number(this.numerator) / Number(this.denominator); }
That works, most of the time. But we might want to tweak it a little. The whole point of our library is that we use large integers to get the precision we need. And sometimes these integers will be too large to convert back to a Number. But, we want to get the number as close as we can, wherever possible. So we do a little bit of arithmetic when we convert:
// file: ratio.js -- inside the class declaration toValue() { const intPart = this.numerator / this.denominator; return ( Number(this.numerator - intPart * this.denominator) / Number(this.denominator) + Number(intPart) ); }
By extracting the integer part, we reduce the size of the BigInt values before we convert them to Number. There are other ways to do this that have fewer range problems. In general, they are more complex and slower though. I encourage you to look into them further if you’re interested. But for this article, the simple approach will cover enough cases to be useful.
Multiply and divide
Let’s do something with our numbers. How about multiplication and division? These are not complicated for ratios. For multiplication, we multiply numerators with numerators, and denominators with denominators.
// file: ratio.js -- inside the class declaration times(x) { return simplify( x.numerator * this.numerator, x.denominator * this.denominator ); }
Division is similar. We invert the second ratio, then multiply.
// file: ratio.js -- inside the class declaration divideBy(x) { return simplify( this.numerator * x.denominator, this.denominator * x.numerator ); }
Add and subtract
We now have multiplication and division. The next logical thing to write is addition and subtraction. These are slightly more complicated than multiplication and division. But not too much.
To add two ratios together, we first need to manipulate them so they have the same denominator. Then we add the numerators together. In code, that might look something like this:
// file: ratio.js -- inside the class declaration add(x) { return simplify( this.numerator * x.denominator + x.numerator * this.denominator, this.denominator * x.denominator ); }
Everything is multiplied by denominators. And we use
simplify() to keep the ratios as small as possible.
Subtraction is similar. We manipulate the two ratios so that denominators line up as before. Then we subtract instead of adding the numerators.
// file: ratio.js -- inside the class declaration subtract(x) { return simplify( this.numerator * x.denominator - x.numerator * this.denominator, this.denominator * x.denominator ); }
So we have our basic operators. We can add, subtract, multiply and divide. But we still need a few other methods. In particular, numbers have an important property: we can compare them to each other.
Less than and greater than
We’ve already discussed
.equals(). But we need more than just equality. We’d also like to be able to tell if one ratio is larger or smaller than another. So we’ll create a method
.lte() that will tell us if a ratio is less than or equal to another ratio. Like
.equals(), it’s not obvious which of two ratios is smaller. To compare them, we need to convert both to have the same denominator. Then, we can compare numerators to see which is larger. With a bit of simplification, it might look like so:
// file: ratio.js -- inside the class declaration lte(other) { const { numerator: thisN, denominator: thisD } = simplify( this.numerator, this.denominator ); const { numerator: otherN, denominator: otherD } = simplify( other.numerator, other.denominator ); return thisN * otherD <= otherN * thisD; }
Once we have
.lte() and
.equals() we can derive all the other comparisons. We could have chosen any comparison operator. But once we have
equals() and any one of \(>\), \(<\), \(\geq\) or \(\leq\), then we can derive the others with boolean logic. In this case, we’ve gone with
lte() because that’s what the FantasyLand standard uses. Here’s how working out the others might look.
// file: ratio.js -- inside the class declaration lt(other) { return this.lte(other) && !this.equals(other); } gt(other) { return !this.lte(other); } gte(other) { return this.gt(other) || this.equals(other); }
Floor and ceiling
We can now compare ratios. And we can also multiply and divide, add and subtract. But if we’re going to do more interesting things with our library, we need more tools. Some of the handy ones from JavaScript’s
Math object include
.floor() and
.ceil().
We’ll start with
.floor(). Floor takes a value and rounds it down. With positive numbers, that means we just keep the integer part and throw away any remainder. But for negative numbers, we round away from zero, so it needs a little extra care.
// file: ratio.js -- inside the class declaration floor() { const one = new Ratio(BigInt(1), BigInt(0)); const trunc = simplify(this.numerator / this.denominator, BigInt(1)); if (this.gte(one) || trunc.equals(this)) { return trunc; } return trunc.minus(one); }
With that in place, we can leverage it to help us calculate ceiling values. This is where we round up.
// file: ratio.js -- inside the class declaration ceil() { const one = new Ratio(BigInt(1), BigInt(0)); return this.equals(this.floor()) ? this : this.floor().add(one); }
We now have most of what we’d need for lots of math operations. And with
.toValue() we can easily convert our calculations back to decimal numbers. But what if we want to convert a floating point number to a ratio?
Numbers to Ratios
Converting a number to a ratio is more involved than it might seem at first glance. And there are many different ways to do it. The way I’ve done it is not the most accurate, but it’s good enough. To make it work, we first convert the number to a string we know will be in a consistent format. For this, JavaScript gives us the
.toExponential() method. It gives us the number in exponential notation. Here’s some examples so you get the idea:
let x = 12.345; console.log(x.toExponential(5)); // ⦘ '1.23450e+1'' x = 0.000000000042; console.log(x.toExponential(3)); // ⦘ '4.200e-11' x = 123456789; console.log(x.toExponential(4)); // ⦘ '1.2346e+8'
It works by representing the number as a normalised decimal value and a multiplier. We call the normalised decimal bit the significand. And the multiplier, the exponent. Here, ‘normalised’ means the absolute value of the significand is always less than 10. And the exponent is always a power of 10. We indicate the start of the multiplier with the letter ‘e’, short for ‘exponent’.
The advantage of this notation is that it’s consistent. There’s always exactly one digit to the left of the decimal point. And
.toExponential() lets us specify how many significant digits we want. Then comes the ‘e’ and the exponent (always an integer). Because it’s so consistent, we can use a cheeky regular expression to parse it.
The process goes something like this. As mentioned,
.toExponential() takes a parameter to specify the number of significant digits. We want maximum digits. So we set the precision to 100 (which is as many as most JavaScript engines will allow). For this example though, we’ll stick with a precision of 10. Now, imagine we have a number like
0.987654321e0. What we want to do is move that decimal point 10 digits to the right. That would give us
9876543210. Then we divide it by \(10^{10}\), and we get \(\frac{9876543210}{10000000000}\). This, in turn, simplifies to \(\frac{987654321}{10000000000}\).
We have to pay attention to that exponent though. If we have a number like
0.987654321e9, we still move the decimal point 10 digits to the right. But we divide by ten to the power of \(10 - 9 = 1\).
$$ \begin{align} 0.987654321\times10^{9} &= \frac{9876543210}{10^{1}} \\ &= \frac{987654321}{1} \end{align} $$
To make all this happen, we define a couple of helper functions:
// Transform a ‘+’ or ‘-‘ character to +1 or -1 function pm(c) { return parseFloat(c + "1"); } // Create a new bigint of 10^n. This turns out to be a bit // faster than multiplying. function exp10(n) { return BigInt(`1${[...new Array(n)].map(() => 0).join("")}`); }
With those in place we can put the whole
fromNumber() function together.
// file: ratio.js -- inside the class declaration static fromNumber(x) { const expParse = /(-?\d)\.(\d+)e([-+])(\d+)/; const [, n, decimals, sgn, pow] = x.toExponential(PRECISION).match(expParse) || []; const exp = PRECISION - pm(sgn) * +pow; return exp < 0 ? simplify(BigInt(`${n}${decimals}`) * exp10(-1 * exp), BigInt(1)) : simplify(BigInt(`${n}${decimals}`), exp10(exp)); }
We now have most of the basic functions covered. We can go from numbers to ratios, and back again. For my particular application though, I needed more. In particular, I needed to find exponents and logarithms.
Exponentiation
Exponentiation is where you multiply something by itself repeatedly. For example \(2^3 = 2 \times 2 \times 2 = 8\). For simple cases where the exponent is an integer, we already have a built-in BigInt operator:
**. So, if we’re taking our rato to the power of an integer, we’re good to go. The power law for ratios looks like so:
$$ \left(\frac{x}{y}\right)^{n} = \frac{x^n}{y^n} $$
Hence, a first cut of our exponentiation method might look something like this:
// file: ratio.js -- inside the class declaration pow(exponent) { if (exponent.denominator === BigInt(1)) { return simplify( this.numerator ** exponent.numerator, this.denominator ** exponent.numerator ); } }
That works fine. Well… mostly fine. Things start to get tricky from here. Because of the limits of hardware and mathematics, we have to make some compromises. We might have to sacrifice precision for the sake of getting an answer in a reasonable amount of time.
With exponentiation it’s not hard to generate very large numbers. And when numbers get large, everything slows down. While writing this article I created calculations that ran for days without finishing. So we need to be careful. But that’s OK. It comes with the territory for BigInt.
There is another problem though. What do we do if the denominator of the exponent is not 1? For example, what if we wanted to calculate \(8^{\frac{2}{3}}\)?
Fortunately, we can split this problem up into two parts. We want to take one ratio to the power of another. For example, we might take \(\frac{x}{y}\) to the power of \(\frac{a}{b}\). The laws of exponentiation say that the following are equivalent:
\[\left(\frac{x}{y}\right)^\frac{a}{b} = \left(\left(\frac{x}{y}\right)^\frac{1}{b}\right)^a = \left(\frac{x^\frac{1}{b}}{y^\frac{1}{b}}\right)^a\]
We already know how to take a BigInt to the power of another BigInt. But what about the fractional power? Well, there’s another equivalence we can bring in here:
\[x^\frac{1}{n} = \sqrt[n]{x}\]
That is, taking \(x\) to the power of \(\frac{1}{n}\) is equivalent to finding the nth root of \(x\). This means, if we can find a way to calculate the nth root of a BigInt, then we can calculate any power.
With a well-crafted web-search or two, it doesn’t take long to find an algorithm for estimating the nth root. The most common is Newton’s method. It works by starting with an estimate, \(r\). Then we make the following calculation to get a better estimate:
$$ \begin{align} r &\approx x^{\frac{1}{n}} \\ r^{\prime} &= \frac{1}{n}\left((n-1)r + \left(\frac{x}{r^{n-1}}\right)\right) \end{align} $$
We keep repeating that calculation until we reach the desired precision. Unfortunately, there are some roots that can’t be represented as a finite fraction. To put it another way, to get perfect precision we’d need infinitely long BigInt values. In practice, this means we have to pick an arbitrary limit on how many iterations we’ll do.
We’ll come back to this point. For now, let’s work out how we can calculate a good estimate of the nth root. Because the estimate \(r\) will be a ratio, we can write it as:
$$ r = \frac{a}{b} $$
And that allows us to rewrite the estimate calculation as:
\[\frac{a^{\prime}}{b^{\prime}} = \frac{(n - 1)a^{n} + x b^{n}}{n b a^{n - 1}}\]
This puts it in a form where everything is in terms of integer calculations suitable for use with BigInt. Feel free to plug \(\frac{a}{b}\) into the equation for \(r'\) above and check my derivation. Putting that into JavaScript looks something like the following:
const estimate = [...new Array(NUM_ITERATIONS)].reduce(r => { return simplify( (n - BigInt(1)) * r.numerator ** n + x * r.denominator ** n, n * r.denominator * r.numerator ** (n - BigInt(1)) ); }, INITIAL_ESTIMATE);
We just repeat that calculation until we reach a suitable accuracy for our nth root estimate. The trouble is, we need to come up with suitable values for our constants. That is,
NUM_ITERATIONS and
INITIAL_ESTIMATE.
A lot of algorithms start with their
INITIAL_ESTIMATE as 1. It’s a reasonable choice. Most of the time we have no real good way of guessing what the nth root might be. But in our case, we can cheat. Let’s assume (for the moment) that our numerator and denominator are in the range allowed by
Number. We can then use
Math.pow() to get an initial estimate. That might look like so:
// Get an initial estimate using floating point math // Recall that x is a bigint value and n is the desired root. const initialEstimate = Ratio.fromNumber( Math.pow(Number(x), 1 / Number(n)) );
So we have a value for our initial estimate. But what about
NUM_ITERATIONS? Well, in practice, what I did was start with a guess of 10. And then I would run my property tests. I kept dialling the number back until they finished in a reasonable amount of time. And the figure that finally worked was… 1. One iteration. Which makes me a little sad, but we are at least a little more accurate than floating point calculations. In practice, you can tune this number number up if you’re not calculating a lot of fractional powers.
To keep things simple, we’ll pull the nth root calculation out into its own function. Putting it all together it might look like the following:
// file: ratio.js -- inside the class declaration static nthRoot(x, n) { // Handle special cases if (x === BigInt(1)) return new Ratio(BigInt(1), BigInt(1)); if (x === BigInt(0)) return new Ratio(BigInt(0), BigInt(1)); if (x < 0) return new Ratio(BigInt(1), BigInt(0)); // Infinity // Get an initial estimate using floating point math const initialEstimate = Ratio.fromNumber( Math.pow(Number(x), 1 / Number(n)) ); const NUM_ITERATIONS = 1; return [...new Array(NUM_ITERATIONS)].reduce((r) => { return simplify( n - BigInt(1) * (r.numerator ** n) + x * (r.denominator ** n), n * r.denominator * r.numerator ** (n - BigInt(1)) ); }, initialEstimate); } pow(n) { const { numerator: nNumerator, denominator: nDenominator } = n.simplify(); const { numerator, denominator } = this.simplify(); if (nNumerator < 0) return this.invert().pow(n.abs()); if (nNumerator === BigInt(0)) return Ratio.one; if (nDenominator === BigInt(1)) { return new Ratio(numerator ** nNumerator, denominator ** nNumerator); } if (numerator < 0 && nDenominator !== BigInt(1)) { return Ratio.infinity; } const { numerator: newN, denominator: newD } = Ratio.nthRoot( numerator, nDenominator ).divideBy(Ratio.nthRoot(denominator, nDenominator)); return new Ratio(newN ** nNumerator, newD ** nNumerator); }
It’s not perfect, and it’s slow. But it gets the job done. Well, mostly. There’s still the issue of how to get an estimate if we have integers larger than
Number.MAX_VALUE. I’ll leave that as an exercise to the reader though, as this article is already far too long.
Logarithms
I have to admit, logarithms stumped me for weeks. For the thing I’m building, I need to calculate logarithms in base 10. So I went searching for algorithms to calculate logs. And there’s plenty of them. But I couldn’t find one that worked well enough to be included in a math library.
Why is it so hard? My goal was to calculate logarithms to be more accurate than floating point. Otherwise, why bother? The floating point log function,
Math.log10(), is fast and built-in. So, I looked at algorithms that provided ways to iteratively calculate logarithms. And they work. But to get accuracy higher than floating point, they’re slow. Not just a little bit slow. Very slow.
What happens is that as we go through the iterations, the fraction we build gets more and more accurate. But that accuracy comes at a cost. The BigInt values in our fraction become larger and larger. And as they get larger, multiplying them together starts to take a long time. At one point I left a calculation running for three days. But while that calculation was running, I remembered something.
I remembered that I wanted the
log10() method so that I could calculate nice scale values for charts. And for those calculations, every time I called
.log10(), I would immediately call
.floor(). Which means I only need the integer part of the log. Calculating the logarithm to 100 decimal places was just a waste of effort.
Better yet, there’s a simple way to calculate the integer part of a base 10 logarithm. All we need to do is count the digits. A naïve attempt might look like the following:
// file: ratio.js -- inside the class declaration floorLog10() { return simplify(BigInt((this.numerator / this.denominator).toString().length - 1), BigInt(1)); }
Unfortunately, that doesn’t work for values less than one. But even then, we can use some logarithm laws to work around it.
$$ \begin{align} \log_{10}\left(\frac{a}{b}\right) &= \log_{10}(a) - \log_{10}(b) \\ \log_{10}\left(\frac{1}{x}\right) &= \log_{10}(1) - \log_{10}(x) \\ &= -\log_{10}(x) \end{align} $$
Therefore:
$$ \log_{10}\left(\frac{b}{a}\right) = -\log_{10}\left(\frac{a}{b}\right) $$
Putting it all together, we get a more robust
floorLog10() method:
// file: ratio.js -- inside the class declaration invert() { return simplify(this.denominator, this.numerator); } floorLog10() { if (this.equals(simplify(BigInt(0), BigInt(1)))) { return new Ratio(BigInt(-1), BigInt(0)); } return this.numerator >= this.denominator ? simplify((this.numerator / this.denominator).toString().length - 1, 1) : simplify(BigInt(-1), BigInt(1)).subtract(this.invert().floorLog10()); }
Again. Why bother?
At this point the library has all the functions I need for my charting application. But you might still be wondering, why go to all this trouble? There’s already several arbitrary precision libraries around. Why not just use one of those and be done with it?
To be fair, most of the time I would use an existing library. Especially if I’m in a hurry. There’s no point in doing all this work if someone else has already done a superior job.
The key word there is ‘superior’ though. And that’s where my motivations for wanting to write my own library come into play. The
floorLog10() method above is the perfect case study. For what I want to do, it provides the precise calculation I need. It does it efficiently, in about six lines of code.
If I were to use someone else’s library I’d face one of two scenarios:
- They don’t implement a
log10()or any other logarithm methods; or
- They do implement a
log10()method (or equivalent).
In the first scenario, I’d end up having to write
floorLog10() anyway. In the second scenario, I’d probably end up using their logarithm method. And my code would have been slower and more complex than it needed to be.
Writing my own library allows me to tailor it to the application. Sure, other people might find it useful, but I’m not beholden to their needs. So my application doesn’t have to carry around complex code it never uses.
Besides all that, I learned a lot writing my own library. I now understand the practical limitations of BigInt much better than before. I know that I can tune the performance of my nth root method. I can tweak it depending on how many calculations I’m running and what accuracy I need.
Sometimes it’s worth writing your own general purpose library. Even if you don’t plan to open-source it. Even if nobody else ever uses it. You can learn a lot and, besides, it can be fun.
Finally, if you’re interested in finding out more about the problems with floating point numbers, check out. And if you want to see the library all together and making some calculations, you can check out this code sandbox.
To be precise, we can represent any rational number. That is, any number that can be represented as a ratio of two integers. There are some numbers that cannot be represented this way. They’re called irrational numbers. ↩︎ | https://jrsinclair.com/articles/2020/sick-of-the-jokes-write-your-own-arbitrary-precision-javascript-math-library/ | CC-MAIN-2021-31 | refinedweb | 5,006 | 60.82 |
so what do you use then?
I use the same compiler that's in C::B (mingw, which is the port of the Gnu Compiler Collection to Windows) from the command line for shorter projects and VC++ Express Edition for projects of more than a few files. C::B is a great program but I wasn't using many of the features.
You have to use what you feel comfortable with. Any setup will have it's gotchas. VC++ EE has a great debugger right of the bat. C::B has gdb which is awesome (I envy those who use it effectively) but has somewhat of a learning curve) and seems to integrate well with the environment.
Edited by jonsca: n/a
int main() { using namespace std; int x; cout << "how many legs do you have?" << endl; cin >> x; switch (x) { case 1: cout << "thats weird..." << endl; break; case 2: cout << "your normal..." << endl; break; case 3: cout << "ya freak!!!!!!!!!" << endl; break; default: cout << "i dont know what you are..." << endl; } system("pause"); return 0; }
so i put this code into the code::blocks program and tried to run it.
it came up with the error: 'cout' was not declared in this scope
whats causing this? i have the same exact script in dev c++ and its working fine...
#include <iostream>
ok i just made a new script using structures and this is what i got:
#include <iostream> #include <cmath> struct newperson { char person[20]; char name[20]; int age; }; int main() { using namespace std; newperson bob = { "this is bob", "Bob's age is:", 36 }; cout << bob.person << endl; cout << bob.name << endl; cout << bob.age << endl; newperson jimmy = { "this is Jimmy", "Jimmy's age is:", 48 }; cout << jimmy.person << endl; cout << jimmy.name << endl; cout << jimmy.age << endl; system("pause"); return 0; }
this works and all but i want to add a person to the side of: this is bob, and this is jimmy.
something like this:
O
\ /
|
/ \
well thats the best one i can think of how to make with /'s and stuff right now... i tried this:
cout << " O
\ /
|
/ \" << endl
but that didnt work...
Edited by skorm909: n/a
havnt learned strings yet i dont think, but now i got some code:
#include <iostream> #include <cmath> #include <fstream> #include <cstdlib> struct peoples { char person[20]; char stick[80]; char discrip[20]; int age; }; int main() { using namespace std; peoples = { "this is bob:", "file for stickfigure here", "bob's age is: ", 36 } system("pause"); return 0; }
and what i want to do for this is in "file for stickfigure here"
basically have a stick figure in the program then move onto the next line so it would endup being like this...
this is bob.
(stick figure here)
bob's age is:
36
is there a way i can do this?
havnt learned strings yet i dont think, but now i got some code:
#include <iostream> #include <cmath> [B]//Don't need it[/B] #include <fstream> [B]//Don't need it[/B] #include <cstdlib> [B]//Don't need it[/B] struct peoples { char person[20]; char stick[80]; [B]//See below[/B] char discrip[20]; int age; }; int main() { using namespace std; [b] //Needs to be outside of main [/b] peoples = //[b] need an instance now, see below[/b] { "this is bob:", "file for stickfigure here", "bob's age is: ", 36 } system("pause"); [b] //lose this bad habit before you pick it up[/b] return 0; }
See my changes below:
struct peoples { char person[20]; char stick[3][6]; //3 rows of 6 columns char discrip[20]; int age; }; int main() { peoples mypeople= //making a struct mypeople { //that is of type peoples "this is bob:", {"\\ O /", //initializing 2D array inside " | ", //HW: why do we need \\ for a backslash "/ \\"}, "bob's age is: ", 36 }; return 0; }
My code above needs the #include and using statements
Don't use
system("pause"); see this use
cin.get(); which will wait for a key.
Edited by jonsca: n/a
ok and i made this today, it converts your age into dog years then asks some questions but what i want to know is if i have the questions, how do i make it so if they get it wrong it says wrong, then to the side add a point to the right/wrong.
so have it like:
question: ssfgesg
answer: sgesg
right. 1/1
question: wgsgseg
answer: shesh
wrong: 1/2
then total score= 1/2
something like that...
anyway heres the code:
#include <iostream> #include <cmath> int main() { using namespace std; int hi; int name; int years; int house; int yellow; int blue; int green; cout << "to find out your age in dog years, type in your age:" << endl; cin >> hi; cout << "calculating..." << endl; cout << "your age in dog years is..." << endl; cout << hi * 7 << endl; cout << "if the green house is made of green bricks, what color are the stairs?" << endl; cout << "pick one, 1. green , 2. blue , 3. yellow , 4. how would i know?" << endl; cin >> green; if ( green == 1 || green == 1.) cout << "Correct!!" << endl; else cout << "wrong..." << endl; cout << "if the yellow house is made of yellow bricks, what color are the doors?" << endl; cout << "pick one, 1. green , 2. blue , 3. yellow , 4. how would i know?" << endl; cin >> yellow; if ( yellow == 3 || yellow == 3.) cout << "Correct!!" << endl; else cout << "wrong..." << endl; cout << "if the blue house has everything made of blue... what is it made out of?" << endl; cout << "pick one, 1. blue bricks , 2. yellow bricks , 3. green bricks , 4. glass" << endl; cin >> blue; if ( blue == 4. || blue == 4) cout << "CORRECT! You win!!!!" << endl; else cout << "you suck, go do it again." << endl; system("pause"); return 0; }
if ( green == 1 || green == 1.) There is no such thing as 1. with an integer. Just use
if (green == 1) For keeping track, make another integer variable called correct and one called total or something like that. Set them both to 0 when you declare them (so
int correct = 0; ).
if(green == 1) { cout<<"Correct"<<endl; correct++; //shorthand for correct = correct + 1; } //need the braces for multiple statements under one if else cout <<"Wrong"<<endl; total++; //after both if and else are done cout <<"You have "<<correct<<"/"<<total<<endl; if(yellow == 3) { cout <<"Correct"<<endl; correct++; //don't redeclare it or set it to 0 again } else cout<<"Wrong"<<endl; total++; cout <<"You have "<<correct<<"/"<<total<<endl;
Repeat that for as many as you want.
You're starting to get it ok. Keep reinforcing what you are learning but don't be afraid to delve further into the language so you can expand your repertoire.
Edited by jonsca: n/a
ok thanks i had to add:
int correct; int total; correct = 0; total = 0;
then after that i just followed what you said and it all worked out fine,
thanks =).
now i just have to figure out what else to add....
any ideas?
just like, give me an idea and see if i can do it without help.
Edited by skorm909: n/a.
well what i was wanting to do is like have a program that pops up and has buttons to run different code i made but everytime i try looking on how to do this i can never find anything...
as for right now i want to make it so its kind of a game where i have the questions and depending on the score at the end they either have to redo the questions or go to a new set...
so would that be like:
if (correct == >3) //then something like run to the next line of code, isnt there like a skip function i can use to do this? // then if (correct == <3) // then something like run a loop back to the beginning of the questions....
have a program that pops up and has buttons to run different code i made
Unless you've got some GUI experience in another language that's going to be a bit of a road...give it time.
i want to make it so its kind of a game where i have the questions and depending on the score at the end they either have to redo the questions or go to a new set...
That's going to take some strings knowledge. Grab some tutorials. Start simple. Look into arrays to store your questions. Look into files to store additional sets of questions.
correct == >3 correct ==<3
See if you can figure out what's wrong with those two statements.
Edited by jonsca: n/a
It may seem silly but just say them out loud if you forget "greater than > or equal = to", >= and "less than < or equal = to", <=
Search around on this site for "text based RPG." People early on in their programming seem to really enjoy creating though without using functions and the like they can get a little unwieldy. I know a user named Restrictment had posted the code for his some months back. It couldn't hurt just to look at it and see where he went with it.
ok thanks,
in my history class we got an assignment to do a quarter project however we want,
i figured since i started c++ and i know the basics of javascript too, why not try and make a website with html?
i think if i did it on a free site that makes it for you and all that it wouldnt mean as much,
can i import some of my c++ things into the html site or is that only for javascript too?
also if you know any places where i can find tutorials for html or javascript i would really appreciate it...
C++ won't help you really at all with web stuff (though there are some technologies like this which allow users to run C code in the browser). C# (which is related to C++) can be used in ASP.NET coding on the web.
In terms of tutorials for HTML and Javascript (which is a smidge like C++ actually) I would pop over to the folks in the DaniWeb Web Development forums and see what they have for sticky threads over there. I'd imagine there are quite a few. I went through some of the w3schools material at one point and I found it pretty well laid out but definitely see what they recommend first.
No problem. Good luck!; // ... | https://www.daniweb.com/programming/software-development/threads/258440/c-error/2 | CC-MAIN-2018-34 | refinedweb | 1,738 | 86.64 |
* Serge E. Hallyn <serue us ibm com> [2009-06-30 15:06:13]: > Quoting Balbir Singh (balbir linux vnet ibm com): > > On Tue, Jun 23, 2009 at 8:26 PM, Serge E. Hallyn<serue us ibm com> wrote: > > > A > > > >) > > Thanks, Balbir. By the last sentence, are you talking about having > cgroup in its own libcgroup, or do you mean something else? > > On the topic of cgroups, does anyone not agree that we should try > to get rid of the ns cgroup, at least once user namespaces can > prevent root in a container from escaping their cgroup? > I would have no objections to trying to obsolete ns cgroup once user namespaces can do what you suggest. -- Balbir | https://www.redhat.com/archives/libvir-list/2009-July/msg00000.html | CC-MAIN-2017-39 | refinedweb | 116 | 74.53 |
Hello all,
I am currently finishing this exercise:
Here the capacitive touch sensor A1 is used to measure changes in capacitance when in contact with moist soil.
What I was trying to do is make my code take the value of the sensor when the microcontroler first starts up and use this as a baseline to measure capacitance against.
My code looks like this:
from adafruit_circuitplayground.express import cpx import time import touchio from board import * touch = touchio.TouchIn(A1) touch_init = touch.raw_value #calibrates capacity base value step_size_capacitance = 20 #how much capacity lies between each capacity step, some trial and error needed while True: if cpx.button_a: print(cpx.temperature) if cpx.button_b: print(cpx.light) else: if cpx.switch: print((touch.raw_value, touch_init)) if touch.raw_value <= touch_init: cpx.pixels.fill((50,0,0)) if touch.raw_value > touch_init and touch.raw_value < (touch_init+step_size_capacitance):
This are the first 26 lines of my code. As you see I instantiate touchio.touchin in the variable touch and then use touch.raw to get the output.
I afterwards use this instance to save the value as touch_init, which is my baseline capacitance.
Now my question: Why does this work?
You see, later I call touch_init to compare against touch.raw_value. My understanding would be the interpreter would then look for the definition of touch_init, up outside the loop, and use touch.raw_value to get it, which in turn would not be the initial value but the current one.
But this does not happen. The print statement clearly shows touch_init staying constant even when A1 is touched. Now, don’t get me wrong - I am as happy as the next guy when my code works. But it seems I missunterstood how the logic behaves in that case and would love to learn the reason for it for future reference.
Thanks in advance for any input! | https://discuss.codecademy.com/t/question-regarding-while-loop-and-variables-outside-the-loop-with-circuitpython/452929 | CC-MAIN-2020-05 | refinedweb | 310 | 68.87 |
patch:
Hmm, your mailer seems to mangle whitespaces, I often can apply your
patches mailed inline with "patch -l" only (the mime attached ones are
fine).
Two small fixes I need in the big stack of patches i have now to
build kernels successfully. The first is a simple missing include:
==============================[ cut here ]==============================
--- linux-uml-2.6.9.orig/arch/um/os-Linux/signal.c 2004-10-28 20:11:02.757586671 +0200
+++ linux-uml-2.6.9/arch/um/os-Linux/signal.c 2004-10-28 20:23:32.730183963 +0200
@@ -6,6 +6,7 @@
#include <signal.h>
#include "time_user.h"
#include "mode.h"
+#include "choose-mode.h"
#include "sysdep/signal.h"
void sig_handler(int sig)
==============================[ cut here ]==============================
The second one is a fixup for the host-skas3 patch. That one is needed
if you use one source tree for both host and uml builds. Without that
fixup the host-skas3 patch breaks uml kernel builds (and also all other
architectures as only i386 has sysemu right now ...).
==============================[ cut here ]==============================
--- uml-2.6.9-rc2.orig/arch/um/include/skas_ptrace.h 2004-09-16 16:10:16.000000000 +0200
+++ uml-2.6.9-rc2/arch/um/include/skas_ptrace.h 2004-09-16 16:10:24.000000000 +0200
@@ -6,6 +6,7 @@
#ifndef __SKAS_PTRACE_H
#define __SKAS_PTRACE_H
+#ifndef PTRACE_FAULTINFO
struct ptrace_faultinfo {
int is_write;
unsigned long addr;
@@ -21,6 +22,7 @@ struct ptrace_ldt {
#define PTRACE_SIGPENDING 53
#define PTRACE_LDT 54
#define PTRACE_SWITCH_MM 55
+#endif
#endif
--- uml-2.6.9-rc2.orig/kernel/fork.c 2004-09-16 16:10:21.000000000 +0200
+++ uml-2.6.9-rc2/kernel/fork.c 2004-09-16 16:12:40.000000000 +0200
@@ -1038,7 +1038 */
==============================[ cut here ]==============================
It's kida quick&dirty, the real fix probably would be to have the skas
ptrace stuff in *one* place, guess that isn't going to happen before
skas is merged mainline through. Whats the status on skas4 btw.?
Gerd
View entire thread | https://sourceforge.net/p/user-mode-linux/mailman/message/13721583/ | CC-MAIN-2017-39 | refinedweb | 323 | 71.1 |
Creating MNE’s data structures from scratch¶
MNE provides mechanisms for creating various core objects directly from NumPy arrays.
import mne import numpy as np
Creating
Info objects¶
Note
for full documentation on the
Info object, see
The Info data structure. See also Creating MNE objects from data arrays.
Normally,
mne.Info objects are created by the various
data import functions.
However, if you wish to create one from scratch, you can use the
mne.create_info() function to initialize the minimally required
fields. Further fields can be assigned later as one would with a regular
dictionary.
The following creates the absolute minimum info structure:
# Create some dummy metadata n_channels = 32 sampling_rate = 200 info = mne.create_info(n_channels, sampling_rate) print(info)
Out:
<Info | 16 non-empty fields bads : list | 0 items ch_names : list | 0, 1, 2, 3, 4, 5, 6, 7, 8, ... chs : list | 32 items (MISC: 32) comps : list | 0 items custom_ref_applied : bool | False dev_head_t : Transform | 3 items events : list | 0 items highpass : float | 0.0 Hz hpi_meas : list | 0 items hpi_results : list | 0 items lowpass : float | 100.0 Hz meas_date : NoneType | unspecified nchan : int | 32 proc_history : list | 0 items projs : list | 0 items sfreq : float | 200.0 Hz acq_pars : NoneType acq_stim : NoneType ctf_head_t : NoneType description : NoneType dev_ctf_t : NoneType dig : >
You can also supply more extensive metadata:
# Names for each channel channel_names = ['MEG1', 'MEG2', 'Cz', 'Pz', 'EOG'] # The type (mag, grad, eeg, eog, misc, ...) of each channel channel_types = ['grad', 'grad', 'eeg', 'eeg', 'eog'] # The sampling rate of the recording sfreq = 1000 # in Hertz # The EEG channels use the standard naming strategy. # By supplying the 'montage' parameter, approximate locations # will be added for them montage = 'standard_1005' # Initialize required fields info = mne.create_info(channel_names, sfreq, channel_types, montage) # Add some more information info['description'] = 'My custom dataset' info['bads'] = ['Pz'] # Names of bad channels print(info)
Out:
<Info | 18 non-empty fields bads : list | Pz ch_names : list | MEG1, MEG2, Cz, Pz, EOG chs : list | 5 items (GRAD: 2, EEG: 2, EOG: 1) comps : list | 0 items custom_ref_applied : bool | False description : str | 17 items dev_head_t : Transform | 3 items dig : list | 5 items (3 Cardinal, 2 EEG) events : list | 0 items highpass : float | 0.0 Hz hpi_meas : list | 0 items hpi_results : list | 0 items lowpass : float | 500.0 Hz meas_date : NoneType | unspecified nchan : int | 5 proc_history : list | 0 items projs : list | 0 items sfreq : float | 1000.0 Hz acq_pars : NoneType acq_stim : NoneType ctf_head_t : NoneType dev_ctf_t : >
Note
When assigning new values to the fields of an
mne.Info object, it is important that the
fields are consistent:
The length of the channel information field chs must be nchan.
The length of the ch_names field must be nchan.
The ch_names field should be consistent with the name field of the channel information contained in chs.
Creating
Raw objects¶
To create a
mne.io.Raw object from scratch, you can use the
mne.io.RawArray class, which implements raw data that is backed by a
numpy array. The correct units for the data are:
V: eeg, eog, seeg, emg, ecg, bio, ecog
T: mag
T/m: grad
M: hbo, hbr
Am: dipole
AU: misc
The
mne.io.RawArray constructor simply takes the data matrix and
mne.Info object:
# Generate some random data data = np.random.randn(5, 1000) # Initialize an info structure info = mne.create_info( ch_names=['MEG1', 'MEG2', 'EEG1', 'EEG2', 'EOG'], ch_types=['grad', 'grad', 'eeg', 'eeg', 'eog'], sfreq=100 ) custom_raw = mne.io.RawArray(data, info) print(custom_raw)
Out:
Creating RawArray with float64 data, n_channels=5, n_times=1000 Current compensation grade : 0 Range : 0 ... 999 = 0.000 ... 9.990 secs Ready. <RawArray | None, n_channels x n_times : 5 x 1000 (10.0 sec), ~54 kB, data loaded>
Creating
Epochs objects¶
To create an
mne.Epochs object from scratch, you can use the
mne.EpochsArray class, which uses a numpy array directly without
wrapping a raw object. The array must be of shape(n_epochs, n_chans,
n_times). The proper units of measure are listed above.
# Generate some random data: 10 epochs, 5 channels, 2 seconds per epoch sfreq = 100 data = np.random.randn(10, 5, sfreq * 2) # Initialize an info structure info = mne.create_info( ch_names=['MEG1', 'MEG2', 'EEG1', 'EEG2', 'EOG'], ch_types=['grad', 'grad', 'eeg', 'eeg', 'eog'], sfreq=sfreq )
It is necessary to supply an “events” array in order to create an Epochs object. This is of shape(n_events, 3) where the first column is the sample number (time) of the event, the second column indicates the value from which the transition is made from (only used when the new value is bigger than the old one), and the third column is the new event value.
More information about the event codes: subject was either smiling or frowning
event_id = dict(smiling=1, frowning=2)
Finally, we must specify the beginning of an epoch (the end will be inferred from the sampling frequency and n_samples)
# Trials were cut from -0.1 to 1.0 seconds tmin = -0.1
Now we can create the
mne.EpochsArray object
custom_epochs = mne.EpochsArray(data, info, events, tmin, event_id) print(custom_epochs) # We can treat the epochs object as we would any other _ = custom_epochs['smiling'].average().plot(time_unit='s')
Out:
10 matching events found No baseline correction applied Not setting metadata 0 projection items activated 0 bad epochs dropped <EpochsArray | 10 events (all good), -0.1 - 1.89 sec, baseline off, ~93 kB, data loaded, 'frowning': 5 'smiling': 5> Need more than one channel to make topography for grad. Disabling interactivity.
Creating
Evoked Objects¶
If you already have data that is collapsed across trials, you may also directly create an evoked array. Its constructor accepts an array of shape(n_chans, n_times) in addition to some bookkeeping parameters. The proper units of measure for the data are listed above.
# The averaged data data_evoked = data.mean(0) # The number of epochs that were averaged nave = data.shape[0] # A comment to describe to evoked (usually the condition name) comment = "Smiley faces" # Create the Evoked object evoked_array = mne.EvokedArray(data_evoked, info, tmin, comment=comment, nave=nave) print(evoked_array) _ = evoked_array.plot(time_unit='s')
Out:
<Evoked | 'Smiley faces' (mean, N=10), [-0.1, 1.89] sec, 5 ch, ~23 kB> Need more than one channel to make topography for grad. Disabling interactivity.
Total running time of the script: ( 0 minutes 4.192 seconds)
Estimated memory usage: 8 MB
Gallery generated by Sphinx-Gallery | https://mne.tools/0.18/auto_tutorials/simulation/plot_creating_data_structures.html | CC-MAIN-2022-33 | refinedweb | 1,049 | 55.54 |
Array multiplication we will find the product of all elements of the given array. and then according to the problem, we will divide the product with the number n. let's take an example −
Input: arr[] = { 12, 35, 69, 74, 165, 54}; N = 47 Output: 14
The array is like {12, 35, 69, 74, 165, 54} so the multiplication will be (12 * 35 * 69 * 74 * 165 * 54) = 19107673200. Now if we want to get the remainder after dividing this by 47 it will be 14.
First multiple all the number then take % by n then find the reminder, But in this approach, if the number is maximum of 2^64 then it gives the wrong answer.
#include <stdio.h> int main() { int arr[] = { 12, 35, 69, 74, 165, 54}; int len = 6; int n = 47 ; int mul = 1; for (int i = 0; i < len; i++) mul = (mul * (arr[i] % n)) % n; printf("the remainder is %d", (mul%n)); return 0; }
the remainder is 14 | https://www.tutorialspoint.com/c-cplusplus-program-to-find-the-reminder-of-array-multiplication-divided-by-n | CC-MAIN-2021-31 | refinedweb | 164 | 70.16 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
xml rpc creates partner but not lead
I have a script that works when creating a partner for xml-rpc using php, but I cant seem to create a lead using xml-rpc for php. Does anyone know how to create a lead using xml-rpc? Thank you
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
Dont use PHP, use Python instead
import xmlrpclib
url=""
sock = xmlrpclib.ServerProxy(url)
uid = sock.login("dbName", "userName", "userPassword")
url = ""
sock = xmlrpclib.ServerProxy(url)
args = {'contact_name':"Python Lead2", 'email_from': "python@email.com", 'addMoreFields': "more data", }
lead_id = sock.execute('dbName', uid, 'userPassword', 'crm.lead','create', args) | https://www.odoo.com/forum/help-1/question/xml-rpc-creates-partner-but-not-lead-36697 | CC-MAIN-2017-17 | refinedweb | 148 | 51.34 |
2.2. Using the latest features of Python
The latest version of the Python 2.x branch, Python 2.7, was released in 2010. It will reach its end of life in 2020. On the other hand, the first version of the Python 3.x branch, Python 3.0, was released in 2008. The decade-long transition period between Python 2 and Python 3, which are slightly incompatible, has been somewhat chaotic.
Choosing between Python 2 (also known as Legacy Python) and Python 3 used to be tricky since many Python users had not transitioned to Python 3 yet, and many libraries were only compatible with Python 2. These times are gone and it is now safe to stick with Python 3 in virtually all cases. The only exceptions are when you have to support old unmaintained libraries, or when your users cannot transition to Python 3 for whatever reason.
In addition to fixing bugs and annoyances of Python 2 (for example related to Unicode support), Python 3 brings many interesting features in terms of syntax, capabilities of the language, and new built-in libraries.
We use the latest stable version of Python in this recipe, which is Python 3.6.
How to do it...
1. In Python 3,
print() is a function whereas it was a statement in Python 2 (it was a historical oddity). This function may accept multiple arguments as well as a few options. Let's create a list:
my_list = list(range(10))
We can print the
my_list object:
print(my_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
But we can also print the ten numbers in the list:
print(*my_list)
0 1 2 3 4 5 6 7 8 9
Finally we can customize the separator and the end of the string to print:
print(*my_list, sep=" + ", end=" = %d" % sum(my_list))
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
2. Python 3 supports more advanced variable unpacking features:
first, second, *rest, last = my_list
print(first, second, last)
0 1 9
rest
[2, 3, 4, 5, 6, 7, 8]
3. In Python 3, variable names can contain Unicode characters. This technique may be useful when writing mathematical code. To type mathematical symbols in the Jupyter Notebook, write LaTeX code and press Tab. For example, to create a variable \(\pi\), type
\pi and then Tab:
from math import pi, cos α = 2 π = pi cos(α * π)
1.000
4. Python 3.6 brings new string literals called f-strings. They offer a convenient syntax to define strings depending on existing variables:
a, b = 1, 2 f"The sum of {a} and {b} is {a + b}"
'The sum of 1 and 2 is 3'
5. We can add custom annotations to function arguments and output. These function annotations convey no semantics, but they can be used in the code as we like. Here is an example coming from :
def kinetic_energy(mass: 'kg', velocity: 'm/s') -> 'J': """The annotations serve here as documentation.""" return .5 * mass * velocity ** 2
These annotations are stored in the
__annotations__ attribute of the function, and they can be used as follows:
annotations = kinetic_energy.__annotations__ print(*(f"{key} is in {value}" for key, value in annotations.items()), sep=", ")
mass is in kg, velocity is in m/s, return is in J
The typing module, which has been included in Python 3.5 on a provisional basis, implements several annotations that can be used to specify typing information in functions.
6. Python 3.5 brings a new operator
@ for matrix multiplication. It is supported by NumPy 1.10 and later:
import numpy as np M = np.array([[0, 1], [1, 0]])
The
* operator is the element-wise multiplication:
M * M
array([[0, 1], [1, 0]])
Previously, matrix multiplication could be performed with
np.dot(). The new syntax is clearer:
M @ M
array([[1, 0], [0, 1]])
7. Python 3.3 brings the new
yield from syntax that allows you, among other things, to compose multiple generators. For example, the two following functions are equivalent:
def gen1(): for i in range(5): for j in range(i): yield j
def gen2(): for i in range(5): yield from range(i)
list(gen1())
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
list(gen2())
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
8. The
functools library provides a
@lru_cache decorator to implement a simple in-memory caching system for Python functions:
import time def f1(x): time.sleep(1) return x
%timeit -n1 -r1 f1(0)
1 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -n1 -r1 f1(0)
1 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
Here, the two successive identical calls to
f1(0) take one second. Now, let's define a cached version of this function:
from functools import lru_cache @lru_cache(maxsize=32) # keep the latest 32 calls def f2(x): time.sleep(1) return x
%timeit -n1 -r1 f2(0)
1 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -n1 -r1 f2(0)
6.14 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
The first call takes one second, whereas the next one returns immediately. In the second case, the function is not called but the output corresponding to the argument of 0 was cached and returned.
9. The new pathlib module offers filesystem facilities that are more convenient to use than the Python 2
os.path methods. The main class is
Path:
from pathlib import Path
We instantiate a
Path object representing the current directory:
p = Path('.')
Let's list all Markdown files in the directory:
sorted(p.glob('*.md'))
[PosixPath('00_intro.md'), PosixPath('01_py3.md'), PosixPath('02_workflows.md'), PosixPath('03_git.md'), PosixPath('04_git_advanced.md'), PosixPath('05_tips.md'), PosixPath('06_high_quality.md'), PosixPath('07_test.md'), PosixPath('08_debugging.md')]
We can easily get the contents of a text file:
_[0].read_text()
'# Introduction\n\n...\n'
Let's obtain the list of subdirectories:
[d for d in p.iterdir() if d.is_dir()]
[PosixPath('images'), PosixPath('.ipynb_checkpoints'), PosixPath('__pycache__'),
Finally, we list all files in the
images subfolder (note the slash
/ operator on
Path instances):
list((p / 'images').iterdir())
[PosixPath('images/github_new.png'), PosixPath('images/folder.png')]
10. Python 3.4 provides a new statistics module which implements basic statistical routines. This module may be useful when depending on NumPy or SciPy is not desirable. Let's import the module:
import random as r import statistics as st
We create a list of normally-distributed random variables:
my_list = [r.normalvariate(0, 1) for _ in range(100000)]
We compute the mean, median, and standard deviation:
print(st.mean(my_list), st.median(my_list), st.stdev(my_list), )
0.00073 -0.00052 1.00050
There's more...
Other interesting features of Python 3 include coroutines with the asyncio module and asynchronous operations with the new
await and
async keywords.
Here are a few references:
- What's new in Python 3.6? at
- f-strings at
- yield from syntax at
- functools at
- pathlib at
- statistics at
- 10 awesome features of Python that you can't use because you refuse to upgrade to Python 3, at
- Python 3 for Scientists, at
- Cool New Features in Python 3.6, at
- The Python Cookbook, by Brian Jones and David Beazley, O'Reilly Media at
- Find the best Python books, at
- The 10 Most Common Mistakes That Python Developers Make, at
- Python 3 statement, to promote the deprecation of Python 2 support by 2020, at | https://ipython-books.github.io/22-using-the-latest-features-of-python-3/ | CC-MAIN-2019-09 | refinedweb | 1,268 | 62.07 |
Hello,
I have a WCF service (written in .net 4.0). I need to have .net 2.0 client interact with the service. Service is exposing the end point as basicHttpBinding and service metadata has httpGentEnabled to true. I'm able to connect to service
in 2.0 using "Add Web Reference" and providing the url ending with ?wsdl. What I'm stuck with is the interaction part. How can I make server call client's method? In order to do that, server has to know some sort of contract that client implements.
How can we make server call client to get data?
Thanks
Sheraz
View
Hello!
Hello All:
I've the following XAML code:
<Image Canvas.
<Custom:Interaction.Behaviors>
<MultiTouch_Behaviors_WP7:MultiTouchBehavior
</Custom:Interaction.Behaviors>
</Image>
I've a situation where I want to add many images with the same behaviors through the code dynamically.
How can I do that?
Hi all,
I have code which allows a client console to connect to a server console using .NET Remoting with a shared dll, and then perform some operations. The only problem I'm aving, is that I want the main bulk of the programming logic to be performed on the server
itself (within the server class, not the library) - to access the database etc. Eventually the (multiple) Clients and Server application will be on seperate physical machines (for now they are on one). Below is the code I have so far. The server
console says "press any key", and the client will say "Name: Test". I want this information to be available on the Server application!!!
The general idea of this set up is to pass the MyObj class between client and server (the client can request a MyObj with data, or it can send it as part of a method param). I then need this class to be available on the Server app where it will retrieve/store
the classes' data into a database, and perform additional logic on the data, and then pass it back to the client.
//Server code
public class Server
{
public static void
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/25529-wcf-interaction-with-net-20-app.aspx | CC-MAIN-2016-44 | refinedweb | 363 | 65.83 |
I’ll have to hold my hands up here. My original remarks on the composite pattern was pretty much 100% wrong. In fairness to myself, I’m not the only one to have dismissed it as being tricky and slightly special case. (As an aside, I really don’t think Command is a starter pattern. To be honest, I’m still not convinced I’m doing it right.) Like the visitor pattern, we tend to associate it with dealing with trees* and such relatively obscure topics as semantic evaluation.
Actually, it’s closest to the adapter pattern. But while the adapter pattern is about jamming a square peg into a round hole, the composite pattern is about slipping two round pegs into the same round hole. Of course, the physical realization of this would be impossible, but code’s a lot more flexible than IKEA furniture.
So, how do we achieve this? Well, imagine a simple interface like this
public interface ILogger { void WriteLine(string line); }
and two implementations
public class ConsoleLogger : ILogger { public void WriteLine(string line) { Console.WriteLine(line); } } // Yeah, the implementation of FileLogger is awful // you don't need to tell me public class FileLogger : ILogger { string fileName; public FileLogger(string fileName) { this.fileName = fileName; } public void WriteLine(string line) { using (var writer = new StreamWriter(fileName, true)) { writer.WriteLine(line); writer.Flush(); } } }
So, imagine we now want to write to the console and to the file. Or to two different files. Do we need to write a new logger each of these cases? No, we just need the one, the Composite logger.
public class CompositeLogger : ILogger { IEnumerable<ILogger> underlying; public CompositeLogger(IEnumerable<ILogger> underlying) { this.underlying = underlying; } public void WriteLine(string line) { foreach (var logger in underlying) { logger.WriteLine(line); } } }
This class gives us all the aggregation we need and allows us to easily implement the single responsibility principle. A class taking one logger can now write to two loggers without changing the code. Incidentally, if you look at the Solution Transform source code, you’ll see that I have two composite classes that work exactly as defined above.
Aggregation of Results
That’s the basic idea. However, my example rather deliberately skirted an important detail: what happens if your interface returns values?** The answer is, it depends. We’re starting to move away from the classical definition Let’s take an example from the dotcom world. Imagine that you were running a shopfront application. You’ve got several suppliers with price providers. But you only want the one price. Well, the sensible thing to do would be to quote the lowest price. So, on top of IPriceProvider you could have MinimumPriceProvider as a composite implementation. In fact, most aggregate functions could be used in various contexts:
- Minimum
- Maximum
- Sum
- Product
- First (or First not null)
- And (True if all of the underlying implementations return true)***
- Or (True if one of the underlying implementations return true)
The price example is oversimplified, however. Usually, you don’t only want to know the lowest price, you want to know who is quoting the lowest price. The composite pattern doesn’t really apply here. Actually, we’re probably talking about chain of responsibility again. Composite objects are dumb. If you’re talking logic and decision making, composite isn’t the right design.
Composites in Use
There’s a couple of composite implementations that you never even think about. Any logging system is an obvious example, but MulticastDelegates are composites as well: they expose the method signature and call multiple implementations when invoked. It’s also a fundamental building block of any publish and subscribe system. Jeremy Miller’s got a list of common composites but, inevitably, most of them are tree structures. Obviously, you start putting composites in other composites and you get a tree structure, but there are plenty of flatter problems that find composites useful.
So, when should you use it? Basically. anytime you process list of objects, revisit whether your code would be simpler if you just dealt with one object, and used a composite to for aggregation/distribution duties.
*Please bear in mind that I’m referring to that JavaWorld article as an example of someone making a mistake. I don’t really want to dissect exactly what’s wrong with the rest of the article, but I’m not recommending it.
**In fact, I don’t think you can return values according to the classical definition. It’s hard to find an example on the internet that does. I’m sure someone with a copy of Gamma et al handy will correct me.
***Take a look at the Rhino Mocks constraints code for a good example of this. | https://colourcoding.net/2010/03/08/the-composite-pattern-revisited/ | CC-MAIN-2019-04 | refinedweb | 783 | 56.55 |
BufferedInputStream - sample program in Java
By: Daniel Malcolm Printer Friendly Format
Buffering I/O is a very common performance optimization. Java's BufferedInputStream class allows you to "wrap" any InputStream into a buffered stream and achieve this performance improvement.
BufferedInputStream has two constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)
The first form creates a buffered stream using a default buffer size. In the second, the size of the buffer is passed in bufSize. Use of sizes that are multiples of memory page, disk block, and so on can have are InputStream, BufferedInputStream also supports the mark() and reset() methods. This support is reflected by BufferedInputStream.markSupported() returning true.
The following example contrives a situation where we can use mark() to remember where we are in an input stream and later use reset() to.
// Use buffered input.
import java.io.*;
class BufferedInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "This is a © copyright symbol " +
"but this is © not.\\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream;
}
}
}
}
Notice that this example uses mark(32), which preserves the mark for the next 32 bytes read (which is enough for all entity references). Here is the output produced by this program:
This is a (c) copyright symbol but this is © not.
Caution: Use of mark() is restricted to access within the buffer. This means that you can only specify a parameter to mark() that is smaller than the buffer size of the stream. don't give example from book this example i
View Tutorial By: aniruddha at 2011-03-23 00:34:32 | https://java-samples.com/showtutorial.php?tutorialid=389 | CC-MAIN-2022-21 | refinedweb | 270 | 55.34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.