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 |
|---|---|---|---|---|---|
Greetings,
I have this code that when i input 5 scores it should average them and give me a grade instead of its percentage. Instaed of me summing say 5, 100% scores togther my grade should dispolay an A but the grade i always get is an F, go figure... anyways can anyone help me figure out why this is happening.
Code:#include <iostream> #include <string> //cin, cout, <<, >> using namespace std; int main() { double score1, score2, score3, score4, score5, percentage; char grade; cout << "Input five test scores: "; cin >> score1, score2, score3, score4, score5; percentage = 5 / (score1 + score2 + score3 + score4 + score5); if (percentage >= 90) grade = 'A'; //grade must be 90 or better for an A else if (percentage >= 80) //grade must be 80 or better for an B grade = 'B'; else if (percentage >= 70) //grade must be 70 or better for an C grade = 'C'; else if (percentage >= 60) //grade must be 60 or better for an D grade = 'D'; else grade = 'F'; //anything less than 60 % is failing cout << "\nYour letter grade is " << grade << "\n"; return percentage; } | http://cboard.cprogramming.com/cplusplus-programming/25771-error-my-program.html | CC-MAIN-2014-10 | refinedweb | 177 | 52.2 |
I have a NetWare server running Apache that has directory aliases that call out to other NetWare servers. I'm about to migrate one of those NetWare servers to SLES10SP3 with OES2. When I test the Apache config with a new alias calling to a SLES server, I can get a directory listing of files truncated to 8 characters. I cannot download said files, just get a listing of them. I do have long namespace set on the NSS volume of the SLES server, and indeed if I light up Apache2 on there and call the same directory as an alias, it serves up fine.
So, the only thing that DOESN'T work, is calling it through Apache on the NetWare box.
Any ideas, are appreciated.
Tom
Your problem is that you're running Apache 1.3 on your NetWare server. Apache 1.3 and Apache 2 (and 2.2) are linked to different base libraries. Apache 1.3 is linked to CLIB, the library that originated with NetWare 2.x. Apache 2.0 is linked to LIBC, the replacement for CLIB that was introduced around NetWare 5.x. Because of this, when accessing remote servers CLIB-linked applications had to go to very creative lengths to get names that are not in the DOS namespace. LIBC has native methods for accessing the LONG or UNIX namespaces, and don't have these problems.
It comes down to the NCP semantics used by both libraries.
Your problem comes in when trying to access OES-Linux servers. When Novell ported the NCP stack over to non-NetWare platforms, which they did when they ported eDirectory to Windows/Linux/Solaris/AIX, they chose to not bother with the old-school semantics and just use the newer modern ones. Then OES came along and they just extended the NCP stack they already had for eDir. They didn't put the old semantics in.
In order to access resources on OES-linux servers, you'll need to use Apache 2.0 (or 2.2) on your NetWare servers. Apache 1.3 simply can't do it the way you need.
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
145 times
active | http://serverfault.com/questions/167854/netware-to-sles-apache-alias | CC-MAIN-2014-52 | refinedweb | 377 | 74.69 |
Tracker bug for gentoolkit-0.2.5
Created attachment 179571 [details]
setup.py
python distutils installer for djanderson's rewrite of equery
Created attachment 179735 [details]
setup.py
(All of the changes described below are intended to be transparent to the lay end-user, although in some cases they may break scripts.)
Depends upon a reorganization of gentoolkit, which I describe in detail in an email to tools-portage@gentoo.org. In essence, though, it consists of the following:
- python modules would be part of the gentoolkit package (so gentoolkit.equery, for example)
- separate dev bits from non-dev parts
- move non-python scripts to scripts folder
- mangle the python stuff so it can be called from site-packages
Created attachment 179736 [details]
MANIFEST.in
Manifest template file for distutils -- see comment #2
I'm going to do the refactoring of equery in gentoolkit-0.3 and will skip going to 0.2.5.
Will _rc9 work with python 3? Currently my equery (which uses python2.5) from app-portage/gentoolkit-0.3.0_rc8) doesn't work with my sys-apps/portage-2.1.7.16 ...
Traceback (most recent call last):
File "/usr/bin/equery", line 32, in <module>
from gentoolkit import equery, errors
File "/usr/lib64/python2.5/site-packages/gentoolkit/equery/__init__.py", line 31, in <module>
import portage
File "/usr/lib64/portage/pym/portage/__init__.py", line 58
except ImportError as e:
^
SyntaxError: invalid syntax
(In reply to comment #5)
> Will _rc9 work with python 3? Currently my equery (which uses python2.5) from
> app-portage/gentoolkit-0.3.0_rc8) doesn't work with my
> sys-apps/portage-2.1.7.16 ...
That's an interesting problem. The short answer is, no, python 3 support isn't planned for 0.3.0.
The traceback you got is actually due to the fact that portage 2.1.7* doesn't support python 2.5 anymore. (You can see that in its DEPEND line in the ebuild).
0.3.0 branch is tested up to py2.7 without deprecation warnings, the easiest option is to switch your default python version to 2.6 or 2.7 and reinstall gentoolkit rc8. Another option for you is to run 2to3 over the source and use python 3. I haven't tried it, but I imagine it applies cleanly. If you try this and come up with errors, please submit bugs.
I'll try to add automatic python version detection in the next major version of gentoolkit, which shouldn't take nearly as long to get out the door as this one.
Starting March 16, I'll be unavailable to do any work or even answer questions on "my parts" of gentoolkit for an extended period of time (up to 3~4 months). I'd like to propose a feature freeze starting now so that we have at least a week to really thrash the current code base around. Any new feature bugs marked for inclusion should be postponed to the next minor version. Everyone involved okay with that?
That is fine with me. We will work forward with fixing the bugs and hopefully by the time you get available again, we will be ready for gentoolkit-0.3.1.
All depending bugs are now closed. | https://bugs.gentoo.org/show_bug.cgi?id=237964 | CC-MAIN-2022-33 | refinedweb | 544 | 67.96 |
.
You can also alter the way the output and logic of
Carp works, by changing some global variables in the
Carp namespace. See the section on
GLOBAL VARIABLES below..
This variable determines how many call frames are to be skipped when reporting where an error occurred on a call to one of
Carp's functions. For example:
$Carp::CarpLevel = 1; sub bar { .... or _error('Wrong input') } sub _error { Carp::carp(@_) }
This would make Carp report the error as coming from
bar's caller, rather than from
_error's caller, as it normally would.
Defaults to
0. value of
0 to show all arguments to a function call.
Defaults to
8.. | http://search.cpan.org/~rgarcia/perl-5.9.3/lib/Carp.pm | CC-MAIN-2016-50 | refinedweb | 111 | 75.2 |
In my earlier article from April 2011 on interface implementation I noted that C# supports a seldom-used feature called “interface re-implementation”. This feature is useful when you need it but unfortunately is one of those features that can bite you if you use it incorrectly or accidentally.
Every interface method of every interface you implement in a class or struct has to be “mapped” to a method in the type (either a method directly implemented by the type or a method that the type obtained via inheritance, doesn’t matter) that implements the interface method. That’s pretty straightforward. The idea of interface re-implementation is basically that if you re-state on a derived class that you implement an interface that was already implemented by a base class, then when analyzing the derived class, we abandon all the information we had previously computed about the “mappings” in the base class.
This is useful particularly in the case where a base class does an explicit implementation of an interface and you would like to replace its implementation with your own:
interface I
{
void M();
}
class Echo : I
{
void I.M() { … }
}
class Foxtrot : Echo, I
{
void I.M() { … }
}
Echo does not have a public, protected, or internal virtual method M that Foxtrot can override; if Foxtrot wants to replace Echo‘s behaviour then its only chance to do so is via interface re-implementation.
Like I said, that can be useful but you should be aware that this is a sharp tool that can cut you in some situations. Here’s a situation we found ourselves in recently on the Roslyn team where we managed to cut ourselves with our own tool!
We have two very similar interfaces, IInternal and IPublic. We intend that our component be used by the public — you guys — via the IPublic interface. As an internal implementation detail, we also have an internal interface IInternal that we use to communicate with a particular subsystem that has been provided for us by another team within Microsoft. The methods of IInternal are a superset of the methods of IPublic:
internal interface IInternal
{
void M();
void N();
}
public interface IPublic
{
void M();
}
public abstract class Bravo : IInternal (*)
{
// These are our internal workings that we use to communicate
// with our private implementation details;
// they are explicitly implemented methods of an internal interface,
// so they cannot be called by the public.
void IInternal.M() { … }
void IInternal.N() { … }
}
public abstract class Charlie: Bravo, IPublic
{
// class Charlie, on the other hand, wants to expose M both
// as a method of Charlie and as an implicit implementation
// of IPublic.M:
public void M() { … }
}
public sealed class Delta : Charlie, IInternal
{
// Delta is a derived class of Bravo via Charlie; it needs to
// change how IInternal.N behaves, so it re-implements the
// interface and provides a new, overriding implementation:
void IInternal.N() { … }
}
This is wrong. There are three methods that Delta must provide: IInternal.M, IInternal.N and IPublic.M. IPublic.M is implemented in Delta by Charlie, as usual. But we are doing an interface re-implementation of IInternal, so we start fresh. What is the implementation of IInternal.N? Obviously the explicitly implemented method in Delta. But what is the implementation of IInternal.M? It’s the public method in Charlie, not the invisible-to-everyone explicit method in Bravo. When an instance of Delta is passed off to the internal subsystem it will now call the public method Charlie.M instead of the correct code: the explicit implementation in Bravo.
There is no way for Delta to get to Bravo‘s implementation of IInternal.M; that is a private implementation detail of Bravo. The interface re-implementation pattern is simply a bad technique to use here; the scenario is too complicated for it to work without you cutting yourself accidentally. A better pattern is to have only one implementation of the internal interface that then defers to an internal-only method:
public abstract class Bravo : IInternal
{
void IInternal.M() { this.InternalM(); }
internal virtual void InternalM() { … }
void IInternal.N() { this.InternalN(); }
internal virtual void InternalN() { … }
}
public abstract class Charlie: Bravo, IPublic
{
public void M() { … }
}
public sealed class Delta: Charlie
{
internal override void InternalN() { … }
}
And now Delta can even call base.InternalN if it needs to call Bravo.InternalN.
Once more we see that designing for inheritance is trickier than you might think.
(*) People are sometimes surprised that this works. The accessibility domain of a derived class must be a subset of the accessibility domain of its base class; that is, you cannot derive a public class from an internal base class. The same is not true of interfaces; interfaces can be as private as you like. In fact, a public class can implement a private interface nested inside itself!
Nice to know about this, I hadn't heard of interface re-implementation previously.
Could you elaborate a bit on why a public class is permitted to implement a private (even nested) interface?
For precisely the reason I stated: sometimes you want to have various internal components communicating with each other using internal interfaces. — Eric
Having one class implement two interfaces with methods with the same names that (are supposed to) do different things is a very bad sign.
It is a bad sign I agree, but sometimes it is the lesser of two evils. We need to expose public methods with names like "IsStatic" and "BaseType" and so on; we also need to expose similar but slightly different functionality to internal helper libraries based on CCI that have similarly-named methods. We'd rather not build adaptor classes just to bridge this gap, and so we are in a cleft stick of our own devising. — Eric
Also, I rarely explicitly implement interfaces without it being more than a call to a protected or internal member; that just makes it harder to call the method.
That's a good habit to be in. — Eric
It was excellent
I think there might be a mistake in your first code example with I, Echo and Foxtrot. Echo should be:
class Echo : I
{
void I.M() { … }
}
This reminds me of how IDispose is implemented with derived classes.
This should be flagged with a compiler warning.
We are considering it; if we got bitten by it then maybe other people get bitten by this as well. However, it is dangerous business adding a compiler warning. A compiler warning should warn about code that is technically legal but unlikely to be correct. What is the bright line here that allows us to disambiguate between a behaviour that the user intended and one they caused by accident? That is, suppose we had wanted the Charlie's implementation to match the re-implemented interface method; how would we have expressed that in Delta so as to prevent the warning? (Remember, the code in Charlie or Bravo might not be in source; those types might be in assemblies that the author of Delta cannot change.) A warning that needs a pragma to turn off isn't a very good warning. We'll keep pondering it. — Eric
"In fact, a public class can implement a private interface nested inside itself!"
That's strange! Wouldn't it create some kind of circular dependency?
De jure, usually no; the C# specification allows for that (though the specification is somewhat vague on the topic of precisely how to evaluate an identifier in a base type list when doing so might refer to a nested interface type of a base class.) De facto, there are some bugs in the cycle detector such that sometimes we accidentally detect such topologies as circular dependencies and disallow them. — Eric
A compiler warning will let us know that someone, most likely, accidentally overrode an existing interface. This is similar to how we get warnings of possible data loss when converting a 4 byte long to a 2 byte short.
Are you working on a private pilot's license by chance? Can't help but notice the overt use of the phonetic alphabet. 🙂
>> That is, suppose we had wanted the Charlie's implementation to match the re-implemented interface method; how would we have expressed that in Delta so as to prevent the warning?
Maybe something similar to C++'s `using` declaration?
public sealed class Delta : Charlie, IInternal{
void IInternal.N(){ … }
// WARNING:
// Class Delta reimplements interface 'IInternal', but doesn't reimplement 'IInternal.M'.
}
public sealed class Epsilon : Charlie, IInternal{
void IInternal.N(){ … }
using base.M;
}
Using "base" is pretty limited, though. It would be more useful, I think to specify the class explicitly (as in C#):
/* This would be equivalent to the above */
using Charlie.M;
And if that's the syntax, then perhaps you could get what you really wanted in the first place with:
using Bravo.M;
But since M is not actually a member of Bravo, this might not make sense; perhaps instead you'd need something like:
using Bravo.IInternal.M;
which, of course, means "use whatever method would be used when a Bravo instance was accessed through the IInternal interface."
However, this looks confusing, because it looks like we're referring to a member "M" on type "IInternal" that's a *nested* type of "Bravo", which of course is not the case; so perhaps we'd be better off borrowing the scope-resolution operator from C++ as well (which, like the "using" keyword, has the advantage of already existing in the language).
using Bravo::IInternal.M;
>> It would be more useful, I think to specify the class explicitly (as in C#):
Insert a comma after "think", and change "C#" to "C++".
Eric, Microsoft might do well to run the MSDN blogs off of Stack Exchange's software. Trying to post code-containing comments in plain text is no fun. Not to mention the blog software seems to swallow every first attempt to post, and provides no way to edit. | https://blogs.msdn.microsoft.com/ericlippert/2011/12/08/so-many-interfaces-part-two/ | CC-MAIN-2017-13 | refinedweb | 1,653 | 52.8 |
dpm_addfs - add a filesystem to a disk pool
#include <sys/types.h> #include "dpm_api.h" int dpm_addfs (char *poolname, char *server, char *fs, int status)
dpm_addfs adds a filesystem to a disk pool. poolname specifies the disk pool name previously defined using dpm_addpool. poolname, server or fs is a NULL pointer. EEXIST this filesystem is already part of a pool. ENOMEM Memory could not be allocated for storing the filesystem definition. EINVAL The pool is unknown or the length of poolname exceeds CA_MAXPOOLNAMELEN or the length of server exceeds CA_MAXHOSTNAMELEN or the length of fs exceeds 79. SENOSHOST Host unknown. SEINTERNAL Database error. SECOMERR Communication error. | http://huge-man-linux.net/man3/dpm_addfs.html | CC-MAIN-2018-05 | refinedweb | 106 | 61.93 |
29 September 2009 12:25 [Source: ICIS news]
MOSCOW (ICIS news)--?xml:namespace>
The state-owned 99.567% stake was auctioned on Tuesday at an initial price of hryvnya (HRN) 4bn (€320m, $471m).
After the auction, the SPF head, Dmitry Parfenenko, described the auction's result as "inadequate" and said that the stake was worth HRN8-9bn.
The country’s prime minister, Yulia Tymoshenko, said in a statement: “It became evident on live television how the three participants in the auction conspired to buy the Odessa Port Plant for a song.”
Nortima represented the interests of Ukrainian tycoon Igor Kolomoisky, owner of the Privat metals and banking group.
Ahead of the auction, Parfenenko said there were no legal obstacles to privatising the plant. Earlier on Tuesday,
On 17 September, Yushchenko issued a decree to suspend the government's order allowing the privatisation of the plant, saying that the plant was of strategic importance to
The 1.5m tonnes/year
(HRN1 = €0.08, . | http://www.icis.com/Articles/2009/09/29/9251265/ukraine-holds-odessa-auction-rejects-inadequate-winning-bid.html | CC-MAIN-2013-20 | refinedweb | 162 | 62.98 |
omapi - Man Page
Object Management Application Programming Interface
Description
OMAPI is an programming layer designed for controlling remote applications, and for querying them for their state. It is currently used by the ISC DHCP server and this outline addresses the parts of OMAPI appropriate to the clients of DHCP server. It does this by also describing the use of a thin API layered on top of OMAPI called ´dhcpctl´
OMAPI uses TCP/IP as the transport for server communication, and security can be imposed by having the client and server cryptographically sign messages using a shared secret.
dhcpctl works by presenting the client with handles to objects that act as surrogates for the real objects in the server. For example a client will create a handle for a lease object, and will request the server to fill the lease handle's state. The client application can then pull details such as the lease expiration time from the lease handle.
Modifications can be made to the server state by creating handles to new objects, or by modifying attributes of handles to existing objects, and then instructing the server to update itself according to the changes made.
Usage
The client application must always call dhcpctl_initialize() before making calls to any other dhcpctl functions. This initializes various internal data structures.
To create the connection to the server the client must use dhcpctl_connect() function. As well as making the physical connection it will also set up the connection data structures to do authentication on each message, if that is required.
All the dhcpctl functions return an integer value of type isc_result_t. A successful call will yield a result of ISC_R_SUCCESS. If the call fails for a reason local to the client (e.g. insufficient local memory, or invalid arguments to the call) then the return value of the dhcpctl function will show that. If the call succeeds but the server couldn't process the request the error value from the server is returned through another way, shown below.
The easiest way to understand dhcpctl is to see it in action. The following program is fully functional, but almost all error checking has been removed to make is shorter and easier to understand. This program will query the server running on the localhost for the details of the lease for IP address 10.0.0.101. It will then print out the time the lease ends.
#include <stdarg.h> #include <sys/time.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <isc/result.h> #include <dhcpctl/dhcpctl.h> int main (int argc, char **argv) {)); }
Authentication
If the server demands authenticated connections then before opening the connection the user must call dhcpctl_new_authenticator. as it would in dhcpd.conf:
key "a-key-name" { algorithm hmac-md5; secret "a-shared-secret"; }; # Set the omapi-key value to use # authenticated connections omapi-key a-key-name;
The authenticator handle that is created by the call to dhcpctl_new_authenticator must be given as the last (the 4th) argument to the call to dhcpctl_connect(). All messages will then be signed with the given secret string using the specified algorithm.
See Also
dhcpctl(3), omshell(1), dhcpd(8), dhclient(8), dhcpd.conf(5), dhclient.conf(5).
Author
omapi is maintained by ISC. To learn more about Internet Systems Consortium, see
Referenced By
dhclient(8), dhcpctl(3), dhcpd(8), omshell(1). | https://www.mankier.com/3/omapi | CC-MAIN-2021-17 | refinedweb | 561 | 55.44 |
q)
You can look up how QString does it but as you mention, probably boost is the fastest solution. boost::format is header only. No need to link anything. Only the things you use will be added to your program, not the whole 1.2gb
well but i still need to choose and include bunch of headers
is it even worth it?
😓
It's 1 line in code and 1 line in the project file. Let's no be this lazy, shall we?!
how is it 1 line? i added the format.hpp but it has dependencies so i need to add them too
p.s. i can't be lazy cause i'm copying all the needed header files to my project dir :D
p.s.2 or i'm doing something worng?
- Konstantin Tokarev
@user4592357 said in q)
Boost has a tool to extract only needed parts
thanks, but seems like all the folder got copied
here's how i did it:
bcp.exe --boost=..\..\ format C:\Documents\proj\dependencies\boost_1_65_1\boost
@user4592357 said in qstring .arg like thing in pure c++:
or i'm doing something worng?
Exactly, you are doing the difficult way. Do not copy every file in your folder.
- just add 1 line in the project file (assuming you use qmake on windows):
INCLUDEPATH += C:/Boost/boost_1_65_0
- re-run qmake
- add
#include<boost/format.hpp>in your source file
@user4592357 The above has nothing to do with Qt, just with the build system you use.
Since you posted here I supposed you were using Qt Creator.
If you use visual studio you should just add
C:\Boost\boost_1_65_0to the "Additional include directories" under Project Properies->C/C++->General
i've done that with the whole 1.2gb boost directly. that works
now i need to send the project to my teacher but i don't want to include 1.2gb of files.
and how can including just the header work if it includes other files? i still don't get it
What program are you using to write, compile and link your binaries?
What OS are you on?
visual studio 2017 on windows 10
@VRonin said in qstring .arg like thing in pure c++:
if you use visual studio you should just add C:\Boost\boost_1_65_0 to the "Additional include directories" under Project Properies->C/C++->General
Did you try this before copying the 1.2 GB? of course
C:\Boost\boost_1_65_0is just an example and you should point to the folder where you have downloaded boost
What about stringstream?
()
I always use something like this
#include <iostream> #include <sstream> #include <string> std::ostringstream mystring; std::string someText = "something"; int number = 11; mystring << "This is " << someText << " in pure c++ " << number; std::cout << mystring.str();
- Konstantin Tokarev
@sneubert But it works well only for simple formatting, when you need to print columns or specify precision of floating-point numbers, you have to face the nightmare of ios flags
@Konstantin-Tokarev
yes u are right even though for my use cases the list of manipulators
() is sufficient and keep in
mind that only the brave ones are rewarded :-) | https://forum.qt.io/topic/85122/qstring-arg-like-thing-in-pure-c | CC-MAIN-2018-22 | refinedweb | 522 | 73.37 |
[Quizzler
Home] [Quizzler
Products] [Support]
[Download
Software] [Free
Quiz Library]
Quizzler
is the leading cross platform quiz and assessment software used
extensively by both students and teachers. We offer products
for Windows, Macintosh, Palm handhelds, and Pocket PC handhelds.
You can even export your quizzes to run on iPhone, iPods, or
create interactive web pages!
You can use the free Quizzler Reader to read any quiz, and
play lots of free quizzes from our Quiz Library. You can also
create your own quizzes or flashcards using our simple and easy
Quizzler Maker software.
We've created and collected many quizzes that are free for
you to download, or try online. In fact, you will find over
15,000 questions in our quiz library. We encourage Quizzler
users to send us your quizzes to include in the library -- please
Take me to the free quiz library
now.
Quizzler Maker 5.6 adds automatic quiz creation "wizards".
With just a couple clicks you can generate your own customized
quizzes: addition, subtraction, multiplication, division, number
series, algebra. Version 5.6 now exports to the iPhone and iPod
Touch!
You may already have some quiz questions that are in a Word
document, for example. Just by adding a few lines to the top
of the file and rearranging the questions slightly, you can
import all the questions at once into Quizzler Maker. Just make
sure your plain text file complies with the Quizzler file Format,
and use the "Open" menu option in Quizzler Maker to
import the questions.
Quizzler Maker uses plain text files as its "source",
and produces encrypted PDB files as output. You can freely distribute
the PDB files and know that your quiz is protected from prying
eyes. Your intellectual property is safe and students can't
cheat by peaking at the answers.
Quizzler Maker 5.6 now exports web pages optimized for iPhone.
friendly mobile site here with free online quizzes.
Quizzler
Reader. FREE. Use this to read any quiz you create
with Quizzler Maker. (certain commercial quizzes must be registered
before they function) Runs on Windows, Mac, Palm OS and Pocket
PC handheld PDAs and smartphones. For iPhone and iPod, the built-in
browsers are used.
Quizzler
Maker. Use this to create your own quizzes, to
print quizzes, to export quizzes to iPod, and create interactive
quiz web pages. FREE version will build quizzes with up to 10
questions; registered version will build larger quizzes and
includes automatic quiz generator for math quizzes.
Quizzler is special because it runs on many platforms: Windows,
Macintosh, Palm OS, Windows Mobile/Pocket PC. You can even export
your quizzes to an iPod or iPhone (not all features supported)
and create interactive web pages.
Quizzler
lets you use colored and formatted text, pictures, and up to
10 possible answers. You can switch between flashcard mode and
multiple choice. You can choose study mode or exam mode. Questions
and/or answers are randomized for you.
Quizzler authors can embed "smart" advanced features,
so you have more control over how they are used. You can assign
points to each answer, hide the score until the end, set a timer,
set a limited number of uses, and even require a pass code to
begin the quiz.
Pocket Mobility Inc., 6281 North
55th, Longmont, CO 80503 | http://quizzlerpro.com/ | CC-MAIN-2014-15 | refinedweb | 549 | 73.17 |
Hi My goal is read only line from file , and find fibonacci series that has minimun 3 element.I want to control numbers from 1 to 6 digit. Fibonacci series starts 1,1,2,3,5,8,13,21,34,55,89, ...... .For example;File text document
49693463452312343388645
I division string 1 to 6 digit. Check 4 is fibonacci number , no , go ahaed 49 is fibonacci number , no, next 496 is fibonacci ,no, 4969 after 44693 ,after 496934 no.There isnt any fibonacci , go to next digit and do it again 9 , 96,969,9693,96934.
use 5.010;
use strict;
use warnings;
open(FILE, "<:encoding(UTF-8)", "aa.txt") or die "Could not open file:
+ $!";
my $numbers;
while (<FILE>) {
$numbers="$_" ;
print "$_";
}
chomp $numbers;
print "\n$numbers";
my $len=length($numbers);
print "\n$len\n";
my $i;
my $abc;
foreach my $i (0..$len){
foreach my $j (1..6) {
print "$j----->";
$abc = substr($numbers,$i,$j);
print "$abc\n";
}
print "***********************************\n";
}
close FILE;
[download]
I read to find fibonacci series with PERFECT SQUARE. I didn't use it. C code example
// C++ program to check if x is a perfect square
#include <iostream>
#include <math.h>
using namespace std;
// A utility function that returns true if x is perfect square
bool isPerfectSquare(int x) {
int s = sqrt(x);
return (s*s == x);
}
// Returns true if n is a Fibinacci Number, else false
bool isFibonacci(int n) {
// n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return isPerfectSquare(5*n*n + 4) || isPerfectSquare(5*n*n - 4);
}
// A utility function to test above functions
int main() {
for (int i = 1; i <= 10; i++)
isFibonacci(i)? cout << i << " is a Fibonacci Number \n":
cout << i << " is a not Fibonacci Number \n" ;
+
return 0;
}
[download]
2017-12-29 Athanasius restored original content
This appears to have been posted to Meditations, but I'm not sure if you meant it to be a question? Anyway, you're describing scanning a string looking for a pattern, which is exactly what regular expressions are good at. Ignoring the duplicate 1's, there are only 29 Fibonacci numbers with 1 to 6 digits, a regex can handle that just fine (and it would have no problem handling much more). See Building Regex Alternations Dynamically.
This code can handle huge numbers too, try changing $DIGITS to e.g.
60. And note that you can use the same regex to find sequences of numbers, e.g. (?:$re){3,} (although that doesn't check if they are consecutive in the sequence).
#!/usr/bin/env perl
use warnings;
use strict;
my $DIGITS = 6;
my %fib;
{ use bigint;
for ( my ($f,$t)=(1,1); length($f)<=$DIGITS; ($f,$t)=($t,$f+$t) ) {
my $s = "$f";
$fib{$s} = [$s];
while (length $s > 1) {
chop $s;
push @{$fib{$f}}, $s if exists $fib{$s};
}
} }
#use Data::Dump; dd \%fib;
print "There are ",0+keys(%fib)," fibs with up to $DIGITS digits\n";
my ($re) = map {qr/$_/} join '|', map {quotemeta}
sort { length $b <=> length $a or $b cmp $a } keys %fib;
print "$re\n";
while (<DATA>) {
chomp;
print "Searching '$_'\n";
while (/(?=($re))./g) {
print "Found ",join(', ',@{$fib{$1}})," at ",$-[0],"\n";
}
}
__DATA__
496934634523123433886451447233402467622113
690168906931029935139391829792095612517948949963798093315456
[download]
Update: You appear to have edited your node to remove its content, please see How do I change/delete my post? for why you shouldn't do that. Content restored, thanks Athanasius. Also made very minor fixups.
Hi,?
The %fib was built but not actually used.
Well not quite, it is used for what you said:
to help looking for a fib whose initial digits are a fib too
This is what I was using it for, since I didn't feel like getting too fancy with the regex. The code I wrote was mostly just an implementation of my interpretation of the description the OP gave:
"Check 4 is fibonacci number , no , go ahaed 49 is fibonacci number , no, next 496 is fibonacci ,no, 4969 after 44693 [sic] ,after 496934 no.There isnt any fibonacci , go to next digit and do it again 9 , 96,969,9693,96934."
I wonder if any value of %fib could be an array with more than 3 elements?
Good question, I didn't try cranking up $DIGITS past 60 yet...
the task is too much unclear
Agreed, which is why I just implemented the part I (thought I) understood ;-)
Hello darkblackblue,
As the fellow Monks say this looks like a school assignment. Well I could suggest another approach to your problem but it only contains half of the solution, I have left the rest for you to solve.
Sample of code:
I used different hard coded input instead of reading your data from your file but you get the point that the input is data from your file. What I am doing on this sample of code is comparing the string part by part as you wanted with a list of fibonacci numbers. The module that I am using is Math::Fibonacci. What the script does not do is to compare the numbers by subtracting the elements one by one until the end as you described. I have left this part out.
Update: I just observed that the darkblackblue has asked the question since the 28th December. I assume that he/she was not able to resolve it. Just to add complete answer to the question for future reference see sample of code bellow:
Hope this helps,. | https://www.perlmonks.org/?showspoiler=1206352-1;node_id=1206326 | CC-MAIN-2019-43 | refinedweb | 920 | 68.4 |
void setup(){ int index; Serial.begin(9600); for (int k=0; k<=7; k++) { float m = pow(2,k); int q = int(m); Serial.print("m = "); Serial.print(m); Serial.print("\t q = "); Serial.println(q); }}void loop(){}
Ah, p. 77 in the Arduino Cookbook states that when casting to an integer, floating-point numbers do not round correctly.
Very unexpected!
Floats are NOT rounded when converted to ints. They are truncated.
QuoteVery unexpected!Not by me.
ALL integer maths "rounds" down. Try 3/2
It has been years since programming in C and it will be nice to become familiar again with details like these ...
PATH=%path%;C:\Program Files\Arduino_105\hardware\tools\avr\utils\bin;CD %TEMP%MD %PUBLIC%\ELFtempfor /R %TEMP% %%f in (*.elf) do XCOPY /D /Y %%f %PUBLIC%\ELFtemp\DIR %PUBLIC%\ELFtemp\*.elf /s /b /O:-D /T:W >ElfRhereSET /P ELF= <ElfRhereECHO %ELF% >MemUsage.txtAVR-SIZE -C %ELF% >>MemUsage.txtNOTEPAD MemUsage.txtSET ELF=""
... and if you programmed on a PC or minicomputer in C, then C++ for microcontrollers is even more distant.
Underneath the Arduino GUI is the AVR GCC compiler: is also the AVR-LIBC library that is available: use with Arduino introduced here: to keep in mind:You can generally swing between Arduino'ish commands and C++ commandsYou can resort to extern C {} or you can do inline assembler as advance coding.
The compiler does a tremendous amount of optimizations ... sometimes taking out some of your code or even rearranging it. Never assume. If you really want to know what happened, you can get the assembler source with just a little work.
IF you are using Windows, you can also get information on the Flash and SRAM usage of your code with a little scripting:
wonder if it can also be done on a Mac? A very quick online search seems to show that it can (again, Arduino Cookbook, Chap. 17).
Not tested, but my bash script should also work just fine on MacOS (in terminal, of course).
Ah, p. 77 in the Arduino Cookbook states that when casting to an integer, floating-point numbers do not round correctly. It seems that 2^4 comes up with something a little less than 16.00 and when cast as an integer, int(16.00 - a_tiny_bit) = 15.Very unexpected!
That's not unexpected at all. All computers work that way.
#include <stdio.h>#include <math.h>main(){ int index, k, q; float m; for (k=0; k<=7; k++) { m = pow(2,k); q = (int) m; printf("m = %f",m); printf("\t q = %d\n",q); }}
32 bit float vs. 64 bit float
Could someone please explain why the Arduino produces different results?Thank you
Isn't the real question, what happens with Atmel Studio on a naked 328P with all the latest packages?
The issue may just be with the AVR-GCC math library. Arduino does not package the latest version of AVR-GCC, so we could be looking at an already "fixed" issue.
Things like this can get under ones skin [...] bought an HP67... And never looked back! | https://forum.arduino.cc/index.php?topic=206870.msg1526804 | CC-MAIN-2020-40 | refinedweb | 516 | 67.25 |
They.
But then, breaking into production as you suggest is highly controlled and would never result in a discrepency between prod and dev in the way you describe.
What is missing in the built in, however, is that you can’t check a whole class, or function group easily. You have to check each method, on its own, then the private/protected/public sections.
matt
Regards, Rick
– test import (find import and activation errors before actually importing)
– undo (backout a transport by automatically resetting all objects to previous version)
– overtake check (prevent older, unapproved changes surfing into production along with newer, approved changes)
Can I have these, please? 😉
Thomas
Good change control process should virtually eliminate the need for an ‘undo’ one would think? I believe that, at this point in time at least, that SAP do not support the concept of undo. There is a SAP note to this effect – its quite old but I don’t know af any later notes. Perhaps some else does?
I believe CTS central will have some kind of feature around this when available. Overwrite and overtake checks are avaialble in in add-on change control technologies but not in CTS just yet.
Regards, Rick
I meant to say that CTS Central wil have something along the lines of an overtake check.
Regards, Rick
SREPO transaction is a powerful tool that gives you an overview of different objects/sources, though it doesn’t give you access to the detailed differences (you have to access the versioning tool of each object to run the individual comparison)
I also provided a “transport simulation” program in the wiki section of SDN, it can be very useful for situations of missing objects in the target system.
I’d love to have a tool to restore or compare version in mass, by transport request especially.
I don’t want to come off as being too critical, but unfortunately It does look like the developer got pulled off the project before they could get to the good bits 🙁 notice how there are no dropdowns on selections, German messages and also an inability to drill down to see if or what the actual differences are – or even copy and paste the object names into the needed alternate session editor.
Another limitation I found during my exploration was that transaction SREPO only considers Y and Z objects to be customer owned , this maybe a problem for some of the larger or more progressive companies using the newer namespaces such as /xyz/.
If you like what you see in transaction SREPO, I suggest you take a look at the free apps in Salt (saltapps.com) especially the Matrix app – it allows you to compare whole landscapes simultaneously, drill down and also analyze the new namespaces (without the long wait), it also provides the transport information and relative versions so that you can see why the difference is there and what to do to fix it.
Cheers,
Dave | https://blogs.sap.com/2010/11/11/custom-code-synchronisation-across-the-sap-landscape/ | CC-MAIN-2018-13 | refinedweb | 495 | 51.01 |
Yep, that would work - neat trick! Although, I agree with you that the
ability to address the object on the stack as an argument would be
nicer. I thought that this could be done programatically using
Digester.addCallParam(java.lang.String pattern, int paramIndex, boolean
fromStack) - just that I could not find a way to do this via XML.
Thanks again.
Naresh
-----Original Message-----
From: Baltz, Kenneth [mailto:Kbaltz@firstam.com]
Sent: Friday, January 24, 2003 11:51 AM
To: Jakarta Commons Users List
Subject: RE: [Digester] How to specify a <call-param-rule> parameter
from top-of-stack
Here's the solution I was given. I think it would be easier if we could
reference the item on the stack as an argument.
The trick is to create a new object that takes care of populating the
HashMap for you.
E.g.
// Has to be public, although an anonymous inner class would be great
public class HashMapProxy {
HashMap _map;
public Hashmap Proxy() {
_map = new HashMap();
}
public void addProduct( Product p ) {
_map.put( p.getPartNumber(), p );
}
public HashMap getMap() {
return _map;
}
}
Use the following Digester code:
digester.addObjectCreate( "products", HashMapProxy.class );
digester.addObjectCreate( "products/product", Product.class );
... initialize your Product object
digester.addSetNext( "products/product", "addProduct" );
HashMapProxy proxy = (HashMapProxy)digester.parse( XML );
return proxy.getMap();
Hope that helps, hope they find a better way.
K.C.
> -----Original Message-----
> From: Naresh Bhatia [mailto:NBhatia@sapient.com]
> Sent: Thursday, January 23, 2003 9:44 PM
> To: commons-user@jakarta.apache.org
> Subject: [Digester] How to specify a <call-param-rule> parameter from
> top-of-stack
>
>
> I am trying to parse an XML file similar to the one shown below:
>
> <products>
> <product partNumber="1000">
> ...
> </product>
> <product partNumber="2000">
> ...
> </product>
> </products>
>
> I want Digester to return a HashMap with partNumber as the key and
> product as the value. How do I put the product on to the HashMap? I
> guess I don't know how <call-param-rule> can specify the object from
> top of the stack as a parameter. Here's my unsuccessful attempt at
> this:
>
> <digester-rules>
> <object-create-rule
>
> <pattern value="products/product">
> <object-create-rule
>
> <set-properties-rule>
> <alias attr-
> </set-properties-rule>
>
> <call-method-rule
> <call-param-rule
> <call-param-rule <--- what to do here?
> </pattern>
>
> </digester-rules>
>
> Thanks.
> Naresh Bhatia
> | http://mail-archives.apache.org/mod_mbox/commons-user/200301.mbox/%3CB6C24FD0883C4C419A9B591BB9FC4C5C26C0DB@cammmsx01.sapient.com%3E | CC-MAIN-2017-47 | refinedweb | 382 | 50.02 |
view raw
I have the task to build a method to search for an identical value for a variable in an array.
When there is a match, the method will return the index-Position, otherwise it should return -1.
My method works when there is a match, but I get an error when there isn´t any match.
My Code so far:
public class Schleifentest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] cherry = {7,5,6,8,9};
int magNumber = 112;
int enthalten2 = Schleifentest.sucheWhile(cherry, magNumber);
System.out.println(enthalten2);
}
public static int sucheWhile(int [] array, int a) {
int i = 0;
while(i <= array.length) {
if (array[i] == a) {
return i;
}
i++;
}
// here is the problem
return -1;
}
}
it should be
while(i < array.length) {...}
suppose that the array has 10 elements. They are indexed from 0 to 9. When you reach the end, with your code, you'll consider the one indexed as 10, that doesn't exist, and you have the error. | https://codedump.io/share/bSNV84DfcIPG/1/searching-for-specific-value-in-array-with-while-loop | CC-MAIN-2017-22 | refinedweb | 170 | 73.27 |
QEMU/KVM on Docker and CoreOS
DEPRECATED
Please use the more modern
qemu Docker images, (
docker pull tianon/qemu) now.
Usage
docker pull ulexus/qemu
docker run --privileged ulexus/qemu QEMU_OPTIONS
Note that
--privileged is required in order to run with the kernel-level virtualization (kvm) optimization.
Background
For the most part, it is fairly easy to run qemu
Basically, this allows me to run QEMU hosts with storage on RBD on my favorite server OS:.
Networking
One of my gripes with Docker right now is that it's not easy for me to manage my own networking. Also, it has abysmal support for things like IPv6. The idea of NATing every connection is repugnant and backward to me. Never-the-less, I understand the motivations.
Still, for my use, I needed the ability to attach to my network bridge instead of the default
docker0 bridge. The entrypoint script allows you to pass the
$BRIDGE_IF environment variable. If set, it will add that bridge interface to the container's
/etc/qemu/bridge.conf file which, in turn, allow your qemu instance to attach to that bridge using the built-in
qemu-bridge-helper.
Note, however, that if you want to do this, you'll need to pass the
--net=host option to your
docker run command, in order to access the host's networking namespace.
Ceph/RBD support
Included in this image is support for Ceph/RBD volumes. In order to use Ceph, you should probably bind-mount your
/etc/ceph directory which contains your ceph.conf and client keyring. I use
docker run -v /etc/ceph:/etc/ceph for this purpose on my CoreOS boxes.
NOTE: using qemu's bridge networking with docker's
--net=host with RBD block storage creates switch loops for me, even with STP. Removing any one of those three seems to work fine. To work around this problem, you can also run with
--privileged --pid=host --ipc=host.
Service file
Also included in this repo is a service file, suitable for use with systemd (CoreOS and fleet), provided as an example. You'll need to fill in your own values, of course, and customize it to your liking.
Entrypoint script
The entrypoint script is site-specific for me, but you can override most of it simply by passing arguments to the execution of this container (which will, in turn, be passed as arguments to
qemu).
If you intend to use the entrypoint script as is, it expects
etcd to be populated with some keys. (
%i below refers to the unit instance, such as
1 for the unit
kvm@1):
/kvm/%i/host- Should match host's hostname; used as a mutex for this VM
/kvm/%i/ram- The amount of RAM to allocate to this VM
/kvm/%i/mac- The MAC address to assign to the NIC of this VM
/kvm/%i/rbd- The RBD image (of the form
/<pool-name>/<rbd-name>)
/kvm/%i/spice_port- The TCP port to use for the spice server
/kvm/%i/extra_flags- (optional) Free-form qemu flags to append | https://hub.docker.com/r/ulexus/qemu/ | CC-MAIN-2018-30 | refinedweb | 511 | 60.45 |
Edit Article
wikiHow to Turn Your Ec2 Based Windows Server Into a Dc
Setting up a single virtual Windows machine on EC2 may be a trivial process, but setting it up as a real DC and connecting multiple virtual machines to it is another story. This how to provides the basis for setting up a proper DC on EC2.
Steps
- 1Launch your instances
- 2Get Administrator password for each instance
- 3Set a new Administrator password
- 4Disable
Ec2SetComputerNamein
%programfiles%\Amazon\Ec2ConfigService\Settings\config.xmlon all servers
- 5Rename the computers
- 6Set the DNS server to point to the DC (
netsh int ip set dns "local area connection" static xx.xxx.xxx.xxx primary) where
xxx.xxx.xxx.xxxis the internal IP address of the DC.
- 7Choose a DNS namespace (
ad.compute-1.internal)
- 8Add the Domain Controller role: (a) Domain controller for a new domain; (b) Domain in a new forest; (c) Use the DNS name from step 7; (d) Specify a Domain NetBIOS name (AD); (e) Specify/Accept the default Database folder and Log folder; note you should use the C: drive for both to ensure they are included in an AMI when bundled; (f) Specify/Accept the default for the SYSVOL folder location (again, you'll want to use the c: drive); (g) install and configure the DNS Server on this computer, and set this computer to use this DNS server as its preferred DNS server; (h) Permissions compatible only with Windows 200 or Windows Server 2003; and (i) Specify a directory services restore mode administrator password.
- 9Point the member servers at the DC for DNS (
netsh int ip set dns "local area connection" static xxx.xxx.xxx.xxx primary) where
xxx.xxx.xxx.xxxis the internal IP address of the DC.
- 10Join the Domain.
Community Q&A
Search
Ask a Question
If this question (or a similar one) is answered twice in this section, please click here to let us know.
Warnings
- Don't do anything critical with EC2 until you know exactly what you are doing and have gained enough experience with it. The information provided is a recap from Jeff W. (Amazon Web Services), and he deserves most (if not all) of the credit for this HOWTO (that also means, if things go wrong, you can blame him more than wikiHow). Use at own risk. | http://www.wikihow.com/Turn-Your-Ec2-Based-Windows-Server-Into-a-Dc | CC-MAIN-2017-17 | refinedweb | 387 | 58.32 |
Challenge
Christmas can be very expensive. Plot a line of how much americans think they're spending on Christmas gifts over the years.
My Solution
Today we built a little line chart with two axes and emoji datapoints. Hover an emoji, get a line highlighting where it falls on the axis. Makes it easy to see what happened when.
It's interesting to see how Christmas spending was on the rise and reached a peak in 2007. Crashed in 2008 then started rising again. Great insight into the US economy.
When times are good, people buy gifts. When times are bad, people don't. 🧐
To build this linechart we used the same insight as yesterday:
Our data is static and never changes. We don't expect to change positions and size of our chart. That means we can cut some corners.
Once again we load data in
componentDidMount using
d3.tsv to parse a tab
separated values file. We feed the result array of objects into a
<Linechart>
component.
The basic linechart
Rendering a basic linechart was pretty quick: D3's got a line generator 🤙
That's an SVG
<path> using
d3.line to create the
d shape attribute.
Wrapped into a React component it looks like this:
class Linechart extends React.Component {x = d3.scalePoint().domain(this.props.data.map((d) => d.year)).range([0, this.props.width])y = d3.scaleLinear().domain([500, d3.max(this.props.data, (d) => d.avg_spend)]).range([this.props.height, 0])line = d3.line().x((d) => this.x(d.year)).y((d) => this.y(d.avg_spend))render() {const { x, y, data } = this.propsreturn (<g transform={`translate(${x}, ${y})`}><Line d={this.line(data)} /></g>)}}
We define two scales,
x and
y to help us translate between datapoints and
coordinates on the screen. Without those year 2018 would render 2018 pixels to
the right and that's too much.
x is a point scale, which like yesterday's band scale
neatly arranges datapoints along a axis. Unlike a band scale it places them in
points at the middle of each ragne.
y is a boring old liear scale. Americans spend so much on gifts that we cut
off the domain at \$500. Makes the graph more readable and less tall.
Then we have the line generator. We define it with
d3.line, tell it how to
get
x and
y coordinates with our scales and leave the rest as defaults.
Rendering is a matter of creating a wrapping
<g> element to position our
graph and group all future additions. Inside, we render a styled
<Line>
component and feed data into the line generator. That handles the rest.
You have to style lines or they come out invisible.
const Line = styled.path`stroke-width: 3px;stroke: ${d3.color("green").brighter(1.5)};fill: none;stroke-linejoin: round;`
Give it a nice thickness, some light green color, remove the default black fill, and make edges round. Lovely.
Note the
d3.color('green').brighter(1.5) trick. We can use D3 to manipulate
colors 🎨
The axes
Because axes are a tricky best to build, we used a trick from React for Data Visualization - blackbox rendering.
That's when you take pure D3 code, wrap it in a React component, and let D3 handle the rendering. It's less efficient and doesn't scale as well, but perfect for little things like this.
You can use my d3blackbox library or make your own. I used the lib 😛
const BottomAxis = d3blackbox((anchor, props) => {const axis = d3.axisBottom().scale(props.scale)d3.select(anchor.current).call(axis)})const LeftAxis = d3blackbox((anchor, props) => {const axis = d3.axisLeft().scale(props.scale)d3.select(anchor.current).call(axis)})
BottomAxis and
LeftAxis are both tiny. Two lines of code is all you need to
render a axis with D3.
- Define the axis generator and give it a scale. We took it from props.
- Select the element you want to render into and call your generator
d3blackbox handles the rest.
It's a higher order component (hook version called
useD3 is also in the
package). Takes your render function whatever it is, renders an anchor element,
positions it with
x and
y props, and makes sure to call your render
function on any update.
Quickest way to slap some D3 into some React 👌
The 💸 money emojis
How do you make a linechart more fun? You add money-flying-away emojis.
Interactive points on each edge of a linechart are pretty common after all. Makes it easier to spot where the line breaks and shows actual data and where it's just a line.
Adding emojis happens in a loop:
{data.map((d) => (<Money x={this.x(d.year)} y={this.y(d.avg_spend)}>💸<title>${d.avg_spend}</title></Money>))}
Iterate through our data and render a styled
text component called
Money
for each datapoint. Using the same scales as we did for the linechart gives us
correct positioning out of the box.
One of the many benefits of scales 😉
Styling deals with setting emoji font size and centering text on the
(x, y)
anchor point.
const Money = styled.text`font-size: 20px;cursor: pointer;text-anchor: middle;alignment-baseline: central;`
Oh and adding a
<title> tag to our text creates a default browser tooltip.
Hover over an emoji for a few seconds and it shows some extra info.
A highlight for easy reading
Linecharts can be hard to read. With datapoints so far from the axes it can be hard to see how everything lines up.
So we added a line to help our users out.
We keep track of what's currently highlighted in component state. When a value exists, we use it to render a vertical line.
class Linechart extends React.Component {state = {highlightYear: null};// ...highlight = year => this.setState({ highlightYear: year });unhighlight = () => this.setState({ highlightYear: null });// ...{highlightYear ? (<Highlightx1={this.x(highlightYear)}y1={-20}x2={this.x(highlightYear)}y2={height + 20}/>) : null}// ...<Moneyx={this.x(d.year)}y={this.y(d.avg_spend)}onMouseOver={() => this.highlight(d.year)}onMouseOut={this.unhighlight}>
Nothing too crazy.
We have a
highlightYear state. This gets set on
onMouseOver in the
<Money> emoji. On
onMouseOut, we reset the highlight year back to
null.
In the render method we then check whether
highlightYear is set. If it is, we
render a vertical line that's styled to be thin and lightgrey. If it isn't, we
don't.
There's a lot we could do with that highlight to make it look smoother, but time was up and this is good enough.
What you learned 🧐
Today you learned:
- D3 point scales
- using class field values for D3 objects
- d3blackbox for simple D3 integrations
- the
<title>trick on text tags
- using D3 axes
- adding a little interactivity
Enjoy ✌️ | https://reactfordataviz.com/cookbook/3/ | CC-MAIN-2022-40 | refinedweb | 1,124 | 68.77 |
Using Atmosphere Packages
Searching for packages
There are a few ways to search for Meteor packages published to Atmosphere:
- Search on the Atmosphere website.
- Use
meteor searchfrom the command line.
- Use a community package search website like Fastosphere.
The main Atmosphere website provides additional curation features like trending packages, package stars, and flags, but some of the other options can be faster if you’re trying to find a specific package. For example, you can use
meteor show kadira:flow-router from the command line to see the description of that package and different available versions.
Package naming
You may notice that, with the exception of Meteor platform packages, all packages on Atmosphere have a name of the form
prefix:package-name. The prefix is the Meteor Developer username of the organization or user that published the package. Meteor uses such a convention for package naming to make sure that it’s clear who has published a certain package, and to avoid an ad-hoc namespacing convention. Meteor platform packages do not have any
prefix:.
Installing Atmosphere Packages
To install an Atmosphere package, you simply run
meteor add:
This will add the newest version of the desired package that is compatible with the other packages in your app. If you want to specify a particular version, you can specify it by adding a suffix to the package name like:
meteor add kadira:flow-router@2.10.0.
Regardless of how you add the package to your app, its actual version will be tracked in the file at
.meteor/versions. This means that anybody collaborating with you on the same app is guaranteed to have the same package versions as you. If you want to update to a newer version of a package after installing it, use
meteor update. You can run
meteor update without any arguments to update all packages and Meteor itself to their latest versions, or pass a specific package to update just that one, for example
meteor update kadira:flow-router.
If your app is running when you add a new package, Meteor will automatically download it and restart your app for you.
The actual files for a given version of an Atmosphere package are stored in your local
~/.meteor/packagesdirectory.
To see all the Atmosphere packages installed run:
To remove an unwanted Atmosphere package run:
You can get more details on all the package commands in the Meteor Command line documentation.
Using Atmosphere Packages
To use an Atmosphere Package in your app you can import it with the
meteor/ prefix:
Typically a package will export one or more symbols, which you’ll need to reference with the destructuring syntax. You can find these exported symbols by either looking in that package’s
package.js file for
api.export calls or by looking in that package’s main JavaScript file for ES2015
export calls like
export const packageName = 'package-name';.
Sometimes a package will have no exports and simply have side effects when included in your app. In such cases you don’t need to import the package at all after installing.
For backwards compatibility with Meteor 1.2 and early releases, Meteor by default makes available directly to your app all symbols referenced in
api.exportin any packages you have installed. However, it is recommended that you import these symbols first before using them.
Importing styles from Atmosphere packages
Using any of Meteor’s supported CSS pre-processors you can import other style files using the
{package-name} syntax as long as those files are designated to be lazily evaluated as “import” files. To get more details on how to determine this see CSS source versus import files.
CSS files in an Atmosphere package are declared with
api.addFiles, and therefore will be eagerly evaluated by default, and then bundled with all the other CSS in your app.
Peer npm dependencies
Atmosphere packages can ship with contained npm dependencies, in which case you don’t need to do anything to make them work. However, some Atmosphere packages will expect that you have installed certain “peer” npm dependencies in your application.
Typically the package will warn you if you have not done so. For example, if you install the
react-meteor-data package into your app, you’ll also need to install the
react and the
react-addons-pure-render-mixin packages:
Atmosphere package namespacing
Each Atmosphere package that you use in your app exists in its own separate namespace, meaning that it sees only its own global variables and any variables provided by the packages that it specifically uses. When a top-level variable is defined in a package, it is either declared with local scope or package scope.
Notice that this is just the normal JavaScript syntax for declaring a variable that is local or global. Meteor scans your source code for global variable assignments and generates a wrapper that makes sure that your globals don’t escape their appropriate namespace.
In addition to local scope and package scope, there are also package exports. A package export is a “pseudo global” variable that a package makes available for you to use when you install that package. For example, the
Email.send. Most packages have only one export, but some packages might have two or three (for example, a package that provides several classes that work together).
It is recommended that you use the
ecmascriptpackage and first call
import { Email } from 'meteor/email';before calling
Email.sendin your app. It is also recommended that package developers now use ES2015
exportfrom their main JavaScript file instead of
api.export.
Your app sees only the exports of the packages that you use directly. If you use package A, and package A uses package B, then you only see package A’s exports. Package B’s exports don’t “leak” into your namespace just because you used package A. Each app or package only sees their own globals plus the APIs of the packages that they specifically use and depend upon. | https://guide.meteor.com/using-atmosphere-packages.html | CC-MAIN-2018-09 | refinedweb | 1,002 | 52.09 |
Great book.
I have about 20 nutshell books!
I love them all.
C# in a nutshell 3rd edition, has a smell of the ink/paper.
Thank You.
static int InchesToFeet (int feet) {...}
should read
static int FeetToInches (int feet) {...}
Two kinds of multidimensional arrays are described: rectangular and jagged. This differs from the C# reference, where only the "rectangular" arrays are considered multidimensional.
I marked this as a serious technical mistake because it can be a source of substantial confusion if you then refer to the .NET documentation. For example, the .NET documentation on Array.Copy describes how it handles multidimensional arrays, and Array.CopyTo is said to work only with single dimensional arrays. Here, however, multidimensional means "multidimensional rectangular array", in your vocabulary, and "single dimensional" includes jagged arrays!
I do see that the book's coverage of Array.Copy and Array.CopyTo carefully refers to a "multidimensional rectangular array" (p. 247). So, at least the book internally consistent. Nonetheless, I still think it would be far better to prevent confusion and follow the terminology that Microsoft uses.
The boolian variable "horizontal" would be better labeled "vertical"! Left and Right edges are vertical, not horizontal!
The book uses the term "listener" without defining it earlier in the text, or having a reference in the index. In fact, I think the authors mean "subscriber" anyway.
In the code of class Stock: the type of delegate should PriceChanged Handler, not PriceChanged :
...
public event PriceChanged PriceChanged;
...
A subscriber decides when to start and stop listening, by calling +- and -=
should read "+= and -="
The example declares
public delegate void PriceChangedHandler( decimal oldPrice,
decimal newPrice );
but in the class that's supposed to be using this type it doesn't use the same type name:
public class Stock
{
...
public event PriceChanged PriceChanged; <--- error
it should say:
public event PriceChangedHandler PriceChanged;
Letter N, 2nd sample input, the format string should be "N2" not "F2"
Specifier ",", Meaning "Multiplier", 2nd sample input, the trailing quotation marks are missing.
using System.Collections.Generic;
is missing in the example (for IEnumerable).
The sentence:
"...assigning the Purchase.Customer property would automatically add the new customer to the Customer.Purchases entity set..."
should read:
"...assigning the Purchase.Customer property would automatically add the new purchase to the Customer.Purchases entity set..."
Page 564, 9th line
Change:
Console.WriteLine(t);
To:
Console.WriteLine(t.FullName);
© 2015, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.oreilly.com/catalog/errataunconfirmed.csp?isbn=9780596527570 | CC-MAIN-2015-11 | refinedweb | 419 | 52.46 |
The library presented in this article is becoming obsolete and un-maintained. I recommend you to read this post about tenacity instead..
It's OK to fail
Often in computing, you have to deal with external resources. That means accessing resources you don't control. Resources that can fail, become flapping, unreachable or unavailable.
Most applications don't deal with that at all, and explode in flight, leaving a skeptical user in front of the computer. A lot of software engineers refuse to deal with failure, and don't bother handling this kind of scenario in their code.
In the best case, applications usually handle simply the case where the external reached system is out of order. They log something, and inform the user that it should try again later.
In this cloud computing area, we tend to design software components with service-oriented architecture in mind. That means having a lot of different services talking to each others over the network. And we all know that networks tend to fail, and distributed systems too. Writing software with failing being part of normal operation is a terrific idea.
Retrying
In order to help applications with the handling of these potential failures, you need a plan. Leaving to the user the burden to "try again later" is rarely a good choice. Therefore, most of the time you want your application to retry.
Retrying an action is a full strategy on its own, with a lot of options. You can retry only on certain condition, and with the number of tries based on time (e.g. every second), based on a number of tentative (e.g. retry 3 times and abort), based on the problem encountered, or even on all of those.
For all of that, I use the retrying library that you can retrieve easily on PyPI.
retrying provides a decorator called
retry that you can use on top of any function or method in Python to make it retry in case of failure. By default,
retry calls your function endlessly until it returns rather than raising an error.
import random from retrying import retry @retry def pick_one(): if random.randint(0, 10) != 1: raise Exception("1 was not picked")
This will execute the function
pick_one until
1 is returned by
random.randint.
retry accepts a few arguments, such as the minimum and maximum delays to use, which also can be randomized. Randomizing delay is a good strategy to avoid detectable pattern or congestion. But more over, it supports exponential delay, which can be used to implement exponential backoff, a good solution for retrying tasks while really avoiding congestion. It's especially handy for background tasks.
@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) def wait_exponential_1000(): print "Wait 2^x * 1000 milliseconds between each retry, up to 10 seconds, then 10 seconds afterwards" raise Exception("Retry!")
You can mix that with a maximum delay, which can give you a good strategy to retry for a while, and then fail anyway:
# Stop retrying after 30 seconds anyway >>> @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_delay=30000) ... def wait_exponential_1000(): ... print "Wait 2^x * 1000 milliseconds between each retry, up to 10 seconds, then 10 seconds afterwards" ... raise Exception("Retry!") ... >>> wait_exponential_1000() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/retrying.py", line 49, in wrapped_f return Retrying(*dargs, **dkw).call(f, *args, **kw) File "/usr/local/lib/python2.7/site-packages/retrying.py", line 212, in call raise attempt.get() File "/usr/local/lib/python2.7/site-packages/retrying.py", line 247, in get six.reraise(self.value[0], self.value[1], self.value[2]) File "/usr/local/lib/python2.7/site-packages/retrying.py", line 200, in call attempt = Attempt(fn(*args, **kwargs), attempt_number, False) File "<stdin>", line 4, in wait_exponential_1000 Exception: Retry!
A pattern I use very often, is the ability to retry only based on some exception type. You can specify a function to filter out exception you want to ignore or the one you want to use to retry.
def retry_on_ioerror(exc): return isinstance(exc, IOError) @retry(retry_on_exception=retry_on_ioerror) def read_file(): with open("myfile", "r") as f: return f.read()
retry will call the function passed as
retry_on_exception with the exception raised as first argument. It's up to the function to then return a boolean indicating if a retry should be performed or not. In the example above, this will only retry to read the file if an
IOError occurs; if any other exception type is raised, no retry will be performed.
The same pattern can be implemented using the keyword argument
retry_on_result, where you can provide a function that analyses the result and retry based on it.
def retry_if_file_empty(result): return len(result) <= 0 @retry(retry_on_result=retry_if_file_empty) def read_file(): with open("myfile", "r") as f: return f.read()
This example will read the file until it stops being empty. If the file does not exist, an
IOError is raised, and the default behavior which triggers retry on all exceptions kicks-in – the retry is therefore performed.
That's it!
retry is really a good and small library that you should leverage rather than implementing your own half-baked solution! | https://julien.danjou.info/python-retrying/ | CC-MAIN-2018-39 | refinedweb | 867 | 55.95 |
Type: Posts; User: Thingol
Get HDPARM's source code and try to understand it. There's no need for assembly.
Try JDIC ( ). It has an implementation of tray icons in Java.
Some hints (or cookie recipes):
To generate the sequence 0, 1, 2, ... n-1:
for (int i = 0; i < n; ++i) {
}
To generate the sequence 1, 2, ... n:
for (int i = 1; i <= n; ++i) {
}
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
main () {
cout << hex << setw(2) << setfill('0') << 0x00 << endl;
cout << hex << setw(2) <<...
getenv does not crash if the environment variable is not found: it returns NULL.
You need to test against NULL before using the result of "getenv" in your programs.
For instance:
#include...
1/3 will give theoretically 0.333333333333.... so your question is not easy to answer. In practice 1.0 / 3.0 will give a finite floating-point number that is very close to 1/3 but is not...
There are three famous C and C++ encryption libraries freely available:
OpenSSL - - used in every web server (except Microsoft IIS and Netscape Web Server) you know.
...
Download a trial copy of IBM Rational PurifyPlus or Compuware Numega, install it, run your program and check for problems.
It's faster and safer than modifying your program.
java.awt.robot
Ctrl+C = 3
Ctrl+Z = 26
Ctrl+<letter> = numerical order of the letter: A = 1, B = 2 ...
- but -
if you're running a non-graphical app, Ctrl+C will trigger the program termination.
Maybe you're supposing that the initial values of variables and member variables are zero. Use the compiler option /RTCu (Uninitialized local usage checks) and correct all errors that will appear in...
Search MSDN for MediaArrival, DeviceArrival, AutoPlay and IHWEventHandler
APIs: GetFileVersionInfoSize , GetFileVersionInfo, VerQueryValue
"void*" is not an "Automation" type.
You can try returning a Long, that a VB program can use as a "opaque handle".
Remember: the main consumers of ActiveX controls are VB programs, that have no...
a) Assembly language is not new at all. It has more than 50 years...
b) It's as powerful as nitroglycerin.
You are not supposed to use it in large amounts (hard to write, harder to maintain, truly...
You're saying good old MS-DOS (and the similar things like DR-DOS, FreeDOS etc)? MS-DOS supports anything because it does almost anything (MS-DOS is not a true operating system at all...). If you...
a) You could write an applet or an ActiveX Control that downloads the data sent by the JSP, and make the applet show the status bar.
b) Don't bother about it, simply set the content-length correctly...
You'll need to write an applet (you can choose to write a 1-pixel applet, just for using its public methods), and learn about LiveConnect in devedge.netscape.com site. (Maybe you'll need to check the...
Q: How to use the hash_map class in C++
A: If you have Visual Studio .NET 2003 you can try the 'hash_map' class instead of the map if you want to use hash tables instead of binary trees to store...
It's always good to think in VB first and then define the IDL interface to your COM DLL.
For instance, if you have a "(ByRef P As String)" (or "P As String") you'll translate it as ([in,out]BSTR...
Maybe IsBadReadPtr?
from MSDN:
IsBadReadPtr
The IsBadReadPtr function verifies that the calling process has read access to the specified range of memory.
BOOL IsBadReadPtr(
But when I try to run the executable on a W98, the resulting error
says something like the executable is linked to missing export
mfc.DLL.688
You'll have to redistribute the correct version of...
Maybe you'll have to use make_pair.
The declaration of make_pair is:
template<class T, class U>
pair<T, U> make_pair(const T& x, const U& y);
so you can use make_pair<NMKey,...
Itr = MMIDCache.insert(Itr, MMIDList::value_type(NMKey, MMIDStructs));
Is MMIDList a map<>?
If yes, value_type is a typedef:
typedef pair<const Key, T> value_type;
so you want to use of of the...
Ohoh, Windows CE is a different beast. There's no GDI+ or other amenities available for Windows CE, I guess.
I've seen a Windows CE in a single-processor x86 board, and it is being used for a small... | http://forums.codeguru.com/search.php?s=30c088d9f4e788c144588528ae9c8ab2&searchid=7002783 | CC-MAIN-2015-22 | refinedweb | 725 | 73.88 |
I'm still confused how to resolve module paths with webpack. Now I write:
myfile = require('../../mydir/myfile.js')
but I'd like to write
myfile = require('mydir/myfile.js')
I was thinking that resolve.alias may help since I see a similar example using
{ xyz: "/some/dir" } as alias then I can
require("xyz/file.js").
But if I set my alias to
{ mydir: '/absolute/path/mydir' },
require('mydir/myfile.js') won't work.
I feel dumb because I've read the doc many times and I feel I'm missing something.
What is the right way to avoid writing all the relative requires with
../../ etc?
See wtk's answer.
A more straightforward way to do this would be to use resolve.root.
resolve.root
The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.
In your case:
var path = require('path'); // ... resolve: { root: path.resolve('./mydir'), extensions: ['', '.js'] }
require('myfile')
or
require('myfile.js')
see also:
My biggest headache was working without a namespaced path. Something like this:
./src/app.js ./src/ui/menu.js ./node_modules/lodash/
Before I used to set my environment to do this:
require('app.js') require('ui/menu') require('lodash')
I found far more convenient avoiding an implicit
src path, which hides important context information.
My aim is to require like this:
require('src/app.js') require('src/ui/menu') require('test/helpers/auth') require('lodash')
As you see, all my app code lives within a mandatory path namespace. This makes quite clear which require call takes a library, app code or a test file.
For this I make sure that my resolve paths are just
node_modules and the current app folder, unless you namespace your app inside your source folder like
src/my_app
This is my default with webpack
resolve: { extensions: ['', '.jsx', '.js', '.json'], root: path.resolve(__dirname), modulesDirectories: ['node_modules'] }
It would be even better if you set the environment var
NODE_PATH to your current project file. This is a more universal solution and it will help if you want to use other tools without webpack: testing, linting...
I have resolve it with Webpack 2 like this:
module.exports = { resolve: { modules: ["mydir", "node_modules"] } }
You can add more directories to array...
Got this solved using Webpack 2 :
resolve: { extensions: ['', '.js'], modules: [__dirname , 'node_modules'] }
This thread is old but since no one posted about require.context I'm going to mention it:
You can use require.context to set the folder to look through like this:
var req = require.context('../../mydir/', true) // true here is for use subdirectories, you can also specify regex as third param return req('./myfile.js')
For future reference, webpack 2 removed everything but
modules as a way to resolve paths. This means
root will not work.
The example configuration starts with:
{ modules: [path.resolve(__dirname, "app"), "node_modules"] // (was split into `root`, `modulesDirectories` and `fallback` in the old options)
resolve.alias should work exactly the way you described, so I'm providing this as an answer to help mitigate any confusion that may result from the suggestion in the original question that it does not work.
a resolve configuration like the one below will give you the desired results:
// used to resolve absolute path to project's root directory (where web pack.config.js should be located) var path = require( 'path' ); ... { ... resolve: { // add alias for application code directory alias:{ mydir: path.resolve( __dirname, 'path', 'to', 'mydir' ) }, extensions: [ '', '.js' ] } }
require( 'mydir/myfile.js' ) will work as expected. If it does not, there must be some other issue.
If you have multiple modules that you want to add to the search path,
resolve.root makes sense, but if you just want to be able to reference components within your application code without relative paths,
alias seems to be the most straight-forward and explicit.
An important advantage of
alias is that it gives you the opportunity to namespace your
requires which can add clarity to your code; just like it is easy to see from other
requires what module is being referenced,
alias allows you to write descriptive
requires that make it obvious you're requiring internal modules, e.g.
require( 'my-project/component' ).
resolve.root just plops you into the desired directory without giving you the opportunity to namespace it further.
In case anyone else runs into this problem, I was able to get it working like this:
var path = require('path'); // ... resolve: { root: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')], extensions: ['', '.js'] };
where my directory structure is:
. ??? dist ??? node_modules ??? package.json ??? README.md ??? src ? ??? components ? ??? index.html ? ??? main.js ? ??? styles ??? webpack.config.js
Then from anywhere in the
src directory I can call:
import MyComponent from 'components/MyComponent';
If you're using create-react-app, you can simply add a
.env file containing
NODE_PATH=src/
Source:
I didn't get why anybody suggested to include myDir's parent directory into modulesDirectories in webpack, that should make the trick easily:
resolve: { modulesDirectories: [ 'parentDir', 'node_modules', ], extensions: ['', '.js', '.jsx'] },
Simply use babel-plugin-module-resolver:
$ npm i babel-plugin-module-resolver --save-dev
Then create a
.babelrc file under root if you don't have one already:
{ "plugins": [ [ "module-resolver", { "root": ["./"] } ] ] }
And everything under root will be treated as absolute import:
import { Layout } from 'components'
For VSCode/Eslint support, see here. | https://javascriptinfo.com/view/36737/resolving-require-paths-with-webpack | CC-MAIN-2021-04 | refinedweb | 897 | 58.28 |
When i run the below code, Collection.sort(l) will throw below exception.
Exception in thread "main" java.lang.ClassCastException:
learning.CollectionSort cannot be cast to java.lang.Comparable
public class CollectionSort {
public static void main (String[] args){
List l = new ArrayList();
CollectionSort obj1 = new CollectionSort();
CollectionSort obj2 = new CollectionSort();
l.add(obj1);
l.add(obj2);
Collections.sort(l);
for (int i = 0; i < l.size(); i++){
System.out.println(l.get(i));
}
}
}
But in the above code, we have no properties in this class. So is possible to sort the above list?
Yes, you could write a
Comparator that orders based on hash code (
hashCode()) or string value (
toString()), and use that to sort the list ...
Collections.sort(l, new MyComparator()).
But it is unclear would be gained by that, as the resulting orders have no particular meaning. Indeed, if you are free to choose whatever basis you wish for sorting, then why not sort the list elements by their index in the list? Then your list is always trivially sorted without invoking any methods. | https://codedump.io/share/xJsr5Sp4BNjK/1/java-collection-sorting | CC-MAIN-2018-13 | refinedweb | 176 | 60.21 |
Unsplash.com is a website which provide stock free professional like images from artists, photographers across the glob. The Unsplashbot project is meant to use those resources which offered by the website.
Using this module python users can simply search download images they want with two lines code.
This is a beautiful python package with selenium scripts to automate downloading of free stock images/videos from Unsplash.com, for fun, design and productivity.
- Language : Python
- Packages used : Selenium, Webdriver_Manager
How to use
Import the module and use in a python script. The module can be cloned into your local system using git
git clone
and then import the module into your script like
from unsplashbot import unsplash unsplash.search().filter_by_tag('Fruits')
Which will automatically search and download images from Unsplash.com
Use pip instead of git clone
If you need not use source just use Python Package Index to install unsplashbot
pip install unsplashbot
The complete documentation can be found on Github Repository. | https://developerm.dev/portfolio/unsplash-bot/ | CC-MAIN-2021-17 | refinedweb | 163 | 53.92 |
Generated code - WCF Data Services support
LLBLGen Pro Runtime Framework supports the WCF Data Services shipped by Microsoft. The support is for .NET 4 and higher. LLBLGen Pro Runtime Framework comes with a full Data Service Provider implementation which makes it real easy to create your own WCF Data services based on a model in Adapter or SelfServicing code.
The WCF Data Services is designed to be usable with existing Visual Studio.NET tooling. The following information describes how to define a WCF Data Services for generated code in Adapter or SelfServicing. The example below will add a service for 'Northwind', using Adapter, however you can use the same code for SelfServicing.
LLBLGen Pro WCF Data Services support is implemented in the SD.LLBLGen.Pro.ODataSupportClasses.dll assembly. This assembly supports OData v1, v2 and v3 and is compiled against v5.7.0 of the WCF Data Services Server assembly available from nuget, instead of the .NET 4 version of the same assembly.
Your application will therefore need to reference this same assembly (or newer) to use ODataSupportClasses. This nuget based WCF Data Services Server assembly supports OData v1, 2 and 3.
If you need OData v4 support and thus want to have the OData Support Classes compiled against v6.x of the WCF Data Services, you have to compile the OData Support Classes yourself from the source code archive of the LLBLGen Pro Runtime Framework, which is available to you on the LLBLGen Pro website, in the customer area under 'Extras'. v6.x isn't backwards compatible with OData v3 and earlier hence this limitation.
By default, the LLBLGen Pro runtime framework setting
'ConvertNulledReferenceTypesToDefaultValue' is set to true. This results
in null string fields to return the value
"" instead of null. As a
result, the string field will be set to
"" when updating the entity
instead of null and this could lead to wrong updates for these fields as
"" might mean something else in your application than null. To overcome
this, set 'ConvertNulledReferenceTypesToDefaultValue' to false in the
project settings (in the Conventions: LLBLGen Pro Runtime Framework node)
Creating a WCF Data Services Tutorial
- The VS.NET project (using .NET 4.0 or higher) which will host the WCF Data Services service has to have a reference to the following LLBLGen Pro runtime framework dlls:
- SD.LLBLGen.Pro.ORMSupportClasses.dll
- SD.LLBLGen.Pro.ODataSupportClasses.dll
- The VS.NET project also has to have references to the generated code projects. For Adapter, you need to reference both projects.
- Code has to be generated for .NET 4.0 or higher
- The VS.NET project has to have a reference to the WCF Data Services Server assembly available from nuget
- To add a WCF Data Services service class, right-click the VS.NET project to which to add the service to in Solution Explorer and select 'Add -> New item…'
- Select under 'Web' (be sure to select .NET 4 or higher) the item WCF Data Service and specify a proper name for the file/service and click Add.
- This will add a yourservicename.svc file with associated yourservicename.svc.cs/vb file. Open the service's code by right-clicking it in Solution Explorer and selecting 'View code'.
- The service class derives by default from i. This has to be changed to LLBLGenProODataServiceBase<LinqMetaData>. The LLBLGenProODataServiceBase is in the namespace SD.LLBLGen.Pro.ODataSupportClasses (so you have to add a using/imports statement for that namespace at the top of the file, use the smart-tag in the VS.NET editor for that). The LinqMetaData class is in the generated code of the model you want to expose through the service. This class is in the namespace Rootnamespace.Linq, where Rootnamespace is the namespace you specified when you generated code in the designer.
The service, which we've called NorthwindService, now looks something like this: (in red the changes are specified you have to make.) Note that RootNamespace is the root namespace of your generated code.
using System; using System.Collections.Generic; using System.Data.Services; using System.Data.Services.Common; using System.Linq; using System.ServiceModel.Web; using System.Web; using SD.LLBLGen.Pro.ODataSupportClasses; using RootNamespace.Linq; namespace MyNamespace { public class NorthwindService : LLBLGenProODataServiceBase<LinqMetaData> { //; } } }
- For development it's key to add the following attribute to the service class, so exceptions are returned in full to the client. It's recommended this attribute is removed when the service is in production:
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
- In the InitializeService method, you can add additional configuration options. For example to be able to fetch all entities, add:
It's also recommended to add config.UseVerboseErrors=true; to this method during development.
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
There are three methods in the service class which have to get an implementation. They're specified below in code and are simply factory methods. In comments, selfservicing variants are given.
protected override LinqMetaData CreateLinqMetaDataInstance() { // adapter return new LinqMetaData(new DataAccessAdapter()); // selfservicing: // return new LinqMetaData(); } protected override ITransactionController CreateTransactionControllerInstance() { // adapter return new DataAccessAdapter(); // selfservicing: //return new Transaction(System.Data.IsolationLevel.ReadCommitted, "Trans"); } protected override IUnitOfWorkCore CreateUnitOfWorkInstance() { // adapter return new UnitOfWork2(); // selfservicing // return new UnitOfWork(); }
- You have to specify an override to the property ContainerName, which should return the name of the service. In our example this becomes:
protected override string ContainerName { get { return "NorthwindService"; } }
- Optional: you can specify an override to the property ContainerNamespace. By default it uses the namespace of the LinqMetaData type, but it's recommended to specify a namespace which makes sense in the context of the service, as this namespace is used for the entities returned from the service, e.g. you can use the namespace or name of the project containing the service.
- Optional: If you're using ORM Profiler, add the call to the interceptor to the InitializeService() method.
- The VS.NET project containing the service needs to be able to read the connection string. It's therefore key to add the connection string for the generated code to the project's app.config or web.config file.
- The service is now ready to use. To the service file you can add WebGet methods and other methods, e.g. methods annotated with QueryInterceptor attributes.
- To test the service, compile and start it. If you have added the service to a Website application, you can simply start the service by requesting it from a web browser. To see whether the meta-data is fully obtained, append $metadata to the service URL.
- See for details about using WCF Data Services.
The easiest way to consume the service in a .NET application is to add a Service Reference (in VS.NET) of the service you just created. This way VS.NET will generate classes for you, one for each entity exposed by the service and a context class to work with the entity classes on the client.
Limitations
We did our best to support WCF Data Services in full to make sure everything in your LLBLGen Pro model/generated code is exposable through the service. However as it turned out, WCF Data Services in its current version (.NET 4 framework) has limitations and these limitations can make it a problem to expose the generated code through a service, even though the generated code works OK when used in normal .NET code. These limitations are described below.
Most of them will result in an error either when you obtain the
$metadata or when you fetch data. If you run into one of these
limitations, it's best to create a copy of the LLBLGen Pro project file
and remove the entities/fields/types which cause a problem and
re-generate the code, and use that in the service.
No enum / DateTime2 etc. support
As WCF Data Services builds an entity data model (EDM), the types are based on the EDM type system. This means that it can't deal with fields which have an Enum type. The LLBLGenProODataServiceBase class filters out fields with Enum types and all other types which aren't mappable to an EDM type.
These fields don't show up in the entity exposed by the service. The types which are supported are listed in the list of DataTypes on this page:. Our provider doesn't use the Reflection provider, but the same list of types applies.
No byte[] type support for PK fields.
A field in the primary key of an entity isn't allowed to be of type byte[]. This is a limitation of WCF Data Services, and a left-over from Entity Framework, which has the same limitation.
Typed Views and OData
When generating typed views as poco classes with linq, they can be used with OData, using WCF Data Services and the OData Support Classes. However due to limitations in WCF Data Services from Microsoft, the typed views are not directly queryable, as they are defined as complex types in the OData service, not as entity types.
The main reason for that is that entity types require a PK in WCF Data Services and typed views don't have a PK. To use the typed views in OData a service method has to be added which returns an IQueryable and which has a [WebGet] attribute.
It's still not possible to use orderby, paging and the like on this method due to limitations in WCF Data Services with respect to complex types, unfortunately.
The WCF Data Services client is even more limited in that it can't deal with a collection of complex types, so the service method's return type won't be consumable from a .net class if the client is used: the more low-level reader has to be used in this case.
No navigators supported in subtypes if you select OData v1 or OData v2
If you select OData v1 or OData v2 using the DataServiceBehavior settings, navigators on subtypes are filtered out by the ODataSupportClasses. This is a limitation of WCF Data Services in .NET 4 / 4.5. This limitation means that if you have inheritance in your entity model, any subtype can't have a relationship with another entity, all relationships have to be defined on the root of the hierarchy.
This is quite a limiting factor for many people. If you run into this, be sure to set the OData protocol to v3 using the following in the InitializeService method:
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
Many to Many relationships are single sided and read-only
In LLBLGen Pro, many to many relationships are always read-only and this won't change in a WCF Data Service. To update many-to-many relationships, you have to append entities over the intermediate entity and the 1:n/m:1 relationships instead, like you'd do normally when using LLBLGen Pro code.
$Expand has some limitations with fetches 2+ levels deep
The WCF Data Services framework creates a projection of nested queries
to implement an
$Expand directive. This in general works however it
goes wrong with expanded m:1/1:1 relationship navigators which are 2+
levels deep, due to a limitation in our Linq provider.
Our Linq provider fetches nested queries using separate, prefetch path like queries which are merged in memory and which utilize optimizations based on parent sets. The downside is that to be able to do this, the nested query has to be configured in such a way that there's a correlation filter constructable to tie nested query to outer query.
The way WCF Data Services constructs the nested queries makes this currently not possible to do, so these nested queries fail.
Acknowledgements
We'd like to thank Brian Chance for his work in this area. His templates (which used the RelfectionProvider) to bring WCF Data Services support to LLBLGen Pro were a great source of information during the development of the data source provider. | https://www.llblgen.com/documentation/5.3/LLBLGen%20Pro%20RTF/Using%20the%20generated%20code/gencode_wcfdataservices.htm | CC-MAIN-2018-51 | refinedweb | 1,972 | 55.44 |
“Alexa – how did Redgate create a skill for SQL Clone?”
SQL Clone is a database provisioning tool from Redgate. It creates a data image, which is a copy of a database at a particular point in time, and then from that image it can create multiple, lightweight, database clones (a few tens of MB each) for deployment to the development and test servers. Each developer’s clone can be queried and updated independently, with any changes stored locally in a differencing file.
This opens up the interesting possibility that a DBA can use SQL Clone to provide a curated set of data images, from which developers can create database clones, on demand.
But we all know that developers are inherently lazy, so how far could we take this self-service database cloning idea? To celebrate the launch of SQL Clone v1, we decided to see if we could create an Alexa skill that would allow a developer, armed with an Amazon Echo, to voice-activate the creation of a new database clone, in between sips of coffee.
You can see our solution in action on YouTube, and this blog explains in detail how we did it.
Overview
We created a custom Alexa skill and added it to an Echo device. When the skill is activated, Alexa parses the command and triggers an AWS Lambda function. This Lambda function adds a message containing the database name to an AWS SQS queue. A polling application, running on a local machine, polls the SQS queue for messages. When it finds a message that contains a valid database name, it triggers a ‘clone’ operation. This creates a clone from a data image that has the same database name, and deploys it to a SQL Server instance. To do all of this, the polling app uses a C# library distributed with the SQL Clone PowerShell cmdlets.
Required components
If you want to set up something similar, you’ll need an Amazon Echo, a machine running SQL Clone, a machine running the polling app, and an Amazon account logged into these services:
You’ll need a credit card for AWS but it’s unlikely that you’ll exceed the free tier.
Creating the workflow
It’s actually easiest to configure the components in reverse order, so we’ll start by configuring SQL Clone and finish up with configuring the Echo.
Setting SQL Clone and the PowerShell cmdlets
You’ll need SQL Clone installed and running, so download the fully-functional free trial.
Once it’s up, you need to download and install the PowerShell client to get the C# libraries to trigger SQL Clone.
In the SQL Clone server’s web app, go to Settings > PowerShell > Download cmdlets and install SqlClonePowershellClient.msi.
By default, this installer will add the necessary libraries to:
C:\Program Files (x86)\Red Gate\SQL Clone PowerShell Client\RedGate.SqlClone.Powershell
You’ll need to add these libraries as references in the polling app.
Creating the polling app
The polling app is a simple console application created in Visual Studio that polls an SQS queue continuously, in a loop, looking for messages and, when it finds one, it calls the SQL Clone API to trigger a clone operation. Polling a queue isn’t the most elegant solution but by making outgoing requests you avoid having to deal with firewall issues.
You’ll need to add to the app the libraries obtained in the previous section as references so that it can call SQL Clone’s API. They can then be referenced in the app like this:
using RedGate.SqlClone.Client.Api;
The polling app doesn’t have to be running on the same machine as SQL Clone, as long as you can access the SQL Clone server’s web app from that machine, you should be fine (by default this is http://<machinename>:14145).
Since the application needs to interrogate an AWS SQS queue for messages, you’ll need the AWS SDK for .Net (you can find it on Nuget as AWSSDK). The library can be referenced in the app like this:
using Amazon.SQS;
using Amazon.SQS.Model;
You will need to create a
AWSSecretKey and
AWSAccessKey in order to connect to your SQS Queue. We added ours to an
App.config file in the solution:
Listing 1
See the AWS Developer Blog for more details.
Before you can access the AWS SQS queue you’ll need create one in the AWS portal. Once you’ve done this, you can copy its URL to use in the polling app.
Processing messages from SQS
The polling app checks the queue for messages. If there aren’t any, it sleeps for five seconds before trying again. If there is a message, it checks that the body contains a valid database name, starts the clone operation by calling
CreateClone() and then deletes the message from the queue.
Since Alexa interprets database names from your voice, it won’t get spaces and capitalization right, so we have a dictionary to translate spoken database names to actual ones.
Listing 2
Creating a clone using SQL Clone API
Before the polling app can call SQL Clone’s API, it needs to establish a connection to the SQL Clone management service, identified by the URL used to access the server’s web app.
The app queries the available images and SQL Server instances to which we can deploy clones.
AgentName is the host name of the machine on which SQL Clone agent is installed.
Listing 3
Creating an AWS Lambda function
When the user asks Alexa to create a copy of a database, it triggers the Lambda function, which then needs to identify the database name in the request, and pass this as a message to the SQS queue.
The easiest way to get the Alexa SDK into an AWS Lambda function is to start from the
alexa-skill-kit-sdk-factskill blueprint from the Create a Lambda function page in AWS. This blueprint is a readymade function for receiving and responding to an Alexa skill.
Once you’ve created the Lambda function, grab the ARN (Amazon Resource Name) so you can reference it later from when configuring the Alexa skill.
Receiving the request from Alexa
We modified the factskill code to send messages to the SQS queue, when triggered by an Alexa command.
Listing 4
The
event object is the package that the function will receive from Alexa. The
event.request.intent property contains information about the Alexa command (which we’ll go into later), in this case it’s a
CloneIntent action.
validNames is a list of image names that are ready to be cloned. If the request contains a DatabaseName that matches a name in the list of images, then the function calls
ExecuteCreateClone().
Adding messages to the AWS SQS queue
Using the URL for the SQS queue that we created, we send it a message containing the database name. The
alexa.execute(); call must happen inside the callback otherwise the function can exit before the message has finished sending. For the request to be accepted by Alexa, all code paths must call
alexa.execute();.
Listing 5
User feedback via Alexa
User feedback is really important for voice interfaces (especially during development) so we have different responses depending on how the function executed. As these strings are read out by Alexa it helps to spell things phonetically (eg,
SQL => sequel).
Listing 6
Creating a custom Alexa skill
You can create custom Alexa skills in the developer portal at Amazon. The skill’s information differs by language, so make sure you’ve defined the skill using the same language that your Echo device uses.
When creating the Skill information, the Name property is the name that your custom skill will appears as (in our case, SQLClone), whereas the Invocation Name is the command that will activate your device (in our case, sequel clone).
The Interaction Model section defines how users can interact with your skill. You can incorporate multiple intents, each of which is an action that can be performed by a skill.
Here’s the intent schema that our interaction model used:
Listing 7
We called the intent that initiates a clone operation
CloneIntent (this was referenced in the Lambda function – see Listing 4).
When creating a database clone using SQL Clone, the user needs to specify a database name, which can only be from a known list of possible values. Custom slot types are useful here, as you can define expected values of these arguments in advance to assist Alexa in parsing the voice command. As our database names don’t correspond to real English words, we found breaking them down was more effective.
Here’s our
DatabaseName slot definition:
LIST_OF_DATABASES:
• stack over flow
• adventure works
In order for Alexa to have a better chance of successfully parsing a request, we define multiple variants of sample utterances. These utterances are the phrases that will trigger intents. The
{DatabaseName} parameter corresponds to the slot definition.
CloneIntent create a copy of the {DatabaseName} database
CloneIntent create a copy of {DatabaseName} database
Before you can start testing your skill, you’ll need to add to your skill’s Configuration page the ARN of the Lamdba function that we created earlier.
When you’ve published your custom skill, you can add it to your Echo device. The easiest way to do this is through the Amazon Alexa portal.
Summary
That’s it! Once you’ve added the skill to your device and started up the polling app, a developer will be able to deploy a new database clone with just a voice command.
Find out more about how SQL Clone makes database provisioning easy with a 14-day fully functional free trial.
Tools in this post
SQL Clone
Clone SQL Server databases in seconds and save up to 99% disk space. Clone
How Redgate use SQL Clone internally to provision databases
A common thread behind the software we develop is a problem or issue we've come across in the software development process. We then adopt the software ourselves, which gives us a real understanding of... | https://www.red-gate.com/blog/alexa-redgate-create-skill-sql-clone | CC-MAIN-2017-43 | refinedweb | 1,688 | 58.82 |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Testing Exceptions2:39 with Alena Holligan
Sometimes code throws an exception when not used properly. PHPUnit gives us way to test for that output as well.
NOTE
In namespaced context the Exception class needs to be prefixed with global prefix operator. If you get a failure message when trying to use an InvalidArgumentException, add a slash before the exception to make sure you are using the exception from the global namespace:
\InvalidArgumentException
Testing Exceptions
PHPUnit Exception Documentation
Tips
- Excepted exceptions are written BEFORE the code expected to throw the exception.
- If you're having problems with
InvalidArgumentExceptionyou can try calling the base implementation of that exception by using the global namespace (a \ before the exception).
\InvalidArgumentException
Example:
/** @test */ function addIngredientMustReceiveValidAmount() { $this->expectException(\InvalidArgumentException::class); $recipe = new Recipe(); $recipe->addIngredient("garlic", "two"); }
From our Code Coverage, report we can see that we should be getting an exception on 0:00
our addIngredient method if we don't enter a valid amount or a valid measurement. 0:05
Let's add tests for these exceptions. 0:13
Since we don't need a full recipe for these tests, 0:17
I'm going to add them to my RecipesTest.php file. 0:20
Our test be function 0:26
addIngredientMustReceiveValidAmount. 0:30
For this test, I'm just going to check for a valid exception. 0:41
When testing for exceptions, we add our expected exception first, 0:46
$this->expectException(InvalidArgumentExc- eption::class). 0:52
Then we'll add our recipe. 1:01
And the code we expect to throw the exception, $recipe->addIngredient. 1:06
We'll add garlic with the word two, let's run this test. 1:14
Great, let's add our next exception. 1:22
Function addIngredientMustReceiveValidMeasurement. 1:30
And this time, for the expected exception, we're going to check a message. 1:42
We'll start with a blank message, and then we'll start $recipe. 1:50
= new Recipe(), and 1:57
then $recipe->addIngredient("garlic"), 2. 2:00
And this time an invalid "tbl" for tablespoon, now let's run our test. 2:08
As expected we get the error. 2:17
But now we can copy and paste this message. 2:18
Great, run the test again, and it all passes. 2:29
Let's refresh our Code Coverage report. 2:35 | https://teamtreehouse.com/library/testing-exceptions | CC-MAIN-2021-21 | refinedweb | 416 | 56.76 |
(Want to talk about this or any other data-modelling topic in person? Sign up for our GOTO Amsterdam tutorial, June 18.)
Many graph database applications need to version a graph so as to see what it looked like at a particular point in time. Neo4j doesn’t provide intrinsic support either at the level of its labelled property graph model or in its Cypher query language for versioning. Therefore, to version a graph we need to make our application graph data model and queries version aware.
I’ll say this up front: versioning necessarily creates a lot more data – both more nodes and more relationships. In addition, queries will tend to be more complex, and slower, because every
MATCH must take account of one or more versioned elements. Given these overheads, apply versioning with care. Perhaps not all of your graph needs to be versioned. If that’s the case, version only those portions of the graph that require it.
In this post I’m going to discuss what I consider to be the easiest form of versioning – time-based versioning. Time-based versioning gives us a universal versioning scheme: pick an instant, convert it to a
long value, and the resulting version number applies to all parts of the graph. Version-number-based versioning, where each entity has its own independently varying version number (and scheme even), is more complex to implement. I’ll be dealing with that in a future post.
All graph versioning strategies with Neo4j must make tradeoffs between the cost of writes, the amount of on-disk storage require, the degree of fragmentation incurred, and the performance of reads for both current and historical queries. The design described here strikes a balance between these competing considerations. At the end of the post I describe some variations and optimisations.
The examples here were written using Neo4j Community 2.0.3. I’ve also included the examples in a GraphGist.
The key to versioning a graph is separating structure from state. This allows us to version the graph’s structure independently of its state.
To help describe how to design a version-aware graph model, I’m going to introduce some new terminology: identity nodes, state nodes, structural relationships and state relationships.
Identity nodes are used to represent the positions of entities in a domain-meaningful graph structure. Each identity node contains one or more immutable properties, which together constitute an entity’s identity. In a version-free graph (the kind of graph we build normally) nodes tend to identify an entity, locate it in the network structure, and represent its state. Identity nodes in a version-aware graph, in contrast, serve only to identify an entity and locate it in a network structure.
Identity nodes are connected to one another using timestamped structural relationships. These structural relationships are similar to the domain relationships we’d include in a version-free graph, except they have two additional properties,
from and
to, both of which are timestamps.
Connected to each identity node are one or more state nodes. Each state node represents an immutable snapshot of an entity’s state. State nodes are connected to identity nodes using timestamped state relationships.
The following example describes a simple domain made up of shops, products and suppliers. A Shop
SELLS one or more Products, which are
SUPPLIED_BY Suppliers. Over time prices change, shops sell different products, and source them from different suppliers. With a versioned graph we’ll be able to see which products a shop was selling, what price they were being sold at, and who was supplying them, at any point in the graph’s history.
The diagram below shows a version-aware graph representation of this domain. To help you see how structural and state-based elements are combined in the same graph, I’ve drawn identity nodes and structural relationships in blue, state nodes and state relationships in red. In the data itself, I’ve labelled the identity nodes
Product, and
Supplier, and the state nodes
ShopState,
ProductState and
SupplierState. Structural relationships are named
SELLS and
SUPPLIED_BY. All state relationships are named
STATE.
This graph represents the domain in its initial state on 1 January 2014. All the relationships, both structural and state, are current. Each relationship has a
from property with a
long millisecond value representing 1 January 2014, and a
to property with a very large
long value (End-Of-Time, or EOT, which is a magic number – in this case
Long.MAX_VALUE) that effectively means there is no current upper bound to the period associated with the relationship.
Here’s the Cypher for creating this graph in its initial state:
CREATE (s1:Shop{shop_id:1}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (ss1:ShopState{name:'General Store'}), (p1:Product{product_id:1}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (ps1:ProductState{name:'Cheese',price:1.00}), (p2:Product{product_id:2}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (ps2:ProductState{name:'Crisps',price:0.50}), (p3:Product{product_id:3}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (ps3:ProductState{name:'Orange Juice',price:1.50}), (u1:Supplier{supplier_id:1}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (us1:SupplierState{name:'International Imports'}), (u2:Supplier{supplier_id:2}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (us2:SupplierState{name:'Local Markets'}), (s2:Shop{shop_id:2}) -[:STATE{from:1388534400000,to:9223372036854775807}]-> (ss2:ShopState{name:'Cornershop'}), (s1)-[:SELLS{from:1388534400000,to:9223372036854775807}]->(p1), (s1)-[:SELLS{from:1388534400000,to:9223372036854775807}]->(p2), (s2)-[:SELLS{from:1388534400000,to:9223372036854775807}]->(p3), (p1)-[:SUPPLIED_BY{from:1388534400000,to:9223372036854775807}]->(u2), (p2)-[:SUPPLIED_BY{from:1388534400000,to:9223372036854775807}]->(u1), (p3)-[:SUPPLIED_BY{from:1388534400000,to:9223372036854775807}]->(u2)
To query the current state of a version-aware graph, we need to match current structural and state relationships, which we can do simply by matching the
to property on relationships against our EOT value. Here’s a query for finding all products that currently retail for one pound or less, together with their suppliers, and the shops where they can be purchased:
MATCH (u:Supplier)<-[:SUPPLIED_BY{to:9223372036854775807}]- (p:Product)-[:STATE{to:9223372036854775807}]->(ps:ProductState) WHERE ps.price <= 1.0 MATCH (p)<-[:SELLS{to:9223372036854775807}]-(s:Shop) MATCH (u)-[:STATE{to:9223372036854775807}]->(us:SupplierState) MATCH (s)-[:STATE{to:9223372036854775807}]->(ss:ShopState) RETURN us.name AS supplier, ps.name AS product, ps.price AS price, ss.name AS shop ORDER BY price DESC
Results:
+--------------------------------------------------------------+ | supplier | product | price | shop | +--------------------------------------------------------------+ | "Local Markets" | "Cheese" | 1.0 | "General Store" | | "International Imports" | "Crisps" | 0.5 | "General Store" | +--------------------------------------------------------------+
As you can see, because of the need to make all parts of the query version-aware, even simple queries can become quite complex.
The kinds of changes we may need to track in a version-aware graph include changes to state and changes to structure. Changes to state involve adding, removing and modifying node properties. Structural changes involve adding and deleting relationships, as well as modifying the strength, weight or quality of relationships by changing one or more of their properties.
In the following query, we move product 1 from shop 1 to shop 2. This change will be effective from 1 February 2014 (1391212800000 milliseconds since 1970-01-01T00:00:00Z).
MATCH (p:Product{product_id:1})<-[r:SELLS]-(:Shop) WHERE r.to = 9223372036854775807 MATCH (s:Shop{shop_id:2}) SET r.to = 1391212800000 CREATE (s)-[:SELLS{from:1391212800000,to:9223372036854775807}]->(p)
As part of this query, we archive the old
SELLS relationship, setting its
to property to the millisecond value representing 1 February 2014, and introduce a new
SELLS relationship that connects product 1’s identity node to shop 2’s identity node. We set the
from property of this new relationship to 1 February 2014, and its
to property to EOT.
This is what the graph looks like after we’ve made the change. I’ve used a dashed blue arrow to show the archived
SELLS relationship, and a thick blue arrow to show the new
SELLS relationship.
In the following query, we update product 1’s price. As with our structural change, this change will be effective from 1 February 2014.
MATCH (p:Product{product_id:1}) -[r1:STATE{to:9223372036854775807}]->(currentState:ProductState) SET r1.to = 1391212800000 CREATE (p)-[r2:STATE{from:1391212800000,to:9223372036854775807}]-> (newState:ProductState) SET newState = currentState SET newState.price = 2.0
This time, we archive the product’s current
STATE relationship, and then create a new state node and a new
STATE relationship. We copy the product’s properties from the old state node to the new state node (
SET newState = currentState), and then update the price.
We’ve seen that to query the current state of the graph, we need to do an exact match on the
to property of both structural and state relationships, matching against our EOT value. Historical queries are slightly different, in that we’re looking for relationships whose
from-to period covers the millisecond instant we’re interested in; that is, relationships where the
from value is less than or equal to the instant we’re interested in, and the
to value is greater than that instant. These kinds of comparisons must be done in the
WHERE clause.
The following query finds all the products sold by shop 1 on 5 January 2014 (1388880000000 milliseconds from the Java epoch):
MATCH (s:Shop{shop_id:1})-[r1:SELLS]->(p:Product) WHERE (r1.from <= 1388880000000 AND r1.to > 1388880000000) MATCH (p)-[r2:STATE]->(ps:ProductState) WHERE (r2.from <= 1388880000000 AND r2.to > 1388880000000) RETURN p.product_id AS productId, ps.name AS product, ps.price AS price ORDER BY price DESC
Results:
+------------------------------+ | productId | product | price | +------------------------------+ | 1 | "Cheese" | 1.0 | | 2 | "Crisps" | 0.5 | +------------------------------+
And here’s the same query for 5 February 2014:
MATCH (s:Shop{shop_id:1})-[r1:SELLS]->(p:Product) WHERE (r1.from <= 1391558400000 AND r1.to > 1391558400000) MATCH (p)-[r2:STATE]->(ps:ProductState) WHERE (r2.from <= 1391558400000 AND r2.to > 1391558400000) RETURN p.product_id AS productId, ps.name AS product, ps.price AS price ORDER BY price DESC
Results:
+------------------------------+ | productId | product | price | +------------------------------+ | 2 | "Crisps" | 0.5 | +------------------------------+
Some further comments on this approach:
This design is purely additive in nature. To delete a structural relationship we simply archive it; that is, timestamp its
to property. To delete a node we must archive both its current state relationship and any current structural relationships. Current relationships (both structural and state) are those with an EOT value.
This additive model strikes a reasonable balance between the competing considerations mentioned at the beginning of this post: the cost of writes, the amount of on-disk storage require, the degree of fragmentation incurred, and the performance of reads for both current and historical queries. Changes in state require the addition of nothing more than a single new state relationship and one new state node, which keeps the cost of writes down. Nothing is rewritten; therefore, nothing is deleted, which in turn keeps store growth to a minimum. On the other hand, both current and historical queries require scanning timestamped relationships, and every state lookup requires traversing at least one state relationship.
Indexes and constraints are not version aware. When using indexes (or label scans), you will have to test the results of each lookup. For a node to be included in the results for a particular point in time, it must be reachable by a single state relationships whose period includes that point. For entities that change frequently, or are (logically) deleted frequently, this check can impact the performance of index lookups.
Having multiple states for a particular entity poses problems for unique constraints. If a uniquely constrained property value doesn’t change between versions, the constraint will fail because there will now be duplicate property values. To get round this problem, we have to introduce a
version property that increments with each state change, and a synthetic property that combines the current version number with the value of the property we want to constrain. We then apply the unique constraint to this synthetic property instead of the underlying domain property. I’ll write this up in more detail in the near future.
The design strategy described here can be modified in several ways, depending on your needs:
I’ve attached state nodes to identity nodes in a radial fashion. This works well when there are no more than several tens of changes to an entity’s state over its lifetime. If an entity changes far more often than that, you might consider using a linked list.
Linked lists are also useful when you need to compare successive states: the ordering imposed by the linked list helps you identify next and previous states. In fact, you can combine radial relationships with linked lists:
For graphs with entities that change frequently, you might consider adding a
CURRENT_STATE relationship that connects an entity’s identity node directly to its latest state node. This allows you to navigate directly to that entity’s current state, without having to iterate many radial state relationships, or traverse a linked list. The use of a
CURRENT_STATE relationship, however, requires more housekeeping when updating state: you’ll have to delete the old
CURRENT_STATE relationship, and then create a new one.
For graphs where most entities change infrequently, or not at all, you might consider overloading each entity’s identity node with that entity’s initial state. You then add state nodes and relationships only with the first change to an entity’s state. If you adopt this strategy, you should continue to adjust structure at the level of the identity nodes, however, not the latest state nodes. Further, while it helps reduce the number of additional nodes and relationships in the graph, it does impose some additional cognitive overhead when visualising the resulting structure, because you now have to make sense of a structure in which current structural relationships are connected to historical initial state nodes.
Following on from the idea of overloading the identity node with initial state, and as an alternative to using a
CURRENT_STATE relationship, you might consider overloading the identity node with the current state of the entity, and building a linked list of previous states. The following diagram shows what our shop-product-supplier model would look like after if we were to adopt this approach:
At first glance, this looks simpler. There are fewer nodes, for starters. But it comes with its own compromises. Updating a node requires us not only to create a new node at the head of the linked list, but also to physically delete all the structural relationships attached to the old head of the list, before then recreating them on behalf of the new head of the list. The model is optimised for querying the current state of the graph, but at the expense of more costly writes and increased space on disk (because each time we recreate a batch of relationships, we add them to the end of the stores on disk). I’ll be looking at this model in more detail in a future post.
]]>
This work is licensed under a Creative Commons Attribution 4.0 International License
This example shows a simple solution for calculating the shortest weighted path between two nodes in a reasonably dense graph (say 30 relationships per node) using Cypher.
Consider the following graph:
Let’s say we want to calculate the shortest weighted path between
A and
I. All we have to do is sum the
weights along each path. Doing this, we find that
(A)->(B)->(C)->(I) is weight 15,
(A)->(D)->(E)->(I) is weight 12, and
(A)->(F)->(G)->(H)->(I) is weight 8. Therefore,
(A)->(F)->(G)->(H)->(I) is the shortest weighted path, even though it has one more relationship than either of the other two paths.
The Cypher to accomplish this is as follows:
START startNode=node:node_auto_index(name={startNode}), endNode=node:node_auto_index(name={endNode}) MATCH p=(startNode)-[:CONNECTED_TO*1..4]->(endNode) RETURN p AS shortestPath, reduce(weight=0, r in relationships(p) : weight+r.weight) AS totalWeight ORDER BY totalWeight ASC LIMIT 1
The summing of
weights is accomplished using Cypher’s
reduce function.
For modestly sized graphs with up to 30 relationships per node, this query performs reasonably well. For very large, extremely densely connected graphs, however, it’s not going to cut it: those types of graph require an implementation of a shortest weighted path algorithm such as Dijkstra or A*. Running on a MacBook Air against a graph comprising 1 million nodes, 12.5 million relationships, with between 4 and 20 outgoing
CONNECTED_TO relationships per node (average 12), average execution time is 120 ms. Increasing the depth of the search and/or the density of the graph will increase query times.
This example has been tested against Neo4j 1.9. The code for the example can be downloaded from here.
Instead of using
r in relationships(p) to iterate the relationships along each path, we could bind a path’s
CONNECTED_TO relationships to an identifier instead, like this:
MATCH p=(startNode)-[rels:CONNECTED_TO*1..4]->(endNode) RETURN p AS shortestPath, reduce(weight=0, r in rels : weight+r.weight) AS totalWeight
My tests, however, show that using
r in relationships(p) is faster than using identifiers..]]>
The current version of Neo4j has two different types of index: named indexes and automatic indexes. The Cypher query examples throughout the Graph Databases book use named indexes. In this query, for example,
venue,
city and
author are named node indexes:
START theater=node:venue(name='Theatre Royal'), newcastle=node:city(name='Newcastle'), bard=node:author(lastname='Shakespeare') MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater) <-[:VENUE]-()-[:PERFORMANCE_OF]->()-[:PRODUCTION_OF]-> (play)<-[:WROTE_PLAY]-(bard) RETURN DISTINCT play.title AS play
There’s a problem, however: data created using a Cypher
CREATE statement won’t be indexed in a named index. This has led to some confusion for anyone wanting to code along with the examples: if you use the
CREATE statements as published, the query examples won’t work.
(You can find out more about Neo4j indexes in the documentation.)
If you want to code along with the examples, the easiest thing to do is create the data using Cypher and automatic indexes. You’ll need to modify the queries to use the automatic indexes, but the changes aren’t complicated.
The examples below show how to run the Shakespeare examples (pp.47-50) using automatic indexes.
Before you create any data, you’ll need to configure the automatic indexes. The approach you take will depend on whether you are running Neo4j in embedded or server mode.
If running in embedded mode, configure the database at startup:
GraphDatabaseService graphDb = new GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( storeDirectory ). setConfig( GraphDatabaseSettings.node_keys_indexable, "name,lastname" ). setConfig( GraphDatabaseSettings.node_auto_indexing, "true" ). newGraphDatabase();
If running in server mode and executing Cypher statements through the console or using the REST API, add the following to the
conf/neo4j.properties file.
node_auto_indexing=true node_keys_indexable=name,lastname
The Shakespeare queries should then be modified as follows. In each case we’ve replaced a named node index (e.g.
node:author) with an automatic node index (
node:node_auto_index).
p.47:
START theater=node:node_auto_index(name='Theatre Royal'), newcastle=node:node_auto_index(name='Newcastle'), bard=node:node_auto_index(lastname='Shakespeare') MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater) <-[:VENUE]-()-[:PERFORMANCE_OF]->()-[:PRODUCTION_OF]-> (play)<-[:WROTE_PLAY]-(bard) RETURN DISTINCT play.title AS play
p.48:
START theater=node:node_auto_index(name='Theatre Royal'), newcastle=node:node_auto_index(name='Newcastle'), bard=node:node_auto_index(lastname='Shakespeare') MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater) <-[:VENUE]-()-[:PERFORMANCE_OF]->()-[:PRODUCTION_OF]-> (play)<-[w:WROTE_PLAY]-(bard) WHERE w.year > 1608 RETURN DISTINCT play.title AS play
p.49:
START theater=node:node_auto_index(name='Theatre Royal'), newcastle=node:node_auto_index(name='Newcastle'), bard=node:node_auto_index(lastname='Shakespeare') MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater) <-[:VENUE]-()-[p:PERFORMANCE_OF]->()-[:PRODUCTION_OF]-> (play)<-[:WROTE_PLAY]-(bard) RETURN play.title AS play, count(p) AS performance_count ORDER BY performance_count DESC
p.50:
START bard=node:node_auto_index(lastname='Shakespeare') MATCH (bard)-[w:WROTE_PLAY]->(play) WITH play ORDER BY w.year DESC RETURN collect(play.title) AS plays
The code that we used to generate most of the examples for the book, including the use cases, can be found on my GitHub account.]]>:
Along the way you’ll learn about:
So come and join me for what promises to be an entertaining hack-n-slash workshop. Attendees should be familiar with C# and unit testing, and have some knowledge of HTTP.
Full details and registration for the entire event can be found here.]]>
Jim Webber and I have been busy these last few months writing a tutorial for Neo4j. As we did with REST in Practice, we’ve chosen an example domain that falls a little outside the enterprise norm. With REST in Practice we chose the everyday world of the coffee shop; this time round, we’ve gone for the grand old universe of Doctor Who.
As we’ve worked on the tutorial,. For example, each incarnation of the Doctor has been played by one actor, except the first, who was originally played by William Hartnell, and then later by Richard Hurdnall, who reprised the tetchy first incarnation some years after William Hartnell’s death for the twenty-fifth anniversary story, The Five Doctors. Each episode has a title; at least, they did when the series first began, in 1963, and they do today. But towards the end of the third season, the original series stopped assigning individual episode titles (in the original series, stories typically took place over several episodes); a story’s episodes were simply labelled Part 1, Part 2, etc. And so on.
The earliest alien monsters to appear in Doctor Who, the Daleks have long held a fascination for the British viewing public, and for the enquiring minds of Doctor Who fandom. In 2002, Jon Green began researching the history of the Dalek props created for the original series, which ran from 1963 to 1988. Jon was later joined by a second researcher, Gav, and the result of their hard work is the wonderful Dalek 6388.
Recently, I imported some of this Dalek research into our Doctor Who database. From the wealth of detail available on Dalek 6388 I chose to focus on the ways the different prop parts were reused in different stories.
Each episode or story featuring the Daleks made use of one or more Dalek props. Each prop came in two parts: the top half, called the shoulders, and the bottom half, called the skirt. These parts were handmade, and as a result there were many differences between them: the hemisphere spacing, collars, slats, eyestalks, and gun boxes in particular varied in subtle but noticeable ways. Reconstructing the history of the props has been largely a matter of identifying specific parts in screenshots and photos based on these visual clues.
Over time, the different shoulders and skirts were mixed and matched. For example, the shoulders originally belonging to Dalek 1, one of the props created for the very first Dalek story, The Daleks, were later paired with the skirt belonging to Dalek 5 for the story Day of the Daleks. This composite prop is known as Dalek One-5. A couple of seasons later, the shoulders were paired with the skirt belonging to Dalek 7 for the Daleks’ last outing with Jon Pertwee’s Doctor, Death to the Daleks. This composite prop is known as Dalek One-7.
With the details from Dalek 6388 added to our dataset we now have something that resembles a supply chain traceability scheme – another excellent use for Neo4j. Here’s how some of that data is structured (click the image for a closeup view):
The screenshot above shows some of the Dalek prop data as viewed in Neoclipse. Neoclipse allows you to view, create and edit nodes, as well as search any indexes you’ve created for your store. Neo4j’s browser-based Webadmin tool also includes a visualisation tab for viewing a database running in server mode.
The screenshot above show three of the stories in which the Daleks appeared: The Daleks, The Dalek Invasion of Earth and The Power of the Daleks. (They’ve appeared in many more stories – the view here shows only a fraction of the data we have. Even here I’ve only shown full details of the props for one of the stories, The Power of the Daleks. Portions of the data associated with the other two stories are then included to show how the data is interconnected.)
Below each story node is a node representing the group of Dalek props used in that story. I’ve chosen to create these group nodes because there is potentially other data to be included at the group level. For example, each story was assigned a budget for building or maintaining the props used in that story. Moreover, in the research, the voice artists and operators responsible for bringing the Daleks to life are not associated with individual props but with the group as a whole (the details of the voice artists and operators are not, however, currently in our dataset). Hence the Dalek props group nodes
USED_IN each story.
Focusing now on the props used in The Power of the Daleks, we can see that four props appeared in the story: Dalek 1, Dalek 2, Dalek 7, and Dalek Six-5. Daleks 1 and 2 also appeared in the two earlier stories, The Daleks and The Dalek Invasion of Earth (together with some other props not shown here), as well as in several other stories not shown in the screenshot. Daleks 7 and Six-5 are here not associated with any other stories, but in the full dataset, Dalek 7 is shown to have appeared in two other stores, The Evil of the Daleks and The Chase, while Dalek Six-5 appeared in four other stories following its debut in the The Power of the Daleks.
Dalek Six-5 is one of those composite props I mentioned previously. It is
COMPOSED_OF shoulders whose
ORIGINAL_PROP was Dalek 6, and a skirt originally made for Dalek 5. The shoulders, as the graph in the screenshot shows, appeared as part of at least one other composite prop, Dalek Six-7, where they were paired with the skirt belonging to Dalek 7, which also appears in The Power of the Daleks. Dalek Six-5‘s skirt, whose
ORIGINAL_PROP was Dalek 5, was at some other time paired with the shoulders from Dalek 1 to create the composite prop Dalek One-5. (To find out which story Dalek One-5 appeared in, all we’d have to do is expand the graph beyond the nodes shown here.)
The Dalek prop data captures many of the significant domain concepts and relationships described in the Dalek 6388 research. Once we’d built the dataset, I set about asking it some tricky questions. At the top of my list of pressing questions was this one: what’s the hardest working Dalek prop part in showbiz? That is, which of those shoulders and skirts has appeared in more stories than any other part?
Neo4j offers several different ways to query a graph. There’s the Core API, which allows you to deal imperatively with nodes and relationships, and the original Traverser API, which offers a slightly more declarative route into a graph. For more sophisticated traversals there’s the Traversal Framework, which, being more powerful than the Traversal API, has a slightly steeper learning curve. For querying the server there’s the REST API. Next, there’s Gremlin, a powerful graph traversal language with a plugin for Neo4j, and the Pattern Matching library, which is like a regex language for graphs. And finally, introduced in the latest 1.4 milestones, there’s Cypher, a new declarative graph pattern matching language – a SQL for graphs.
In the rest of this post we’ll look at three different ways of figuring out which was the hardest working Dalek prop part. In the first example we’ll look at the Traversal Framework. In the next we’ll use the Pattern Matching library. Finally, we’ll use Cypher.
There’s quite a bit of code here. If you haven’t the patience to wade through it all, do just one thing: go look at the Cypher query. It’s a thing of Dalek-like precision.
Here’s what the query to find the hardest working Dalek prop part looks like using the Traversal Framework:
@Test public void shouldFindTheHardestWorkingPropsUsingTraversalFramework() { Node theDaleks = database.index().forNodes("species") .get("species", "Dalek").getSingle(); Traverser traverser = Traversal.description() .relationships(Rels.APPEARED_IN, Direction.OUTGOING) .relationships(Rels.USED_IN, Direction.INCOMING) .relationships(Rels.MEMBER_OF, Direction.INCOMING) .relationships(Rels.COMPOSED_OF, Direction.OUTGOING) .relationships(Rels.ORIGINAL_PROP, Direction.OUTGOING) .depthFirst() .evaluator(new Evaluator() { @Override public Evaluation evaluate(Path path) { if (path.lastRelationship() != null && path.lastRelationship().isType(Rels.ORIGINAL_PROP)){ return Evaluation.INCLUDE_AND_PRUNE; } return Evaluation.EXCLUDE_AND_CONTINUE; } }) .uniqueness(Uniqueness.NONE) .traverse(theDaleks); assertHardestWorkingPropParts(getSortedResults(traverser), "Dalek 1 shoulder", 12, "Dalek 5 skirt", 12, "Dalek 6 shoulder", 12); }
This example shows an idiomatic usage of the Neo4j Traversal Framework. First, we lookup a starting node for the traversal in an index. In this instance, we look up the Dalek species node. Then we build a traversal description and execute the traversal from this starting node. The traversal crawls the subgraph below the starting node. With each node that it visits, it calls the
evaluate() method on the custom evaluator supplied with the description. This method determines whether the traverser is positioned over a node of interest (in this case, an original prop node). If it is, the traverser returns the path to this node to the calling code, and then begins a new travesal further up the subtree. If it isn’t a node of interest, the traverser continues deeper into the subgraph.
The description specifies the types of relationship we’re prepared to follow, and their direction. Every relationship in Neo4j has a type label and a direction. The direction helps provide semantic clarity when dealing with asymmetric relationships between nodes. While a relationship between two nodes is always directed – it has a start node, a direction, and an end node – a traverser can be programmed to follow either an
INCOMING or an
OUTGOING relationship, and even to ignore the direction entirely (using
Direction.BOTH).
Note that we’ve specified that the traversal proceed depth first. This means that from the Dalek species node it will strike out on a depth first hunt for an original prop, following the first
APPEARED_IN relationship to an episode and then searching the nodes below that episode. Once it has found a first matching original prop, the traverser returns the path to the prop to the calling code (
INCLUDE_AND_PRUNE), and then moves successively back up that path, trying alternate branches, until it works its way all the way back to the species node, from where it tries the next
APPEARED_IN relationship.
Here’s the route the traverser takes from the starting Dalek species node through all the nodes below The Power of the Daleks:
Now that the traverser is back at the Dalek species node, it tries the next
APPEARED_IN relationship:
And so on.
When it’s run, our traverser will return all the paths from the Dalek species node to the original props nodes associated with each prop part. Each path contains all the details of the nodes and relationships along that path, starting with the Dalek species node and ending with the original prop node, with the relevant episode and prop part nodes somewhere in between.
By itself, the traverser result doesn’t tell us which prop part has been used the most; for that, we need to do some accumulation. To generate the counted and sorted results, our code calls
getSortedResults(), which is simply a helper method that delegates to a
ResultsAssembler instance. This
ResultsAssembler is responsible for accumulating the results for each prop part.
Here’s the
getSortedResults() method:
private Map<String, Integer> getSortedResults(Traverser traverser) { Map<String, Integer> results = new ResultsAssembler<Path>(traverser) .sortResults(new PathAccessor()); return results; }
And here is the code for the
ResultsAssembler:
public interface QueryResultAccessor<T> { String getOriginalProp(T queryResult); String getPart(T queryResult); } public class ResultsAssembler<T>{ private final Iterable<T> queryResults; public ResultsAssembler(Iterable<T> queryResults) { super(); this.queryResults = queryResults; } public Map<String, Integer> sortResults(QueryResultAccessor<T> accessor){ Map<String, Integer> unsortedResults = new HashMap<String, Integer>(); for (T queryResult : queryResults){ String originalProp = accessor.getOriginalProp(queryResult); String part = accessor.getPart(queryResult); String key = originalProp + " " + part; if (!unsortedResults.containsKey(key)){ unsortedResults.put(key, 0); } unsortedResults.put(key, unsortedResults.get(key) + 1); } Comparator<String> valueComparator = Ordering.natural() .onResultOf(Functions.forMap(unsortedResults)) .reverse().compound(Ordering.natural()); return ImmutableSortedMap.copyOf(unsortedResults, valueComparator); } }
The
ResultsAssembler builds a map of prop part keys and episode count values. The assembler uses a
QueryResultAccessor to retrieve the original prop name and prop part from a query result. Here the query result is a path, but when we get round to the next example, which uses the Pattern Matching library, it’s a pattern match object. Hence the generic parameters.
Here’s the
PathAccessor we use to access the original prop name and prop part from a path. The original prop details are held in the last node in the path, while the prop part details are held in the penultimate node. The
getOriginalProp() method can retrieve the original prop details quite easily from the path’s
endNode() property. To get the part name (shoulders or skirt) the
getPath() method uses the path’s
nodes() iterator and an iterator helper function to access the last but one node.
private class PathAccessor implements QueryResultAccessor<Path>{ @Override public String getOriginalProp(Path queryResult) { Node originalPropNode = queryResult.endNode(); return getPropertyValueOrNull(originalPropNode, "prop"); } @Override public String getPart(Path queryResult) { Iterable<Node> pathNodes = IteratorUtil.asIterable( queryResult.nodes().iterator()); Node partNode = IteratorUtil.fromEnd(pathNodes, 1); return getPropertyValueOrNull(partNode, "part"); } private String getPropertyValueOrNull(Node node, String property){ if (!node.hasProperty(property)){ return null; } return node.getProperty(property).toString(); } }
Having accumulated and sorted the results, our unit test can then assert that the results contain the top three most used prop parts: Dalek 1‘s shoulders, Dalek 5‘s skirt, and Dalek 6‘s shoulders. Each of these parts appeared in 12 stories.
What do Dalek 1‘s shoulders look like today, nearly 50 years after they first appeared on TV? Dalek 6388, of course, has the answer.
The Traversal Framework helped us find the hardest working Dalek prop parts in showbiz, but we still had to do quite a bit of work to accumulate the results. While the traversal description itself was relatively trivial, having to iterate nodes in each of the returned paths proved quite tedious. With the Pattern Matching library we can avoid some of the messy iterative code that cropped up in the
PathAccessor.
Using the Pattern Matching library we create an abstract subgraph that describes the graph patterns we want to match in our real graph. When matching, we anchor this abstact graph to a starting node in the real graph, much as we started the traversal in the previous example from a node we’d looked up in an index. The matcher then matches subgraph instances corresponding to the nodes, relationships and constraints defined in our abstract subgraph.
@Test public void shouldFindTheHardestWorkingPropsUsingPatternMatchers(){ Node theDaleksNode = database.index().forNodes("species") .get("species", "Dalek").getSingle(); final PatternNode theDaleks = new PatternNode(); final PatternNode episode = new PatternNode(); final PatternNode props = new PatternNode(); final PatternNode prop = new PatternNode(); final PatternNode part = new PatternNode(); final PatternNode originalProp = new PatternNode(); theDaleks.setAssociation(theDaleksNode); theDaleks.createRelationshipTo(episode, Rels.APPEARED_IN); props.createRelationshipTo(episode, Rels.USED_IN); prop.createRelationshipTo(props, Rels.MEMBER_OF); prop.createRelationshipTo(part, Rels.COMPOSED_OF); part.createRelationshipTo(originalProp, Rels.ORIGINAL_PROP); PatternMatcher pm = PatternMatcher.getMatcher(); final Iterable<PatternMatch> matches = pm.match(theDaleks, theDaleksNode); assertHardestWorkingPropParts(getSortedResults(matches, originalProp, part), "Dalek 1 shoulder", 12, "Dalek 5 skirt", 12, "Dalek 6 shoulder", 12); }
The pattern node objects that we define as part of our abstract subgraph can then be used as keys into the match results. Below is the
getSortedResults() method and
MatchAccessor class for the pattern matching example. You’ll notice that we pass the
originalProp and
part pattern node objects into the
MatchAccessor. The accessor then calls the match’s
getNodeFor() method with one or other of these pattern nodes in order to retrieve the real, matched node.
private Map<String, Integer> getSortedResults(Iterable<PatternMatch> matches, PatternNode originalProp, PatternNode part) { Map<String, Integer> results = new ResultsAssembler<PatternMatch>(matches) .getSortedResults(new MatchAccessor(originalProp, part)); return results; } private class MatchAccessor implements QueryResultAccessor<PatternMatch>{ private final PatternNode originalProp; private final PatternNode part; public MatchAccessor(PatternNode originalProp, PatternNode part) { super(); this.originalProp = originalProp; this.part = part; } @Override public String getOriginalProp(PatternMatch queryResult) { return queryResult.getNodeFor(originalProp).getProperty("prop").toString(); } @Override public String getPart(PatternMatch queryResult) { return queryResult.getNodeFor(part).getProperty("part").toString(); } }
The Pattern Matching example still required us to accumulate the results in order to work out which was the hardest working prop part in the original series. The abstract pattern nodes provided convenient keys into matched nodes, but we still had then to pass the matched nodes’ contents to the
ResultsAssembler in order to build a map of prop parts and usage counts. With Cypher, all that manual accumulation disappears. Better still, the entire query is expressed using a very simple, declarative syntax. Unencumbered by a “fluent” interface, a Cypher query concisely describes our desired route into the graph:
public void shouldFindTheHardestWorkingPropsUsingCypher() throws Exception { CypherParser parser = new CypherParser(); ExecutionEngine engine = new ExecutionEngine(universe.getDatabase()); String cql = "start daleks=(Species,species,'Dalek')" + " match (daleks)-[:APPEARED_IN]->(episode)" + "<-[:USED_IN]-(props)" + "<-[:MEMBER_OF]-(prop)" + "-[:COMPOSED_OF]->(part)" + "-[:ORIGINAL_PROP]->(originalprop)" + " return originalprop.prop, part.part, count(episode.title)" + " order by count(episode.title) desc" + " limit 3"; Query query = parser.parse(cql); ExecutionResult result = engine.execute(query); assertHardestWorkingPropParts(result.javaIterator(), "Dalek 1", "shoulder", 12, "Dalek 5", "skirt", 12, "Dalek 6", "shoulder", 12); } private void assertHardestWorkingPropParts( Iterator<Map<String, Object>> results, Object... partsAndCounts) { for (int index = 0; index < partsAndCounts.length; index = index + 3){ Map<String, Object> row = results.next(); assertEquals(partsAndCounts[index], row.get("originalprop.prop")); assertEquals(partsAndCounts[index + 1], row.get("part.part")); assertEquals(partsAndCounts[index + 2], row.get("count(episode.title)")); } assertFalse(results.hasNext()); }
Most of that is just boilerplate code for setting up the Cypher engine and executing the query. The really concise part is the query itself. Here it is in full:
start daleks=(Species,species,'Dalek') match (daleks)-[:APPEARED_IN]->(episode)<-[:USED_IN]-(props)<-[:MEMBER_OF]- (prop)-[:COMPOSED_OF]->(part)-[:ORIGINAL_PROP]->(originalprop) return originalprop.prop, part.part, count(episode.title) order by count(episode.title) desc limit 3
Spend a couple of moments looking at it and you’ll soon appreciate its simplicity and declarative expressiveness. If only the Daleks had such power…
Cypher is still in its infancy, and its syntax is still in flux. In the 1.4 release timeframe, which culminates this week with the release of Neo4j 1.4 GA, Cypher performs only non-mutating operations. Over the course of the 1.5 release, we expect to add mutating operations.
Our Neo4j tutorial is freely available from GitHub. Download it now and try some of the exercises. And keep checking back for updates: as Neo4j grows, so will the tutorial.
Jim and I are also running one- and two-day versions of the tutorial at a number of conferences and other events:
(Dalek prop image belongs to the Project Dalek Forum gallery, another excellent resource for Dalek prop researchers and Dalek builders.)]]>
Last Friday (May 6th) marked a watershed in my career, being the day I left ThoughtWorks to join Neo Technology.
ThoughtWorks has been my professional home for over seven years; its technical excellence, together with its cultural and professional attitudes, are deeply imbued in my approach to software development. I leave behind many good friends, a new generation of technical leaders, and a company whose focus on the entire value stream of software delivery will continue to reinvigorate and challenge the industry for a long time to come.
But what a company to move on to! Neo Technology is prominently stationed at the most exciting extreme of the NoSql spectrum; its graph database, Neo4j, tackles the complexity inherent in a densely connected information universe head on. As a fit for my interests in data, its representation, and the meaning that can be extracted from pursuing the many intricate relationships between connected entities (an interest that goes all the way back to my building a hypertext system while doing postgraduate research), it can’t be bettered. On top of that, it’s a friendly, welcoming company built on innovation and deep technical excellence. I’m incredibly pleased and proud to join such an awesome team.
With the delightful title ‘Director of Customer Success’ (how I’m tempted to add an exclamation mark to that…), I’m responsible for ensuring our customers get the very best value from Neo and its technologies. It’s a wide-ranging remit; one that I’ll be rounding out in more detail over the next few weeks. In the meantime I’ll be meeting some of our customers from around the world, and diving into the code to better understand the inner workings of the database. Perhaps I’ll meet some of you at the next Neo4j User Group meetup in London on May 31st. And if you’re interested in learning more about Neo4j and/or love Doctor Who and want to explore its universe in more depth, look out for the day-long tutorials that Jim Webber and I will be running throughout the rest of this year (with the first at UberConf in Denver, July 12-15).]]>
The ThoughtWorks Technology Radar for Jan 2011 is now out. This issue we focus on:
The Radar helps decision makers understand emerging technologies and trends that affect the market today. It’s written by the ThoughtWorks Technical Advisory Board, which meets regularly to discuss the global technology strategy for ThoughtWorks and the technology trends that significantly impact our industry.]]>
The deadline for submitting papers for WS-REST 2011 has been extended to 10 February 2011. If you haven’t already submitted a paper, now’s your chance.
Papers must be submitted electronically in PDF format. Templates are available here
Easychair page:
WS-REST Web site:
WS-REST Twitter:
WS-REST Email: chairs@ws-rest.org
I’m going to be giving variations on my RESTful domain applications talk at JFokus in Stockholm, Feb 14-16, and JAX London, April 11-13. Come along to find out all about domain application protocols: what they are, why they’re important (and implicit in almost every application, irrespective of whether we’ve given them any thought or not), and how we can implement them in a RESTful application without having to import a specific process description into the client part of the app.
I’ll be building on some of this material at QCon London (March 9-11), but there I’ll go deeper into some implementation specifics, with examples drawn from some recent work with Microsoft’s new WCF HTTP libraries. (The QCon REST track has a particularly stunning lineup.) Also as part of QCon London, Jim Webber and I will be running our day-long REST in Practice tutorial.
You can register for QCon here. When doing so, use the ROBI100 promotional code. This gives you a £100 discount; at the same time, QCon will donate £100 to the Crisis Charity in London (the national charity for single homeless people).]]> | http://feeds.feedburner.com/iansrobinson | CC-MAIN-2016-40 | refinedweb | 7,218 | 53.92 |
Building an Arduino Robot, Part II: Programming the Arduino
Welcome to the second article in the tutorial series in which I'm building a remote controlled Arduino based vehicle robot.
Here is the list of articles I have published:
- Part I: Hardware Components
- Part II: Programming the Arduino (this article)
- Part III: Assembling the Robot
- Part IV: A (Not So) Basic Robot Firmware
- Part V: Avoiding Obstacles
- Part VI: Remote Control
In the previous article I introduced you to my project. I showed you the parts I bought and what features I wanted to implement in my little remote controlled robot vehicle.
Today I will introduce you to the programming side of my project. This is a pretty long article that is heavy in information that can be applied to most Arduino projects. By the end of it you will know the basics of programming sensors, motors and other devices connected to the Arduino, and will also have an understanding of how a wireless remote controller can communicate with the Arduino board over Bluetooth. I encourage you to get the parts I listed in the previous article and try these tests along with me.
The Arduino Pins
The Arduino board communicates with connected devices via its input and output pins, so I'll quickly go over what these pins are.
Here is a diagram of a typical Arduino board.
On the left side you have the USB port (grey box) and the power input jack (black box). During testing I will be powering my Arduino with a USB cable, but the final robot will receive power from a battery box connected to the power input jack.
On the top, from right to left there are 14 pins labeled
0 to
13. These are the digital pins. These pins can be individually configured as inputs or outputs, meaning that digital data can be read or written from connected devices on these pins. Since these pins are digital, they have only two possible states,
HIGH and
LOW.
Some of the digital pins have preassigned functions. Pins 0 and 1 are also labeld
RX and
TX respectively. These are used by the serial communication hardware to send and receive data. Pin 13 has a LED attached to it on most Arduino boards, so it is a convenient pin to send simple visual information out to the real world. The pin 13 LED is located below the pin 13 itself, labeled with the letter
L in the diagram above. Pins 3, 5, 6, 9, 10 and 11 are marked with a
~ or a
PWM label, short for pulse width modulation. These pins are capable of producing simulated analog output over a digital line. These can be used, for example, to light a LED at different levels of intensity.
The next pin on the top from right to left is
GND, short for ground. The ground is what closes a circuit and allows the electric current to flow uninterrupted. Connected devices can connect their own GND pin here.
The next pin on the top left is labeled
AREF, short for analog reference. This pin is rarely used, it tells the Arduino how to configure the voltage range of the analog pins.
Some Arduino boards have more pins to the left of
AREF. Since these are not in all boards I will not discuss them here.
On the bottom right we have six pins labeled
0 to
5. These are the analog input pins. Unlike the digital pins which have only two possible states, an analog pin can have 1024 possible states, according to the voltage applied to it. Typically the voltage range goes up to 5V, but the range can be changed by applying the desired maximum voltage to the
AREF pin. Also unlike the digital pins which can be configured as inputs or outputs, the analog pins can only be inputs.
An interesting property of the analog pins is that they can be used as digital pins as well, with pin numbers 14 to 19. You will see later that an important part of any project is allocating pins to components. If you are running short of digital pins keep in mind that you have six more available to you.
Continuing on the bottom from right to left we find a pin labeled
VIN. This pin provides direct access to the voltage provided by the power supply. So for example, if you power your Arduino with a 9V power supply through the power jack, then this pin gives you 9V.
The next two pins are labeled
GND and are two more ground pins, exactly like the one in the top row. They are here just for convenience.
The next two pins are labeled
5V and
3.3V and just return those voltages, regardless of what the voltage of the power supply is.
Next we have the
RESET pin. When this pin is connected to
GND the board will reset. So this is a handy pin to build an external reset button.
As with the top row of pins, some boards have a more pins on the bottom left that I will not cover here. If you are interested in finding out what extra pins in your board do you should consult the documentation for your board.
Programming the Arduino with Sketches
By now you are probably wondering how can you make the Arduino do things.
The easiest way to program the board is with the Arduino software, which is free and open source, and available for Windows, Mac OS X and Linux users.
Here is a screenshot of the Arduino software:
The white area is where the program is written. The programming language that the Arduino platform uses is called C++ (pronounced see plus plus), a language that is regarded as very powerful but difficult to learn. I will try to explain the basics of C++ in this and the following articles, but I will not cover C++ programming in detail. If you have any specific C++ programming questions I'll be happy to address them in the comments at the bottom.
C++ programs are written as regular text. Arduino calls these programs Sketches. Then a utility called compiler reads the sketch and converts it to machine instructions that the Arduino understands.
The black area at the bottom of the Arduino software window is where status information appears. For example, if your C++ code has an error this is where you will see the details.
The Arduino software also has a toolbar, with the following buttons (in order, from left to right):
- Verify: Runs the C++ compiler on your program. If there are any errors you will see them in the black status area.
- Upload: Compiles your C++ program like the Verify button does, and if compilation is successful it uploads the resulting program to the Arduino board, which must be connected to the computer through the USB port.
- New: Clears the program currently loaded.
- Open: Shows a dropdown with a long list of example programs to load or the option to load a sketch from disk.
- Save: Saves the current program to a file on disk.
- Serial Monitor: Opens the serial monitor console. This is used mostly for debugging, as I will show in a little bit.
"Hello, world!", Arduino style
To begin, let's write a very simple program that writes a message to the serial port. We will see this message in the Serial Monitor.
I assume you will be doing this with me, so please follow along.
First install the Arduino software. Installation instructions are very simple, you should not have any trouble with this step.
Start the Arduino software making sure the Arduino board is not connected to your computer. Open the Tools menu, then the Port submenu. Take note of the options that appear here and then close the Arduino software.
Next connect your Arduino board to your computer using the USB cable. If you are doing this on Windows, then see this page for instructions on how to install the Arduino board drivers. If you are on Windows 8, also see this page for information on how to bypass the requirement for signed drivers. Mac and Linux users are lucky and do not need to install any drivers.
With the Arduino board connected, launch the Arduino software again. In the Tools menu open the Board submenu and make sure the correct model of Arduino board is selected. Then in the Port submenu find the serial port entry that did not appear in the list when you had the Arduino board disconnected. That's the serial port that is assigned to the Arduino connection, so select that one.
Then in the white area type (or copy/paste) the following C++ program:
void setup() { Serial.begin(9600); } void loop() { Serial.println("Hello, world!"); delay(1000); }
Press the Upload button to compile and upload the sketch to the board. If you made any mistakes they will be indicated in the black status area. At this point the errors will look very cryptic if you are not used to programming in C++, so the best you can do is compare what you typed against the above and fix any differences you find until the upload operation succeeds.
If the Upload is successful the status area will show a message similar to the following:
Binary sketch size: 1,978 bytes (of a 32,256 byte maximum)
At this point the program is running inside the Arduino. You will notice that the LED labeled
TX blinks every once in a while, indicating the Arduino board is transmitting data through the serial port.
To see the data click on the Serial Monitor button in the toolbar. At the bottom right of the serial monitor window make sure the drop-down is set to
9600 baud. You should now see the message
Hello, world! printing in the window every second.
Congratulations, you've completed your first Arduino sketch!
I'm sure you want to understand a little bit how this sketch works, so let me give you some information.
Arduino sketches have two main functions, called
setup and
loop. When the program starts it will execute the
setup function. This function is supposed to initialize the hardware and get it ready for operation. Then the
loop function will be called repeatedly until the Arduino is reset or powered off. If you look at the code above you will see these two functions, each starting with the word
void followed by the function name, and ending with a closing curly bracket.
What goes before the opening curly bracket is called the declaration of the function. What goes in between the opening and closing curly brackets is the actual code of the function, or in other words, the instructions that the Arduino executes when the function is invoked.
In this small example the
setup function initializes the serial interface by calling the
Serial.begin function. What goes in between the parenthesis are called arguments, and each function defines what arguments it needs, if any. The
Serial.begin function requires the speed of the serial communication to be given as an argument, in baud units. I selected 9600 bauds in this example. The statement ends with a semicolon, this acts as a statement separator.
Now how do you know what functions you can use in your sketches?
That's what the Arduino reference is for. This page has a quick reference for C++ and the list of all the functions that are provided by the Arduino development environment.
For example, let's say you want to know all the functions related to serial port communications. Then you can open the Serial link under the Communications section. You will find the
begin function I used above listed there. Note that outside of any context the function is called
Serial.begin, but when the context is clearly in the
Serial class, then it is enough to call the function
begin. If you now wanted to see information about the arguments required by the
Serial.begin function you just click on it to go to the Serial.begin documentation.
The Arduino reference documentation is very good so I recommend you keep it open in a browser window at all times when you are writing sketches.
Let's go back to our example. The second function is the
loop function. This function makes two function calls. First it calls
Serial.println, passing the message
"Hello, World!" as an argument. As you can guess, the
Serial.println function prints a message to the serial port. The message is given as a character string, within double quotes. The function is called
println and not
The second and last instruction in the
loop function is a call to a function called
delay. This function pauses the program for the amount of time specified as an argument. The units of time are given as milliseconds, so I'm passing the value
1000 to pause the program for one second.
Since the
loop function is invoked repeatedly, the result of this program is that the text
Hello, world! is printed to the Serial Monitor every second.
Working with LEDs
Let's look at an improved version of the previous sketch:
void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { Serial.println("Hello, world!"); digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500); }
Enter the code above in the code window of the Arduino software replacing the old sketch and upload it to your board to test it.
If you understood the first sketch then you can probably figure out what this version does easily.
In the
setup function in addition to initializing the serial port like before I'm also initializing pin 13 as an output pin. Recall that digital pins can be used as inputs or outputs, so whenever you need to use a pin you have to configure it for the intended use. In this case I'm making it an output pin, which means that I can write a value to this pin, and the value I write will affect the electrical current coming out it. See the
pinMode documentation for details on this.
The
loop function prints the message to the serial port like before, but then sets pin 13 to a
HIGH state with the
digitalWrite function. In most Arduino boards this lights the on-board LED. Then the program pauses for 500 milliseconds, or half a second. Then the state of pin 13 is changed to
LOW to turn the LED off. Then the program sleeps for another half a second.
The
loop function is called over and over again, so what the above code does is make the LED blink! It blinks at a rate of one blink per second, staying on for the first half second, then off for the other half.
Programming the Distance Sensor
Now you know how to do the basic stuff that appears in every Arduino introductory tutorial. Are you ready to do something real with your Arduino? I hope you are!
I'm going to show you how to program the HC-SR04 distance sensor. Recall that I will be using this sensor to help my robot "see" and avoid walls and obstacles.
For most devices that connect to the Arduino board there are already appropriate libraries of functions incorporated into the Arduino software. You can see what libraries are included by going to the Sketch menu, "Import Library..." submenu. You will see libraries there for motors, LCDs and a variety of other devices.
Unfortunately there is nothing for distance sensors. So how can one control such a device?
In most cases manufacturers of Arduino compatible devices provide the required libraries to control their products. Other times developers write their own libraries and make them available as open source. The documentation of the device is the first place to go, but as always in cases like this, Google is your best friend.
Searching around I've found not one but three open source Arduino libraries for my distance sensor, here, here and here. I quickly reviewed them and out of the three the arduino-new-ping library appeared to be the most complete, so I decided to give that one a try first. If that one does not work I can always go get one of the other two.
The library comes in a zip file, available as a download link in the page linked above. To install it and make it available in the Arduino software you just need to unzip it and copy the top folder (called
NewPing) inside the
libraries folder in your Arduino sketches folder. The Arduino sketches folder is in your home directory, see the documentation for details.
After you install the NewPing library close and reopen the Arduino software so that it can recognize it.
Now start a new sketch, go to the Sketch menu and select "Import Library...". You should now see
NewPing in the list. If you select this library the following line will be added to your sketch:
#include <NewPing.h>
This is telling the C++ compiler that you will be using the functions from the NewPing third party library. Note that you don't have to go through the menus to get this text written for you, if you prefer you can write it yourself.
Before I show you the sketch that controls the distance sensor take a look at the following wiring diagram:
As you see in the diagram I'm using the breadboard and some jumper cables to make all the connections.
First I connected the
5V output from the Arduino to the "red" side of the top section of the breadboard, and the
GND line to the "blue" side. The top and bottom sections of the breadboard have "red" and "blue" sides, and these are typically used to distribute power and ground lines to the whole breadboard. Plugging the
5V output to one of the red pins makes the 5V available to all the red pins in that row, and likewise, connecting
GND to a blue pin makes GND available in all the blue pins in the row.
Next I transferred the
5V and
GND lines to the bottom part of the breadboard with two more jumper cables. This is always a good practice when prototyping, setting up the breadboard like this ensures that you can always grab your power and ground lines from the side that is most convenient.
The distance sensor plugs nicely into four consecutive pins in the middle of the breadboard. The two middle sections of the breadboard connect groups of five vertically aligned pins together, so to make a connection to one of the sensor pins I just plug one end of the jumper cable into any of the remaining four pins in the same group.
The leftmost pin is labeled
VCC, this is the pin that should be connected to the
5V line. So to do that I connect a jumper cable to this pin from the sensor to one of the red pins in the breadboard bottom. The next two pins are labeled
Trig and
Echo. These connect to any two available pins in the Arduino board. Since any pins will do, I will be using analog pins 0 and 1, which as I said before can double up as digital pins 14 and 15. The rightmost pin is labeled
GND, so the connection can go to any of the blue pins at the top or bottom of the breadboard.
Here is an actual picture of how this circuit looks in real life:
So far it's been pretty easy, right?
Let's see what the sketch looks like:
#include <NewPing.h> #define TRIGGER_PIN 14 #define ECHO_PIN 15 #define MAX_DISTANCE 200 NewPing DistanceSensor(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); void setup() { Serial.begin(9600); } void loop() { unsigned int cm = DistanceSensor.ping_cm(); Serial.print("Distance: "); Serial.print(cm); Serial.println("cm"); delay(1000); }
There are a couple new things in this sketch that I haven't used in the previous ones, but overall things are largely similar.
The
#include statement at the top tells the C++ compiler that I will be using a third party library. The
NewPing.h between the angle brackets refers to a header file that is inside this library. This file contains the definitions for all the functions provided by the library. If a library does not have documentation, chances are there is information at the top of this file.
Next there are a few
#define lines. If you recall the LED blinking sketch from above, I have written the pin number 13 in a couple of places there. Instead of using the number directly I could have defined a constant. That's what
#define does. You use it to give a value a meaningful name, then in the rest of the sketch you can write the name instead of the value. This is useful to make the code more readable, but also makes it very easy to change the pin assignments, because then you just go to the top of the sketch and update the numbers in just one place.
In this sketch we have three
#define statements. The first two create constants for the
Trig and
Echo pins of the distance sensor which I connected to pins 14 and 15 respectively (analog pins 0 and 1). The third
#define is to set a constant for the maximum distance that I want the sensor to recognize, which I set to 2 meters, using centimeter units.
Next we have the following statement:
NewPing DistanceSensor(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
This statement creates an object that represents the distance sensor. The syntax for object creation requires the class of the object first (
NewPing in this case), then the name I want to give the object (
DistanceSensor) and then any arguments enclosed in parenthesis. The arguments that the NewPing object requires are the trigger pin, the echo pin and the maximum distance to consider, all in that order and separated with commas. These happen to be the three constants defined above, so I can write the names instead of the values.
Note that the object is created outside of any functions. Objects can exist only at the level they are created, so creating the object inside the
loop function would make it disappear when that function ends. The next time
loop is called a new object would be created and initialized, which would be a waste of time and effort. Putting the object creation outside of any functions makes it a global object that persists across function calls.
The
setup function is exactly like the one I used before, it just sets up the serial communication so that we can see output from the Arduino board in the Serial Monitor.
The
loop function starts with a type of instruction that I haven't used before:
unsigned int cm = DistanceSensor.ping_cm();
Let's analyze this statement one piece at a time. To the right of the
= sign I am invoking a function called
ping_cm provided by the
DistanceSensor object created above. This function is slightly different than functions I used before, because in addition to doing something it returns a result, which in this case is the distance to the closest object measured in centimeters.
Since I intend to use this distance result later in the sketch I have to store it somewhere, so to the left of the
= sign I have created a variable, which is basically a space in memory where a value can be stored. The C++ syntax for variable creation requires me to provide the type of values this variable will store first (
unsigned int in this case, a positive integer) and then the variable name, which is any name of my choosing that I will use later to refer to the value stored in the variable.
As a side note, the distance sensor library documentation indicates that there is also a
ping_in function that is equivalent to
ping_cm but returns the distance result in inches. Another option provided by the library is a function
ping, which just returns the time it took the ultrasonic signal to make a round trip back to the sensor in microseconds. You can then divide this time by the time it takes sound to travel twice the distance units of your choice to get the distance in those units. For my purposes having the distance in centimeters is accurate enough.
Next in the
loop function I have three consecutive prints to the serial port. The first two prints use the
Serial.print function and the last uses
Serial.println. That means that the second and third prints will go to the same line as the first, and after the third message is printed the cursor will move to the next line.
The first and last print statements print text messages like in the previous sketches. The middle print, however, prints the
cm variable, in which I have the result of the distance sensor
ping_cm function.
The final line in the
loop function does a
delay of one second, exactly like before.
When you run this sketch on your board and move your hand or some other object closer and farther away from the sensor you will see something like this in the serial monitor:
Distance: 28cm Distance: 28cm Distance: 21cm Distance: 18cm Distance: 15cm Distance: 15cm Distance: 12cm Distance: 12cm Distance: 24cm
Fun with motors
Let's move on to something else. The vehicle kit that I'm using for my project comes with two wheels, each with an attached motor.
The motor driver board that I have is the Adafruit Motor Shield, which comes with its own library, called AF_Motor. If you are using the same motor controller then go ahead and install this library in your Arduino environment. If you are using a different motor controller then you'll have to find the library that works for your hardware.
Most motor controllers come as a shield, which means that the motor board plugs right on top of the Arduino board, connecting to both rows of pins, even though many of the pins are not used to control motors. The nicer motor shields provide pass-thru headers with access to all the Arduino pins. Unfortunately the Adafruit shield does not give access to the pins, so connecting additional components becomes difficult. This is a problem I'll have to work around.
The Adafruit motor controller can drive up to four DC motors, labeled M1 through M4 in the board. I need just two, so for convenience I'm going to connect my two motors one on each side of the board, using the M1 and M3 connectors.
To test the motors on the assembled kit I turned it upside down, so that I can see the wheels turn without the vehicle moving while the Arduino is connected to the USB power. The motor connections are extremely simple, each motor has just two connections:
The Arduino board is hidden underneath the motor shield in this picture.
Here is the sketch that I used to test the motors:
#include <AFMotor.h> AF_DCMotor Motor1(1); AF_DCMotor Motor2(3); void setup() { } void loop() { Motor1.setSpeed(255); Motor2.setSpeed(255); Motor1.run(FORWARD); Motor2.run(FORWARD); delay(1000); Motor1.run(BACKWARD); Motor2.run(BACKWARD); delay(1000); Motor1.run(FORWARD); Motor2.run(BACKWARD); delay(1000); Motor1.run(BACKWARD); Motor2.run(FORWARD); delay(1000); Motor1.setSpeed(0); Motor2.setSpeed(0); Motor1.run(BRAKE); Motor2.run(BRAKE); delay(1000); }
I don't think I need to explain every line in this sketch, since it does not have any new C++ constructs. Like the distance sensor, each motor requires an object to be created, this time one of class
AF_DCMotor. The only argument is the motor number, from 1 to 4. I created two motors, numbers 1 and 3 to match the motors connected to ports M1 and M3 of the controller.
The motors are controlled with two functions,
setSpeed and
run. The
setSpeed function takes a numeric argument with range 0 to 255, indicating the speed the motor should turn. The
run function configures the mode in which the motor runs, which can be
FORWARD,
BACKWARD,
BRAKE or
RELEASE.
The sketch above makes the wheels do a few tricks: one second of both wheels going forward, then one second of both wheels going backwards, then one wheel forward and the other backwards, then each wheel reverses direction, then the wheels stop for a second. Then the cycle repeats with the next invocation of the
loop function.
Remote Control over Bluetooth
The final piece of hardware that I intend to use in my Android robot vehicle is the Bluetooth slave, which connects to my smartphone to receive remote control commands.
I expected bluetooth communication would be the most complex aspect of my project, but after reading the one page documentation that came with my device I was proved wrong. Turns out the bluetooth slave works over the standard serial communication protocols in the Arduino board, which means you use the functions in the
Serial class like I used in all the previous sketches. When the Arduino board with Bluetooth is paired with a smartphone a
Serial.print command will send the data not to the PC but to the phone! The
Serial class also has functions to read data from the other end, so I will use these functions to receive commands from the smartphone.
The wiring of the bluetooth slave is pretty simple:
Note how the
RX and
TX pins in the Bluetooth slave go to digital pins 0 and 1 respectively, the pins that are dedicated to serial communications.
This is how my actual circuit looks like with everything connected, noting that in the picture below the Bluetooth dongle is facing the other side, so the connections appear reversed from the diagram above:
An example sketch that allows remote communication is below:
void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { if (Serial.available() > 0) { char ch = Serial.read(); Serial.print("Received: "); Serial.println(ch); if (ch == 'a') { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); } } }
The
setup function does not have anything I haven't done before. From reading it you can guess that I'm going to be playing with the pin 13 LED again.
In the
loop function I'm introducing a new type of C++ statement, the if statement, sometimes also called conditional. A conditional is useful when you want the program to do something only when a condition is true.
What follows after the
if keyword is the condition, enclosed in parenthesis. In my sketch the condition that I'm checking is
Serial.available() > 0. To know if this condition is true or not the Arduino will invoke the function
Serial.available, which returns the number of data bytes that have been received in the serial port, and compare that number against 0. If the number of available bytes is greater than 0 then the condition is true, so the instructions that are between the opening and closing curly brackets will be executed. If the condition is not true, then the whole group of instructions inside the curly brackets will be skipped.
Do you understand why a conditional makes sense in this case? The
Serial.available function will return a positive number only when the master on the other end of the serial communication has sent data. Saying
if Serial.available() > 0 in C++ is the same as saying "if there is data available" in English. If the condition is not true (which is the same as saying it is false), then it means that at that moment the remote controller has not sent any data, so in that case I have nothing to do and skip the whole thing.
So what happens when the condition is true?
The very first thing I do inside the
if block is read a byte from the serial port, using the
Serial.read function. Note that I use a variable to store the result, but this time I declared the variable with the type
char, which in C++ is the type that represents one byte of data.
Once I have my byte of data I print it, using our old friends the
println functions.
After I print the data received I have another conditional (note how I indent my sketch to make it very clear that I have one if statement inside another). This time my condition is
ch == 'a', which as I'm sure you guessed, will be true only when the lower case letter a is the data received. In that case I set pin 13 to HIGH, which turns the LED on.
The
else statement that follows is an extension to the
if. I said before that when the
if condition is false the instructions inside the curly brackets are skipped. When a conditional has both
if and
else blocks the condition determines which of the two blocks executes. If the condition is true the block that follows the
if executes and the block that follows the
else is skipped. If the condition is false the block that follows the
if is skipped and the block that follows the
else executes.
Do you see what this conditional does, then? When the Arduino receives an
a it will turn on the pin 13 LED. Any other data received will turn it off. With this simple sketch I built a remote control for the LED in the Arduino board!
When trying to upload this sketch to my Arduino I've found that often the upload failed. I believe this is a result of a collision between the serial communication established by the computer and the one from the Bluetooth slave. It appears that the Bluetooth slave wins and prevents the computer from talking to the Arduino. I have found that disconnecting the
RX and
TX pins from the Bluetooth slave when I need to upload a new sketch solves the issue.
Are you ready to try this?
Go ahead and install BlueTerm in your Android device. This app works exactly like the Serial Monitor from the Arduino software. I suppose there is an equivalent app for iOS, if you have found one that works please let me know in the comments below.
Update: It appears that nBlueTerm is an equivalent application for iOS devices, though I haven't had a chance to test it yet.
If you don't have a smartphone or the Bluetooth slave you can try this sketch using the serial communication to the computer and the Serial Monitor.
Once you have the app in your Android device and the sketch uploaded to the Arduino you are ready to go. Start by powering up the Arduino (via USB cable or power supply). The red LED in the Bluetooth slave will blink rapidly, indicating it is ready to pair with another device. Start BlueTerm in your smartphone and select "Connect Device" from the menu. The Bluetooth pairing window should appear and should show a device with name
linvor. Select this device to establish a connection. Use
1234 as pairing code.
Once the connection is established the LED in the Bluetooth slave goes steady, and on the smartphone you have a terminal like the one in the Serial Monitor. Any letters that you type are sent over to the Arduino, and the Arduino responds back with a message that confirms that it has received the same letter. When you type the lower case letter
a in addition to the above the LED in the Arduino board lights up. When you press any other key the LED goes off. Pretty cool, right?
Final words
I hope you found the information in this article useful. Please let me know if you have any questions below in the comments.
In the next article I'll be discussing a much lighter topic. I will show you how I mounted and connected all the hardware into the vehicle kit platform. Then after that I 'll show you how I developed the firmware for my robot from scratch!
As always, I thank you for being a loyal reader. I hope to see you next time!
Miguel
#1 F.Javier Fernandez said :
Very nice series of articles, clear explanation evev for beginners . Equivalent Bluetooth applivation for IOS is nBlueTerm, available free @ Appstore.
#2 Miguel Grinberg said :
@F.Javier: thanks for the tip!
#3 Markus said :
Hi Miguel Your guideline is verry helpful for me Im lookong forward for the next Part Regards Markus
#4 Dimitri said :
Such a detailed explanation! Thanks for spending your time on this project.
#5 salem said :
i cant believe that they are guys like you , who want to share their projects for free , what can i say . thank you thank you
#6 Bas15 said :
Thanks a lot It is wonderful,
#7 Chaminda Amarasinghe said :
Hi Miguel, Thanks. Very nice article
#8 Kevin said :
Hi - You recommend the Arduino Motor Shield R3, though, you article uses the Adafruit. I would like to use the Arduino MS R3 - can I use the AFMotor library? Thanks.
#9 Miguel Grinberg said :
@Kevin: Unfortunately the Adafruit motor shield is different than the Arduino one. To use the Arduino R3 shield you will need to write different code to control the motors, and you will not use the AFMotor library. The changes should be pretty simple though.
#10 sid said :
I am using arduino motor shield r3 and have written a code for the same with bluetooth module but i want to use ping sensor code also with it.I am totally new to this.how can i power both ping sensor and bluetooth from motor shield and how to write another program along with my motor shield and bluetooth code. | http://blog.miguelgrinberg.com/post/building-an-arduino-robot-part-ii-programming-the-arduino | CC-MAIN-2014-41 | refinedweb | 6,324 | 70.33 |
#include <atomic>
#include <future>
#include <thread>
Go to the source code of this file.
The interface to the operating system process and thread control primitives
Created 9/8/1995 Heikki Tuuri
Compares two thread ids for equality.
Return the thread handle.
The purpose of this function is to cast the native handle to an integer type for consistency
The thread sleeps at least the time given in microseconds.
Advises the OS to give up remainder of the thread's time slice.
Operating system thread native handle.
Returns the thread identifier of current thread.
Currently the thread identifier in Unix is the thread handle itself.
Set priority for current thread.
Set priority for current thread. | https://dev.mysql.com/doc/dev/mysql-server/latest/os0thread_8h.html | CC-MAIN-2021-10 | refinedweb | 114 | 60.21 |
Unanswered: store.getById too slow
Unanswered: store.getById too slow
Hi,
I need a faster search mechanism than iterating through all the records in the store by using store.getById(...).
I've looked at the code and tried to replace it with
Code:
Ext.override(Ext.data.Store, { getById: function (id) { return (this.snapshot || this.data).getByKey(id); } });
What can I do to search the store by id using a map?
Thanks,
Stevo
- Join Date
- Jul 2010
- Location
- Houston, Tx
- 9,154
- Vote Rating
- 475
- Answers
- 685
Is there no unique id field in the table?
Can you use a for/loop for all the records and perform your action instead of do a hard id search for each?
I have unique id's, which I'd love to use, but the store doesn't let me, there is no api for it
I need to find one specific record from the store by it's id (idProperty). I don't want to use for loop, that's expensive, I want to use (some kind of) map
How many records are in the store that you're using getById() on? I'm wondering why it's being slow for you. If you really want to map the records, you could do it when the store loads (or some other event happens). Here is sample code for writing a map and overriding the default getById function to use it:
Code:
Ext.define('App.override.Store', { override: 'Ext.data.Store', getById: function (id) { return this.idMap[id]; } }); var store = Ext.create('Ext.data.Store', { storeId: 'names', fields: ['id','Name'], data: [ { id: 1, Name: 'Bob' }, { id: 2, Name: 'Joe' }, { id: 3, Name: 'Watson' }, ] }); store.on('load', function(store, records, successful) { store.idMap = {}; if (successful) { Ext.Array.forEach(records, function(record) { store.idMap[record.getId()] = record; }); } }); | http://www.sencha.com/forum/showthread.php?259470-store.getById-too-slow&p=952889 | CC-MAIN-2014-49 | refinedweb | 302 | 74.79 |
One of the robust and most commonly used Python library is NumPy. The Python Library is a collection of script modules which are accessible to a Python program. It helps to simplify the programming process and it also removes the need to rewrite commonly used commands again and again. NumPy stands for Numerical Python which provides a multidimensional array object, an assortment of routines for fast operations on arrays, and various derived objects (such as masked arrays and matrices), including mathematical, logical, basic linear algebra, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic statistical operations, random simulation and much more.
Some of the key features of NumPy are:
In this tutorial, we will go through how to use NumPy to analyze data on Starbucks Menu. This data set consist of information related to various Beverage available at Starbucks which include attributes like Calories, Total Fat (g), Sodium (mg), Total Carbohydrates (g),Cholesterol (mg), Sugars (g), Protein (g),Caffeine (mg). Here we will learn how we can work with NumPy, and we will try to figure out the Nutrition facts for Starbucks Menu.
Calories, Total Fat (g), Sodium (mg), Total Carbohydrates (g),Cholesterol (mg), Sugars (g), Protein (g),Caffeine (mg),Nutrition_Value 3,0.1,0,5,0,0,0.3,175,5 70,0.1,5,75,10,9,6,75,5 110,1.5,5,60,21,17,7,85,6 100,0.1,5,70,19,18,6,75,4 5,0,0,5,1,0,0.4,75,5
Here we have the first few rows of the starbucks.csv file, which we’ll be using throughout this tutorial:
The data is in the csv (colon separated values) format — each record is separated by a colon (,), and rows are separated by a new line. There are approx. 1800 rows, including a header row, and 9 columnsin the file.
Learn Python in 16 hrs from experts
Before we get started, a quick note on version — we’ll be using Python 3.5. Our code examples will be done using Jupyter notebook.
Here we have the list of topics if you want to jump right into a specific one:
Before proceeding to NumPy, on important thing if you have ssv format file data set, then convert it into csv format file by using the csv.reader object and pass the keyword argument delimiter as “,” , this will help us to read into the content and split up all the content that are available in the ssv file
import csv with open('Starbucks.csv', 'r') as f: starbucks = list(csv.reader(f, delimiter=',')) print(starbucks)
It’s always good to have data in the right format ina table to make it easier to view:
As we can observe from the table above, here we have first 3 three rows from the entire table, where the first row contains column headers. The first row is the header row and next rows after header represent the various Beverage at Starbucks. The first element of each row is the Calories, the second is the total fats, and so on. We can find the average Nutrition value. The below code will:
Nutrition_Value = [float(item[-1]) for item in Starbucks[1:]] Sum(Nutrition_Value) / len(Nutrition_Value)
5.6360225140712945
Here, we are able to do the calculation in the way we wanted, but the code is fairly little complex and it won’t be fun if we have to repeat something similar every time to compute average Nutrition_Value. So, we are Lucky use NumPy library to make it easier to work with our data.
Let’s explore it!
Wish to Learn Python? Click Here
In NumPy, it is very easy to work with multidimensional arrays. Here in this tutorial, we will dive into various types of multidimensional arrays but currently, we are focusing on 2-dimensional arrays.
A 2-dimensional array is also called as a matrix and is just anacronym about a list of lists. A 2-dimensional array is a collection of rows and columns. By specifying a row number and a column number, we can easily extract an element from a matrix.
In the below 2-dimensional array, the first row is the header row, and the first column is the Beverage column:
If we pick the element which is present at the first row and the second column, that is total fat. If we pick the element in the third row and the second column, here we will get 0.1.
In a NumPy array, the rank is specified to the number of dimensions, and each dimension is called an axis. So, the first axis is the row, and the second axis is the column.
So, this are the basics of matrices, now, we will see how we can get from our list of lists to a NumPy array.
The numpy.array function is used to create a NumPy array. Here we just have to pass in a list of lists, it will automatically generate a NumPy array with the same number of rows and columns. Because for easy computation, we want all the elements in the array to be float elements, so, we’ll leave off the header row and column, which contains strings.
This is the limitations of NumPy. As in NumPy,all the elements in an array have to be of the same type.Here, if we include the header row and first column, then all the elements in the array will be read in as a string. So, to do computations in the way we want like find the average Nutrition_Value, we need the elements to be presented in floats.
In the below code, we:
import numpy as np starbucks = np.array(starbucks[1:], dtype=np.float) starbucks
Now, to check the number of rows and columns in our data, we will use the shape property of NumPy arrays:
starbucks.shape
Do you know, we can use a variety of methods to create NumPy arrays?First, we will look at the creation of an array where every element is zero. The below code will create an array with 4 rows and 3 columns, where every element is 0, here we will be using numpy.zeros:
import numpy as np empty_array = np.zeros((4,3)) empty_array
An array with all zero elements will be useful at the time when you want an array of fixed size, otherwise, it will not have any value.
Similarly, we can create an array of all ones
import numpy as np All_One_array = np.ones((4,3)) All_One_array
import numpy as np Random_array = np.random.rand(4,3) Random_array
We can also create an array is random number using numpy.random.rand. Here’s an example:
Creating an array which is completely filled random numbers can be useful at a time when we want to quickly test our code with sample arrays.
Here in NumPywe can directly read csv or other files into an array. This can be done by using the numpy.genfromtxt function. We will use this function on our initial data on Starbucks.
So, here in the code:
• To read in the Starbucks.csv file, here we will use the genfromtxt function.
• Next, we have specified the keyword argument delimiter as”,” so that the fields are parsed properly.
• And then we have specified the keyword argument skip_header=1, this will help to eliminate the header row.
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1)
Here, if we read it into a list and then converted it to an array of floats, the Starbucks will be looking the same. Here, NumPy will automatically pick a data type for the elements in an array based on their format.
So, how we can do Indexing and slicing in the created NumPy Arrays to retrieve results from them. In NumPy, the index for first row and column starts with 0. Suppose if we want to select the fifth column then its index will be 4 or if we want to select 3-row data then, its index is 2 and so on.
Let’s say, we want to select the element at row 7 and column 3 so, we will pass index 6 as row index,
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) starbucks[6,4]
and the index 4 as the column index:
So, here with the help of the index, we have shown indexing.
Suppose we want to select the first 5 elements from the 2nd column. This we can implement by using a colon (:). A colon in slicing indicates that we want to select all the elements from the starting index up to but here we are not including the ending index.
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) starbucks[0:5,1]
And suppose we want to select the entire column then just by using the colon (:), with no starting or ending indices we will get the desired result.
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) starbucks[0:5,1]
And suppose we want to select the entire array then use two colons to select all the rows and column. But this is not required while creating a good application.
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) starbucks[:,:]
So, how we, can assign values to certain elements in arrays?
We can do that by directly assigning that value to the particular element. Here in the example code:
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) starbucks[1,5] =10 starbucks[1,5]
starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) starbucks[:5]=10
Even we can overwrite the entire column by using this code: This will overwrite the entire 6th column with 10
Currently, we have worked with Starbucks array which was a 2-dimensional array. However, NumPy package provides us a privilege to work with a multidimensional array. The most common multi-
Fifth_starbucks= np.genfromtxt("Starbucks.csv", delimiter=",", skip_header=1) Fifth_starbucks = starbucks[5,:] Fifth_starbucks
dimensional array is a One-dimensional array. Have you noticed when we sliced the Starbucks data, there we have created the one-dimensional array.A 1-dimensional array will have a single index to retrieve an element from it. Do you know, each row and column in a 2-dimensional array is treated as a 1-dimensional array. As for a list of lists is analogous is a 2-dimensional array, similarly for a single list,the analogous is a 1-dimensional array. Here suppose we slice Starbucks data and retrieve only the fifthrow, then as output, we will receive a 1-dimensional array.
And suppose if we want to retrieve an individual element from Fifth_starbucks we can do that by using a single index.
Fifth_starbucks[0]
Even most of the NumPy functions, such as numpy.random.rand, which we have used with multidimensional arrays to generate a random vector can be used with a single dimensional array as well. Here we just have to pass the single parameter.
np.random.rand(5)
Mostly for our applications, we deal with the 1, 2, 3-dimensional array, it is very real that we come across the array which is more than a three-dimensional array, think this as a list of lists of lists.
For a better understanding of this let’s take an example of the monthly earning of a supermarket. The month vise data will be in a form of a list and if we want a quick look on it then we can see that data in a quarter vise and year vise.
A monthly earning of a supermarket will look something like this:
[400, 250, 300, 470, 560, 630, 820, 740, 605, 340,420,340]
Here, the supermarket has earned $400 in January, $250 in February, and so on. If we split this earning in a quartervise then it will be a list of the list:
One_Year = [ [400, 250, 300], [470, 560, 630], [820, 740, 605] [340,420,340]] ]
Here, we can retrieve the earning of January month by calling One_Year[0],[0]. And if we want a result
for a complete quarter, then we can all One_Year[0] or One_Year[1]. So, this is a two-dimensional array.
But here if we add the earning of another year then it will become the third dimension:
Yearly_Earning = [ [ [400, 250, 300], [470, 560, 630], [820, 740, 605], [340,420,340]] ] [ [500, 350, 430], [430, 760, 640], [720, 530, 800], [345,900, 700] ] ]
Here, we can retrieve the first year earning of the month of January by calling Yearly_Earning[0],[0],[0]
So, here we need three indexes to retrieve a single element we have the same case in a three-dimensional array in NumPy, in fact, we can convert this Yearly_Earning to an array and then we can get the earnings for January month of the first year. It will be:
Yearly_Earning = np.array(Yearly_Earning) Yearly_Earning [0,0,0]
We will get the result as
400
Here, we know the shape of the array, we will use:
Yearly_Earning.shape
The result will be
2,4,3
Here, in three-dimensional array also Indexing and slicing work exact in the same way as two-dimensional array but here we have to pass in one extra axis.
Suppose if we need the earning for January of all years, then it could be:
Yearly_Earning[:,0,0]
The result will be:
array ([400,500])
Suppose, if we require to get first-quarter earnings from both years, then:
Yearly_Earning[:,0,:]
The result will be:
array ( [ [400, 250, 300], [500, 350, 430]])
By adding more dimensions, we can make it much easier for us to query our data as it will be organized in a certain way.
Suppose if we go from 3-dimensional arrays to 4-dimensional or a larger array than that, there also we will apply the same properties, and they can be indexed and sliced in the same ways.
As we have discussed earlier, each element of a NumPy array can be stored in a single data type. In our example of Starbucks, all element contains only float values. In NumPy values are stored using its own data types, which are different from Python data types like float and str. The reason behind this is that the core of NumPy is written in the C programming language, which stores data differently in comparison to the Python data types. NumPy itself map data types between Python and Cand allow us to use NumPy arrays without any conversion hitches.
You can find the data type of a NumPy array by accessing its dtype property:
Starbucks.dtype
NumPy provides various data types, which are inline with Python data types, like float, and str. Some of the important NumPy data types are:
Even we have additional datatypes with a suffix which indicates the bits of memory that that data type can take up. Like int 32 is a 32-bit integer data type, and float 64 is a 64-bit float data type.
To convert an array to a different type we can use the numpy.ndarray.astype method. This method will make a copy of the actual array and will return a new array with the specified data type. For example, if we want to convert Starbucks data to the int data type, we need to perform this:
starbucks.astype(int)
With the output, we can observe that all of the elements in the resulting array are integers. And to check the name property of the d type of the resulting array, we will use the following code:
integer_starbucks = starbucks.astype(int) integer_starbucks.dtype.name
Here the array has been converted to a 32-bit integer data type which means it will be storing the values as 32-bit integers.
If you want more control over the way, the array is stored in memory and allows for very long integer values then we can directly create a NumPy dtype objects like numpy.int64:
np.int64
Now, we can directly use these to convert between data types:
integer_starbucks.astype(np.int64)
It is easy to perform mathematical operations on arrays using NumPy.One of the important advantages of using NumPy is that it male easy to perform the computation.
It is easy to perform basic arithmetic operations on numpy arrays. We can use both +, -, *, / symbols or add(), subtract(), multiply(), divide() methods to perform basic operations like addition, subtraction, multiplication and division respectively. By using sqrt() function, we can find the square root of each element in numpy array.
Let’s say after the quality check we want to add 10 to the Nutrition_Value of Starbucks Beverages then
starbucks[:,8] + 10
Have you noticed after performing the above operation we have not to change the Starbucks array –but a new 1-dimensional array is returned where 10 has been added to each element in the Nutrition_Value column of Starbucks data.
Similarly, instead of + if we modify the array with +=, then the result would be:
starbucks[:,8] += 10 starbucks[:,8]
In the same way, we can perform the other operations. Suppose we want to multiply each of the Nutrition_Valueby 2, which we could do in this way:
starbucks[:,8] * 2
We can perform mathematical operations between multiple arrays. This operation will be applied to the pairs of elements. Suppose, if we add the Nutrition_Value column to itself, here’s what we get:
starbucks[:,8] + starbucks[:,8]
Did you noticed that the output is equivalent to starbucks[:,8] * 2 — this is because here each pair of elements is added by NumPy. The first array first element is added to the second array first element, the first array second element to the second array second element, and so on.
Also, we can use this to multiple arrays. Let’s say we want to pick a beverage that is fat filled with nutrition value then we have to multiply Total fat, Protein, and nutrition_Value, and later we can select the beverage with the highest score
starbucks[:,1] * starbucks[:,6] * starbucks[:,8]
We can perform all of the common operations like /, *, -, +, ^, to work between arrays.
Till now, we have performed the operation on are the exact same size array, and it is done the corresponded elements. But what if the dimension of the two arrays is not similar. However, it is possible to perform NumPy on two arrays which are dissimilar by using broadcast. In broadcast, we will try to match up the elements by using certain rules. Few essential steps involve in broadcasting are:
For example, we can compare the following two array shapes :
X: (60,5) Y: (5)
The comparison is possible here because the array X has the trailing dimension length as 5, and the array Yhas trailing dimension length as 5. They’re equal, as trailing dimension are equal. But Array Y is then out of elements, so for broadcasting, array X is stretched to become an array of with the same shape as array Y., and then arrays are compatible for mathematical operations.
Let’s take another example which is also compatible
X: (3,4) Y: (10,4)
Here, the last dimension of both arrays are matching, and Array X first dimension is of length 1.
Now, for better understanding we will look at another two arrays that don’t match:
X: (52,52) Y: (55,55)
Here, in this example neither the lengths of the dimensions are equal, nor either of the arrays has dimension length equal to 1.
Let’s illustrate the principle of Broadcast with the help of our Starbucks dataset:
starbucks * np.array([1,2])
The error statement “ValueError: operands could not be broadcast together with shapes (1888,9) (2,)”
As the two arrays don’t have a matching trailing dimension so the above example didn’t work.
Here’s an example where the last dimension is matching:
X_array = np.array( [ [3,4], [5,7] ] ) Y_array = np.array([5,2]) X_array + Y_array
Elements of random_Example_array are broadcast over each row of Starbucks, so the first column of Starbucks has the first value in random_Example_array added to it, and so on.
NumPy provides so many methods other than arithmetic operations to solve more complex calculations in the array. One of the most commonly used NumPy array methods is numpy.ndarray.sum method. This method helps to find the sum of all the elements in an array when used by default:
starbucks[:,8].sum()
The total of all of our Nutrition_Value column is 271.5.
Here, as a keyword argument for sum method,we can also pass the axis to find sums over an axis.
Suppose if we call sum across our Starbucks matrix, and pass in axis as 0, then we will be able to find the sums over the first axis of the array. As a result, this will provide the sum of all the values in every column.
You would have understood this as the sums over the first axis would give us the sum of each column, or another way to think about this is that the specified axis is the one “going away”.
So if we assign axis=0, then this means that we would like the rows to go away, and we are willing to find the sums for each of the remaining axes across each row:
starbucks.sum(axis=0)
To verify whether our sum is correct, we can check the shape. In our dataset the shape should be 9, corresponding to the number of columns:
starbucks.sum(axis=0).shape
Here, if we provide in axis=1, then it will find the sums over the second axis of the array.
starbucks.sum(axis=1)
Other than the sum, in NumPy we have several other methods which work like the sum method, including:
In NumPy, it possible to test and check whether the rows match the certain values by using mathematical comparison operations like <, >, >=, <=, and ==.
Suppose in our Starbucks data, if we want to check which beverage shave a Nutrition_Value greater than 5, we can do this:
starbucks[:,8] > 5
As a result, we have received a Boolean array which tells us which of the beverage have a Nutrition_Value greater than 5. We can perform similar things with the other operators. For instance, we can see if there is any beverage which has a Nutrition_Value equal to 10:
starbucks[:,8] == 10
With a Boolean and a NumPy array, one of the powerful things we can do is select only certain rows or columns as per our requirement. For example, if we are will select only those rows from the Starbucks data where Nutrition_Value of beverage is greater than 5:
Highly_Nutrition = starbucks[:,8] > 5 starbucks[Highly_Nutrition,:][:3,:]
Here, we have selected only three rows where Highly_Nutrition contains value is True, with its all columns.
So, Subsetting makes it easier to filter arrays with certain criteria.
Another example, If we are looking for a beverage with a lot of protein and Highly_Nutrition. In order to specify the multiple conditions, we will place each condition in parentheses, and we will separate conditions with an ampersand (&):
Highly_Nutrition_and_Max_Protein = (starbucks[:,8] > 5) & (starbucks[:,6] > 6) starbucks[Highly_Nutrition_and_Max_Protein,2:]
Here, even we can combine subsetting and assignment to overwrite certain values in an array:
Highly_Nutrition_and_Max_Protein = (starbucks[:,8] > 5) & (starbucks[:,6] > 6) starbucks[Highly_Nutrition_and_Max_Protein,2:] = 5 starbucks[Highly_Nutrition_and_Max_Protein,2:]
In NumPy, it is very easy to change the shape of arrays and still protective all of their elements. There are often many functions which make it easier to access array elements.
One of the simplest ways of reshaping an array is to flip the axes, like columns,become rows and vice versa. We can perform this operation with the numpy.transpose function:
np.transpose(starbucks).shape
Another important function is numpy.ravel function. This function will turn an array into a one-dimensional representation. This function will turn an array into a long sequence of values:
starbucks.ravel()
Here we have an example which will help you to better understand and see the ordering of numpy.ravel:
Example_Array_One = np.array( [ [1, 2, 3, 4], [5, 6, 7, 8] ] ) Example_Array_One.ravel()
And finally, we are going to use the numpy.reshape function. This function will help to reshape an array to a certain shape as per our requirement. In the below example we will turn the third row of Starbucks data into a 2-dimensional array with 3 rows and 3 columns:
starbucks[2,:].reshape((3,3))
With NumPy, we can easily combine multiple arrays into a single unified array. To perform this task, we can use numpy.vstack to vertically stack multiple arrays. Consider this in this way the second arrays’ items are being added as new rows to the first array.
Let’s take an example where we want to combine the old Nutritional dataset of Starbucks beverages with our existing dataset, wines, which contains information on the current Nutritional value of Starbucks beverages.
In the below code, we:
import csv with open('starbucks_old_data.csv', 'r') as f: starbucks_old = list(csv.reader(f, delimiter=',')) import numpy as np starbucks_old = np.array(starbucks_old[1:], dtype=np.float) starbucks_old.shape
Here we can see, we have attributes for 196 beverages that we have the starbucks_old data, we can combine all the wine data.
Now, we will use the v stack function to combine starbucks and starbucks_old data and then we will display the shape of the result.
All_beverages = np.vstack((starbucks, starbucks_old)) All_beverages.shape
So, here we can observe, the result has 2084 rows, which is the sum of the number of rows in starbucks and starbucks_olddata.
Similarly, If we want to combine arrays horizontally, which means that our number of rows will stay constant, but the columns will be joined. For this purpose we can use the numpy.hstack function.
And another useful function is numpy.concatenate. it is a general purpose version of hstack and vstack. With the help of this fuction, if we want to concatenate two arrays, then we can pass them into concatenate and we have to specify the axis keyword argument that we want to concatenate along. When we concatenating along the first axis, it is similar to vstack, and when we concatenating along the second axis, it is similar to hstack:
np.concatenate((starbucks, starbucks_old), axis=0)
This brings us to the end of the Pythons NumPy library tutorial. In this tutorial, we learned in detail the NumPy library with the help of a real-time data set. Here we have also explored how to perform various operations via the NumPy library, which is most commonly used in many data science applications.
While in this Python tutorial, we have covered quite a bit of NumPy’s core functionality, still there is a lot to know more about it. If you want to learn more, I’d suggest you try out our IntelliPaat course like Data Science in Python which covers the various technique of how Python is deployed for Data Science, work with various libraries for Data Science, do data munging, data cleaning, advanced numeric analysis and in much more depth than what we were able to cover here.
I would suggest you practice the examples which I have explained in this tutorial. If you want to become a data scientist, the NumPy library is definitely one of the most important tools that you must need to learn and practice to be a successful and productive team member in your workplace.
Further check out our offer for Python certification.Previous Next
Learn SQL in 16 hrs from experts
"0 Responses on NumPy Tutorial - Learn Python NumPy from Experts" | https://intellipaat.com/tutorial/python-tutorial/Numpy-tutorial-python/ | CC-MAIN-2019-09 | refinedweb | 4,596 | 59.23 |
public class RandomPermutation { int [] numberChoice = new int[10]; int [] permuted = new int[10]; public static void main(String[] args) { RandomPermutation rp = new RandomPermutation(); rp.displayPermutedArrays(); } void displayPermutedArrays(){ for(int i=1;i<=10;i++){ System.out.println( i + " " + permuted); } } void generatePermutedArray(){ int sentinel=-1; int index; for (int k = 1; k <=10; k++) { do{ index=(int)(Math.random()*10);} while(numberChoice[index]=sentinel); } } }
Hi guys, I am new to java, and I am working on a project that wants me to loop an array ten times with the numbers in all different orders. I am not sure how to use this do while loop that needs reference to my arrays. I keep getting an error right here :
while(numberChoice[index]=sentinel);
It says it is compiled with errors, and it will run however this shows up:
1 [I@5ade5cd9
2 [I@5ade5cd9
3 [I@5ade5cd9
4 [I@5ade5cd9
5 [I@5ade5cd9
6 [I@5ade5cd9
7 [I@5ade5cd9
8 [I@5ade5cd9
9 [I@5ade5cd9
10 [I@5ade5cd9
When what I want is something similar to : 1 [2, 3, 7, 1, 10, 8, 9, 5, 4, 6] and so on. I got it working with an ArrayList, but I was told not to use that, and to do it this way. Anyway, I am just not sure what I'm doing wrong, and if someone could guide me with this problem that would be great. | http://www.dreamincode.net/forums/topic/277281-help-with-permuted-arraydo-while-loop/ | CC-MAIN-2016-07 | refinedweb | 233 | 63.02 |
Created on 2012-01-18 01:15 by brandjon, last changed 2015-08-27 21:42 by memeplex. This issue is now closed.?
(Er, that should be /Lib/multiprocessing/process.py :: Process._bootstrap of course.)
> But I observe that unless I explicitly flush stdout and stderr before
> terminating, the output is lost entirely, even if the exit is not
> abnormal. This isn't the desired behavior, is it?
Indeed that's a bit surprising. Which Python version are you using? Under Unix or Windows?
On Windows, the problem appears under Python 3.2.2 and 3.1.3, but not under 2.7.1. On Linux, I have not reproduced the problem on versions 2.6.3, 2.7.2, 3.1.1, or 3.2.2.
So to summarize:
- It seems there should be a stderr flush call on the line I indicated, for symmetry with the surrounding code.
- Even without this line, it should still be flushed automatically upon child process exit, but this doesn't happen under Windows and Python 3.x.
Le dimanche 22 janvier 2012 à 17:58 +0000, Jon Brandvein a écrit :
> Jon Brandvein <jon.brandvein@gmail.com> added the comment:
>
> On Windows, the problem appears under Python 3.2.2 and 3.1.3, but not
> under 2.7.1. On Linux, I have not reproduced the problem on versions
> 2.6.3, 2.7.2, 3.1.1, or 3.2.2.
Thanks.
> - Even without this line, it should still be flushed automatically
> upon child process exit, but this doesn't happen under Windows and
> Python 3.x.
Yes, that's what surprises me. There's no reason for stderr not to be
flushed implicitly at process end, since that's part of sys.stderr's
destructor, which should be called at shutdown.
That said, it certainly doesn't harm to add a flush() call there.
I've been looking over this package some more, and in particular, /Lib/multiprocessing/forking.py. There's plenty I don't understand, and I do have questions, if you would be willing to indulge me.
I see that both the unix and windows codepaths define an "exit" alias for terminating the child process without performing any cleanup. On unix, this is os._exit (though it calls it directly in Popen.__init__() instead of using the alias). On Windows, it is the win32 ExitProcess() function. A quick check confirms that replacing this windows alias with "exit = sys.exit" causes flushing to occur.
So my main question is: What's wrong with using sys.exit()? I would speculate it's either because there's shared state between child and parent, or to avoid propagating SystemExit through user code in the case freeze_support() was used.
If forking.py is to terminate directly via the OS, I think it's forking.py's responsibility to flush stdout and stderr in main() on the Windows side, the way it does in Popen.__init__() on the unix side.
I also want to point out that the sys.exit() in freeze_support() is unreachable due to the exit() in main().
So it no longer surprises me that the output is not being flushed in Python 3 under windows. What surprises me is that it *is* flushed in Python 2. I remember hearing something about differences between 2 and 3 in how they handle buffering, so I'm investigating this for my own curiosity.
Incidentally, Python 2 still flushes when I remove newlines from my output text, so line buffering doesn't seem to be impacting my observations.
Some more information: When I write to a new file created by open(), all versions flush correctly. However, if I reassign sys.stdout to that file, Python 3.x does not (again, under Windows). I wonder what it is that causes these other files to flush.
(Note: I am testing by calling time.sleep() and inspecting the output file during and after the pause.)
It turns out the file output was flushing due to garbage collection. When I created and held a global reference to it, it ceased to flush. Clearly, reassigning sys.stdout also held a reference to it. So it wasn't any kind of special sys.stdout-specific logic.
I tried using os.fsync to determine whether data was being saved in an OS-level buffer. But since the OS may be free to ignore fsync, it's kind of worthless for this purpose.
I also found that under Python 2.x, even a low-level exit like os._exit or multiprocessing.win32.ExitProcess, called from within a user-level function in the child, caused flushing.
My best guess is that
1. Python 2.x is not buffering data at the Python level. I can't see how it could be and still flush it out when calling _exit().
2. Python 3.x is buffering at the Python level, and the Python File object needs to be destroyed or explicitly flushed before the hard low-level exit() in forking.py.
The solutions I can think of for Python 3.x are:
1. Replace "exit = win32.ExitProcess" with "exit = sys.exit". All outstanding file objects will be destroyed and flushed naturally as the interpreter is torn down.
2. Add an explicit stdout/stderr flush where appropriate in forking.py and process.py, to ensure tracebacks get written and to match the unix behavior. Leave it to the user to worry about flushing their own streams.
3. Continue to use win32.ExitProcess, but add some kind of mechanism for walking through all existing Python File objects and flushing/destroying them. This was a fleeting thought; it really amounts to reimplementing the behavior of destructing the Python interpreter.
I'd really like to hear if there are good reasons for why (1) isn't how it's done currently. I'd also like to hear an explanation of Python 2.x's buffering.
> I also found that under Python 2.x, even a low-level exit like
> os._exit or multiprocessing.win32.ExitProcess, called from within a
> user-level function in the child, caused flushing.
The difference is the following:
- Python 2.x uses C stdio (write() calls C fwrite(), flush() calls C
fflush(), etc.); buffering is managed by the libc and what you see at
shutdown is the behaviour of your platform's libc
- Python 3.x uses its own buffering mechanism; it flushes automatically
when the object destructor is called, but os._exit() bypasses all
destructors
Now why os._exit() is used. The problem with sys.exit() is that it's too
high-level: it merely raises a SystemExit exception. That exception can
be caught by upper levels in the code stack. When you use fork() and you
are in the child process, you don't want to give back control to the
calling function, especially if that function isn't fork()-aware (think
about what happens if that function writes to a file, both in the child
and the parent).
This happens for example when running multiprocessing's own test suite:
if forking.py used sys.exit(), the child's SystemExit exception would be
caught by the unittest framework, be interpreted as a test failure, and
the rest of the test suite would proceed... in both processes!
It is less obvious, however, why ExitProcess is used under Windows.
Windows doesn't use fork(), it launches a separate process from scratch.
Perhaps for "consistency" with the Unix behaviour.
> 2. Add an explicit stdout/stderr flush where appropriate in
> forking.py and process.py, to ensure tracebacks get written and to
> match the unix behavior. Leave it to the user to worry about flushing
> their own streams.
That's the simplest solution, and the least likely to break
compatibility with user code.
I propose applying the following patch.
We could open a separate issue to suggest "exit = sys.exit" under Windows (it doesn't seem to break any tests).
Regarding the patch: I'd also like to see sys.stdout.flush() and sys.stderr.flush() between "exitcode = self._boostrap()" and "exit(exitcode)" in /Lib/multiprocessing/forking.py :: main(). (The extra stderr flush would be for symmetry with Popen.__init__() for unix.)
The remainder of this post is what I wrote before seeing your patch.
Thank you for the explanation concerning libc and buffering.
As for os._exit, I can see the need under unix, where the child process has a stack inherited from the parent. Also, allowing the child to cleanup shared resources would be disastrous for the parent. (I was going to propose the idea of making a sys.exit()-like function that did not rely on the exception mechanism to unwind the stack. But it wouldn't be usable here for this reason.)
Under Windows, the child process's multiprocessing.forking.main() is launched either by directly calling main() on the command line, or from within freeze_support() in the user program. In the latter case, the user can be advised not to catch SystemExit around freeze_support(), just as they are already advised to make calling freeze_support() the first statement within "if __name__ == '__main__':". So I don't see any harm in switching to sys.exit() there.
I think that in general, the differences between multiprocessing's behavior under unix and windows are a weakness, as is the lack of a precise specification for this behavior.
At the same time, multiprocessing is a lot more convenient to use than the subprocess module when the child process is a Python program. In particular, I use multiprocessing for its support of passing pickled objects between parent and child. With subprocess, I don't think it's even possible to share a file descriptor between parent and child under Windows.
I'm wondering whether it would be desirable to make an option for the unix side of multiprocessing to behave more like the windows one, and invoke the Python interpreter from the beginning with no trace of the parent's stack. That is, it'd follow a more traditional fork()-then-exec*() pattern. Then you'd be able to have the interpreter destruct naturally under both platforms, close resources, etc.
Are there use cases that require just forking under unix? Is the performance significantly better without an exec*()?
Perhaps it would be better If I took this discussion to python-ideas.
There's already a bug / pending patch for this behavior here:
No need to take it to -ideas.
> I propose applying the following patch.
The test looks good to me (except we don't remove TESTFN explicitely,
but I'm not sure it's really necessary).
As for the patch, couldn't we put all the file stream flushing in one place?
stdout and stderr are already flushed on Unix (which explains why this
only happens on Windows: the libc puts non-tty streams in _IOFBF, so
this wouldn't work without explicit flushing neither).
Lib/multiprocessing/forking.py:Popen.__init__:
code = process_obj._bootstrap()
sys.stdout.flush()
sys.stderr.flush()
os._exit(code)
Also, there's already a flush() a couple lines above (in _bootstrap):
sys.stderr.write(e.args[0] + '\n')
sys.stderr.flush()
So I'd suggest to just put:
sys.stdout.flush()
sys.stderr.flush()
At the end of _bootstrap, and remove the flushing done by
Popen.__init__ on Unix.
Updated patch sanitizing the various flushes done on exit, as per Charles-François's recommendation. Also removes TESTFN explicitly.
LGTM.
(I just noticed a bug in Rietveld: when one selects "expand 10 after",
the line right after that marker appears duplicated in the new view).
Patch looks fine. I like the use of "finally" for the flush.
New changeset 2863d9273abd by Antoine Pitrou in branch '3.2':
Issue #13812: When a multiprocessing Process child raises an exception, flush stderr after printing the exception traceback.
New changeset 96c1de5acbd3 by Antoine Pitrou in branch 'default':
Issue #13812: When a multiprocessing Process child raises an exception, flush stderr after printing the exception traceback.
Patch now committed, thanks.
I would like to reopen this issue because of the following, very related, behavior. Try this:
```
import multiprocessing as mp
import time
def g():
time.sleep(100)
def f():
mp.Process(target=g).start()
1/0
mp.Process(target=f).start()
```
It won't show the ZeroDivisionError until you keyboard interrupt the g() process or wait for it to end. This is because _exit_function will join every active non-daemon child, which happens before printing and flushing the error. IMO the exception should be shown before joining children, since keeping the error silent is asking for trouble.
You should open a new issue. Bonus if you can supply a unit test and patch :)
I posted a tentative solution there. | https://bugs.python.org/issue13812 | CC-MAIN-2022-05 | refinedweb | 2,120 | 68.57 |
amusement park scheduling rides using dynamic programming
You arrive at Waldo's World Amusement Park with T minutes remaining until expressed as minutes before the park closes. Ride i itself takes ri minutes and all times are measured in integer minutes.
I tried solving it using a method similar to 0 1 knapsack problem. But the Table W which contains the waiting time for ride i varies wrt to time t. Is it exactly a knapsack plus activity selection combined problem?
1 answer
- answered 2018-02-13 01:53 גלעד ברקן
Would this make any sense? Let
f(t)represent the most achievable rides at time
t. Then:
// Higher t is back in time // since t is how many minutes // before the park closes f(t) = max( // Not taking any ride f(t - 1), // Take ride i 1 + f(t - W(i, t) - r_i) ) for all i
See also questions close to this topic
- Count the number of ways to make a sequence sorted by deleting one item
I recently cam across a question that is basically a variant of the following problem:
We want to make a sequence sorted in non-decreasing order by deleting exactly one item from it. How many ways can we do that ?
For example, in the sequence
[2, 4, 5, 4], the number of ways will be
2as we can delete
5or the last
4.
I was thinking in terms of longest increasing subsequence but couldn't properly relate it with this problem. Any pointer / direction regarding the solution strategy would be highly appreciated.
- Merge sort "maximum recursion depth exceeded in comparison "
I want to code merge sort in Python 3.
Here is my code:
import math def Merge(array,start,mid,end): n1 = mid - start +1 n2 = end - mid i = 0 j = 0 left = [None] * n1 right = [None] * n2 inv = 0 for i in range(0,n1): left[i] = array[start + i - 1] for j in range(0,n2): right[j] = array[mid + j] left.append(math.inf) right.append(math.inf) new_list = [] for k in range(0,end): if left[i] <= right[j]: array[k] = left[i] i+=1 elif left[i] > right[j]: array[k] = right[j] j+=1 def MergeSort(array,start,end): if len(array) <= 1: return array mid = math.ceil((start + end)/2) MergeSort(array,start,mid) MergeSort(array,mid+start,end) Merge(array,start,mid,end) stuff = [1, -5, 17, 32, 6] MergeSort(stuff, 0, len(stuff)) print(stuff)
I tested first function(Merge) it works as it should. But I have a problem with the recursion. I cannot figure out where is the problem. The error is "maximum recursion depth exceeded in comparison".
- How to improve my way of thinking in javaScript?
I'm learning ES5 javaScript and want to test myself, so went to codewars site and there was a problems which says :
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. An "Avengers" ticket costs 25 dollars.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
Return YES, if Vasya can sell a ticket to each person and give the change with the bills he has at hand at that moment. Otherwise return NO.
That challenge is in the first level on the codewars, I thought about it for an hour and I still didn't able to solve it. So my question is how can I improve my way of thinking to be able to solve that kind of questions and harder ones ?
- Algorithm to solve optimal clustering of word vectors
I have word vectors split out into N groups, where each group contains M vectors. The problem is to find an optimal clustering of vectors where one and only one vector appears from each of the N groups.
As an example, say we had 3 groups of vectors as so:
- {"Hot Dog", "Hot sauce", "Hotshot"}
- {"Hamburger", "Hamburg", "Hamburgler"}
- {"Pizza", "Pisa", "Piazza"}
The optimal cluster would be {"Hot Dog", "Hamburger", "Pizza"} because according to some function I have F(), these vectors are clustered closely to each other within the vector space I have defined.
I can arrive at this result in a brute force way by merely trying every combination. But as N and M grow, this becomes unfeasible. Is there a dynamic programming approach I could use? Any reference algorithm I can look up?
Thanks.
Edit:
To clarify my example above, each of those strings is like an ID for a vector so to rephrase it, Group 1 is {v1, v2, v3} Group 2 is {v4, v5, v6}, Group 3 is {v7, v8, v9}.
My desired output is {v1, v4, v7} but in a non-brute force way.
@m69's comment below correctly describes what I mean by a cluster - a group of vectors whose distance to one another as computed by some function F() is all within some threshold t.
- Choose subset of points with geometry closest to orginal
I have list
n (n < 500)of positive integers representing elevation profile. I need to choose at most
m (m < 255)points of them to make new geometry as similar as orginal one as possible. For input
[10, 21, 15, 2, 8, 35, 94, 223, 370, 575, 701, 661, 592, 356] and m = 8I want to return
[10, 0, 0, 0, 8, 0, 94, 0, 370, 575, 701, 0, 592, 356](
0means that we skip that number). Because when we connect points by lines we have geometry
[10.0, 9.5, 9.0, 8.5, 8.0, 51.0, 94.0, 232.0, 370.0, 575.0, 701.0, 646.5, 592.0, 356.0], errors for points are
[0.0, 11.5, 6.0, 6.5, 0.0, 16.0, 0.0, 9.0, 0.0, 0.0, 0.0, 14.5, 0.0, 0.0]so the maximum error is
16
I tried dynamic programming approach where
dp[i][j]was solution for array starting not earlier than at
iposition and using not more than
jelements. To compute it for every
kfrom
ito
nI compute maximum error if
kis the first element and take maximum of it and
dp[k + 1][j - 1].
Can we spend
O(1)time for every
kto calculate maximum distance from points
[i .. k - 1]to line connecting points
i - 1and
k? Does anyone have idea how to solve whole problem in
O(n^2)?
- Calculating importance of independent variable in explaining variance of dependent variable in linear regression
I am working on a Media Mix Modeling (MMM) project where I have to build linear model for predicting traffic factoring in various spends as input variables. I have got the linear model equation which is:
Traffic = 1918 + 0.08*TV_Spend + 0.01*Print_Spend + 0.05*Display_spend
Now, I want to calculate two things which I don't know how to do: (1) How much each variable is contributing in explaining variance of traffic? (2) What percentage of total traffic is due to each independent variable?
Please suggest me how both of these can be calculated.
- How do I do a regression analysis with panel data in R?
So I'm a noob at R and it's been more than a year since I've used R, and I've seem to forgot a lot... :(
I have a panel data that includes different countries with observations from 2005, 2010, and 2015 that looks like this:
Location Year Health_Spending Total NCD Deaths_male 1 CAN 2005 3282.454 101.4 2 CAN 2010 4225.189 105.5 3 CAN 2015 4632.837 109.2 4 ESP 2005 2126.553 179.9 5 ESP 2010 2882.912 180.6 6 ESP 2015 3175.457 183.1 Total NCD Deaths_female 1 102.7 2 107.3 3 110.2 4 170.4 5 170.6 6 180.8
I'm trying to run a regression analysis with Health_Spending as Y, and Total NCD Deaths_male & Total NCD Deaths_female as X1 and X2.
I've been looking up and it seems like plm package is used a lot to analyze panel data in R, but I'm having trouble figuring out how to use it.
Can a kind soul help me out and guide me on what I need to do?
(here's a dput version of my data just in case)
structure(list(Location = c("CAN", "CAN", "CAN", "ESP", "ESP", "ESP", "GBR", "GBR", "GBR", "ISR", "ISR", "ISR", "JPN", "JPN", "JPN", "KOR", "KOR", "KOR", "MEX", "MEX", "MEX", "NLD", "NLD", "NLD", "NOR", "NOR", "NOR", "POL", "POL", "POL", "TUR", "TUR", "TUR", "USA", "USA", "USA"), Year = c), Health_Spending = c(3282.454, 4225.189, 4632.837, 2126.553, 2882.912, 3175.457, 2331.136, 3040.114, 4071.806, 1768.952, 2032.725, 2646.915, 2463.725, 3205.216, 4428.349, 1183.438, 1895.699, 2481.587, 730.816, 911.351, 1037.424, 3454.707, 4633.738, 5148.399, 3980.768, 5162.669, 6239.435, 806.974, 1352.424, 1687.009, 582.888, 871.677, 1028.911, 6443.02, 7939.798, 9491.4 ), `Total NCD Deaths_male` = c("101.4", "105.5", "109.2", "179.9", "180.6", "183.1", "245.8", "242.0", "249.0", "16.7", "16.8", "18.0", "460.3", "503.7", "543.2", "105.7", "110.2", "118.3", "194.7", "230.7", "257.5", "58.9", "58.6", "63.2", "17.4", "17.5", "17.1", "172.7", "175.1", "175.9", "185.3", "197.4", "211.8", "1024.9", "1061.6", "1159.5"), `Total NCD Deaths_female` = c("102.7", "107.3", "110.2", "170.4", "170.6", "180.8", "268.2", "259.0", "264.1", "17.5", "17.4", "18.7", "405.0", "458.9", "528.4", "92.9", "93.3", "102.2", "181.4", "214.2", "235.5", "62.1", "62.6", "67.7", "18.4", "18.8", "18.2", "163.1", "168.6", "174.6", "150.3", "162.6", "181.0", "1111.6", "1115.5", "1183.4")), .Names = c("Location", "Year", "Health_Spending", "Total NCD Deaths_male", "Total NCD Deaths_female" ), class = "data.frame", row.names = c(NA, -36L))
- Average Case Analysis of Sequential Search with Geometric Probability Distribution
I was kind of aware of getting the average running time in a uniform distribution. Say for example we have 6 array elements.
| 1/6 | 1/6 | 1/6 | 1/6 | 1/6 | 1/6 |
Above is the array with the uniform probability distribution of a search element being positioned in every subscript in the array.
So getting the average running time in a uniform distribution will be like the solution below:
T(n) = (1/6)*1 + (1/6)*2 + (1/6)*3 + (1/6)*4 + (1/6)*5 + (1/6)*6 = (1/6) * ( 1 + 2 + 3 + 4 + 5 + 6 ) = 3.5
or when in express in n terms:
T(n) = (1/n) * ((n(n+1))/2) = (n+1) / 2 = ϴ(n)
But what about the average-case number of key comparisons in sequential search under a geometric probability distribution?
Example:
Prob(target X is in the jth position) = 1/(2^(j+1)) where j = 0, 1, 2,3,4,5,6,... | 1/(2^(0+1)) | 1/(2^(1+1)) | 1/(2^(2+1)) | 1/(2^(3+1)) | 1/(2^(4+1)) | 1/(2^(5+1)) |
Then
T(j) = ((1/2)* 1) + ((1/4)* 2) + ((1/8)* 3) + ((1/16)* 4) + ((1/32)* 5) + ((1/64)* 6) = .5 + .25(2) + .125(3) + .0625(4) + .03125(5) + .015625(6) = .5 + .5 + .375 + .25 + .15625 + .09375 = 1.875
I dont know how to express it in j terms:
T(j) = ?
What is the upperbound O(j)? lowerbound Ω(j)? tightbound ϴ(j)?
Any help or ideas , will be very much appreciated. | http://quabr.com/48757785/amusement-park-scheduling-rides-using-dynamic-programming | CC-MAIN-2018-34 | refinedweb | 2,006 | 68.91 |
In one of my previous posts I was showing everyone how you can use Dynamo to parse through an HTML (TXT) file and use it to isolate elements in view. One of my readers made a comment that it would be nice if you could use the same strategy to isolate elements that caused clashes and instead of using warning report to use an interference report. Without further ado, Julien, here it is:
Interference Report Parser in action.
This component will parse the HTML report generated using the Interference Check tool in Revit. Its output will be a list of Element IDs (as strings for now) as well as Total Number of Clashes that were in the Report. Please make sure that you have installed BeautifulSoup and Regular Expression for Python for this component to work. You can use this component with Isolate in View component to isolate elements that caused the clashes. Please see the Isolate in View component description below.
Please see below:
lib_path = r’C:\Program Files (x86)\IronPython 2.7\Lib\BeautifulSoup-3.2.1′
pyt_path = r’C:\Program Files (x86)\IronPython 2.7\Lib’
sys.path.append(lib_path)
sys.path.append(pyt_path)
from BeautifulSoup import BeautifulSoup
import re
Good luck! | http://archi-lab.net/interference-report-parsing-wdynamo/ | CC-MAIN-2017-13 | refinedweb | 205 | 62.88 |
Hi the next version of Windows is nearly done is if you live in a hobbit hole, so I’ll leave all those breathless announcements to the rest of the internet.
This week we talk:
- DFSR and reeeeaaaaallllyy big pre-existing recovery
- DfsUtil reparse point hunting
- USMT 4.0 group membership changes
- Server Manager remoting menu
- USMT 4.0 and offline files
- GMSA backgrounder
- DFSR disabledirectoryverification
- Other Stuff
Let’s get to it.
Question
I accidentally chose the wrong source replicated folder when setting up DFSR and now I have a few terabytes of data in the preexisting folder. I found your RestoreDfsr script to pull out the intentionally-mangled data, but it’s taking a long time to put everything back. Is there an alternative?
Answer
The script just wraps xcopy and makes copies rather than moving files, so it is not scalable when you get into the multi-TB realm (heck, you might even run out of disk space). If it’s reaaaallly slow (when compared to another server just copying some similar files) I’d worry that your disk drivers or firmware or SAN or NAS anti-virus or third party backup agents or whatever are contributing to the performance issues.
However!
All of the files and folders in pre-existing deeper than the root are not mangled and don’t require any special scripts to copy out. Only the files and folders at the root of the preexisting RF are mangled and require the preexistingmanifest.xml for the heavy lifting. Therefore, a quicker way to fix this would be to just figure out the original folder names at the root by examining the pre-existing manifest file with your eyeballs. Rename them to their original name and then use Windows Explorer MOVE (not copy) to just move them back into the original folder. That would leave only the mangled files in the root of the pre-existing folder, which you could then use the script to restore – presumably with less data to restore and where the slower xcopy performance no longer matters.
Question
When I run dfsutil diag viewdfsdirs c: verbose on this Win2008 R2 server, I see errors like this:
Unable to open file by ID
Unable to open file by ID
This volume (C:\) contains 5 DFS Directories.
Done processing this command.
C:\DFSRoots\root1\link1
C:\DFSRoots\root2\link2
C:\DFSRoots\root3\link3
What is the ID in the error? How can I tell the other two folders that it’s missing?
Answer
Dfsutil.exe uses the reparse point index to find DFS links on a volume.
Due to some error, dfsutil.exe failed to open some of them. We definitely need a better error that tells you return code and failed path. Sorry.
First, look in c:\dfsroots. The two link folders not returned by your list below are probably in there. If they are not in c:\dfsroots at all, use:
DIR c:\ /S /AL
That returns all reparse points on the volume. Any besides the default ones (in user profiles, programdata, and sysvol) are probably your bad guys. You’d want to make sure they still show up correctly in fsutil, that you have no errors with chkdsk, that they have not been intercepted by some wacky third party, etc.
You can also use (if you have later OSes):
Dfsdiag /testreferral /dfspath:\\contoso.com\namespace /full > output.txt
Question
I am using USMT 4.0 to migrate users that are members of the Administrators group and using a config.xml to make those users only be members of the Users group on the destination computer. I am running these USMT scripts as the users themselves, so they are already administrators on both the source and destination computer when scanstate and loadstate run.
I am finding that the users are still members of administrators after loadstate. Am I doing something wrong or does this XML not work?
<Configuration>
<ProfileControl>
<localGroups>
<mappings>
<changeGroup from="administrators" to="Users" appliesTo="MigratedUsers">
<include>
<pattern>*</pattern>
</include>
</changeGroup>
</mappings>
</localGroups>
</ProfileControl>
</Configuration>
Answer
Long answer, deep breath:
1. USMT 4.0 requires that the user running loadstate.exe is a member of the built-in Administrators group and holds privileges SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege, SeDebugPrivilege, SeSecurityPrivilege.
2. It is not a best practice that you log on as the end user being migrated or that end users run their own migrations:
- From a security perspective, it’s bad if USMT migration users have to know the end user’s domain password.
- From a USMT perspective, it’s bad because the end user’s more complex profile and settings are more likely to be in-use and fight the migration, unlike a simple migration user that exists only to run USMT.
- If the end user is running it himself, it’s bad because they have no way to understand if USMT is working correctly.
- Therefore, you should always use separate migration user accounts.
It’s easy to misinterpret the results of using this XML, though. It is not retroactive - if the group memberships already exist on the destination before running loadstate, USMT does not alter them. USMT is designed to copy/skip/manipulate source groups but not destroy destination existing groups.
Since your design requires destination administrator group memberships before running loadstate, this XML cannot work as you desire. If you switch to using separate migration accounts, MDT, or SCCM, then it will work correctly.
Question
I am using new Server Manager in Windows Server 2012 Release Candidate to manage the remote machines in my environment. If I right-click a remote server I see that list of management tools for the given roles I installed. When I run some of the GUI tools like LDP or Computer Management, they target the remote servers automatically. However, the command-line tools just show the help. Is this intentional or should it run in the context of the remote server?
Answer
All of the command-line tools are run in this fashion, even when they support remote servers (like repadmin or dcdiag) and even when targeting the local server. We can’t get into a design that deals out a million command-line arguments – imagine trying to provide the menus to support all the various remote scenarios with NETDOM, for example. 😀
Since providing a remote server alone isn’t enough to make most tools work – Dcdiag alone has several dozen other arguments – we just went with “let’s get the admin a prompt and some help, and let them have at it; they’re IT pros and smart”.
If you haven’t used Server Manager yet, get to it. It’s a great tool that I find myself missing in my Win200L environments.
The “L” is for legacy. YeeaaaahhinyourfaceolderproductsthatIstillsupport!!!
Question
Does USMT 4.0 migrate the Offline Files cache from Windows XP to Windows 7? My testing indicates no, but I find articles implying it should work.
Answer
Unfortunately not. Through an oversight, the migration manifest and down-level plugin DLL were never included. The rules of USMT 4.0 are:
- USMT 4.0 does not migrate CSC settings and the "dirty" (unsynchronized to server) file cache from Windows XP source computers
- USMT 4.0 does migrate CSC settings and the "dirty" (unsynchronized to server) file cache from Windows Vista and Windows 7 source computers
In order to migrate the CSC dirty cache, USMT needs plugin DLLs provided by Offline Files. The Offline Files changes from XP to Windows 7 were huge, but even Win7 to Win7 and Vista to Win7 need the plugins for the path conversions.
To workaround this issue, just ensure that users manually synchronize so that all offline files are up to date on the file server. Then migrate.
If you are migrating from Vista (why?! it’s great!!!) or Windows 7 and you want to get the entire cache of dirty and synchronized files, you can use the DWORD value to force the cscmig.dll plugin to grab everything:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\CSC\Parameters
MigrationParameters = 1
This is rather silly in a LAN environment, as it will take a long time and increase the size of your compressed store for little reason; these files are going to sync back to the user anyway after the migration. Maybe useful for remote users though; your call.
Question
I'm using Windows Server 2012 Release Candidate and I'm trying to create a new Managed Service Account. I'm running the following from an elevated PS Active Directory module:
New-ADServiceAccount -name Goo
The command fails with error:
NewADServiceAccount : Key does not exist
Answer
There are new steps required for managed service accounts in Win2012. We created an object class called a group Managed Service Account (gMSA). GMSA supersedes the previous standalone Managed Service Account (sMSA) functionality introduced in Windows Server 2008 R2. It adds support for multiple computers to share the same service account with the same password automatically generated by a domain controller. This makes server farms using MSAs possible for the first time. SQL 2012, Win2012 IIS app pools, scheduled tasks, custom services, etc. all understand it. It’s very slick.
The new Microsoft Key Distribution Service on Win2012 DCs provides the mechanism to obtain the latest specific key for an Active Directory account. The KDS also continuously creates epoch keys for use with any accounts created in that epoch period. For a gMSA, the domain controller computes the password on the keys provided by the KDS in addition to other attributes of the gMSA. Administrator-authorized Windows Server 2012 and Windows 8 member hosts obtain the password values by contacting a Win2012 DC through Netlogon and cache that password for use by applications. The administrator never knows the password and it’s secure as it can be – just like a computer account password, it’s the maximum 240-bytes of randomly generated goo, changed every 30 days by default. The new KDS is used for other features besides gMSA as well.
And this finally brings me to your issue – you have to first create the root key, using the Add-KdsRootKey cmdlet. This root key is then used as part of all the subsequent gMSA work.
If you want to see some preliminary step-by-step documentation, check out Getting Started with Group Managed Service Accounts. I’ll be coming back to this new feature in detail after we RTM Windows Server 2012.
Question
What does the what /disabledirectoryverification option do in DFSRadmin.exe membership new?
Answer
If the folder you specified for the RF with /localpath does not exist with membership new, dfsradmin.exe will create it for you by default with the correct permissions. If it does exist already, it will modify the existing permissions to let the DFSR service use that folder. If the folder already exists with the correct permissions, it does nothing. Using this argument prevents all of these convenient actions.
You would use this argument mainly if you were a crazy person.
Other Stuff
I didn’t get to go to Comic-Con this year, but thanks to the InterWaste, you can at least see some of the footage sans the special trailers. The best ones I’ve found are… well, pretty obvious:
- The Walking Dead panel (part 1,part 2, part 3) + Kirkman’s panel. Because, you know, there are supposed to be comics at comic-con
- Firefly 10th Anniversary panel
- Community panel
- Expendables 2 panel (with Arnold and Terry Crews! Pah-pah-pah-pah-pah-pah-power!)
- Robert Downey Jr. making a bunch of kids’ day
- But the best of all time was still from last year… Game of Thrones Season 1 panel. Jason Momoa steals the show.
There are often some heavy-duty spoilers in these panels – no whining if you find out that Superman is from Krypton and Batman’s parents were killed by the Joker. They also get a little sweary sometimes.
Naturally, if comic-con is your thing, you need your fill of cosplay. The two best galleries are Comicvine.com and – rather oddly – tested.com.
This is how David Fisher sees himself when he looks in the mirror.
It’s summer, which means good reading. IO9 has their annual list of the best Sci-Fi and Fantasy to check out. Redshirts was pretty good and I am starting Ready Player One shortly as no one can shut up about it (Ernest Cline will give you a Delorean if you are an ultrageek). Charles Stross is an automatic if you’re in IT or a British person; in that vein I recently enjoyed The Rook and am revisiting William Gibson this month.
And finally:
Hey, look it’s Ned in a restaurant, grab a picture!
And look, he’s with Satan!
Until next time,
- Ned “I always feel like someone’s watching me” Pyle | https://blogs.technet.microsoft.com/supportingwindows/2012/07/20/friday-mail-sack-i-dont-like-the-taste-of-pants-edition/ | CC-MAIN-2017-34 | refinedweb | 2,143 | 62.78 |
Xapi
The OSM Extended API (or xapi, pronounced zappy) is a read-only API protocol, based on a modified version of the OSM main API, that provides enhanced search and querying capabilities. It offers search queries for some common simple use cases and helps to take load off the main API. In particular, it reimplements the standard map request such that it can be performed much faster. Xapi uses a REST style interface with X-path flavouring. More sophisticated queries can be handled with other read-only mirrors such as Overpass API which support a more powerful but more complex syntax
Xapi only ever deals with elements that are current and does not return any elements that are historical or deleted. The source database is a mirror of the main OSM database and is updated via the per-minute diff dumps. The data is normally no more than about 10 minutes behind the main database.
All responses are in the same format as the standard protocol, but with the addition of some namespaced extensions. Tag queries use an X-path like syntax to specify search terms. The visible attribute is excluded from the response because it always has a true value.
Contents
- 1 Web services available
- 2 Implementations
- 3 Query Map
- 4 Query Tags
- 5 Predicates
- 6 Tags
- 7 Usage
- 8 Limitations
- 9 Proposed Future Extensions
- 10 Implementation-specific differences
- 11 Alternatives
- 12 See also
Web services available
Known public running deployments :
-?... Running normally Overpass API based
-?... Running normally Overpass API based
-?... Running normally Overpass API based Provided by OpenStreetMap_France more info at Servers/api.openstreetmap.fr
-... Running normally (a bit slow though) - JXAPI based provided by Open Mapquest. To be decomissioned on October 31, 2016 (Since 2015-09 a key is required. See MapQuest XAPI service)
-... No answer JXAPI based by Ian Dees
-... status: Error 500 on all requests JXAPI based provided by Rambler, stats page, relations not fully supported
Implementations
There are several code/database implementation of the XAPI idea. These are listed below.
Overpass API
Overpass API now has a XAPI Compatibility Layer. It supports most XAPI queries, as well as its own, more extensible query language.
jXAPI
In January 2011 Ian Dees created a new Java version of XAPI backed onto postGIS. See his diary entry for details. Several people are now running this on different servers.
pnorman's blog post on jXAPI setup has some information on tuning postgresql for a large dataset and speeding up the initial load of data.
Xappy.js
Xappy.js is a reimplementation of the OSM XAPI in node.js (Java Script). Currently using Postgres and the PostGIS extension with the option to implement other backends. No known public instances
The original XAPI
The original XAPI was created using GT.M (formerly MUMPS) by User:80n. There were multiple instances of the xapi service running on several different servers. Each server could be accessed directly or via a redirect which was used to direct the request to a suitable server of its choosing. Source code is here
No known public instances
Query Map
The Map query is identical to the main API map query and returns:
- All nodes that are inside a given bounding box and any relations that reference them.
- All ways that reference at least one node that is inside a given bounding box, any relations that reference them [the ways], and any nodes outside the bounding box that the ways may reference.
GET /api/0.6/map?bbox=left,bottom,right,top
where:
Notes
- Unlike the main API which restricts queries to 0.25 square degrees, XAPI allows much larger requests, up to 10,000,000 elements (this is still less than a third of California) or 100 square degrees, whichever is smaller.
- The map query is functionally identical to the tag query
/api/0.6/*[bbox=left,bottom,right,top]
- There must not be spaces in the string of values defining the box.
Query Tags
Xapi implements queries for all three kinds of elements; nodes, ways and relations.
Nodes
A node request will return an xml document containing nodes and their associated tags. The URL for a node request takes the following form:[...]
This will return a standard OSM API response containing nodes and tags. For example:
<?xml version='1.0' standalone='no'?> <osm version='0.6' generator='xapi: OSM Extended API' xmlns: <node id='672180' lat='48.2111685091189' lon='16.3035366605548' timestamp='2006-09-11T16:28:25+01:00' version='1' changeset='10968'> <tag k='amenity' v='hospital'/> <tag k='name' v='Wilhelminenspital'/> </node> <node id='3596186' lat='53.4633699598014' lon='-2.22667910006381' timestamp='2007-06-21T17:10:58+01:00' version='2' changeset='2213'> <tag k='amenity' v='hospital'/> <tag k='name' v='Manchester Royal Infirmary'/> </node> ... </osm>
Ways
The URL for way requests has the following form:[...]
This returns an xml document containing ways that match the search terms. For each matching way the nodes referenced by that way are also returned. An example of the response from a <tag k='source' v='Yahoo'/> </node> ... <way id='4958218' timestamp='2007-07-25T01:55:35+01:00' version='3' changeset='2211'> <nd ref='218963'/> <nd ref='331193'/> ... <tag k='landuse' v='residential'/> <tag k='source' v='landsat'/> </way> </osm>
Relations
The URL for relation requests has the following form:[...]
This returns an xml document containing relations that match the search terms. For each matching relation the nodes and ways referenced by that relation are also returned. An example of the response from a relation ... <way ... <relation id='2670' timestamp='2007-10-25T03:05:34Z' version='32' changeset='2211'> <member type='way' ref='3992472' role=''/> <member type='way' ref='3992524' role=''/> <member type='way' ref='4253050' role=''/> <member type='way' ref='4253053' role=''/> <member type='way' ref='4266813' role=''/> <member type='way' ref='10285106' role=''/> <tag k='name' v='Fonnereau Way'/> <tag k='network' v='Ipswich footpaths'/> <tag k='type' v='route'/> </relation> </osm>
All Elements
All elements (nodes, ways and relations) that match the given filter predicates can be requested using the following URL:*[...]
This returns an xml document containing nodes, ways and relations that match the search terms. For each matching way the nodes and referenced by that way are also returned. Likewise, for each matching relation the ways and nodes referenced by that relation are also returned. An example of the response from this type of query looks like this:
<?xml version='1.0' standalone='no'?> <osm version='0.6' generator='xapi: OSM Extended API' xmlns: </node> ... <way id='4958218' timestamp='2007-07-25T01:55:35+01:00' version='1' changeset='2211'> <nd ref='218963'/> <nd ref='331193'/> ... <tag k='amenity' v='hotel'/> <tag k='building' v='hotel'/> </way> <relation id='123456' timestamp='2007-10-25T03:05:34Z' version='32' changeset='2211'> <member type='node' ref='331193' role=''/> <member type='node' ref='331194' role=''/> ... <tag k='amenity' v='hotel'/> <tag k='operator' v='Premier Inns'/> <tag k='type' v='operators'/> </relation> </osm>
Predicates
Each API request can be suffixed with selection predicates which determine which elements to select. For example [amenity=hospital] will select all elements that have an amenity tag with a value of hospital. The full url to select all nodes that are tagged as hospitals would be:[amenity=hospital]
A request can be suffixed with multiple predicates, each of which further constrains the results (currently limited to one tag predicate and one bbox predicate, though jXAPI and Overpass servers support multiple tag predicates). For example:[amenity=hospital][bbox=-6,50,2,61]
this request will select and return all nodes with a tag of amenity=hospital within the bounding box that covers the whole of the England, Wales and Scotland.
Tag PredicatesA selection predicate must be of the form
[key=value]. For example:
node[amenity=hospital]will match any node that has an amenity key with a value of hospital, ie
<tag k="amenity" v="hospital"/>
A union operator may be used to select multiple values. For example to select all major roads:
way[highway=motorway|motorway_link|trunk|primary]
The union operator can also be used with the key. For example to select golf courses:
node[amenity|leisure=golf_course]
A wildcard can be used for the value (but not for the key), so predicates similar to the following examples are possible:
way[construction=*]
way[highway=*]
Key wildcards were supported in the past, but this is no longer maintained.
Note: The URL needs to be UTF-8 url encoded in case of non-ascii characters.
BBox Predicates
Another form of selection predicate is the bbox pseudo key. A selection predicate of the form
[bbox=left,bottom,right,top] defines a bounding box that is used to limit the extent of the result document. Only elements that have some part within the bbox will be included in the result document.
Unlike the standard OSM API, the bbox predicate is not limited in size unless it is used without a tag predicate, in which case it is limited to 100 square degrees.
The default extent, if a bbox predicate is not specified, is the whole planet. This is equivalent to specifying
[bbox=-180,-90,180,90].
Child Element Predicates
Items can be selected based on whether or not they have child elements. For example, ways can be selected that do not have any tags or do not have any nodes. This is achieved by using an XPath-like element test. Specifically the following are implemented:
/api/0.6/way[nd]- selects ways that have at least one node
/api/0.6/way[tag]- selects ways that have at least one tag
/api/0.6/way[not(nd)]- only selects ways that do not have any nodes
/api/0.6/way[not(tag)]- only selects ways that do not have any tags
/api/0.6/node[way]- selects nodes that belong to at least one way
/api/0.6/node[not(way)]- selects nodes that do not belong to any way
/api/0.6/node[not(tag)]- selects nodes that do not have any tags
/api/0.6/relation[node]- selects relations that have at least one node member
/api/0.6/relation[way]- selects relations that have at least one way member
/api/0.6/relation[relation]- selects relations that have at least one relation member
/api/0.6/relation[not(node)]- selects relations that do not have any node members
/api/0.6/relation[not(way)]- selects relations that do not have any way members
/api/0.6/relation[not(relation)]- selects relations that do not have any relation members
Notes:
- If using wget then parenthesis characters need to be escaped, so for negation predicates, use
[not\(way\)]rather than
[not(way)].
- In the OSM xml schema nodes do not really have ways as child elements. However, there is, logically, a many-to-many relationship between nodes and ways, and so xapi implements this relationship and enables nodes to be selected based on whether or not they are members of a way. Of course, the output xml is the same as normal and does not include way elements within a node element.
Escaping
Values within predicates can be escaped by prefixing a backslash character. For example to retrieve elements with a tag value that contains a pipe character such as
[route=46|46A] you would need to use
[route=46\|46A].
The following characters can be escaped in this way: | [ ] * / = ( ) \ and space
Spaces in tag values do not normally need to be escaped but this is dependent on the client. In this case you need to use URL escaping which requires that each space be replaced by %20. So
[route=46 46A] would become
[route=46%2046A].
The main method of querying Xapi is using a tag/value combination in a predicate. In addition to all the normal tags that you expect to find, the following attributes can also be queried using
/api/0.6/*[@attribute=value]
- @user - the username of the last person to change an element
- @uid - the user id of the last person to change an element
- @changeset - the changeset in which an element was changed
Usage
Xapi URLs can be used from within any web-browser, however a simple query can return several Mb of data which can overwhelm some browsers. It is recommended that a tool such as wget or curl be used with the output directed to a file. For example, the following command uses wget to select all hospitals and store the result document in a file named data.osm. Note that wget has a default timeout of 15 minutes which may be too short for some queries so be sure to add the --timeout=0 option to turn this off.
wget --timeout=0[amenity=hospital] -O data.osm
Note: If you use curl, it will handle redirections automatically, so you need to query the host server directly or use the "--location" option. Also you need to use the "--globoff" option, otherwise it will try to interpret the brackets ("[", "]") as part of the command line:
curl --location --globoff "[amenity=hospital]" -o data.osm
If you use a script regularly to fetch data from Xapi it would be helpful to set the user agent string to something meaningful. This will help us understand more about how Xapi is being used.
Limitations
- Predicates. Currently each request is limited to one tag predicate and one bbox predicate. In the future it is hoped that more sophisticated conditions will be implemented. Multiple bboxes would be great for applications like GpsMid - they already implemented data retrieval over xapi in Osm2GpsMid for single regions which is very helpful.
- Request grammar. The request grammar is not formally defined and is not processed using a proper parser, so malformed requests may have unpredictable results. Caveat Emptor.
Proposed Future Extensions
- "Search by region": the ability to limit queries not by a bounding box, but by recognized regions (e.g. Countries, Counties, continents). Proposed Jan 2011.
- json output: We have this feature in xappy.js it might be used by setting the http content-type header to "application/json". Here some format infos: Xappy.js#JSON output
Implementation-specific differences
Some xapi implementations differ from the specification set out in this page.
Jxapi
Relations
pgsnapshot and jxapi relation support for relations by area is quirky. These quirks can result in a response that does disagrees with the documented Xapi API and are not backwards-compatible. Todo: list quirks.
Request Metadata
jxapi uses the format used by osmosis state.txt for xapi:planetDate, not the documented xapi format.
Bounds =
jxapi returns a bounds element, like the main API. This could cause issues with any programs expecting xapi output exactly as documented but any programs capable of parsing the normal API output should have no issues.
API element queries
jxapi supports the GET /api/0.6/[node|way|relation]/#id and GET /api/0.6/[nodes|ways|relations]?#parameters queries of [API v0.6]. It is not clear if this is part of the Xapi specification but if not the addition is backwards compatible.
Metadata queries
The standard instructions for setting up jxapi do not include the indexes required to optimize the @user, @uid and @changeset queries. They will run but may run very slowly if not restricted to a small region.
Overpass
Request Metadata
The request metadata returned from overpass differs from the xapi metadata. Todo: list how it differs
Metadata
Overpass does not return the metadata (version number and changeset) by default. An xapi request against the overpass xapi compatibility layer will not result in a .osm file that can be used for editing. See @meta below.
@meta
As a work-around to the above, [@meta] can be added to a request to have the metadata returned and an editable file.
Alternatives
See also
- API v0.6
- Xapi source code uses GT.M a high-performance schemaless database. (up again Jan 2011)
- xappy.js a reimplementation in Java Script
- XAPI Viewer | http://wiki.openstreetmap.org/wiki/Zappy | CC-MAIN-2016-44 | refinedweb | 2,657 | 55.54 |
Hello everybody!
First of all, Merry Christmas!
And now to the point : I want to make a game (yeah Cliché beginning) and I want the main character (1ST-Person camera) to be split in 2. I mean it in a sense of left eye right eye. So with the left eye you see like a human (it's a horror game) and the right like a camera. I want each eye to see different things. Like in the left part of the screen I see ghosts, while on the right part I do not see them.
I know I can make the screen split in two with Screen.width/2. But now the question. How should I make it? I mean the 2 camera's. Make 2 Camera's and give them each another tag? I honestly do not know how to begin, yet I am all fired up with coal from Santa, and I want to do it. Both the eyes have to be controlled by player 1, so it's not going to be a multiplayer game. Don't mind the controls, I can get that done. The problem is with the camera's.
And for that I need your help.
So, thanks in advance, and have a nice day! Daniel Nowak Janssen
Try using layers and by assigning culling mask(number of layers each camera sees) to each camera. Select camera ->camera component->culling mask->select the layer of the game objects for which this camera should see. Hope this may help you at a very basic level Nsks
Answer by LazyElephant
·
Dec 15, 2015 at 05:46 AM
What you will need is called a scissor rect as talked about in this other question
In a test scene, the steps I followed to get this working were:
Create a new layer to hold your invisible objects. (Edit->Project Settings->Tags and Layers)
Create an empty game object to use as a parent for your two cameras, this will allow you to move them around as if they were one.
Move the default camera in the scene to be a child of the empty game object. Make sure that the transform of the camera is at (0, 0, 0). In the inspector, click on the Culling Mask and uncheck the layer you want your invisible objects to be on. Make sure the Depth is set to 0.
Add a 2nd camera to the scene and make it a child of the empty game object. make sure the transform is the same as the first camera. In the inspector, make sure the Culling Mask is Everything and set the Depth to 1. Remove the Audio Listener component from this camera or unity will give you errors about having 2 in the scene.
Create a new c# script and name it Scissor. Copy and paste the code below into it. Note that this is the same code as in the question I linked, but changed a little because it wasn't running in Unity 5 since they removed the camera shortcut in favor of using GetComponent.
using UnityEngine;
using System.Collections;
public class Scissor : MonoBehaviour {
public Rect scissorRect = new Rect (0,0,1,1);
private Camera _camera;
void Awake(){
_camera = GetComponent<Camera>();
}
public static void SetScissorRect( Camera cam, Rect r )
{;
}
// Update is called once per frame
void OnPreRender ()
{
SetScissorRect( _camera, scissorRect );
}
}
Add the new script to your 2nd camera. In the inspector, change the Scissor Rect of the script to w=0.5 and h=1. This will set the view port to the left half of the screen.
The only other thing you have to remember to do is put all the objects that are invisible on the special layer you created. They should only be displayed in the left half of the screen. Hope this helps.
First of all thank you!
Second of all, What does matrix do in this context? Does it do the arbitrary linear 3D transformations? Can you maybe explain to me what that Matrix 4x4 does?
Thank you again for your time, And have a Merry Christmas, Daniel Nowak Janssen
I don't understand the details either, but I can give a basic explanation. In Unity, if you resize the camera's view port, it doesn't just cut out the parts of the screen that would be outside the new size, it shrinks the scene down a bit. For instance, if you have a cube in the direct center of the screen and change the camera width to .5, you'll still see all of the cube in the screen, still in the middle of the view port, although smaller. You can test this yourself in the editor.
The three matrices made with the Matrix4x4.TRS (Translate, Rotate, Scale) change the view port of the camera to match what you would see on just the portion of the screen you want as if the camera view port were still full size.
Somehow, my second camera does not show only the layer I want. I made a new layer called Ghost, and I made one enemy in that layer. But both my camera's see the same enemy, but only the left part of the screen should see the enemy. Maybe I did something wrong? I do not know, but maybe it is conflicting with my MouseLook script. (It makes you move your camera. Here is the script :
using UnityEngine;
using System.Collections;
public class MouseLook : MonoBehaviour {
public enum RotationAxes
{
MouseXAndY = 0,
MouseX= 1,
MouseY= 2
}
public RotationAxes axes = RotationAxes.MouseXAndY;
public float SensitivityHor = 9.0f;
public float SensitivityVer = 9.0f;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
private float _rotationX = 0;
// Update is called once per frame
void Start()
{
Rigidbody body = GetComponent<Rigidbody>();
if (body != null)
body.freezeRotation = true;
}
void Update () {
if ( axes == RotationAxes.MouseX)
{
//horizontal movement
transform.Rotate(0,Input.GetAxis("Mouse X") * SensitivityHor, 0);
}
else if (axes == RotationAxes.MouseY)
{
//vertical movement
_rotationX -= Input.GetAxis("Mouse Y") * SensitivityVer;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
else
{
//makes it possible to rotate my head
_rotationX -= Input.GetAxis("Mouse Y") * SensitivityVer;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float delta = Input.GetAxis("Mouse X") * SensitivityHor;
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
}
I made 2 Camera's and made them children to my Main character (a capsule for testing) and still the enemy does not disappear on the right side of my screen. it just stays visible although it should not.
Thanks again for your help, and have a Merry Christmas. Daniel Nowak Jans.
Jerky 3rd Person Camera Following Movement and Rotation
0
Answers
Unity - Dancing Ball World camera following and rotating system
1
Answer
Camera movement and gun follow in unity
0
Answers
Camera movement similar to World of Guns
1
Answer
Camera isn't following mouse in FPS
0
Answers | https://answers.unity.com/questions/1112309/screen-is-2-cameras-with-each-different-properties.html | CC-MAIN-2020-05 | refinedweb | 1,158 | 74.49 |
Building Angular 2 Demos With System.js And TypeScript
If you've followed my blog for any time now, you've probably come to understand that I love ES5. Sometimes, I think maybe I'm one of the few people who actually thinks JavaScript is an awesome language. And, for months now, I've tried my hardest to write all of my Angular 2 demos using a single ES5 [and HTML] file. But, I must admit that some of the syntax provided for in ES6 and TypeScript is nice. And, it's the wave of the future. So, I'm going to try and get my new Angular 2 demos done with System.js and TypeScript.
Run this demo in my JavaScript Demos project on GitHub.
I know that not everyone enjoyed my "one page" approach to demos. But, for me, a single page made everything easier to think about. I could read it from top-to-bottom and each module depended on one of the modules below it. No jumping around from file to file, switching mental contexts, trying to follow the flow of logic. It was simple, easy, and I could CMD-D to seamlessly jump from one reference to another (using SublimeText).
I tried really hard to keep the "one page" approach while also leveraging TypeScript. But, no matter what I tried, it seemed to be the worst of both worlds. I neither got the benefits of ES5 hoisting nor the benefits of ES6 module exports. And, it just looked ugly. So, I have finally given up and am breaking the demos up into individual files.
That said, I am still refusing to add a build step. It's very important to me that my demos be runnable with as little overhead as possible. At least, whenever they can. As such, I'm using the System.js TyepScript plugin to perform on-the-fly transpiling to ES5 in the browser.
Now, I don't really know much about System.js or TypeScript. So, I'd like to give a huge shout-out to Meligy who helped me get this working. Also, special thanks to Martin Hochel, Guy Bedford, and a few others for letting me hassle them with questions. You guys all rock!
Because I keep all of my JavaScript demos in a single repository, I didn't want each demo to have it's own copy of all the NPM modules. But, because the demos are hosted on GitHub pages, I also don't have the luxury of running "npm install" for each demo. As such, all of the demos need to share a common set of NPM modules that are committed to the repository. Luckily, with System.js path and map aliasing, I can have all the commonly loaded modules be pulled from my vendor scripts.
In the common files, I now have:
- /vendor/angularjs-2-beta/rc1/node_modules
- /vendor/angularjs-2-beta/rc1/package.json
- /vendor/angularjs-2-beta/rc1/tsconfig.json
Notice that the package.json file is part of the common files. Any "npm install" that I do will be in the common files and the result of said install will be available to all of my System.js-based Angular 2 demos.
In the actual demo, I then configure System.js to point to "/vendor/angularjs-2-beta/rc1/" for all of the common dependencies:
(function() { // Alias the path to the common rc1 vendor scripts. var paths = { "rc1/*": "../../vendor/angularjs-2-beta/rc1/*" }; // Tell Angular how normalize path and package aliases. var map = { "@angular": "rc1/node_modules/@angular", "angular2-in-memory-web-api": "rc1/node_modules/angular2-in-memory-web-api", "rxjs": "rc1/node_modules/rxjs", "ts": "rc1/node_modules/plugin-typescript/lib/plugin.js", "tsconfig.json": "rc1/tsconfig.json", "typescript": "rc1/node_modules/typescript/lib/typescript.js" }; // Setup meta data for individual areas of the application. var packages = { "app": { main: "main.ts", defaultExtension: "ts" }, "rc1/node_modules": { defaultExtension: "js" } }; var ngPackageNames = [ "common", "compiler", "core", "http", "platform-browser", "platform-browser-dynamic", "router", "router-deprecated", "upgrade" ]; ngPackageNames.forEach( function iterator( packageName ) { packages[ "@angular/" + packageName ] = { main: ( packageName + ".umd.js" ) // , // defaultExtension: "js" }; } ); System.config({ paths: paths, map: map, packages: packages, transpiler: "ts", typescriptOptions: { tsconfig: true }, meta: { typescript: { exports: "ts" } } }); // Load "./app/main.ts" (gets full path from package configuration above). System .import( "app" ) .then( function handleResolve() { console.info( "System.js successfully bootstrapped app." ); }, function handleReject( error ) { console.warn( "System.js could not bootstrap the app." ); console.error( error ); } ) ; })();
As you can see, I'm mapping all "rc1/*" paths to the vendor directory. And, I'm mapping all common dependencies onto "rc1/". Most of the general logic in this file was taken from the Plunkr "Getting Started" guide for Angular 2.
My main demo page then loads several hard dependencies from the common node modules followed by the above configuration file:
<!doctype html> <html> <head> <meta charset="utf-8" /> <title> Building Angular 2 Demos With System.js And TypeScript </title> <link rel="stylesheet" type="text/css" href="./demo.css"></link> <!-- Load libraries (including polyfill(s) for older browsers. --> <script type="text/javascript" src="../../vendor/angularjs-2-beta/rc1/node_modules/core-js/client/shim.min.js"></script> <script type="text/javascript" src="../../vendor/angularjs-2-beta/rc1/node_modules/zone.js/dist/zone.js"></script> <script type="text/javascript" src="../../vendor/angularjs-2-beta/rc1/node_modules/reflect-metadata/Reflect.js"></script> <script type="text/javascript" src="../../vendor/angularjs-2-beta/rc1/node_modules/systemjs/dist/system.src.js"></script> <!-- Configure SystemJS loader. --> <script type="text/javascript" src="./system.config.js"></script> </head> <body> <h1> Building Angular 2 Demos With System.js And TypeScript </h1> <my-app> Loading... </my-app> </body> </html>
To test this all out, I created a very simple demo that loads a service that makes an API request to load an external JSON file (of friends). Here's my root component:
// Import the core angular services. import { Component } from "@angular/core"; import { HTTP_PROVIDERS } from "@angular/http"; import { NgInit } from "@angular/core"; // Import the application components and services. import { FriendService } from "./friend.service"; // I provide the root component of the application. @Component({ selector: "my-app", providers: [ HTTP_PROVIDERS, FriendService ], template: ` <div * Loading friends... </div> <div * <p> You Have {{ friends.length }} friends! </p> <ul> <li * <span>{{ friend.name }}</span> </li> </ul> </div> ` }) export class AppComponent implements NgInit { // I hold the collection of friends to display. public friends: any[]; // I provide access to the friend repository. public friendService: FriendService; // I determine if the data has been fully loaded. public isDoneLoading: boolean; public isLoading: boolean; // I initialize the component. constructor( friendService: FriendService ) { this.friends = []; this.friendService = friendService; this.isDoneLoading = false; this.isLoading = true; } // --- // PUBLIC METHODS. // --- // I get called once after the component has been instantiated and the input // properties have been bound. public ngOnInit(): void { this.friendService .getFriends() .subscribe( handleResolve.bind( this ) ) ; function handleResolve( newFriends: any[] ) : void { this.friends = newFriends; // Flag the data as fully loaded. this.isLoading = false; this.isDoneLoading = true; } } }
As you can see, it's all written in TypeScript. This will be transpiled on-the-fly to an ES5 target when System.js goes to load it (via the application bootstrapping, which I have not shown).
The root component provides the Http-related services and depends on the FriendService:
// Import the core angular services. import { Http } from "@angular/http"; import { Injectable } from "@angular/core"; import { Observable } from "rxjs"; import { Response } from "@angular/http"; // Enable RxJS operators. import "rxjs/add/operator/map"; // I provide a service for accessing the Friend repository. @Injectable() export class FriendService { // I hold the URL prefix for the API call. private baseUrl: string; // I provide an HTTP client implementation. private http: Http; // I initialize the service. constructor( http: Http ) { this.baseUrl = "./app/"; this.http = http; } // --- // PUBLIC METHODS. // --- // I return the entire collection of friends as an Observable. public getFriends() : Observable { var stream = this.http .get( this.baseUrl + "friends.json" ) .map( this.unwrapResolve ) ; return( stream ); } // --- // PRIVATE METHODS. // --- // I unwrap the raw HTTP response, returning the deserialized data. private unwrapResolve( response: Response ) : string { return( response.json() ); } }
As you can see, this is also written in TypeScript.
Now, while the on-the-fly, in-browser TypeScript transpiler properly converts everything over to ES5, it doesn't appear to actually take into account type-checking. Meaning, if I have a function that's defined as returning an array but it actually returns a string, the transpiler doesn't throw an error. As such, if I include an incorrect type annotation, I probably won't notice it as it won't actually stop the demo from working. Oh well, you can't win every battle.
Part of me is sad that it has come this point. But, part of me is also excited for the future. I think that, in some ways, I stunt my learning by holding on too tightly to the existing technology. Now that I've taken the plunge on my demos, hopefully it will accelerate my learning of technologies like ES6, ES7, and TypeScript.
Reader Comments
@All,
Because type-checking wasn't actually working in this demo, I actually made two type-based errors:
import { NgInit } from "@angular/core";
.... was supposed to be:
import { OnInit } from "@angular/core";
And the RxJS import:
import { Observable } from "rxjs";
.... was supposed to be:
import { Observable } from "rxjs/Obersvable";
This just goes to show you why trying to use Types without having Type Checking enabled is kind of a dangerous thing.
@All,
I was finally able to get type checking enabled thanks to Frank Wallis and Guy Bedford:
sdfasdfasdf
Hi Ben,
Can you share any URL or project to understand how to configure package.json,systemconfig.js,tsconfig.json,typing.json
because i am very irritated to understand about those things.
@Sazdxfvb,
@Sazdxfvb,
awesome
i want to provide these kind of commenting & reply in my project can you please tell me that how can i implement this feature in my project. | https://www.bennadel.com/blog/3094-building-angular-2-demos-with-system-js-and-typescript.htm | CC-MAIN-2021-43 | refinedweb | 1,636 | 51.44 |
Windows Live Tools for Microsoft Visual Studio enables developers to incorporate a set of Windows Live services into their Web sites using Visual Studio and ASP.NET.
Using the Contacts ASP.NET Server Control, your users can easily share their contacts between Windows Live and your Web site. With the SilverlightStreamingMediaPlayer ASP.NET Server Control, you can show videos on your Web site from your Silverlight Streaming account with just drag-and-drop. The IDLoginStatus and IDLoginView ASP.NET Server Controls provide Windows Live ID authentication at your Web site for your users. Microsoft released its second community technology preview (CTP) in December, 2007. You can download this CTP from.
Through this CTP, Microsoft is releasing four ASP.NET Server Controls: Contacts, IDLoginStatus, IDLoginView, and SilverlightStreamingMediaPlayer. To help you develop Windows Live Web sites, Microsoft has created a project template as well. This release only works with Visual Studio 2008 and Visual Web Developer 2008 Express Edition at this time.
A key aspect to note is that the user is in control of their data.
Installation of the Windows Live Tools is straightforward. After installation is complete, Visual Studio displays an “ASP.NET Windows Live Web Site” project template in the File | New Web Site dialog box (Figure 1). Also, you can find these controls listed as “Windows Live Tools” in the Toolbox.
Creating Your First Project with the Windows Live Tools
To start your first project that integrates Windows Live services, navigate to File | New Web Site, and select the “ASP.NET Windows Live Web Site” template. Fill out the details to proceed with project creation. Open the Default.aspx Web page in designer mode by choosing “View Designer” from the context menu in the Solution Explorer.
This article will drill down into each of the newly introduced controls and what they offer for your Web site.
Contacts
Have you ever wondered why you have to enter a new shipping address for each Web site whenever you buy a gift for a friend? What if you could share the shipping address across multiple Web sites using a central address book? The Contacts control is a solution that allows you to safely transfer your contact information between Windows Live Contacts (a user’s single address book between Windows Live Messenger and Windows Live Hotmail) and the shopping Web site. Also, the Contacts control can help a Web site build viral communication channels where users can message one another the context of the Web site. For example, a shopping Web site can specify a promotion message that their users can send one another from the Web site.
The Contacts control offers three different views to best suit your needs: Tile, TileList, and List. In Tile/TileList views, Web site users can start an IM conversation or open an e-mail with a pre-defined message/custom greeting from the Web site, such as “Let’s discuss this topic.” List view allows users to select and share their Windows Live Contacts across multiple Web sites and centralize address book management in one place. It’s an off-the-shelf address book pre-filled with data for any Web site on the Internet.
The user maintains control of the data and has the authority to choose to share or not share their data with your Web site.
I’ll show you how easy it is to use Windows Live Contacts in your Web site. Drag-and-drop the Contacts ASP.NET Server Control from the Toolbox onto the Default.aspx Web page. The drag-and-drop operation adds the privacyPolicy.htm file to your project (you can replace this file with your own privacy policy statement). Run the Web site by hitting Ctrl+F5. Visual Studio, after compiling the Web site, launches the browser and displays Default.aspx. You will need to sign in using your Windows Live ID. After you are signed-in, the Contacts control renders your contacts from messenger and Hotmail. Figure 2 shows the Contacts control with its default settings.
Sharing Contacts Data
The Contacts control maintains secure data isolation between Windows Live Contacts and your Web site.
The control fetches your user’s contacts data from Windows Live servers via a secure HTTPS connection. The user selects the contacts that they want to share with your Web site, initiates the sharing of data, and reviews what data is being shared. Only then is any data released to your Web site.
Another key aspect that requires special mention is the privacy statement for your Web site. The Contacts control requires that you provide a privacy statement URL. The Contacts control renders a privacy statement URL to the user while transferring contact information to your Web site. In your privacy statement, you must clearly state the usage of the data being transferred. You can either discard this data after use or store it in your servers for future usage. If you choose to store the data, you should clearly state this in your privacy statement and provide a means for the user to review or delete the stored data.
To enable sharing contacts data for the shipping address scenario as mentioned earlier, you would need to:
- Set the PrivacyStatementURL to a Web page/link that describes the privacy statement for your Web site.
- Set the View property to List.
- Set the DataDesired property to specify which data elements need to be fetched from Windows Live Contacts.
- Provide client/server-side event handlers to receive the data and handle the shipping process for the purchased items.
Next, I’ll show you how to modify the project to allow users to share their contacts data on Default.aspx. You can get the complete reference to the data elements allowed for the DataDesired property at. Set the following values for the DataDesired property in the property grid for the Contacts control: firstname, lastname, personalstreet, personalcity, personalstate, personalcountry, and personalpostalcode.
Once data is transferred by the Contacts control, you can process the data in the OnClientData or OnServerData event handlers.
The event handler for OnClientData (in JavaScript) can look like the following:
<script type="text/javascript"> function Contacts1_OnClientData(sender, args) { var s = args.contacts.length+ " records\r\n"; for (var i = 0; i < args.contacts.length; i++){ for (var j in args.contacts[i]){ s += j + ": " + args.contacts[i][j]+"\r\n"; } s += "\r\n"; } alert(s); } </script>
Once you execute this code, you will notice that an alert comes up, which enumerates the data elements and their values (Figure 3). The OnClientData event handler receives the transferred contacts as an array of objects. Each object represents one contact selected by the user for transfer. Each contact object has data elements corresponding to the DataDesired property. If a certain data element does not exist for a contact, it will not be returned.
You can also specify similar processing logic in server-side code. The Contacts control offers a corresponding server-side event for processing data received from the transfer (Listing 1).
The declaration for the Contacts control on the default.aspx Web page would look like:
<live:Contacts
Writing Contacts Data
The Contacts control allows you to write into a user’s address book. For example, a Web page may allow users to transfer Contacts data from their Web site to Windows Live Contacts. When modifications are being attempted to a user’s address book, an alert is raised notifying the user. Users are then required to review the modification and approve. Once approved, the modifications are transmitted to Windows Live servers via a secure HTTPS connection. Again, the user is in control of their data in this case as well.
IDLoginView does template switching and association of Windows Live ID and ASP.NET membership profile.
For example, adding a contact to a signed-in user’s address book is very simple. The Contacts control provides the CreateContact method, which takes a list of contacts (List<Contact>). The Microsoft.Live.ServerControls namespace contains the definition of the Contact class. The Contact class has member properties that represent a contact’s data elements. A complete list of data elements is available at.
To demonstrate this, refer to Listing 2 and Listing 3. Listing 2 shows Default.aspx and Listing 3 shows Default.aspx.cs. Default.aspx has a Contacts control, an update panel, a text box where users can input e-mail for the contact to be added, and three button controls: adding a contact, adding a list of contacts, and deleting contacts.
The event handler, btnAdd_Click (defined in Listing 3), shows that it is very easy to add contacts to a user’s contacts. You start with creating a Contact object-set the data elements that you are interested in, create a generic List of contacts, and then pass it to the CreateContacts method. The Contacts control can then either abort or commit the operation. The following code snippet only shows how to set this for e-mail; however, you can extend the code to set whatever data elements your application desires:
//add contact to signed-in users' contacts protected void btnAdd_Click(object sender, EventArgs e) { List<Contact> objContacts = new List<Contact>(); Contact objContact = new Contact(); objContact.EmailPersonal = txtEmail.ToString().Trim(); objContacts.Add(objContact); Contacts1.CreateContacts(objContacts); Contacts1.CommitContacts(); }
Listing 3 also has btnAddList_Click, which you use to submit multiple contacts for addition. You can submit a maximum of 30 contacts in one operation. Use btnDeleteList_Click to perform batch deletions of contacts. You will notice that you must call the CommitContacts method after create or delete operations; otherwise, these operations won’t be finalized. btnDeleteList_Click also highlights how errors are reported back from create/delete operations. In btnDeleteList_Click, the code is attempting to delete four contacts where the fourth contact was never added. Once the CommitContacts method executes (after DeleteContacts) and the user approves the operation, a delete request is posted to Windows Live servers. After the request completes, the OnClientCommit event is raised followed by the OnServerCommit event. Figure 4 shows the event argument returned on the client side, args, which reports an error for the attempt to delete the nonexistent contact.
The Contacts control also offers other events for sign-in/sign-out, error handling, and properties for styling (text, color, height, and width). The reference for the Contacts control is available online at.
IDLoginStatus
IDLoginStatus provides Windows Live ID authentication, which can be used to identify visitors to your Web site. IDLoginStatus provides a unique, site-specific identifier for each Windows Live user. This allows the Web site to personalize the experience for the visiting user.
When a user clicks on the Sign-in link, the IDLoginStatus control redirects to the sign-in Web page on Windows Live servers () along with an application ID. After the user enters their credentials, the sign-in page redirects the user to the page with the IDLoginStatus control.
To obtain an application ID for your Web site, you need to register your application with the Windows Live ID service. You can do so by visiting (see sidebar: “Registering Your Application with Windows Live ID”).
IDLoginStatus provides an easy workflow for developers within the Visual Studio development environment. After you drag-and-drop the IDLoginStatus control onto your Web page, you can get a new application ID by clicking “Create new Application ID” from the IDLoginStatus tasks (Figure 5). After you complete the registration of your application and close the form, the IDLoginStatus control saves the application ID and application secret into Web.Config and sets the ApplicationIDConfigKey and ApplicationSecretConfigKey properties on the IDLoginStatus control. The control adds wll_appid and wll_secret keys into the <appSettings> section of the Web.Config file. At run time, the control checks the values of ApplicationIDConfigKey and ApplicationSecretConfigKey properties and reads the Web.Config keys.
The following snippet from Web.Config highlights this:
<appSettings> <add key="wll_appid" value="FF167FFE80FFF932" /> <add key="wll_secret" value="CoDeMagazine123" /> </appSettings>
The HTML declaration for IDLoginStatus looks like the following:
<live:IDLoginStatus
IDLoginStatus offers both client side and server side events for sign-in/sign-out. IDLoginStatus also returns AuthEventArgs, which contains the ApplicationUserID, TimeStamp (the time the user authenticated in seconds measured from Jan 1, 1970 GMT), and ApplicationContext (a parameter to round trip your application state through the redirections to and from the Windows Live servers). The ApplicationUserID is the unique site-specific identifier for the signed-in user.
If you are using ASP.NET membership, IDLoginStatus enables single-sign-on. You can set the AutomaticallyConvertAuthentication property to true. When this property is set to true, the IDLoginStatus control verifies whether the current signed-in user has previously associated with an ASP.NET membership profile and automatically logs-in to ASP.NET membership on existence of an association. Read more about this in IDLoginView.
You can find the complete reference for the IDLoginStatus control at.
IDLoginView
The IDLoginView control extends ASP.NET’s LoginView control. Where the LoginView control provides template switching based on a user’s logged-in state in ASP.NET membership, IDLoginView provides switching based on a user’s logged-in state in both ASP.NET membership and Windows Live ID.
IDLoginView adds three new templates in addition to the two provided in the LoginView control:
- AnonymousTemplate: Displayed to Web site users who are not logged into the Web site (inherited from LoginView).
- LoggedInTemplate: Displayed to Web site users who are logged into ASP.NET membership at the Web site (inherited from LoginView).
- LoggedInIDTemplate: Displayed to Web site users who are logged in with Windows Live ID at the Web site.
- LoggedInAllTemplate: Displayed to Web site users who are logged into both ASP.NET membership and Windows Live ID.
- AssociatePromptTemplate: Displayed to Web site users when they have logged in with both ASP.NET membership and Windows Live ID, but have not yet associated these two identities.
Not only does IDLoginView provide template switching based on a user’s logged-in state, but it also allows association of Windows Live ID and ASP.NET membership identities. Based on your choice, the AssociatePromptTemplate is presented to the user asking whether they want to associate their Windows Live ID and ASP.NET membership for a single-sign-on experience.
Refer to Listing 4 (IDLoginView.aspx) and Listing 5 (IDLoginView.aspx.cs) for the following discussion.
After you drag and drop the IDLoginView control onto your Web page, start by setting these two properties: AutomaticallyAssociateAuthentication and PromptOnAssociation. Setting the AutomaticallyAssociateAuthentication property to true instructs the IDLoginView control to associate ASP.NET membership and Windows Live ID when the user is logged in with both identities. IDLoginView calls AssociationManager.AssociateAuthentication passing the ApplicationUserID (Windows Live ID’s unique identifier for the signed-in user at your Web site) and the ASP.NET membership identity. If you chose to set the PromptOnAssociation property to true, the IDLoginView asks the user whether to associate their Windows Live ID with their ASP.NET membership before establishing an association (Figure 6).
If you haven’t yet, you need to launch the ASP.NET Web Site Administration Tool from Website | ASP.NET Configuration. Please make sure that you make the following changes:
- Set Authentication type to “From the Internet”. By default, this is not the case. You can access this setting from the Security tab of ASP.NET Web Site Administration, and then clicking “Select the authentication type”.
- Set up a few users by choosing “Create User”. This will create users for your Web site who will be saved in the ASPNETDB.MDF database in the App_Data folder.
Having set up the users for the Web site, you can test the template switching and association features in IDLoginStatus and IDLoginView, as provided in Listing 4 and Listing 5.
You may be surprised to see that all of the template switching and association functionality can be realized without you having to write a single line of code.
When a Web site visitor signs-in to your Web page using the IDLoginStatus control, IDLoginStatus sets the webauth cookie, which contains the ApplicationUserID for the signed-in user. The IDLoginView detects the state change after the IDLoginStatus control sets this cookie. IDLoginView then switches the template to the LoggedInIDTemplate and renders the specified contents. You can provide the content applicable to users having Windows Live ID in this template. Then, if a user signs-in to ASP.NET membership, IDLoginView switches to the LoggedInAllTemplate. At this time, if you had set the AutomaticallyAssociateAuthentication and PromptOnAssociation properties to true, IDLoginView renders the AssociatePromptTemplate to the user. If the user chooses to associate the two identities, IDLoginStatus creates an association between Windows Live ID and ASP.NET membership.
The btnRemove_Click event handler (Listing 5) shows how a developer can remove this association, if the user so chooses.
AssociationManager
The AssociationManager allows a developer to directly query, set, or remove associations for the signed-in user. The Microsoft.Live.ServerControls namespace contains this class. Include a using statement for the Microsoft.Live.ServerControls namespace in your program.
SilverlightStreamingMediaPlayer
You can upload cool videos you created to your Silverlight Streaming account () and play them on your Web site with drag-and-drop.
This control allows you to play your videos from a Silverlight Streaming service account. It extends the MediaPlayer control provided by the ASP.NET 3.5 Extensions Preview release.
Developers at design time can provide account credentials for their Silverlight Streaming account and choose the video that their Web page should play. After you drag-and-drop this control onto your Web page, you can specify the video to be played through the “Select Media File” form. This form is accessible through the control’s tasks window or property grid (Figure 7). Developers don’t need to write code to make a connection to Silverlight Streaming servers and choose videos. All this is encapsulated so that you can just specify the credentials and choose a video.
After you choose the video you want to play, the control saves this video URL in streaming:// format in the control’s MediaSource property. Also, it saves the Account and Key for your Silverlight Streaming account into Web.Config’s <appSettings> section. The following snippet from Web.Config highlights this. I’ve used example values for the AccountID and AccountKey keys:
<appSettings> <add key="AccountID" value="MyAccount…" /> <add key="AccountKey" value="MyKey…" /> </appSettings>
The control’s declaration would look like the following snippet:
<live:SilverlightStreamingMediaPlayer </live:SilverlightStreamingMediaPlayer>
At run time, the control converts streaming:// URLs to HTTP URLs. You can also set the URL of the video from client side JavaScript with the code snippet below-you need to hook this JavaScript function to an action, say the click of a button:
<script type="text/javascript"> //set URL for silverlight //streaming media player function SetMediaUrl() { var objSLSMPlayer = $find("StreamingMediaPlayer1"); objSLSMPlayer.set_mediaSource("streaming: /20709/VideoLibrary/Assets/Lake.wmv"); } </script>
Details about the underlying ASP.NET MediaPlayer are available at this link:.
Wrapping Up
I hope the above is helpful in getting you started with the Windows Live Tools. I would love to hear your feedback about Windows Live Tools and how you are going to use it. You can leave your suggestions to improve the feature set or bugs you find as you are using Windows Live Tools at. | http://www.codemag.com/article/0804102 | CC-MAIN-2018-26 | refinedweb | 3,208 | 56.55 |
Details
- Type:
Bug
- Status: Open
- Priority:
Major
- Resolution: Unresolved
- Labels:None
Description
When generating wrapper for a Java interface that extends more than one other interface, then only the first extended interface is used when generating the C++ class.
In cpp.header(), the code snippets:
if cls.isInterface(): if interfaces: superCls = interfaces.pop(0)
and:
line(out, indent, 'class %s%s : public %s {', _dll_export, cppname(names[-1]), absname(cppnames(superNames)))
are likely responsible.
Activity
- All
- Work Log
- History
- Activity
- Transitions
Certainly, I should have done that when creating the issue - sorry.
I attached all the files I used when verifying the bug, but here are the highlights:
The Java interface C is defined as:
public interface C extends B, A { void c(); }
The generated header file for it, C.h, contains (copying only the relevant lines):
#include "testjcc/B.h" namespace testjcc { class A; } namespace testjcc { class C : public ::testjcc::B {
As you can see, A has a forward declaration, but is not included or inherited. Changing the order of the interfaces in the Java file changes the generated file so that A is included and inherited instead.
I'd expect both A.h & B.h to be included, and the first line of the class to be:
class C : public ::testjcc::B, public ::testjcc::A {
I made a first stab at a solution. It is only implemented in the Python 2 version, and the Python wrapper generation isn't done, but I'll attach it as a patch in the hope that it will be of use to you.
I am currently unable to work any more on this beyond the patch that I sent.
I have gotten to the same point as you - the Python side needs to be reworked to accomodate
multiple parents, the current static initializations don't work with multiple base classes.
It's work in progress...
Thanks for the update. Did you think that the changes in the patch are reasonable?
I've been working on this bug for a while now and I'm wondering how far a fix can get and what it achieves. I am about to check-in a large body of changes that makes a fix possible by switching Python type construction to use PyType_FromSpecWithBases() which can create a type with multiple base types. This is Python 3 only and this is fine. Python 2 support is in maintenance mode only.
What would fixing this bug achieve ?
- wrappers would be correct with regards to their super types and side-casting interfaces would work
- wrappers would inherit static fields and methods declared on interfaces beyond the first one)
Other than that, all is already working. For a non abstract java class to implement multiple interfaces, it has to have local implementations of all their methods (or inherit some from a parent class with local implementations) - thus I don't see any functional inheritance losses at the moment (beyond the static ones).
Also, Python has, to say the least, some strange layout requirements when constructing a type from multiple bases - they all have to have the same tp_basicsize. This is not the case with the JCC t_type, the types used with Python (their sizeof() is tp_basicsize), that wrap the C++/Java bridge types as they may have an array of type parameter of variable size (depending on the number of type parameters) when the java type being wrapped is generic. At the moment, I'm not even sure how much Python can support JCC types with multiple base types - maybe the t_type layout can be modified a bit to fix the size of type parameters by moving to an array pointer.
All that being said, it would be very nice if multiple inheritance could be properly supported:
- it would better model 'class foo extends bar implements baz, ..."
- it would better model the interface tree you proposed in the test
The new code now has a lot of stuff in place for supporting multiple inheritance but it is not enabled:
- placeholder for virtual inheritance
- support for multiple parents everywhere
- Python type construction supports multiple bases
The code doesn't have the change in logic yet to properly track 'extends foo implements bar' and the code still suffers from the bug reported here, only the first interface is used as parent for a sub-interface.
I'm going to continue working on this on and off as it's an interesting problem...
We ran into it because we are developing an API where the public parts are interfaces, and the implementing classes are private. The problem was that the methods declared in the second inherited interface was not accessible.
I guess an alternate approach would be to include the methods from the inherited interfaces (except the one the C++ class inherits from). That would solve the problems we've run into so far. It looks to me that you'd run into problems when passing objects as arguments from C++, though:
Given the declarations below:
class A { void f(B b) { /* ... */ } } interface B { /* ... */ } class C extends D implements B { /* ... */ } class D { /* ... */ } interface E { /* ... */ } interface F extends E, B { /* ... */ }
When trying to use the C++ wrappers to call A.f, wouldn't you currently get compilation errors if you passed the b argument from a reference of type C or F? What about in Python? Exception at runtime?
If you use the wrappers generated for interfaces, you're going to face the problem reported here.
If you use the wrappers generated for classes implementing said interfaces, then you should be ok with all implemented methods anywhere as the implementing class has them all (or it is abstract).
You can also force the wrapping of private classes by explicitly listing them on the command line.
There seems to be something off with that code indeed.
However, it would be helpful if you could include a small trivial example java code
that triggers the bug you found and an explanation of what you'd expect it
to do instead. This helps me ensure there is no misunderstanding and also helps with reproducing the bug.
Thanks ! | https://issues.apache.org/jira/browse/PYLUCENE-37 | CC-MAIN-2017-30 | refinedweb | 1,019 | 58.82 |
Hi guys I wanna remove the empty lists but want to have my hierachy in the list of list. So basically in this context I want a output list like
- Nurbscurve
- Nurbscurve
- Emptylist
Hope I make myself clear. Help me out.
Hi guys I wanna remove the empty lists but want to have my hierachy in the list of list. So basically in this context I want a output list like
Hope I make myself clear. Help me out.
Try List.Clean with the boolean set to true:
See also:
I can’t find any illustration for List.Clean with boolean set to true. Please send a screenshot if you used it successfully so we can reuse it as a reference for similar issues.
Try playing with the node levels to see if it helps:
Hi Yna, I do understand how levels work. And I have been playing with the levels and Preserving Hierarchy for a few hours already. The issue is with Empty Lists. When I ask any of these nodes to remove the empty lists… they just remove it through n through.
try it out. You will understand what I mean. Have been using Lists and Levels in Lists for quite sometime now.
Sorry I can’t right now. If no one else does, I’ll come back in a few hours on this topic…
Thanks for the support Yna
Just use “Flatten” node:
Hi Kulkul,
The issue is I won’t have a nurbscurve in every list of lists. Sometimes its all Empty list (when there is no Geometry Intersect in my case).So dynamo entirely remove the Entire Index without a nurbscurve. I want to maintain the index and list it as null or a single empty list when it doesnt find a nurbscurve. Hope that makes it clear. Check the image.
DanEdu.List.Replace should respond to what you describe:
@Amrit_Banerjee Note that Lacing is Longest in the examples below
Hi Yna,
Yes this was what I was doing yesterday as a workaround. But @Vikram_Subbaiah’s Method works like a charm
Great, you will fine in the Primer more information about lacing if needed:
If you need to preserve the complete structure of the list, you can do it like so:
Hi,
I have a similar list problem, but my list only has one level. Is there a way to remove or make Dynamo ignore the “Empty List” values and still preserve the list hierarchy?
What I’m trying to achieve with my script is to check for views placed on sheets and to find views which do not already have the sheet number as a prefix in the view name, and then rename these. The Empty List value shows up for views which already have the sheet number as a prefix and therefor shouldn’t be renamed.
I’ve tried using the List.clean and List.Replace from DanEDU
Any help deeply appreciated!
Until someone who knows how to do this in code blocks comes along, I quickly wrote a python script that should fix it? I am on my way out of the office and didn’t have time to test, but see if it works.
Replaces the SetParameterByName node, same inputs. Python code is:
import clr clr.AddReference('ProtoGeometry') from Autodesk.DesignScript.Geometry import * clr.AddReference('RevitNodes') import Revit clr.ImportExtensions(Revit.Elements) #The inputs to this node will be stored as a list in the IN variables. elements = IN[0] paramName = IN[1] values = IN[2] for i in range(len(values)): if hasattr(values[i], '__iter__'): for j in range(len(values[i])): elements[i][j].SetParameterByName(paramName,values[i][j]) else: continue #Assign your output to the OUT variable. OUT = elements
Let me know if there are any problems.
did you problem got solved?
if not, then please make a new post with your problem, include your .dyn file. It sould be doable to help your, but please include the graph so we dont have to reinvent the wheel
There should hopefulley not be any reason to implement any looping python scripts
Actually I’ve been so busy with other things so I haven’t had time to test the Python suggestion.
If only I could clone myself…
I’ve forgotten to answer you!
I actually ended up rewriting the entire script, turning things around.
Instead of grabbing sheets and looking for the view names for the views on these sheets I’m grabbing views and comparing their view name with their sheet numbers. Much easier! | https://forum.dynamobim.com/t/remove-empty-list-preserving-hierarchy/16434/2 | CC-MAIN-2021-04 | refinedweb | 757 | 73.37 |
9.13: Validate input# character encoding:
[12.29:
. this is an expansion of
Wheeler's how-to on secure programming
]
[9.14:
. staying in control of character encoding
can determine your effectiveness in filtering web content
for preventing cross-site scripting and semantic attacks .
]
when needing to process older documents
in various older (language-specific) character sets,
you need to ensure that an untrusted user cannot control
the setting of another document's character set .
[9.15:
. this page will explain how the various char'encodings can be tricky,
and how mistranslation can affect security .
. UCS (Universal Character Set) is the new standard (subsuming ASCII);
it's the function { integer -> image } for all the images of the world,
requiring more than 2-bytes and less than 4-bytes .
. UTF (UCS Transformation Format) is the generic name for
how to code the UCS -- there are several approaches:
the efficient and backward-compatable way is to use a variant record;
eg, UTF-8:
variant#1 is ascii in a single byte;
variant#{2..4} can be contained in {2..4} bytes, respectively .
. alt'ly, UTF-32 is simply a 4-byte integer
that maps directly to UCS values -- no decoding is needed .
. for handling international characters UTF-8 has become the standard;
. an attacker can exploit an illegal UTF-8 value
by sneaking metacharacters into the string
which can turn parameter names into arbitrary commands .
9.14: 9.15:
. for instance, the wrong way to decode the invalid UTF-8 value
0,C0,80 #16 = (110)0,0000,(10)00,0000 #2
is to remove all the discriminant bits (shown in parentheses),
and return the remaining bits (00#16);
because, the discriminant"(110) was telling you
the remaining bits should have been within 0080 ... 07FF #16;
if the result wasn't in that range, the value is illegal,
and the translator should warn the client .
9.15:
. another example relevant to security
would be filtering to prohibit the char.string that
give a unix filename reference to the parent directory "/../":
/ . . /
2F,2E, 2E,2F#16 . weak parsing could still be caught by this:
2F,C0AE,2E,2F #16 . the same string with 2E replaced by C0AE .
. then the client might misparse this invalid UTF-8 to: 2E#16
when in fact it is an illegal value .
. C0 AE = (110)0,000,(10)10,1110 -utf-8-> 10,1110#2 = 2E#16
(illegal value because for discriminant (110)
the value should be greater than 80#16, and 2E is not ) .
9.15:
. another complication is that
there are some obsolete formats to watch for:
not only does the UTF-8 conversion have to check that it's
holding the correct range of UCS values,
it also has to check for the format being UTF-16:
convert UCS-2 to UTF-8:
. UCS-2 is just the first 2 bytes of 4-byte UCS;
so the UCS conversion can be used by
extending each UCS-2 character with two zero-valued bytes: 00,00,xx,xx#16 ;
however,
pairs of UCS-2 values between D800 and DFFF need special treatment:
because, they are "(surrogate pairs)
being actually UCS-4 characters transformed through UTF-16:
. convert the UTF-16 to UTF-32,
then convert the UTF-32 to UTF-8 .
]
00 .. 1F -- C0 set
80 .. 9F -- C1 set
for compatibility with the ISO/IEC 2022 framework
-- 7F (delete) is also a sort of control char .
. a BOM (byte order mark) is the value U+FEFF
prepended to the unicode char.string,
thereby acting as the signature of a Unicode.string
and indicating the byte ordering:
. here is the format of U+FEFF per UTF form and byte ordering:
00 00 FE FF UTF-32, big-endian
FF FE 00 00 UTF-32, little-endian
FE FF UTF-16, big-endian
FF FE UTF-16, little-endian
EF BB BF UTF-8
-- the UTF-8 format is byte-oriented,
so it is unaffected by byte ordering .
. FEFF occurring in the middle of a file
can be treated as an unsupported character (zero-width invisible characters)
. if you are sending a string to another node on the net,
or an unfamiliar app on your node,
consider the BOM-related values {0,FFFE#16, 0,FFFF#16} invalid:
remove them from everywhere but the beginning of the string .
. the use of this reserve for BOM implies
all these are non-numbers:
U+{00... 10}{FF,FE... FF,FF}
. values in 0,D800 #16 .... 0,DFFF #16
are specifically reserved for use with UTF-16,
and don't have any characters assigned to them.
. { 0,FF,FE#16, 0,FE,FF#16 } are not Unicode char's precisely to preserve
their usefulness of as a BOM (byte-order mark)
--. either value prepended to a char'stream
is also a hint that it's unicode;
though the BOM can also be followed by a "UTF-16" tag:
eg,Big-endian text labelled with UTF-16, with a BOM:
FE FF D8 08 DF 45 00 3D 00 52 ... ;
Little-endian text labelled with UTF-16, with a BOM:
FF FE 08 D8 45 DF 3D 00 52 00 ... .
. the tags { UTF-16BE"(big-endian), "UTF-16LE"(little-endian), }
can be used in place of the BOM;
-- if the BOM is not at the beginning of the stream,
its meaning changes to a [zero-width non-breaking space] .
[9.15:
. FDD0...FDEF #16 represent noncharacters.
Unpaired surrogates are invalid as well,
i.e. any value in D800 ... DBFF #16
not followed by a DC00 ... DFFF #16,
or any value in DC00 ... DFFF #16
not preceded by a D800 ... DBFF #16 .
]
how unicode characters are encoded in UTF-16
. for (values <= 10,FFFF#16):
value < 1,00,00#16 ?
value may be contained in a single 16-bit integer .
value in 1,0000#16 ... 10,FFFF#16 ?
value - 1,0000#16 ( 0,yyyy,yyyy,yyxx,xxxx,xxxx #2 )
is returned in 2 words:
word#1 = 1101,10yy,yyyy,yyyy #2
word#2 = 1101,11xx,xxxx,xxxx #2
encoding ISO 10646 as UTF-16(U <= 0x10FFFF):
U < 0x10000 ?
return U as a 16-bit unsigned integer .
else
Let U' = U - 0x10000.
-- assert U <= 010,FFFF#16, implying U' <= 0F,FFFF#16 (fitting in 20 bits)
word#1`= 0xD800 -- assert word#1 = 1101,10yy,yyyy,yyyy
word#2`= 0xDC00 -- assert word#2 = 1101,11xx,xxxx,xxxx
word#1`[10 low-order bits]`= [U']`[10 high-order bits]
word#2`[10 low-order bits]`= [U']`[10 low-order bits]
return (word#1, word#2) .
Graphically, steps 2 through 4 look like:
U' = yyyy,yyyy,yyxx,xxxx,xxxx
W1 = 1101,10yy,yyyy,yyyy
W2 = 1101,11xx,xxxx,xxxx
U+D800 ... U+DFFF = 1101,1xxx,xxxx,xxxx
decoding ISO 10646 UTF-16 (U):
. word#1 not in 0xD800 ... 0xDFFF ?
return word#1
word#1 not in 0xD800 ... 0xDBFF ?
return error pointer to the value of W1
word#2 null or not in 0xDC00 ... 0xDFFF?
return error pointer to the value of W1
else:
return (word#1`[10 low-order bits] & word#2`[10 low-order bits])
+ 0x10000
) .
Security Considerations
in UTF-16 may contain special characters,
such as the [object replacement character] (0xFFFC),
that might cause external processing,
depending on the interpretation of the processing program
and the availability of an external data stream ..
UTF-16 extends UCS-2 by using 2words;
but not in the same way that UCS-4 does .
. UTF-32 is incompatible with ASCII files;
because, they contain many nul bytes;
implying the strings cannot be manipulated by normal C string handling .
Therefore most UTF-16 systems such as Windows and Java
represent text objects such as program code with 8-bit encodings
(ASCII, ISO-8859-1, or UTF-8), not UTF-16. 10.3+ applications
for lookup of internationalized versions of messages,
these default to UTF-16
and "(files encoded using UTF-8 are not guaranteed to work.
When in doubt, encode the file using UTF-16).
Oddly enough, OSX is not a UTF-16 system.
ÒUnicodeÓ was originally BMP (U+0000 ... U+FFFF
-- Basic Multilingual Plane).
When it became clear that more than 64k characters would be needed,
Unicode was turned into a sort of 21-bit character set
range U-0000,0000 ... U-0010,FFFF .
The 2*1024 surrogate characters (U+D800 ... U+DFFF)
were introduced into the BMP to allow
1024*1024 non-BMP characters to be represented as
a sequence of two 16-bit surrogate characters.
This way UTF-16 was born,
which represents the extended Ò21-bitÓ Unicode
in a way backwards compatible with UCS-2.
The term UTF-32 was introduced in Unicode to describe
a 4-byte encoding of the extended Ò21-bitÓ,FFFF,
in order to turn the new UCS-4 and UTF-32 into practically the same thing.
., ...).
9.14:
In UTF-8, characters from the range U+00,00 ... U+10,FF,FF
(the UTF-16 accessible range)
are encoded using sequences of 1 to 4 octets.
table for converting UTF-32 to UTF-8:
UTF-32 range (hex.) UTF-8 octet sequence (binary)
00... 7F 0xxxxxxx
80... 07,FF 110xxxxx 10xxxxxx
08,00... 0,FF,FF 1110xxxx 10xxxxxx 10xxxxxx
01,00,00... 1F,FF,FF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
C0#16 = 1100,0000#2
C1#16 = 1100,0001#2
F5#16 = 1111,0101#2
FF#16 = 1111,1111#2
D8,00 ... DF,FF -- illegal: control codes used by UTF-16:
. do UTF-16 -> UTF-32 -> UTF-8 ..
[9.15:]
The definition of UTF-8 prohibits encoding character numbers betweenU+, which are reserved for use with the UTF-16encoding form (as surrogate pairs) and do not directly representcharacters. When encoding in UTF-8 from UTF-16 data, it is necessaryto first decode the UTF-16 data to obtain character numbers, whichare then encoded in UTF-8 as described above.
. thus, it is easy to convert to utf-8;
it is considerably less simple, however,
to validate that a utf-8 code was converted correctly;
. the code positions U+D800 to U+DFFF (UTF-16 surrogates)
as well as U+FFFE and U+FFFF
must not occur in normal UTF-8 or UCS-4 data.
(binary view of illegal chars)
U+D800 1101,1000,0000,0000
U+DFFF 1101,1111,1111,1111
U+FFFE 1111,1111,1111,1110
U+FFFF 1111,1111,1111,1111
. for safety reasons, UTF-8 decoders should treat them like
malformed or over-long sequences .
. the table above says this like so:
. say the 2..4 bytes have bits named bit#1 ... bit#32:
and bit#{ 1, 2 } ?
assert bit#3 = 0, and byte#2 starts with 10.base2;
bit#{ 4 ... 8} & bit#{ 11 .. 16} --[ should be in range 0080 ... 07FF ]
< 80.base16 ? raise illegal.coding.error
else: and bit#{ 1, 2, 3 } ?
assert bit#4 = 0, and byte#{2,3} starts with 10.base2;
bit#{ 5 ... 8} & bit#{ 11 .. 16} & bit#{ 19 ... 24 }
--[should be in range 0800 ... FFFF ]
< 800.base16 ? raise illegal.coding.error
else: and bit#{ 1, 2, 3, 4} ?
assert bit#5 = 0, and byte#{2,3,4} starts with 10.base2;
bit#{ 6 ... 8} & bit#{ 11 .. 16} & bit#{ 19 ... 24 } & bit#{ 27 ... 32 }
--[should be in range 1,0000 ... 1F,FFFF ]
< 1,0000.base16 ? raise illegal.coding.error
. among a list of desiderata for any such encoding,is the ability to synchronize a byte stream picked up mid-run,with less that one character being consumed before synchronization.. The model for multibyte processing has it thatASCII does not occur anywhere in a multibyte encoding.There should be no ASCII code values for any part ofa UTF representation of a character that was not in theASCII character set in the UCS representation of the character.Historical file systems disallow the null byte and the ASCII slash characteras a part of the file name
1) zero the 4 octets (bytes) of the UCS-4 character2) Determine which bits encode the character valuefrom the number of octets in the sequenceand the second column of the table above (the bits marked x).3) Distribute the bits from the sequence to the UCS-4 character,first the lower-order bits from the last octet of the sequence andproceeding to the left until no x bits are left.If the UTF-8 sequence is no more than three octets long,decoding can proceed directly to UCS-2.
. UCS (Universal Character Set) is defined by ISO/IEC 10646as having multiple octets (bytes) .. UTF-8 (UCS transformation format -- 8bit)is a way of staying compatable with single-byte ASCIIby using a 1...4-byte variable-length for describingthe same character set as the 4-byte UCS .
. CESU-8 (8-bit Compatibility Encoding Scheme for UTF-16)is intended for internal use within systems processing Unicodein order to provide an ASCII-compatible 8-bit encodingthat is similar to UTF-8 but preserves UTF-16 binary collation.It is not intended nor recommended as an encoding used for open information exchange.
CESU-8 Bit Distribution
UTF-16 Code byte#1 byte#2 byte#3
0000,0000,0xxx,xxxx 0xxxxxxx
0000,0yyy,yyxx,xxxx 110yyyyy 10xxxxxx
zzzz,yyyy,yyxx,xxxx 1110zzzz 10yyyyyy 10xxxxxxis identical to the binary collation of the same data encoded in UTF-16.As a very small percentage of characters in a typical data streamare.
converting {binary, hex}:
1000 8
1001 9
1010 10 A
1011 11 B
1100 12 C
1101 13 D
1110 14 E
1111 15 F
(binary view of illegal chars)
U+D800 ... U+DFFF = 1101,1xxx,xxxx,xxxx
these are for the 2 words in UTF-16:
word#1 = 1101,10yy,yyyy,yyyy
word#2 = 1101,11xx,xxxx,xxxx
U+FFFE 1111,1111,1111,1110
U+FFFF 1111,1111,1111,1111
todo:
see Unicode Technical Report #36, Unicode Security Considerations,
and Unicode Technical Standard #39, Unicode Security Mechanisms. | http://amerdreamdocs.blogspot.com/2009/12/booking-unicode.html | CC-MAIN-2017-26 | refinedweb | 2,301 | 64.61 |
Tool for reqesting stock data from the Yahoo Finance API
Project description
yapywrangler
Update 05/31/2019:
This package was initally released over a year ago in the wake of Yahoo Finance updating their backend API. At that time, the only means of retrieving data required gnarly parsing and took noticable time to process. Because of this, on the initial release, a local file system for caching parts of retrieved files was used to cut down on processing time.
Since then, Yahoo Finance has updated their API resulting in much faster response times, and negating the need for the caching system.
Due to this, yapywrangler has been revised to include just its core request functionality.
Install:
pip install yapywrangler
Usage:
from yapywrangler import get_yahoo_data stock_ticker = "MSFT" data = get_yahoo_data(stock_ticker, start_date='2006-03-26', end_date='2019-05-29') msft = pd.DataFrame(data)
Default Args
start_date: 2000-01-01 end_date: now
Data Format:
{ 'timestamp': [1559136600, 1559223000, 1559321620], 'date': ['2019-05-29', '2019-05-30', '2019-05-31'], 'open': [29.0, 28.399999618530273, 27.56999969482422], 'high': [29.31999969482422, 28.559999465942383, 28.360000610351562], 'low': [27.729999542236328, 27.600000381469727, 27.5], 'close': [28.09000015258789, 28.030000686645508, 27.940000534057617], 'volume': [99969600, 65072900, 40126715] }
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/yapywrangler/ | CC-MAIN-2020-24 | refinedweb | 226 | 63.49 |
Can I convert a file in a string and back in C?
I have the following function that will send a
tosend string using UDP protocol (knowing ip and port of the receiver).
int snd_string(char *tosend, uint16_t rcvport, char *rcvip);
The
tosend string can be really long:
snd_string will divide it in several chunks and send each datagram separately using a reliable application level protocol.
I want to use the same function in order to send a file (whether it be a text file or a binary file). Is there a way to convert the file in a string and the received string back to the original file?
See also questions close to this topic
- Catch mixed enums in switch
In some legacy code I have a lot of enums, and a huge switch cases. I would like to test that the switches have pure enum types. Nonsense example:
typedef enum EN { EN_0, EN_1 } EN_T; typedef enum DK { DK_0, DK_1 } DK_T; EN_T bar = ... switch( bar ) { case EN_0: ... break; case DK_1: //<-- mixed type ... break; }
I tried compiling this with
gcc with -Wall -Wextra -pedantic, and get no warnings. Any ideas of how to test for this? Either as compiler warnings or dedicated test code. As both the switches and enums have 100+ members it has to be generic to some level.
- Why parenthesis around function parameter?
I'm studying section 2.1 from Computer Systems A Programmer's Perspective and I understand what the code is doing but I don't understand why there are parenthesis around the formal parameter "byte_pointer" followed by &x?
typedef unsigned char *byte_pointer; void show_bytes(byte_pointer start, int len) { int i; for (i = 0; i < len; i++) printf(" %.2x", start[i]); printf("\n"); } void show_float(float x) { show_bytes((byte_pointer) &x, sizeof(float)); } void show_int(int x) { show_bytes((byte_pointer) &x, sizeof(int)); } void show_pointer(void *x) { show_bytes((byte_pointer) &x, sizeof(void *)); }
- Code coverage through fault injection
I have a function that hit 'false' once in million and I when it hit, it flaws in a so different code flow and that flow was never tested in my code code coverage testing.
I have used an statistical method to add that flow to code coverage reports. The fault injection looks like in the bellow code.
bool tunneled = FunctionOneInMillionFalse(&Object); #ifdef __CODE_COVERAGE__ // inject an stastical fault here when we are doing code coverage // int iRandomNumber = rand(); if ( iRandomNumber % 2 == 1 ) { tunneled = false; } #endif if (!tunneled) { // the block that need to be tested // }
Is keeping this code in the codebase is wrong ?
-. | http://codegur.com/48248834/can-i-convert-a-file-in-a-string-and-back-in-c | CC-MAIN-2018-05 | refinedweb | 423 | 70.53 |
ng_one2many -- packet multiplexing netgraph node type
#include <sys/types.h>
#include <netgraph/ng_one2many.h>
The one2many provides a simple mechanism for routing packets over several
links in a one-to-many (and in the reverse direction, many-to-one) fashion. configured.
In the future other algorithms may be added as well..
This node type supports up to NG_ONE2MANY_MAX_LINKS hooks named many0,
many1, etc., plus a single hook named one. only valid setting for the xmitAlg field is
NG_ONE2MANY_XMIT_ROUNDROBIN; this is also the default setting. The
only valid setting for failAlg is NG_ONE2MANY_FAIL_MANUAL; this is
also the default setting. corresponding statistics
for the link as well.
This node shuts down upon receipt of a NGM_SHUTDOWN control message, or
when all hooks have been disconnected.
The following commands will set up Ethernet interfaces fxp0 to deliver
packets alternating over the physical interfaces corresponding to networking.
More transmit and link failure algorithms should be supported. A good
candidate is Cisco's Etherchannel.
netgraph(4), ng_bridge(4), ng_ether(4), ngctl(8)
The ng_one2many node type was implemented in FreeBSD 4.2.
The one2many netgraph node (with round-robin algorithm) was written by
Archie Cobbs <archie@FreeBSD.org>. The all algorithm was added by Rogier
R. Mulhuijzen <drwilco@drwilco.net>.
FreeBSD 5.2.1 January 26, 2001 FreeBSD 5.2.1 | https://nixdoc.net/man-pages/FreeBSD/man4/ng_one2many.4.html | CC-MAIN-2020-45 | refinedweb | 216 | 51.44 |
>I'm getting the following error:
>
> Error:Groovyc: Attribute 'value' should have type 'java.lang.Byte'; but
found type 'java.lang.Integer' in @Version
I have a similar type of problem where I cannot find any way to invoke
Arrays.fill() for the byte version - even with explicit workarounds that
should ensure a primitive byte is passed, for example:
def result = new byte[10][10]
final Byte minusOne = -1
for(int i=0; i<10; ++i) {
Arrays.fill(result, 0, dim, minusOne.byteValue())
}
It happens with and without CompileStatic and results in:
java.lang.ArrayStoreException: java.lang.Byte
at java.util.Arrays.fill(Arrays.java:3155)
For these kind of cases I'm left having to create little Java stub
workarounds to get it to call the right underlying Java API.
Would be nice to have at least a way to work around this!
Cheers,
Simon | http://mail-archives.eu.apache.org/mod_mbox/groovy-users/202001.mbox/%3CCAKOHk8Pz5Si_=Dt2rH6SyvXEZLfZNS-=vcus5zyVYPhiYBu8zQ@mail.gmail.com%3E | CC-MAIN-2020-34 | refinedweb | 146 | 57.98 |
1. What is AngularJs?
AngularJs is a JavaScript framework which we use to create highly scalable client application & simplifies the binding of JS object with HTML elements. It extends the syntax of HTML to express application components. It extends the HTML extension using the attributes e.g. ng-
<div ng-app>
Angular JS provides many attributes which extend the feature but all of them start with ng-.
2. What is the key features of AngularJs
AngularJs come with lots of flexibility and features like:
a. Two way data bindings
b. Scope
c. Follow MVC patterns
d. Injectable Types (like Service, factory, Providers)
e. Directive
To see the description of above features please see the next questions.
3. What is 2 way databindings in AngularJS?
There are two way of data binding the binding the model from view to controller and Controller to view.
E.g.
<script type="text/javascript">
// Setter method
var demoApp = angular.module('demoApp', []);
// Getter method
demoApp.controller('DemoController', function( $scope ){
$scope.dep = "Software";
});
</script>
Binding it to model by:
<input name="test" type=”text”
4. What is Directives in AngularJS ?
Directives are declared in the HTML elements. All directive start with the “ng”.
e.g. Simple ng-model.
<input name="test" type=”text”
5. What is Scope in AngularJs?
It provides observers to watch for model changes.
6. What is MVC pattern in AngularJS?
AngularJS works under MVW patterns (Model, View and whatever patterns). Now if you will see the model, vmiew and controller part than, it is like you are defining Model with Module and Controller as
// Defing Modules
var demoApp = angular.module('demoApp', []);
demoApp.controller('DemoController', function( $scope ){
$scope.dep = "Software";
});
7. What is Modules?
A module is work as global namespace. It helps to bootstrap the application. It works as container for different part of our app.
// Defing Modules
var demoApp = angular.module('demoApp', []);
Module will bind to view using ng-app=”myapp”
<html ng-
8. What is controller?
A controller is defined by JavaScript Constructor function. Controller is a function that binds objects to the particulars storage or containers.
Controller is attached to DOM via the ng-controller directives.
Initializing the controller with in JavaScript with module as
demoApp.controller('DemoController', function( $scope ){
$scope.dep = "Software";
});
Use the controller for:
a. Setup the initial state & $scope object.
b. Add Behavior for $scope object.
9. Can we have Nested Controller?
Yes we can derive nested controller.
You can use the nested controller like:
<div class="cont" ng-
My name is {{ name }} and I am a {{ type }}
<div ng-
My name is {{ name }} and I am a {{ type }}
<div ng-
My name is {{ name }} and I am a {{ type }}
</div>
</div>
</div>
10. What is the application flow of AngularJs?
Make the use of special directive of ng-app in HTML attributes. Once it find the ng-app in the html page it start treating the application into special manner and treating the page as AngularJs page than it will check for ng-controller which will defined the scope for an object.
Now after words it will check with other ng- attributes in the application and change the behavior based on the logic of ng- attributes use in the html tags.
11. What is AngularJS service?
Service, Factories and providers are all injectable types.
An AngularJs service encapsulates specific business logic & exposes an API to be used by other components to invoke this logic.
e.g. $timeout service executes function after specifies interval. $http service encapsulates the logic required to interact with REST backbends.
AngularJS service is always Singleton.
Service is registered using service function of angular.module().
The Second argument to service() is a constructor function to inject the service.
e.g.
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
12. What is factory method ?
Factory method is same as service method but it is more robust than service and you can expose only that logic which you want to expose.
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
Difference between factory and service is factory exposes logic on return type but in service you will access logic directly by service name and function name.
13. What is provider method in AngularJs?
A provider is most configurable and verbose version of service because its based on prior setting and logic.
e.g. the built in $route service may behave differently based on Mode(Html mode or hashbag mode) you can configured in $route.Provider
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
14. What is value and constant in AngularJs?
Value is an injectable type that is used to register simple service which can be a string, number, array or function.
e.g. you want to give a version number for website use value service using the value(0 function of angular.Module()
angular.module("myapp").value("appvesrion", "1.0");
Constant: A constant is an injectable type that is the same as a value except that it can be injected into Module.Config(). Register constant by calling Constant().
angular.module("myapp").constant("Data_Source", "a String here");
15. What is main core directive of AngularJs ?
Ng-app : which will bootstrap the application as angular application.
Ng-Model : It bind the model or value to the html input controls
Ng-Bind : it bind the Model or value to the Html Tag.
16. What is ng-init directive?
It initializes the model value for your view.
<div ng-
17. What is ng-repeat?
It is using for repeating the object collection and bind to the view.
<ul>
<li data-
{{ customer.name }} - {{ customer.city}}
</li>
</ul>
18. What is ng-if directive do?
Ng-if directive removes or recreate a portion of the DOM tree based on an {expression}.
If ng-if is false than the control not create the DOM.
<div ng-
<h1>Dynamic DOM based on condition</h1>
Data is : {{ sdata.val }}
<input ng-
</div>
19. What is Ng-Show?
Ng-show directives shows or hides the given HTML elements based on expression provided to ng-show attributes.
e.g. <div ng- show the value </div>
20. What is difference in ng-if and ng-show?
Ng-if completely removes and recreates the elements in the DOM rather than changing its visibility via the display CSS property.
21. What is ng-disabled?
It used to make control enable and disabled based on the expression.
<button ng-disabled=”isSubmittable” > Click Me </button>
22. What is ng-option?
The ng-options attributes can be used to dynamically generated list of <option> elements for the <select> element using array of object.
Here, select as will bind the result of the select expression to the model.
e.g. $scope.items = [{
id =1,
label = ‘Satya’},
id = 2
label =’rathore’}];
<select ng-option=”item as item.label for item in items track by item.id ></select>
Or
<select ng-option=”item.Label for item in items /></select>
23. What is ng-class ?
Ng-class directive allows you to dynamically set the css – class on and Html element based o the expression.
24. What is ng-href ?
Using angular markup like {{#}} as in href cause issue and redirect to 4040 error as it treat as new url. To resolve that problem need to use ng-href
< a href=”#”> Link 1 </a> // wrong
<a ng-href=”#”>Link 2 </a> // correct
25. What is ng-include?
Fetches, compile and includes an external HTML fragment.
We can embedded it into HTML page using ng-include.
<div ng-include=”main.html”></div>
In addition the browser same origin policy and cross domain resource sharing policy may further restrict whether the template is success fully loaded.
e.g. ng-include won’t work for cross domain request on all browser.
26. What is ng-click?
It is used to fire the click event of any control in AngularJs.
<button ng-Send Down</button>
scope.sendDown = function() {
Window.Alert(“I am clicked”);
};
27. What is ng-blur?
Blur event fires when an elements has lost its focus.
28. How to use ng-switch ?
As switch is just the extension of if and else condition on the same line we can use ng-switch in AngularJs.
The ng-switch directive is used to conditionally swap DOM structure on your template based on condition of scope object.
<div ng-switch on=”value” >
<div ng-switch-when=”Home”>Home </div>
<div ng-switch-when=”About”>About </div>
<div ng-switch-when=”Contact”>Contact </div>
</div>
29. What is template in Angular?
Templates are written with HTML that contains Angular specific elemets and attributes.
That will renders to your dynamic view and it can be see by user in browser.
It contains below attributes as
- Directive
- Markup
- Filters
- Form Control
30 What are filters?
Angularjs provide many built in filters which will enhance the output. E.g.
Lowercase – which converts your output string to lowercase.
Uppercase – which converts your output string to uppercase
Currency – it converts into currency. | http://www.getmscode.com/2016/03/top-30-angularjs-interview-questions.html | CC-MAIN-2017-51 | refinedweb | 1,544 | 61.33 |
Greetings and welcome once again to Twisted Conch in 60 Seconds, a series introducing SSH development with Twisted. If you're just joining me, you probably want to go back to the beginning before reading this article.
The previous example constructed a server which could present some data to clients which managed to authenticate successfully. However, it also produced an error message which I didn't explain:
PTY allocation request failed on channel 0
This is an error message the client software displays (so you may see something different depending on which SSH client you use - I am using OpenSSH 5.1). What the client is trying to tell us is that it asked the server to allocate a PTY - a pseudo-terminal - and the server would not do it. The client doesn't think this is a fatal error though, so it continues on to request a shell, which it gets.
It turns out that PTY requests are another very common channel request (that is, a request that is scoped to a particular channel, as the shell request is). Almost any time you expect clients to show up at your server and request a shell, it is somewhat likely that they'll request a PTY as well, so you probably want to handle this case.
Recall how the shell request was handled in the previous example:
class SimpleSession(SSHChannel):
name = 'session'
def request_shell(self, data):
self.write("This session is very simple. Goodbye!\r\n")
self.loseConnection()
return True
As a PTY request is just another type of channel request, I can extend this class with a new method,
request_pty_req, in order to handle this additional request type.
def request_pty_req(self, data):
I didn't talk about the
data parameter last time because the shell request makes no use of it. However, a PTY request does use it. The client packs some information about its capabilities into a particular string format and that's what this method will receive as an argument. Conch provides a method for parsing this string into a more manageable form:
self.terminalName, self.windowSize, modes = parseRequest_pty_req(data)
terminalName is a string giving the name of the terminal. This is typically the value of the
TERM environment variable on the client - which might not be what you expect, and is often simply set to "xterm".
More useful than the terminal name is the
windowSize tuple. This tuple has four elements. The first two give the number of rows and columns available on the client. The third and fourth give the terminal width and height in pixels. For many clients, the latter isn't available or useful so these values are set to
0.
The last value,
modes, is rather complicated. You can read about it in RFC 4254, section 8. Or you can take my word for it for now that you probably don't care about it, at least for now.
Notice that I saved some of that data. I'm going to use it to make
request_shell a little more interesting. Before moving on to that, there's one last thing to do in
request_pty_req though. I need to indicate that the PTY request was successful:
return True
Now, here's a new version of
request_shell which uses those two new attributes:
def request_shell(self, data):
self.write(
"Your terminal name is %r. "
"Your terminal is %d columns wide and %d rows tall." % (
self.terminalName, self.windowSize[0], self.windowSize[1]))
self.loseConnection()
return True
Now when clients connect to the server, they will be able to see what terminal they're running and how big it is. Here's the full code listing for this version of the example, including a new import for
parseRequest_pty_req:
from twisted.conch.ssh.session import parseRequest_pty_req):
self.terminalName, self.windowSize, modes = parseRequest_pty_req(data)
return True
def request_shell(self, data):
self.write(
"Your terminal name is %r.\r\n"
"Your terminal is %d columns wide and %d rows tall.\r\n" % (
self.terminalName, self.windowSize[1], self.windowSize[0]))()
Compared to the last example, only the methods of
SimpleSession have changed. If you run this server, connect to it, and authenticate then you'll be rewarded with a little information about your terminal. Or, if your SSH client does not request a PTY for some reason (for example, if you pass -T to the OpenSSH client) then you'll see an error when the shell request fails, since
terminalName and
windowSize won't have been set.
At this point, I have explained enough of Conch that you could almost write a very simple application with it. For example, you could add an SSH server to your Twisted Web server which sends request logs to the client. This would just involve calling the
write repeatedly, once for each request which was handled. However, for many applications, you may actually want to accept input from the client. Stick around for the next article in which I'll cover precisely that. | http://as.ynchrono.us/2011/04/twisted-conch-in-60-seconds-pty.html | CC-MAIN-2017-30 | refinedweb | 831 | 62.48 |
ReadOnly (Visual Basic)
Specifies that a variable or property can be read but not written.
Rules
Declaration Context. You can use ReadOnly only at module level. This means the declaration context for a ReadOnly element must be a class, structure, or module, and cannot be a source file, namespace, or procedure.
Combined Modifiers. You cannot specify ReadOnly together with Static in the same declaration.
Assigning a Value. Code consuming a ReadOnly property cannot set its value. But code that has access to the underlying storage can assign or change the value at any time.
You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.
When to Use a ReadOnly Variable
There are situations in which you cannot use a Const Statement (Visual Basic) to declare and assign a constant value. For example, the Const statement might not accept the data type you want to assign, or you might not be able to compute the value at compile time with a constant expression. You might not even know the value at compile time. In these cases, you can use a ReadOnly variable to hold a constant value.
ReadOnly characterArray() As Char = {"x"c, "y"c, "z"c}
Sub changeArrayElement()
characterArray(1) = "M"c
End Sub
When initialized, the array pointed to by characterArray() holds "x", "y", and "z". Because the variable characterArray is ReadOnly, you cannot change its value once it is initialized; that is, you cannot assign a new array to it. However, you can change the values of one or more of the array members. Following a call to the procedure changeArrayElement, the array pointed to by characterArray() holds "x", "M", and "z".
Note that this is similar to declaring a procedure parameter to be ByVal (Visual Basic), which prevents the procedure from changing the calling argument itself but allows it to change its members.
The following example defines a ReadOnly property for the date on which an employee was hired. The class stores the property value internally as a Private variable, and only code inside the class can change that value. However, the property is Public, and any code that can access the class can read the property.
The ReadOnly modifier can be used in these contexts: | https://msdn.microsoft.com/en-us/library/z2b2c2ka(v=vs.120).aspx | CC-MAIN-2015-22 | refinedweb | 386 | 53.92 |
Using regex in Python if statement
I am trying to figure out how to incorporate regex into a python if statement. I have a pandas dataframe where I am iterating over the rows and want to perform an action every time the row has a specific combination of text. The regex should match any 7 character string that begins with a capital letter followed by 6 numbers (ie. R142389)
for index, row in df1.iterrows(): if row[4] == REGEX HERE: Perform Action
Am I going about this the right way? Any help would be greatly appreciated!
2 answers
- answered 2018-01-11 21:18 chrisz
Yes, you can do this, just use
match, which will only match at the beginning of the string it is being compared to. You would have to use
searchto search the entire string.
A bit of explanation about the regex:
^asserts position at start of the string
[A-Z]A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
\d{6}matches a digit (equal to
[0-9])
{6}Quantifier — Matches exactly 6 times
$asserts position at the end of the string, or before the line terminator right at the end of the string
import re regex = re.compile('^[A-Z]\d{6}$') possibles = ['R142389', 'hello', 'J123456'] for line in possibles: if regex.match(line): print(line)
Output:
R142389 J123456
- answered 2018-01-11 21:23 Marcelo Villa
I would use the
remodule
import re re.search(pattern, string, flags=0)
where
patternis the regular expression to be matched,
stringis the string going to be searched and
flagswhich are optional modifiers. This funcion returns
Nonewhen there is no match.
Here is the
redocumentation:
And here is an example of the implementation: | http://quabr.com/48215884/using-regex-in-python-if-statement | CC-MAIN-2018-05 | refinedweb | 294 | 60.55 |
User Tag List
Results 1 to 3 of 3
RoR - Displaying an image from the database and server load
I'm displaying a list of records from a database and each has an image thumbnail. I'm storing the image data in the database and using a function in the controller to serve the image:
Code:
def thumb @a = A.find(params[:id]) send_data(@a.thumb_filedata, :filename => @a.name, :type => @a.thumb_content_type, :disposition => 'inline') end
Is this the case?
If so, this obviously this isn't desirable - any suggestions on displaying the thumbnail from binary data in the database without loading the object twice or will I have to change to an image upload?
Is this the case?
- Join Date
- Aug 2005
- 986
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
any suggestions
Yeah, saving in the database works better for this app from a maintenance standpoint but not at the expense of doubling the load...
Thanks
Bookmarks | http://www.sitepoint.com/forums/showthread.php?514114-RoR-Displaying-an-image-from-the-database-and-server-load&p=3616346 | CC-MAIN-2014-23 | refinedweb | 158 | 61.36 |
Visualization. UW CSE 190p Summer 2012. Bare bones visualization in Python with matplotlib. matplotlib. A major design limitation is that it stives to emulate MATLAB More on this in the next lecture One important function for HW6: plot(xvalues, yvalues).
UW CSE 190p
Summer 2012
plot(xvalues, yvalues)
import matplotlib.pyplot as plt
xs = [1,2,3,4,5]
ys = [x**2 for x in xs]
plt.plot(xs, ys)
no return value?
Incrementally modify the figure.
Save your figure to a file
Show it on the screen
import matplotlib.pyplot as plt
xs = range(-100,100,10)
x2 = [x**2 for x in xs]
negx2 = [-x**2 for x in xs]
plt.plot(xs, x2)
plt.plot(xs, negx2)
plt.xlabel("x”)
plt.ylabel("y”)
plt.ylim(-2000, 2000)
plt.axhline(0) # horiz line
plt.axvline(0) # vert line
plt.savefig(“quad.png”)
plt.show()
We can group these options into functions as usual, but remember that they are operating on a global, hidden variable
Review
Bill Howe, eScience Institute
Location of deaths in the 1854 London Cholera Epidemic.
X marks the locations of the water pumps
Dr. John Snow
y = 3 + 0.5x
(variance accounted for by x) = 27.5
(about the regression line) = 13.75
Amount of data in the world
Processing power: Moore’s Law
slide src: Cecilia Aragon, UW HCDE
Amount of data in the world
Processing power: Moore’s Law
Human cognitive capacity
Idea adapted from “Less is More” by Bill Buxton (2001)
slide src: Cecilia Aragon, UW HCDE
Size of effect in the visualization
Lie Factor =
Size of effect in the data
Edward Tufte: Minimize the Lie Factor
Tufte 1997
Edward Tufte: Maximize the data-ink ratio
There was no significant difference between plain and image charts for interactive interpretation accuracy (i.e., when the charts were visible).
There was also no significant difference in recall accuracy after a five-minute gap.
After a long-term gap (2-3 weeks), recall of both the chart topic and the details (categories and trend) was significantly better for Holmes charts.
Participants saw value messages in the Holmes charts significantly more often than in the plain charts.
Participants found the Holmes charts more attractive, most enjoyed them, and found that they were easiest and fastest to remember.
Edward Tufte: Small multiples
Jock Mackinlay: Use the appropriate visual element for the relationship and data being analyzed
Conjectured rank effectiveness of each visualization method by data type
Tufte again: Small multiples
Lloyd Treinish: Color Matters
Lloyd Treinish, IBM Research,
Lloyd Treinish, IBM Research,
Bergstrom, Rosvall, 2011 | http://www.slideserve.com/sheryl/visualization | CC-MAIN-2017-13 | refinedweb | 428 | 56.45 |
Tweeting with Arduino Uno
Daniela Morais
Jun 19 '17
・4 min read
A long time ago I bought an Ethernet ENC28J60 but I just recently tested it and, although I enjoy Java and I've used it in all of my previous projects to develop the interface between Arduino and server, it was clear to me that Python would be a much better choice in this case.
In 2014, I decided to use Panama Hitek Arduino SDK and then I sent them an email sharing my experience with their new SDK version. In 2016, I randomly met the guys from the Panama Hitek at the Fedora Latin America Meeting in IRC. Sharing your experience as a developer and be engaging in communities is very important, maybe you will meet the developers of your favorite framework in these spaces or even work with them. For me, it's one more example of the importance of sharing knowledge and ideas through articles, talks, meetings etc. So, don't be shy or scared of sharing what you know.
IoT is about being connected
IoT, embedded systems and smart devices are different concepts and there's a constant confusion when using these terms.
If your device is disconnected from Internet, it probably isn't generating the value of an IoT device. Being connected is more than reading commands remotely from an app, it's a possibility to interact in different ways with your client and other systems like Twitter and also to collect useful information that can be used to make it even smarter.
First step
Register your app in Twitter to consume their API. Access Twitter Dev to create your Twitter application and generate an access token to enable tweeting from your account ("Keys and Access Tokens" > "Create my access token")
Solutions
The Chuck Norris way
You can develop your own C program to connect with Arduino and send HTTPS requests to the Twitter API. There's a Tweet Library for Arduino available but it's deprecated and needs refactoring to work with Arduino versions higher than 1.6.4.
The easy way
Working with pointers and in a low level can be complicated if you don't have experience with C and micro-controller, registers, digital systems etc. Use a python script and it will be much easier to code and maintain the software. Python will be responsible for exposing a web server which will then be consumed by your Arduino and send the content (e.g, sensor values, commands to turn on or off the lights etc) to Twitter. Note that Arduino UNO has limitations when building HTTP requests (it was necessary to use GET method instead of POST to create a tweet) and for this reason Python doesn't expose an API.
Requirements
- UIPEthernet
- Python 2.7
- pip
- twython
- flask
EtherShield and ETHER_28J60 are common libraries used in most of tutorials, but UIPEthernet is compatible with the original Ethernet which allows you to use the examples avaiable in the Arduino IDE (File > Examples > Ethernet) just by replacing:
#include <SPI.h> #include <Ethernet.h> //Replace here with <UIPEthernet.h>
Download UIPEthernet and install Flask and Twython:
$ cd ~/Arduino/libraries/ $ git clone UIPEthernet $ sudo pip install flask $ sudo pip install twython
Create a configuration file, insert information generated by Twitter for you:
# api_config APP_KEY = 'your_api_key' APP_SECRET = 'your_api_secret' OAUTH_TOKEN = 'your_access_token' OAUTH_TOKEN_SECRET = 'your_token_secret'
In the same folder, create tweet.py:
from twython import Twython from flask import Flask import api_config app = Flask(__name__) APP_KEY = api_config.APP_KEY APP_SECRET = api_config.APP_SECRET OAUTH_TOKEN = api_config.OAUTH_TOKEN OAUTH_TOKEN_SECRET = api_config.OAUTH_TOKEN_SECRET twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) @app.route("/") def index(): return "Hello world, I'm running!" @app.route("/tweet/<message>") def sendTweet(message): twitter.update_status(status=message); return "Done." if __name__ == '__main__': #Fix here app.run(host="your_ip", port=8080, debug=True)
Upload to Arduino:
#include <SPI.h> #include <UIPEthernet.h> byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; char server[] = "ip_server"; //fix here IPAddress ip(192, 168, 1, 177); //fix here EthernetClient client; void setup() { Serial.begin(9600); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); Ethernet.begin(mac, ip); } } void loop() { if (client.connect(server, 8080)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /sendTweet/Hello%20world%20by%20Arduino HTTP/1.1"); client.println("Host: ip_server_with_port"); //fix here client.println("Connection: close"); client.println(); client.stop(); } else { Serial.println("connection failed"); } delay(5000); }
Give the script permission to execute:
$ chmod a+x tweet.py $ python tweet.py
And magic.....
Observations
For some reason, I can't make requests to local servers and it was necessary to host the Python script on Digital Ocean. The server doesn't support HTTPS and some times an error about this was received.
Note that this Python script doesn't expose an API and you must always use URL Encoder/Decoder to send messages in the path param. Special characters can be a problem, try to use curl or wget if you get any errors.
Cool things
Tweetduino
IoT is eating the world
APIs for IoT devices (Brazilian Portuguese)
References
Arduino Ethernet – Pushing data to a (PHP) server
How to Send Tweet From Command Line using Python
Originally posted on my personal blog.
I learned that last month was Dyslexia Awareness Month. However, I’ve found very few places that talk about web accessibility and dyslexia.
Heck yes. I need to start tinkering more with Arduino! | https://dev.to/danielammorais/tweeting-with-arduino-uno | CC-MAIN-2019-09 | refinedweb | 901 | 56.35 |
Aflați mai multe despre abonamentul Scribd
Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori.
Owing inpart to several decades of dispute over justification and how a person isset right with God, we have tended to neglect another component ofconversion no less important. Conversion under the terms of the newcovenant is more than a matter of position and status in Christ, thoughnever less: it includes miraculous Spirit-given transformation, somethingimmeasurably beyond mere human resolution. It is new birth; it makes usnew creatures; it demonstrates that the gospel is the power of God untosalvation. All the creedal orthodoxy in the world cannot replace it. Thereason why You must be born again is so important is that you must beborn again.D. A. Carson,Trinity Evangelical Divinity School, Deerfield, Illinois
Many will be thankful that John Piper is here addressing the key need ofour times. Every awakening begins with the renewed discovery of Christsteaching on the new birth. Here is that amazing teaching in lucid yet comprehensive form; with a relevance to readers worldwide.Iain H. MurrayWhen I was a boy my grandmother asked me, Have you been bornagain? Though I didnt understand what she meant at the time, thatquestion led to my conversion to Christ. In this wonderful book, PastorJohn Piper rescues the term born again from the abuse and overuse towhich it is subject in our culture today. This is a fresh presentation ofthe evangelical doctrine of the new birth, a work fi lled with theologicalinsight and pastoral wisdom.Timothy George,Beeson Divinity School, Samford University, Birmingham, Alabamaand Senior Editor of Christianity Today
The doctrine of the new birth is cheapened and hidden because so manyprofessing Christians have not experienced the reality of the new birth.The reality of the new birth is seemingly so little celebrated because so fewunderstand the majestic doctrine of the new birth. Finally Alive sweeps awayso much confusion and gives its readers so much cause for rejoicing in thesaving work of God through Jesus Christ His beloved Son. Nothing couldbe more vital than Gods people understanding what regeneration looks andfeels and tastes and desires and speaks and walks and thinks like. Nothingcould be more eternally important than Christian people knowing what theBible teaches about the new birth and knowing that they have experienced
it. One wonders why its taken so long for a book on the new birth to bewritten! But now it has and I pray every reader rejoices in God for the richbeauties of Christ Jesus so compellingly shared in its pages.Thabiti Anyabwile,First Baptist Church, Grand Cayman, Cayman Islands
John Piper rescues the term born again from its contemporary status as agauche or glib clich and reunites it with a fully orbed biblical understanding ofthe new birth. Theologically thorough and yet heart-warmingly pastoral andpractical, this important book should help Gods people to value the remarkable status and responsibility of being born again.Richard Cunningham,Universities and Colleges Christian Fellowship (UCCF), U.K.
Regeneration, or new birth, meaning simply the new you through, with,in, and under Christ, is a largely neglected theme today, but this fi ne set ofsermons, criss-crossing the New Testament data with great precision, goesfar to fi ll the gap. Highly recommended.J .I. Packer,Regent College, Vancouver, Canada
The evangelical church is witnessing a resurgent commitment to social actionthe doing of good deeds for a needy culture and world. While correctand commendable for many reasons, one danger now as ever is that gooddeeds will supplant good news. We need constant reminders of the truth ofwhat Jesus said: What will it profit a man if he gains the whole world andforfeits his life? (Matt. 16:26). John Pipers Finally Alive is a vivid and stirringdescription of the Bibles teaching on what it means to be born again. The goodnews of the gospelthat by Gods grace, and through faith in Christ and theall-sufficiency of his atoning death, one may be fully forgiven and born againto newness of life that will never endis a message that must be understood,believed, embraced, and proclaimed for true transformation of life to occur.You must be born again (John 3:7) is a must we dare not lose. Finally Aliveunpacks the truth, the necessity, and the process of the new birth clearly andbeautifully. For those curious about the Christian faith to those deeply committed to Christ and his ways, come read and behold the glory of any and everysinners only hopethe miracle of the new birth that brings forth new life inChrist that will never end.Bruce Ware,The Southern Baptist Theological Seminary, Louisville, Kentucky
FINALLY A LIVEWhat Happens WhenWe Are Born Again
John Piper
John Piper is pastor for Preaching at Bethlehem Baptist Church in Minneapolis, Minnesota. He has ministered at Bethlehem since 1980. John andhis wife, Nol, have four sons, one daughter, and an increasing number ofgrandchildren.
Unless otherwise indicated Scripture quotations are from The Holy Bible, EnglishStandard Version, copyright 2001 by Crossway Bibles, a division of Good NewsPublishers. Used by permission. All rights reserved.Scripture quotations marked KJV are taken from the King James Version of the HolyBible.
ContentsIntroductionAugustine, Lewis, Barna, and the Bible 9
25
87
Contents
ConclusionThe New Birth and the New WorldScripture Index 193Persons Index 197Subject Index 199
189
John 3:78
IntroductionAugustine, Lewis, Barna,and the BibleThe declaration of Jesus that we must be born again (John 3:7)is either deluded or devastating to the one who would be captainof his soul. Not many biblical realities are better designed byGod to reveal our helplessness in sin. The wind blows where itwishes, and you hear its sound, but you do not know where itcomes from or where it goes. So it is with everyone who is bornof the Spirit (John 3:8). It is the Wind, not we, who fi nallyrules the soul.Two stories about the freedom of Gods Spirit in the newbirth will help us avoid superficial stereotypes about how heworks. St. Augustine was converted to Christ in A. D. 386, andC. S. Lewis became a Christian in 1931. For both, it was afterlong struggles with unbelief. But the way the Wind blew withits fi nal converting power was dramatically different for each.Augustines StoryFor Augustine, the idol that kept him from Christ was sex. Hehad given way to his passions for the last sixteen years. He had9
left home at age sixteen, but his mother Monica had never ceasedto pray. He was now almost thirty-two. I began to search for ameans of gaining the strength I needed to enjoy you [O Lord],but I could not find this means until I embraced the mediatorbetween God and men, Jesus Christ.1Then came one of the most important days in church history.It was late August, 386. Augustine was almost thirty-two yearsold. With his best friend Alypius, he was talking about theremarkable sacrifice and holiness of Antony, an Egyptian monk.Augustine was stung by his own bestial bondage to lust, whenothers were free and holy in Christ.There was a small garden attached to the house wherewe lodged.I now found myself driven by the tumultin my breast to take refuge in this garden, where no onecould interrupt that fierce struggle in which I was my owncontestant.I was beside myself with madness that wouldbring me sanity. I was dying a death that would bringme life.I was frantic, overcome by violent anger withmyself for not accepting your will and entering into yourcovenant.I tore my hair and hammered my foreheadwith my fists; I locked my fi ngers and hugged my knees.2
But he began to see more clearly that the gain was far greaterthan the loss, and by a miracle of grace he began to see the beautyof chastity in the presence of Christ. The battle came down tothe beauty of continence in fellowship with Christ versus thetrifles that plucked at his flesh.I flung myself down beneath a fig tree and gave way tothe tears which now streamed from my eyes.All at onceI heard the singsong voice of a child in a nearby house.Whether it was the voice of a boy or a girl I cannot say, but1 Aurelius Augustine, Confessions, 152 (VII, 18).2 Ibid., 170171 (VIII, 8).
10
Finally Alive
11
I know very well when, but hardly how, the final step wastaken. I was driven into Whipsnade one sunny morning.When we set out I did not believe that Jesus Christ is theSon of God, and when we reached the zoo I did. And yet Ihad not exactly spent the journey in thought. Nor in greatemotion. Emotional is perhaps the last word we canapply to some of the most important events. It was morelike when a man, after long sleep, still lying motionless inbed, becomes aware that he is now awake. And it was, likethat moment on top of the bus, ambiguous. Freedom, ornecessity? Or do they differ at their maximum?5
12
13
Here is the way the researchers defi ned born again in theirresearch:Born again Christians were defi ned in these surveys aspeople who said they have made a personal commitmentto Jesus Christ that is still important in their life todayand who also indicated they believe that when they diethey will go to Heaven because they had confessed theirsins and had accepted Jesus Christ as their savior. Respondents were not asked to describe themselves as born again.Being classified as born again is not dependent uponchurch or denominational affi liation or involvement.7
14
these texts not addressed to the false claim that born again peopleare morally indistinguishable from the world? The Bible is profoundly aware of such people in the church. That is one reason why1 John was written. But instead of following the Barna Group, theBible says that the research is not finding that born again peopleare permeated with worldliness; the research is finding that thechurch is permeated by people who are not born again.RegenerationThis is a book about the new birth. What does the Bible teachabout being born again? Another word for being born againis regeneration. It is helpful to use that word from time to time.I hope you are willing to add it to your vocabulary if its notthere. That would include adding the word regenerate as both averb (God regenerates people) and an adjective (only regeneratepeople are saved). Regenerate people and born again people arethe same. I will use the terms interchangeably.Desecrating the Term Born AgainIn this introduction, I will give an overview of where we aregoing and why. You can already see one of the reasons I wantto focus on this issue. The term born again is desecrated whenit is used the way the Barna Group uses it. And, of course, thatparticular misuse of the biblical term is not the only kind.The term born again has come to mean for many people merelythat someone or something got a new lease on life. So a quicksurvey of the internet shows that Cisco Systems, the communications company, has been born again; and the Green Movementhas been born again; the Davie Shipyard in Montreal has beenborn again; the west end in Boston has been born again; Kosherfoods for Orthodox Jews have been born again, and so on. So its
16
not surprising that we have to be careful when we read that 45 percent of Americans say they have been religiously born again.The term born again is very precious and very crucial inthe Bible. So our main concern is to know what God intendswhen the Bible uses this language, so that by his grace we mayexperience it and help others do the same. It is of enormousconsequence that we know what being born again really means.What Really Happened to Us?Another reason for a book on the new birth is to help followersof Christ to know what really happened to us when we wereconverted. It is far more glorious than many think it is. It isalso more glorious than I think it is. It is wonderful beyond allhuman comprehension. But that mystery is not because there islittle about it in the Bible. There is much about it in the Bible.Its because when all is understood as well as we can understandit in this age when we see in a mirror dimly (1 Cor. 13:12),there is still more. So I hope that when we are done, we willknow more fully and know more accurately what happened tous when we were born again.What Must Happen to Be Born AgainAnother reason for this treatment of the new birth is that thereare millions of people who do not yet follow Christ. They are notborn again. I pray that God might use this book as one means oftheir new birth. Some of them are church attenders and churchmembers, even leaders. But they are not born again. They arecultural Christians. Religion is a formal, external thing. There hasbeen no true inner awakening from spiritual death to spiritual life.I want to serve those people by showing them what musthappen to them. And by the word and the prayers of believers
17
and the Spirit of God, I hope that this book will be a means ofmany being born again. The new birth, as we will see, is nota work of man. No human makes the new birth happen. Nopreacher and no writer can make it happen. You cant make ithappen to yourself. God makes it happen. It happens to us, notby us.But it always happens through the word of God. Here is theway the apostle Peter puts it: Since you have been born again,not of perishable seed but of imperishable, through the livingand abiding word of God.And this word is the good news thatwas preached to you (1 Pet. 1:2325). So even though God is theone who begets his children, the seed by which he does it is theword of God, the gospel that we preach. So I pray that one of thegreat effects of these very human chapters will be that very supernatural miracle. My aim is to explain the new birth as clearly as Ican from the Bible so that readers can see it for themselves.There are three reasons I want you who are Christians toknow what happened to you when you were born again:1 When you are truly born again and grow in the grace andknowledge of what the Lord has done for you, your fellowshipwith God will be sweet, and your assurance that he is yourFather will be deep. I want that for you.2 If you know what really happened to you in your new birth, youwill treasure God and his Spirit and his Son and his word morehighly than you ever have. In this, Christ will be glorified.3 In the process of believers discovering what really happenedto them, the seriousness and the supernatural nature ofconversion will rise and that, I pray, will serve a more generalawakening of authenticity in the Christian church so thatreligious hypocrisy will diminish and the world will see reallove and sacrifice and courage in the service of Christ.
18
19
Another question we will ask is: Why is the new birth necessary?Jesus said to Nicodemus in John 3:7, You must be born again.Not I suggest it, or Your life would improve if you addedthis experience. Why is it that unless one is born again hecannot see the kingdom of God (John 3:3)? This is one of thegreat reasons for pursuing a right knowledge of the new birth.Until we realize that we must be born again, and why we mustbe born again, we probably will not realize what our conditionreally is without salvation.Most people do not know what is really wrong with them.One way to help them make a true and terrible and hopefuldiagnosis is to show them the kind of remedy God has provided,namely, the new birth. If you have a sore on your ankle andafter the doctor does his test, he comes in and says, I have hardnews: We have to take your leg off just below the knee, thenthat remedy tells you more about the sore than many eruditemedical words. So it is with the remedy You must be bornagain.After What? and Why? we will ask How? How does it comeabout? What does God do in regeneration? What did he do inhistory to make it possible? If new birth is decisively the work ofGod, which it is, how do I experience it? Is there anything I cando to make it happen? What is my part in bringing it about?After What? and Why? and How? we ask For what? Whatis the aim of the new birth? What effects does it have? Whatchanges come about in life? What is it like to live as a born-againperson?And finally, What can we do to help others be born again? If Godis the great Doer in this affair, what can we do? Does our doingreally matter? We will end with the practical matter of personalevangelism and how it relates to the new birth.
20
21
22
Part OneWhat Is the New Birth?
23
1The Supernatural Creationof Spiritual LifeJesus said to Nicodemus in John 3:3, Truly, truly, I say to you,unless one is born again he cannot see the kingdom of God. Hewas speaking to all of us when he said that. Nicodemus was not aspecial case. You and I must be born again, or we will not see thekingdom of God. That means we will not be saved; we will notbe part of Gods family, and we will not go to heaven. Instead,we will go to hell if we are not born again. Thats what Jesus sayslater in this chapter about the person who does not believe onChrist: The wrath of God remains on him (John 3:36). This isno joking matter. Jesus uses hard words for hard realities. Thatis what love does. The opposite is called pandering.Nicodemus was one of the Pharisees, the most religiousJewish leaders. Jesus said to them in Matthew 23:15 and 33, Woeto you, scribes and Pharisees, hypocrites! For you travel acrosssea and land to make a single proselyte, and when he becomesa proselyte, you make him twice as much a child of hell as25
We do not cause the new birth. God causes the new birth. Anyspiritually good thing that we do is a result of the new birth, nota cause of the new birth. This means that the new birth is takenout of our hands. It is not in our control. And so it confronts uswith our helplessness and our absolute dependence on Someoneoutside ourselves. This is unsettling. We are told that we wontsee the kingdom of God if were not born again. And were toldthat we cant make ourselves to be born again.The third reason Jesus teaching about the new birth isunsettling, therefore, is that it confronts us with the absolutefreedom of God. Apart from God, we are spiritually dead in ourselfishness and rebellion. We are by nature children of wrath(Eph. 2:3). Our rebellion is so deep that we cannot detect ordesire the glory of Christ in the gospel (2 Cor. 4:4). Therefore,if we are going to be born again, it will rely decisively andultimately on God. His decision to make us alive will not be aresponse to what we as spiritual corpses do, but what we do willbe a response to his making us alive. For most people, at least atfirst, this is unsettling.My Hope: Stabilize and Save, Not Just UnsettleIn view of how disturbing this can be to the tender conscienceas well as the hard heart, I want to be very careful. I do not wantto cause tender souls any unnecessary distress. And I do notwant to give false hope to those who have confused morality orreligion for spiritual life. Pray as you read this book that it willnot have either of these destructive effects.I feel like I am taking eternal souls in my hands. And yet Iknow that I have no power in myself to give them life. But Goddoes. And I am very hopeful that he will do what he says inEphesians 2:45: But God, being rich in mercy, because of thegreat love with which he loved us, even when we were dead in27
religious of all the Jewish groups. To this one, Jesus says (inv. 3), Truly, truly, I say to you, unless one is born again he cannot see the kingdom of God. Even more personally, he says inverse 7, You must be born again. So one of Johns points is:All of Nicodemus religion, all of his amazing Pharisaic studyand discipline and law-keeping, cannot replace the need for thenew birth.What Nicodemus needs, and what you and I need, is notreligion but life. The point of referring to new birth is thatbirth brings a new life into the world.8 In one sense, of course,Nicodemus is alive. He is breathing, thinking, feeling, acting. Heis a human created in Gods image. But evidently, Jesus thinkshes dead. There is no spiritual life in Nicodemus. Spiritually, heis unborn. He needs life, not more religious activities or morereligious zeal. He has plenty of that.Recall what Jesus said in Luke 9:60 to the man who wantedto put off following Jesus so he could bury his father. Jesussaid, Leave the dead to bury their own dead. That meansthere are physically dead people who need burying. And thereare spiritually dead people who can bury them. In other words,Jesus thought in terms of people who walk around with muchapparent life, but who are dead. In his parable about the prodigalson, the father says, This my son was dead, and is alive again(Luke 15:24).Nicodemus did not need religion; he needed lifespirituallife. What happens in the new birth is that life comes into being8 Throughout this book, we will not make any significant distinction betweenthe imagery of conception and the imagery of birth. Even pre-scientific, fi rstcentury people knew that children were alive and kicking before birth. Butthe biblical writers did not press the details of gestation in discussing the newbirth. In general, when they (and we) speak of the new birth, we are speakingmore broadly of new life coming into being whether one thinks of the point ofconception or the point of birth.
29
that was not there before. New life happens at new birth. Thisis not religious activity or discipline or decision. This is thecoming into being of life. Thats the first way of describing whathappens in the new birth.Experiencing the Supernatural,Not Just Affirming ItSecond, what happens in the new birth is not merely affirmingthe supernatural in Jesus but experiencing the supernatural inyourself. Nicodemus says in verse 2, Rabbi, we know that youare a teacher come from God, for no one can do these signs thatyou do unless God is with him. In other words, Nicodemussees in Jesus ministry a genuine divine activity. He admits thatJesus is from God. Jesus does the works of God. To this, Jesusdoes not respond by saying, I wish everyone in Palestine couldsee the truth that you see about me. Instead, he says, You mustbe born again, or you will never see the kingdom of God.Seeing signs and wonders, and being amazed at them, andgiving the miracle-worker credit for them that he is from God,saves nobody. This is one of the great dangers of signs andwonders: You dont need a new heart to be amazed at them. Theold, fallen human nature is all thats needed to be amazed at signsand wonders. And the old, fallen human nature is willing to saythat the miracle-worker is from God. The devil himself knowsthat Jesus is the Son of God and works miracles (Mark 1:24). No,Nicodemus, seeing Jesus as a miracle-worker sent from God isnot the key to the kingdom of God. Truly, truly, I say to you,unless one is born again he cannot see the kingdom of God.In other words, what matters is not merely affirming thesupernatural in Jesus but experiencing the supernatural inyourself. The new birth is supernatural, not natural. It cannotbe accounted for by things that are already found in this world.30
32
33
Now there was a man of the Pharisees named Nicodemus, a ruler of the Jews. This man came to Jesus bynight and said to him, Rabbi, we know that you area teacher come from God, for no one can do these signsthat you do unless God is with him. Jesus answeredhim, Truly, truly, I say to you, unless one is bornagain he cannot see the kingdom of God. Nicodemussaid to him, How can a man be born when he is old?Can he enter a second time into his mothers womband be born? Jesus answered, Truly, truly, I say toyou, unless one is born of water and the Spirit, he cannot enter the kingdom of God. That which is born ofthe flesh is flesh, and that which is born of the Spiritis spirit. Do not marvel that I said to you, You mustbe born again. The wind blows where it wishes, andyou hear its sound, but you do not know where it comesfrom or where it goes. So it is with everyone who is bornof the Spirit. Nicodemus said to him, How can thesethings be? Jesus answered him, Are you the teacherof Israel and yet you do not understand these things?John 3:110
2You Are Still You, But NewIn this chapter, we will continue the answer to the question ofChapter 1, What happens in the new birth? Jesus said to Nicodemusin John 3:7, Do not marvel that I said to you, You must beborn again. In verse 3, he told Nicodemusand usthat oureternal lives depend on being born again: Truly, truly, I sayto you, unless one is born again he cannot see the kingdomof God. So we are not dealing with something marginal oroptional or cosmetic in the Christian life. The new birth is notlike the make-up that morticians use to try to make corpses lookmore like they are alive. The new birth is the creation of spirituallife, not the imitation of life.We began to answer the question What happens in the newbirth? with two statements: 1) What happens in the new birth isnot getting new religion but getting new life, and 2) What happens in the new birth is not merely affirming the supernatural inJesus but experiencing the supernatural in yourself.
35
36
Spirit who gives life. And unless you are born of the Spirit, youcannot enter the kingdom of God (John 3:5).So we have life by being connected with the Son of God whois our life, and we have that life by the work of the Spirit. Weconcluded, therefore, that the work of the Spirit in regenerationis to impart new life to us by uniting us to Christ. The way JohnCalvin says it is: The Holy Spirit is the bond by which Christeffectually unites us to himself.9Then we saw the connection with faith in John 20:31: Theseare written so that you may believe that Jesus is the Christ, theSon of God, and that by believing you may have life in hisname. And we saw the connection in 1 John 5:4: Everyonewho has been born of God overcomes the world. And this is thevictory that has overcome the worldour faith. So we summedup what we had seen like this: In the new birth, the Holy Spiritsupernaturally gives us new spiritual life by connecting us withJesus Christ through faith.New Creation, Not Improving the OldWhich brings us now to the third way of describing whathappens in the new birth. What happens in the new birth is notthe improvement of your old human nature but the creation ofa new human naturea nature that is really you, forgiven andcleansed; and a nature that is really new, being formed in you bythe indwelling Spirit of God.Ill take you with me on the short version of the trip I took toarrive at this observation. In John 3:5, Jesus says to Nicodemus,Truly, truly, I say to you, unless one is born of water andthe Spirit, he cannot enter the kingdom of God. What doesJesus mean by the two terms by water and the Spirit? Some9 John Calvin, Institutes of the Christian Religion (Philadelphia: The WestminsterPress, 1960), 538 (III, 1, 1).
37
38
I think this is the passage that gives rise to Jesus words Unlessone is born of water and the Spirit, he cannot enter the kingdomof God. To whom does God say, You shall be my people, andI will be your God (v. 28)? Answer: To the ones to whom hesays, I will sprinkle clean water on you, and you shall be cleanfrom all your uncleannesses (v. 25); and verse 26: To the onesto whom he says, I will give you a new heart, and a new spiritI will put within you. In other words, the ones who will enterthe kingdom are those who have a newness that involves acleansing of the old and a creation of the new.So I conclude that water and Spirit in Ezekiel 36 refer totwo aspects of our newness when we are born again. And thereason both are important is this: When we say that a new spirit(or a new heart) is given to us, we dont mean that we ceaseto be the human beingthe morally accountable selfthat wehave always been. I was the individual human being John Piperbefore I was born again, and I have been the individual humanbeing John Piper since I was born again. There is a continuity.Thats why there has to be cleansing. If the old human being,John Piper, were completely obliterated, the whole concept offorgiveness and cleansing would be irrelevant. There would benothing left over from the past to forgive or cleanse.We know that the Bible tells us that our old self was crucified(Rom. 6:6), and that we have died with Christ (Col. 3:3), andthat we are to consider ourselves dead (Rom. 6:11), and put40
off the old self (Eph. 4:22). But none of that means the samehuman being is not in view throughout life. It means that therewas an old nature, an old character, or principle, or bent, thatneeds to be done away with.So the way to think about your new heart, new spirit, newnature is that it is still you and so needs to be forgiven andcleansedthats the point of the reference to water. My guiltmust be washed away. Cleansing with water is a picture of that.Jeremiah 33:8 puts it like this: I will cleanse them from all theguilt of their sin against me, and I will forgive all the guilt of theirsin and rebellion against me. So the person that we arethatcontinues to existmust be forgiven, and the guilt washed away.The Need to Be NewBut forgiveness and cleansing are not enough. I need to be new.I need to be transformed. I need life. I need a new way of seeingand thinking and valuing. Thats why Ezekiel speaks of a newheart and a new spirit in verses 2627: I will give you a newheart, and a new spirit I will put within you. And I will removethe heart of stone from your flesh and give you a heart of flesh.And I will put my Spirit within you, and cause you to walk in mystatutes and be careful to obey my rules.Heres the way I understand those verses: To be sure, theheart of stone means the dead heart that was unfeeling andunresponsive to spiritual realitythe heart you had before thenew birth. It could respond with passion and desire to lots ofthings. But it was a stone toward the spiritual truth and beautyof Jesus Christ and the glory of God and the path of holiness.That is what has to change if we are to see the kingdom of God.So in the new birth, God takes out the heart of stone and putsin a heart of flesh. The word flesh doesnt mean merely humanas it does in John 3:6 (that which is born of the flesh is flesh).41
Part TwoWhy Must We Be Born Again?
43
Ephesians 2:110
3We Are Spiritually DeadOne of the greatest books about God ever written, JohnCalvins Institutes of the Christian Religion, begins with thissentence: Nearly all the wisdom we possess, that is to say,true and sound wisdom, consists of two parts: the knowledge of God and of ourselves.11 What we may need reminding of in our day is not that the knowledge of Godis difficult to comprehend and to embracethats more or lessobviousbut that the knowledge of ourselves is just as difficultto comprehend and to embrace. Indeed, it may be more difficult, fi rst, because a true knowledge of ourselves assumes atrue knowledge of God, and second, because we tend to thinkwe do know ourselves, when in fact, the depths of our condition are beyond our comprehension without the help of God.
45
He finds her dead (Ezek. 16:48),12 and he gives his Son to diefor her, and then he makes her alive. And he keeps her forever.I give them eternal life, Jesus said, and they will never perish,and no one will snatch them out of my hand (John 10:28).So the question is: What does this mean? This deadness? Thereare at least ten answers in the New Testament. If we considerthem honestly and prayerfully, they will humble us very deeplyand cause us to be amazed at the gift of the new birth. So whatI aim to do is to talk about seven of them in this chapter andthree of them in the next chapter along with the larger question:Do we really need to be changed? Cant we just be forgiven andjustified? Wouldnt that get us to heaven?Here are seven of the biblical explanations of our conditionapart from the new birth and why it is so necessary.1. Apart from the new birth, we are dead in trespasses and sins(Eph. 2:12).Dead implies lifeless. Not physically or morally lifeless, but spiritually lifeless. Verse 1: We are walking and following theworld. Verse 2: We have passions of the flesh, and we carryout the desires of the body and the mind. So we are not deadin the sense that we cant sin. We are dead in the sense that we12 On the day you were born your cord was not cut, nor were you washed withwateryou were born. And when I passed by you and saw you wallowing in yourblood, I said to you in your blood, Live! I made you flourish like a plant ofthe field. And you grew up and became tall and arrived at full adornment. YourbreastsGOD, and you became mine (Ezek. 16:48).
48
3. Apart from the new birth, we love darkness and hate the light(John 3:1920).John 3:1920:This is the judgment: the light has come into the world,and people loved the darkness rather than the light becausetheir works were evil. For everyone who does wickedthings hates the light and does not come to the light, lesthis works should be exposed.
This word from Jesus spells out some of what our nature is likeapart from the new birth. We are not neutral when spirituallight approaches. We resist it. And we are not neutral whenspiritual darkness envelops us. We embrace it. Love and hateare active in the unregenerate heart. And they move in exactlythe wrong directionshating what should be loved and lovingwhat should be hated.4. Apart from the new birth, our hearts are hard like stone(Ezek. 36:26; Eph. 4:18).We saw this in the previous chapter from Ezekiel 36:26 whereGod says, I will remove the heart of stone from your flesh andgive you a heart of flesh. Here in Ephesians 4:18, Paul traces ourcondition back through darkness to alienation, to ignorance, tohardness of heart. They are darkened in their understanding,alienated from the life of God because of the ignorance that is inthem, due to their hardness of heart.At the bottom of our problem is not ignorance. There is somethingdeeper: the ignorance that is in them, due to their hardness ofheart. Our ignorance is guilty ignorance, not innocent ignorance.It is rooted in hard and resistant hearts. Paul says in Romans 1:18that we suppress the truth in unrighteousness. Ignorance is not ourbiggest problem. Hardness and resistance are.50
52
53
4We Are Willing Slavesto Sin and SatanIn the previous chapter, we launched our answer to the questionWhy must we be born again? We started with Ephesians 2:45:But God, being rich in mercy, because of the great love withwhich he loved us, even when we were dead in our trespasses,made us alive together with Christby grace you have beensaved. I said that God made us alive is virtually the sameas the new birth. The reason Paul gives for why we need thismiracle is that we were dead. Even when we were dead in ourtrespasses, God made us alive.This is what we needthe miracle of spiritual life created inour hearts. And the reason we need it is that we are spirituallydead. We are unable to see or savor the beauty and worth ofChrist for who he really is. Those who are not born againdo not say with Paul, I count everything as loss becauseof the surpassing worth of knowing Christ Jesus my Lord(Phil. 3:8).
55
56
When Paul says that God may perhaps grant them repentanceleading to a knowledge of the truth, that is virtually what
57
62 a practice of sinning alsopractices lawlessness; sin is lawlessness. You know thathe appeared to take away sins, and in him there is nosin. No one who abides in him keeps on sinning; noone who keeps on sinning has either seen him or knownhim. Little children, let no one deceive you. Whoeverpractices righteousness is righteous, as he is righteous.Whoever makes a practice of sinning is of the devil,for the devil has been sinning from the beginning.The reason the Son of God appeared was to destroythe works of the devil. No one born of God makes apractice of sinning, for Gods seed abides in him, andhe cannot keep on sinning because he has been born ofGod. By this it is evident who are the children of God,and who are the children of the devil: whoever does notpractice righteousness is not of God, nor is the one whodoes not love his brother.1 John 3:110
5Faith, Justification, Adoption,Purification, GlorificationThis chapter was first composed at Christmastime. Therefore,it attempts to do two things at once. It makes the connectionbetween the incarnation of Christ and regenerationthats theChristmas partand it attempts to carry forward the questionin the previous chapter: What will we miss out on if we are not bornagain? If you read the chapter with those two questions in mind,you may find your way more easily.Why Christmas?Twice in 1 John 3:110 we are told why Christmas happenedthatis, why the eternal, divine Son of God came into the world as ahuman being. In verse 5, John says, You know that he appearedto take away sins, and in him there is no sin. So the sinlessnessof Christ is affirmedin him there is no sin. And the reasonfor his coming is affirmedhe appeared to take away sins.Then, in the second part of verse 8, John says, The reasonthe Son of God appeared was to destroy the works of the devil.65
And the specific focus John has in mind when he says works ofthe devil is the sin that the devil promotes. We see this in thefirst part of verse 8: Whoever makes a practice of sinning is of thedevil, for the devil has been sinning from the beginning. So theworks of the devil that Jesus came to destroy are the works of sin.Two times John tells us that Christmas happenedthe Son ofGod became humanto take away sin, that is, to destroy the worksof the devil, namely, sin. So Jesus was born of a virgin by the HolySpirit (Matt. 1:18, 20), and increased in wisdom and in statureand in favor with God and man (Luke 2:52), and was perfectlyobedient and sinless in all his life and ministry, all the way to thepoint of death, even death on a cross (Phil. 2:58; Heb. 4:15)inorder to destroy the works of the devilto take away sin.Jesus Incarnation and Our RegenerationOne of the questions we are asking in this chapter is: What isthe connection between Jesus birth and our new birth? What is therelationship between Jesus incarnation and our regeneration?To answer this question, lets build a bridge from the previouschapter to this text here in 1 John 3:110.In the last chapter, we saw that when we ask why we need tobe born again, the answer could look backward to our miserablecondition in sin, or could look forward to the great things wewill miss if we are not born againlike entering the kingdom ofGod. We gave ten answers for why we need to be born again inthe first senselooking back on what we were apart from newbirth. And we gave five answers for why we need to be bornagain in the second senselooking forward to what we will notenjoy if we arent born again.The Great Love of GodNow the bridge between that chapter and this text in 1 John 3is the great love of God that gives life to people who are at enmity66
with God and are dead in trespasses and sins. Ephesians 2:45puts it like this: But God, being rich in mercy, because of thegreat love with which he loved us, even when we were dead in ourtrespasses, made us alive together with Christ. So the greatnessof the love of God is magnified in that it gives spiritual lifethatis new birthto those who have no claim on God at all. Wewere spiritually dead, and in our deadness we were walking inlockstep with Gods archenemy, the devil (Eph. 2:2). The justiceof God would have been well served if we had perished foreverin that condition. But for that very reason, our new birthourbeing made aliveis a magnificent display of the greatness ofthe love of God. We owe our spiritual life, and all its impulses,to the greatness and the freedom of the love of God.Now this is the bridge to 1 John 3:12, namely, the great loveof God for those who are not yet in his family.See what kind of love the Father has given to us [theresthe link with the greatness of the love of God], that weshould be called children of God; and so we are. Thereason why the world does not know us is that it did notknow him. Beloved [loved ones!], we are Gods childrennow, and what we will be has not yet appeared; but weknow that when he appears we shall be like him, becausewe shall see him as he is.
Consider four observations that connect this text with the greatness of the love of God in Ephesians 2:4, and with our questionin the previous chapter about why we need to be born again.1. Made Gods ChildrenFirst, when verse 1 says that we are called the children of God,it doesnt mean we were already the children of God but notcalled that, and then God called us that. No, it means that wewere not children of God. We were like the rest of the world67
68
because the life we have through the new birth is life in unionwith the incarnate Christ. Jesus said, I am the living bread thatcame down from heaven. If anyone eats of this bread, he willlive forever. And the bread that I will give for the life of theworld is my flesh (John 6:51). That life that we have in unionwith Christ is the life that Jesus obtained for us by the life helived and the death he died in the flesh.Consider 1 John 5:1012, and keep in mind as you read thatthe Son of God here is the incarnate Son of God. Whoeverbelieves in the Son of God has the testimony in himself.Andthis is the testimony, that God gave us eternal life, and this lifeis in his Son. Whoever has the Son has life; whoever does nothave the Son of God does not have life.In other words, the new birth gives us life by bringing us intospiritual connection with Jesus Christ. He is our life. His newlife in us, with all the changes that it brings, is the testimonyof God that we are his children. And this life is the life of theincarnate Son of God. And the Word became flesh and dweltamong us.And from his fullness [the fullness of the incarnateone] we have all received grace upon grace (John 1:1416)thatis new birth, new life.No Incarnation, No RegenerationSo if there were no incarnationno Christmasthere wouldbe no regeneration for these two reasons: 1) If there were noincarnation, there would be no incarnate Jesus Christ to beholdand believe in, and thats the aim of the new birth. So the newbirth would not happen. 2) If there were no incarnation, therewould be no vital union or connection between us and theincarnate Christ, and so the new birth would abort becausethere would be no source of new saving, forgiving life.Christianity is not a kind of spirituality that floats amorphouslythrough various religions. It is historically rooted in the person71
72
First, 1 John 4:10: In this is love, not that we have loved Godbut that he loved us and sent his Son to be the propitiation forour sins. He sent his Sonthats the incarnationto die in ourplace and so absorb the wrath of God that we deserved. Thatis what propitiation is: It is an act that satisfies the holy wrathof God. Because of Christ crucified, Gods punitive wrath isremoved forever from those who are born again.Second, 1 John 2:1: My little children, I am writing thesethings to you so that you may not sin. But if anyone does sin,we have an advocate with the Father, Jesus Christ the righteous.Why is Jesus in heaven explicitly called the righteous whenhe is described as the advocate we need because of our sin? Itsbecause what he pleads before the Father is not only his blood,but also his righteousness. Which is why 1 John 3:5 says, In himthere is no sin. The perfection we do not have, Jesus provided.The judgment we do not want, Jesus bore.Christmas Was Not OptionalAll of this unspeakably wonderful news could not have come topass if the Son of God had never become man. The incarnationwas necessary for all this to come true. The Son of God becamethe God-man. The Word became flesh (John 1:14). If there hadbeen no incarnation, there would have been no regeneration, nofaith, no justification, no purification, and no final glorification.Christmas was not optional. Therefore, Godbeing richin mercy, out of the great love with which he loved us, whilewe were dead in trespassessent his Son into the world to livewithout sin and die in our place. What a great love the Fatherhas shown to us! What a great obedience and sacrifice the LordJesus gave for us! What a great awakening the Spirit has workedin us to bring us to faith and everlasting life!
74
Part ThreeHow Doesthe New Birth Come About?
75
6Ransomed, Raised, and CalledOne of the unsettling things about the new birth, which Jesussays we all must experience in order to see the kingdom of God(John 3:3), is that we dont control it. We dont decide to make ithappen any more than a baby decides to make his birth happenor, more accurately, make his conception happen. Or even moreaccurately: We dont decide to make it happen any more than deadmen decide to give themselves life. The reason we need to be bornagain is that we are dead in our trespasses and sins. Thats whywe need the new birth, and thats why we cant make it happen.This is one reason why we speak of the sovereign grace of God. Orbetter: This is one reason why we love the sovereign grace of God.Our condition before the new birth is that we treasure sin andself-exaltation so much that we cannot treasure Christ supremely.In other words, we are so rebellious at the root of our fallenhuman nature that we cant fi nd it in ourselves to humbly seeand savor Jesus Christ above all things. And we are guilty forthis. This is real evil in us. We are blameworthy for this spiritualhardness and deadness. Our consciences do not excuse us when77
And third, verse 18 says that God ransomed us from the futileways inherited from our forefathers.Imperishability Unites All ThreeBefore we look at these in more detail, notice first what makesthese three events hang together as Gods way of causing thenew birth. In all three of these works of God, there is a referenceto imperishability. Verses 34:Blessed be the God and Father of our Lord Jesus Christ!According to his great mercy, he has caused us to be bornagain to a living hope through the resurrection of JesusChrist from the dead, to an inheritance that is imperishable.
So the point is that by the new birth, God means for us to have notjust new life but eternal life. Verse 3: We are born again to a livinghope. So the emphasis falls on the hope of our new life. It livesandwill not die. It inherits an imperishable inheritance. Thats the emphasis. Our new life in the new birth is forever. We will never die.Then, notice the same emphasis in verses 1819:...knowing that you were ransomed from the futile waysinherited from your forefathers, not with perishablethings such as silver or gold, but with the precious bloodof Christ, like that of a lamb without blemish or spot.
The blood of Christ (v. 19) is the ransom price paid for our life,and this blood is contrasted with the less valuable silver andgold that might have been paid. And the reason silver and goldare less valuable is that they are perishable. Verse 18: not withperishable things such as silver or gold.So again the point is that the new life that Jesus ransoms withhis blood is not in danger of going back into captivity, becausethe price he pays for our new life (our new birth) is not perishable.80
Verses 1819: You were ransomed from the futile ways inheritedfrom your forefathers, not with perishable things such as silver orgold, but with the precious blood of Christ, like that of a lambwithout blemish or spot. The point here, in regard to the newbirth, is that new eternal life is not possible for enslaved sinnerswithout a ransom being paid. This text implies that we were all inbondage or captivity to ways of thinking and feeling and actingthat would have destroyed us. We were under the wrath of Godwho had handed us over to these futile ways (Rom. 1:21, 24, 26,28). Slavery to these sinful ways would destroy us if we could notbe ransomed from this slavery. God paid this ransom price bysending Christ to bear his own wrath (Rom. 8:3; Gal. 3:13).This is the rock-solid historical foundation that makes ournew birth possible. As a basis for God to unite us to Christ andcreate faith and give us new life, there had to be some objective,historical events in the life of Jesus Christ, the Son of God. Jesussaid in Mark 10:45, The Son of Man came not to be served butto serve, and to give his life as a ransom for many. This is whythe historical event of the incarnation happened.The Son of Man came to give his life a ransom for many. Thishad to happen as the basis of the free and gracious gift of the newbirth for undeserving sinners like us. And since the new birth isthe gift of eternal life, not just new life, the ransom price had to beimperishablenot like silver or gold. The blood of Christ is infinitelyvaluable and, therefore, can never lose its ransoming power. The lifeit obtains lasts forever. So the way God brings about the new birthis by paying a ransom for the eternal life it imparts.The second objective historical event that had to happen for usto be born again with eternal life was the resurrection of Jesusfrom the dead. 1 Peter 1:34:Blessed be the God and Father of our Lord Jesus Christ!According to his great mercy, he has caused us to be bornagain to a living hope through the resurrection of Jesus82
7Through the Washingof RegenerationNotice the word regeneration in Titus 3:5: He [that is, God]saved us, not because of works done by us in righteousness, butaccording to his own mercy, by the washing of regeneration andrenewal of the Holy Spirit. Regeneration is another way of speaking about the new birth or the second birth or being born again.We have discussed what the new birth is (Chapters 12), andwhy it is necessary (Chapters 35). Then in the previous chapter,we began to address how it happens. In this chapter, we continuethat question: How does God bring about the new birth? But first,there are some very important new signals here about what it isand why we need it. Consider one of each.A New Signal about What New Birth IsConsider an unusual signal about what the new birth is. Theword for regeneration in verse 5 ([God] saved usby thewashing of regeneration [palingenesias]) is used only one other87
place in the entire Bible, namely, Matthew 19:28. Jesus says to thetwelve apostles, Truly, I say to you, in the new world (a very loosetranslation of in the regeneration [en te palingenesia]), whenthe Son of Man will sit on his glorious throne, you who havefollowed me will also sit on twelve thrones, judging the twelvetribes of Israel. This is a reference to the rebirth of the creation.Its like saying in the new heavens and the new earth thatIsaiah spoke about in Isaiah 65:17 and 66:22.Jesus conceives of the new birth as something that will happento all creation, not just human beings. Humans are not the onlypart of reality that is fallen and defiled and disordered. The wholecreation is. Why is that? The answer is that when human beingssinned at the very beginning, God made all creation a visibledisplay of the horrors of sin. Disease, degeneration, naturaldisastersthese are all part of the visual, audible, touchableimages of the moral outrage that sin entered the world andpervades the world.The Material Creation Born AgainThe most important passage in the Bible about this isRomans 8:2023. And its important for this chapter becauseit confirms and clarifies what Jesus said about the creationundergoing a new birththe regeneration.The creation [All of it! Not just the people] was subjectedto futility, not willingly, but because of him who subjectedit, [namely, God, since only God can subject the creationto futility in hope] in hope that the creation itself will beset free from its bondage to corruption and obtain thefreedom of the glory of the children of God. [There will bea great renewal someday and it will happen so that creationjoins the children of God in their glorious renewal.]For we know that the whole creation has been groaning
88
in verse 7 that the aim of the new birth is that being justifiedby his grace we might become heirs according to the hope ofeternal life, he means heirs of everything included in thateternal lifenew heavens, new earth, new body, new perfectedrelationships, new sinless sight of all that is good and glorious,and new capacities for a kind of pleasure in God that will exceedall our dreams.Thats the new signal in Titus 3 of what the new birth is: Itsthe first installment of the fi nal, universal regeneration of theuniverse.A New Signal about Why We Need the New BirthThen there is a clear signal why we need this regeneration. Itsfound in Titus 3:3: We ourselves were once foolish, disobedient,led astray, slaves to various passions and pleasures, passing ourdays in malice and envy, hated by others and hating one another.That is not a description of the material creation. Thats adescription of the human heart. Those are moral evils, not physicalevils. Foolish. Disobedient. Led astray. Slaves to sinful pleasures.Malice. Envy. Hating. We are all in that list somewhere.The reason we need regeneration is that God will not welcomesuch hearts into his new creation. As Jesus said, unless we areborn again, we will not see the kingdom of God (John 3:3). Thisis why all of us must be born again. We must be changed.The Meaning of Grace: But GodThen comes one of the most precious phrases in the Bible (v. 4):ButGod. We were foolish, disobedient, led astray, slaves tosinful pleasures, malicious, envious, hated and hating. ButGodBut when the goodness and loving kindness of God appeared, he[God!] saved us.90
This is the same amazing sequence that we saw in Ephesians 2:35: [We were] carrying out the desires of the body andthe mind, and were by nature children of wrath, like the rest ofmankind. But God, being rich in mercy, because of the greatlove with which he loved us, even when we were dead in ourtrespasses, made us alive together with Christby grace youhave been saved. We were dead, but God made us alive. This isthe meaning of grace. The dead can do nothing to make themselves live. But GodThats what we have here in Titus 3:35. We were slaves todesires and pleasures that were so powerful we could not tasteand see that the Lord was good. So far as our ability to knowand trust and love God was concerned, we were dead. ButGod. Verses 45: But when the goodness and loving kindnessof God our Savior appeared, he saved us, not because of worksdone by us in righteousness, but according to his own mercy, bythe washing of regeneration and renewal of the Holy Spirit.How? By Washing and RenewalSo we turn now to the third question: How does God do it? Howdoes the new birth happen? Just as we saw in the words of Jesus inJohn 3, Paul describes regeneration as a cleansing and a renewing.At the end of Titus 3:5, Paul says that God saved us by the washingof regeneration and renewal of the Holy Spirit. Regeneration is akind of washing. And regeneration is a kind of renewal.Recall that Jesus said in John 3:5, Unless one is born of waterand the Spirit, he cannot enter the kingdom of God. Notice theparallel thought in Titus 3:5: You were saved by the washing ofregeneration and renewal of the Holy Spirit.My argument in Chapter 2 concerning John 3 was that thislanguage of water and Spirit came from Ezekiel 36:2527 whereGod promises his people,91
Jesus was saying something like this: The time of the NewCovenant promises has arrived. Ezekiels promise is comingto pass by the Spirit in connection with me. The Spirit giveslife (John 6:63). And I am the way, the truth, and the life(John 14:6). And when the Spirit connects you to me by faith,you experience a new birth. And there are at least two ways tolook at it: cleansing from all that is past and renewal for all thatis future.So when Paul says here in Titus 3:5 that God saved usbythe washing of regeneration and renewal of the Holy Spirit, hemeans roughly the same thing as Jesus did: The promises of theNew Covenant have arrived. The beginning of the kingdom ofGod is here. The final universal regeneration has begun. Andyour new birth is a cleansing from all the sin that you have evercommitted. It is also the creation of a new nature by the HolySpirit. You are still you after the new birth. But there are twochanges: You are clean, and you are new. That is what it meansto be born again, regenerated.How did God bring that about? What Paul wants to emphasize here is that it is owing to the way God is, not owing to whatwe have doneeven done in righteousness. Verses 45 givethree descriptions of the way God is and put this in contrast toanything we might try to do to be born again. But when thegoodness and loving kindness of God our Savior appeared, hesaved us, not because of works done by us in righteousness, butaccording to his own mercy, by the washing of regeneration andrenewal of the Holy Spirit.92
93
This is one reason why I do not think the washing of regeneration in verse 5 refers to baptism. Whether circumcision in theOld Covenant or baptism in the New Covenantit is not goodthings we do, not even sacraments, that cause us to be bornagain. The kindness of God. The love of God. The absolutely freemercy of God. These explain our new birth. Not circumcision.Not baptism. Not any works done by us in righteousness. Newbirth comes and brings righteous deeds with itnot the otherway around.May God give you eyes to see that nothing could make youhumbler and nothing could make you happier than the truththat you have been born again, not because of anything you did,but because of the mercy of God. Submit to that, and be glad.
96
8Through Faith in Jesus ChristJust before writing this book, I read the autobiography of SupremeCourt Justice Clarence Thomas, My Grandfathers Son: A Memoir.He had been raised as a Roman Catholic and attended Holy CrossCollege in Worcester, Massachusetts. But while there, he partedways with the church, though not forever. Here is what he said:During my second week on campus, I went to Mass forthe first and last time at Holy Cross. I dont know whyI botheredprobably habit, or guiltbut whatever thereasons, I got up and walked out midway through thehomily. It was all about Church dogma, not the socialproblems with which I was obsessed, and seemed to mehopelessly irrelevant.13
What Is Relevance?As a preacher, I think a lot about relevance. Why should anyonelisten to what I have to say? Why should anybody care? Relevance13 Clarence Thomas, My Grandfathers Son: A Memoir (New York: HarperCollins,2007), 51.
99
are life-and-death issues. But they are not the most important,because they deal with the relief of suffering during this briefearthly life, not the relief of suffering during the eternity thatfollows. Or to put it positively, they deal with how to maximizewell-being now for eighty years or so, but not with how tomaximize well-being in the presence of God for eighty trillionyears and more.My job as a pastor is to deal in what matters most, and to stayclose to the revealed will of God in the Bible (so you can see it foryourselves), and to pray that, by Gods grace, the young, idealistic, angry Clarence Thomases in the crowd, and everyone else,will see and feel the magnitude of what God says is important.Seeing and Savoring the Magnificence of JesusJesus says in John 3:3, Truly, truly, I say to you, unless one isborn again he cannot see the kingdom of God. Not to see thekingdom of God is to be excluded from the kingdom of God.Jesus said in Matthew 8:1112 that outside the kingdom is outerdarkness. In that place there will be weeping and gnashing ofteeth. He called it eternal punishment (Matt. 25:46). Thealternative to that is to be in the kingdom of God and spendeternity in everlasting joy with the greatest person in theuniverse (John 18:24).Nothing is more important than the glory of Christ personallyseen and savored in the kingdom of God with all the countlessnumber who have believed in his name. That glory will one dayfill the earth with peace and justice and everything good. Christhimself will be the center and radiant through it all.What Is Our Involvement in the New Birth?The question in this chapter is: What is our involvement? Whatdo we do in the act of new birth? How are we involved in it? Let101
me give you the answer first that I see in the Bible, and then Iwill try to show where its found.Your involvement in the event of the new birth is to exercisefaithfaith in the crucified and risen Son of God, Jesus Christ,as the Savior and Lord and Treasure of your life. The way you areengaged in the event of your new birth is by believing on Christ.You are involved in the new birth because in it you receive Christfor who he really is, the supremely valuable Savior, Lord, andTreasure of the universe.The answer continues like this: Your act of believing andGods act of begetting are simultaneous. He does the begettingand you do the believing at the same instant. Andthis is veryimportanthis doing is the decisive cause of your doing. Hisbegetting is the decisive cause of your believing.If you have a hard time thinking of one thing causing anotherthing if they are simultaneous, think of fire and heat or fire andlight. The instant there is fire, there is heat. The instant there isfire, there is light. But we would not say that the heat caused thefire, or the light caused the fire. We say that the fire caused theheat and the light.Thats the answer I see in the Bible to the question How are weinvolved in the new birth? Now we will look at some passages ofScripture that direct me to these thoughts.Obedience to the TruthWe will start here in 1 Peter 1:2223:Having purified your souls by your obedience to the truthfor a sincere brotherly love, love one another earnestlyfrom a pure heart, since you have been born again, notof perishable seed but of imperishable, through the livingand abiding word of God.
102
Notice several things here. One is that the aim of what is happening is love. Having purified your souls by your obedience to thetruth for a sincere brotherly love. In other words, the purification of the soul by obedience to the truth is leading somewhere,namely, to a sincere brotherly love. One of the implications ofseeing this is that the purifying of the soul is not itself the presence of brotherly lovenot yet. The purifying of the soul is forbrotherly love. It is to the end of brotherly love. Love is a verybasic fruit of the Spirit. So verse 22 means that something morebasic than brotherly love is happening when it says having purified your souls by your obedience to the truth.Obedience here is, therefore, not the obedience of love. Itleads to the obedience of love. What is it then? Obedience tothe truth is the right response to the truth. It is called theobedience to the truth (v. 22). And what is that truth? In thiscontext, the truth refers to the word of God. Thats what itscalled in verse 23 (through the living and abiding word of God).And that word of God in verse 25 is called the good news, thegospel: This word is the good news that was preached to you.So obeying the truth in verse 22 means obeying the gospel.And what does obeying the gospel mean? It means believingin Jesus, because what the free offer of the gospel calls for is faith:Believe on the Lord Jesus and you will be saved (Acts 16:31;1 Cor. 15:12). The first and basic command of the gospel is notlove your brother. What the gospel requires first is faith. Soobeying the gospel at this basic level is having faith.You can see this again in the third chapter of this letter.Husbands without faith in Christ are described as disobeyingthe word. Likewise, wives, be subject to your own husbands,so that even if some do not obey the word, they may be wonwithout a word (1 Pet. 3:1). Not obeying the word means theyare not believers. The same thing turns up in 1 Peter 2:8 (they
103
disobey the word) and 4:17 (who do not obey the gospel ofGod). So, not obeying the word means not obeying the gospel,that is, not believing.Paul spoke the same way in 2 Thessalonians 1:8, where he saidthat God will inflict vengeance on those who do not know Godand on those who do not obey the gospel of our Lord Jesus. Inother words, the gospel of the Lord Jesus calls for faith, andthese people did not obey. They did not believe. They rejectedthe word of truth, the gospel.14So when Peter says that you have purified your souls by yourobedience to the truth for a sincere brotherly love (1 Pet. 1:22), hemeans you have purified your souls by faith in the gospel of JesusChrist and this faith leads to brotherly love. Faith works throughlove (Gal. 5:6). Love comes from sincere faith (1 Tim. 1:5).Believing: Acting Out the New BirthRecall from the previous chapter that in John 3:5 and Titus 3:5 thenew birth involves purifyingthe imagery of water and washing.Jesus said, Truly, truly, I say to you, unless one is born of waterand the Spirit, he cannot enter the kingdom of God. And Paulsaid that God saved usby the washing of regeneration. Sowhen Peter says that our souls have been purified by obedienceto the truththat is, by faith in the gospeland says that thispurification leads to love, and is not the same as love, I take himto mean that this purification is the purification which takesplace in the new birth. Its the purification referred to in thewater of John 3:5 and the washing of Titus 3:5. This is thenew birth.14 Ephesians 1:13: In him you also, when you heard the word of truth, the gospelof your salvation, and believed in him, were sealed with the promised HolySpirit. Colossians 1:5: Of this you have heard before in the word of the truth, thegospel.
104
Which means that the new birth in which we are washed, andthe purification by obedience to the truth, are part and parcelof the same event. We are, therefore, integrally involved in thenew birth. It is our new birth. It involves our believing in thegospel of Jesus Christ. Thats why I say that my new birth doesnot take place without me believing. In believing we are actingout the new birth, we are breathing in the new life.Gods Begetting Causes Our BelievingNow in verse 23, Peter explains this in the very language ofbeing born again. Lets put both verses together so you cansee the connection between purifying the soul (our act) andbeing born again (Gods act): Having purified your souls byyour obedience to the truth for a sincere brotherly love, loveone another earnestly from a pure heart, since you have beenborn again not of perishable seed but of imperishable, throughthe living and abiding word of God. The connection betweenour action in the new birth (v. 22) and Gods action in the newbirth (v. 23) is a relationship of effect and cause. Thats impliedin the words since [or because] you have been born again.15Gods action is underneath our action. We purify our hearts inobedience to the gospel, that is, we act out regeneration; and weare able to do that because God regenerates us.God Is the Decisive CauseThere are three clues in this text that Gods action in the newbirth is the cause of our action in the new birth. That is, hisbegetting causes our believing.15 Literally there is simply a participial connection between our purifying andGods giving birth (anagegennemenoi, having been born again, 1 Peter 1:23),but contextually it is clear that this participle is functioning as a ground or acause of what went before.
105
The third clue related to this text that Gods begetting is thecause of our believing is the way Peter uses this same languageat the Jerusalem council in Acts 15. He says that Gentiles andJews are both being saved, not just Jews. And the way he says itis significant: [God] made no distinction between us and them,having cleansed their hearts by faith (Acts 15:9).Here he speaks the same way he does in 1 Peter 1:22, wherehe says, Having purified your souls by your obedience to thetruth That is, having purified your souls by faith Butin Acts 15:9 he uses the same language of purifying and faithbut says explicitly that God does the purifying through ourfaith. [God] made no distinction between us and them, having cleansed their hearts by faith. God cleansed their heartsthrough their faith. This shows us that in the new birth ourfaith is both a crucial aspect and an essential instrument of thepurification which God effects in us. But it is not ultimate. It isnot its own cause. God is.What This Means for UsWhat then does this mean for us? It means four things, andI pray you will receive them with joy.1 It means we must believe in order to be saved. Believe onthe Lord Jesus Christ and you will be saved (Acts 16:31).The new birth does not take the place of faith; the new birthinvolves faith. The new birth is the birth of faith.2 It means that left to ourselves we will not believe. There is nohope that the dead will breathe by themselves.3 It means that God, who is rich in mercy and great love andsovereign grace, is the decisive cause of your faith.4 According to 1 Peter 1:22, the fruit of the born-again heartis love. Which means that nothing in life is untouched by107
108
In the beginning was the Word, and the Word was withGod, and the Word was God. He was in the beginningwith God. All things were made through him, andwithout him was not any thing made that was made.In him was life, and the life was the light of men. Thelight shines in the darkness, and the darkness has notovercome it. There was a man sent from God, whosename was John. He came as a witness, to bear witnessabout the light, that all might believe through him.He was not the light, but came to bear witness aboutthe light. The true light, which enlightens everyone,was coming into the world. He was in the world, andthe world was made through him, yet the world didnot know him. He came to his own, and his own peopledid not receive him. But to all who did receive him,who believed in his name, he gave the right to becomechildren of God, who were born, not of blood nor of thewill of the flesh nor of the will of man, but of God. Andthe Word became flesh and dwelt among us, and wehave seen his glory, glory as of the only Son from theFather, full of grace and truth.John 1:114
9Through Intelligible Good NewsRecently I was listening to a recording of Vishal Mangalwadislecture From Bach to Cobain, which is part of a series that hegave at the University of Minnesota under the title Must theSun Set on the West? In this lecture, he spoke briefly aboutthe use of the mantra in Eastern religions. When I heard whathe said, I thought: That will be very significant in helping memake one of my points in this chapter, namely, how the wordfunctions to bring about the new birth.So let me try to make a connection between the focus ofthe previous chapter on 1 Peter 1:23 and the present focus onJohn 1:1213 by means of pondering how a mantra differs fromthe gospel. It is amazing how many religious websites link themeaning of mantra to John 1:1: In the beginning was theWord, and the Word was with God, and the Word was God.The point they make is that reality is essentially sound, and wecan gain access to ultimate reality by repeating certain sacredsounds. Hence, mantra.
111
112
know what you are doing. Yoga is to the body what mantra isto the mouth. The two are rooted in the same worldview. Takemy own town as an example. When I go to the MinneapolisYWCA website and click on fitness classes, I find 22 referencesto yoga, including Beginning Yoga, MS Yoga, Youngster Yoga,Youth Dance and Yoga, and Yoga for Everybody.One explanation says that in mantra yoga one has to chanta word or a phrase until he/she transcends mind and emotions.In the process the super conscious is discovered and achieved.17Then yoga itself is described like this:Yoga focuses on harmony between mind and body. Yogaderives its philosophy from Indian metaphysical beliefs. Theword yoga comes from the Sanskrit language and meansunion or merger. The ultimate aim of this philosophy isto strike a balance between mind and body and attainself-enlightenment. To achieve this, yoga uses movement,breath, posture, relaxation, and meditation in order toestablish a healthy, lively, and balanced approach to life.18
You were born again through the living and abiding word ofGod. This word is the gospel of Jesus Christ crucified and risen.Dont fall prey to another gospel. There is no other gospel, andthere is no other path to Godor to ultimate well-beingthanhearing, understanding, and believing the scandalous news ofJesus Christ in the gospel.The Word Became FleshSo when we come to John 1:1 (In the beginning was the Word,and the Word was with God, and the Word was God), we willnot stop there, tear it out of its context, and fit it into a worldviewthat tries to transcend the flesh with meditation, mantras, and17, accessed 5-1-08.18, accessed 05-01-08.
115
yoga. No, we will read all the way to verse 14 and beyond: Andthe Word became flesh and dwelt among us, and we have seen hisglory, glory as of the only Son from the Father, full of grace andtruth.This is why the word through which we are born again cannotbe a mantra. It became flesh and dwelt among us and lived aperfect life and died in our place and bore the wrath of Godand rose physically from the dead, and it now comes to us in ahistorical narrative called the gospel. The Word was God and isGod. He was not a sound. He was a Person. He was called theWord because he represents the expression of all that God theFather is.And the Word became flesh. And the story of his savingworkthe gospel, the word of Godis the way Jesus Christ, theWord, comes to us and regenerates us and renews us. We hearthis word, and by grace, we understand this word, and receivethis word, and are born again by this word. And we never, never,never tryby mantras or any other meansto empty our mindsof this word. Never.Born Not of Man but of GodFocus briefly on John 1:1113:He came to his own, and his own people did not receivehim. But to all who did receive him, who believed in hisname, he gave the right to become children of God, whowere born, not of blood nor of the will of the flesh nor ofthe will of man, but of God.
116
The emphasis of John 1:1213 falls on new birth being the workof God, not man. So how does John understand the relationshipbetween our act of believing and Gods act of begetting? DoesGods begetting cause our believing, or does our believing bringabout Gods begetting? Does the new birth bring about faith,or does faith bring about the new birth? If we only had theseverses, the emphasis would fall on: not of the will of the flesh,but of God. That is, Gods begetting, not mans believing wouldappear to be decisive in the new birth.Gods Begetting Causes Our BelievingBut we are not limited to these verses to know what John teachesabout how our faith and Gods work in the new birth relate toeach other. John tells us plainly in 1 John 5:1. This is the clearesttext in the New Testament on the relationship between faithand the new birth. Watch the verbs closely as we read 1 John 5:1:Everyone who believes that Jesus is the Christ has been born ofGod. Here is what John Stott says on this verse, and I agreetotally:The combination of present tense (believes) and perfecttense [has been born] is important. It shows clearly thatbelieving is the consequence, not the cause, of the newbirth. Our present, continuing activity of believing is theresult, and therefore, the evidence, of our past experienceof new birth by which we became and remain Godschildren.19
118
20 For more on faith as a gift of God, see 2 Tim. 2:2526; Eph. 2:8; Phil. 1:29;Acts 5:31; 13:48; 16:14; 18:27.
119
Part FourWhat Are the Effectsof the New Birth?
121
10It Overcomes the WorldWe turn now from the What? and Why? and How? questions tothe effects or the evidences of the new birth. We ask where thenew birth leads. What fruit does it produce in our lives? Whatare the signs in your life that God has caused you to be born again?Now to focus on the effects of the new birth, we turn to thebook of the Bible that is almost totally devoted to answeringthis question, namely, the First Epistle of John. I have a 100year-old commentary on 1 John in my library called The Tests ofLife by Robert Law.21 Its a good title. What it means is that Johnwrote this letter to provide the church with tests or criteria forknowing if we have spiritual life, that is, if we have been bornagain.To encourage you to read through 1 John for yourself, let megive you an overview of what I mean in saying that 1 John iswritten to help you know you have been born again. This chapteris an overview of 1 John, with a brief look at 1 John 5:34. The21 Robert Law, The Tests of Life: A Study of the First Epistle of John (Grand Rapids,MI: Baker Book House, orig. 1909).
123
124
Summing up all these reasons for writing 1 John goes like this:I am writing because you are true believers, but there are deceivers inyour midst, and I want you to be rock-solid confident in your presentpossession of eternal life as regenerate children of God, so that you arenot drawn away after sin. And if this letter has that effect my joy willbe complete. So at the heart of his reason for writing is the desireto help them know they are born againthat they now havenew spiritual life. Eternal life.Eleven Evidences of the New BirthConsider one more overview before we focus on 1 John 5:34.John gives at least eleven evidences that a person is born again.We could probably boil them all down to faith and love. Butfor now well let them stand the way he says them. Not everyverse below uses new-birth language. But it will be plain, if youthink about it for a moment, that even where the language is notpresent, the reality is. Here they are:125
3. Those who are born of God dont hate others but love them.1 John 2:9: Whoever says he is in the light and hates hisbrother is still in darkness.1 John 3:14: We know that we have passed out of deathinto life, because we love the brothers. Whoever does notlove abides in death.1 John 4:78: Beloved, let us love one another, for love isfrom God, and whoever loves has been born of God andknows God. Anyone who does not love does not knowGod, because God is love.1 John 4:20: If anyone says, I love God, and hates hisbrother, he is a liar.
126God, God abides in him, and he in God.1 John 5:12: Whoever has the Son has life; whoever doesnot have the Son of God does not have life.
127
9. Those who are born of God listen submissively to the apostolic Word.1 John 4:6: We are from God. Whoever knows Godlistens to us; whoever is not from God does not listen tous. By this we know the Spirit of truth and the spirit oferror.
10. Those who are born of God believe that Jesus is the Christ.1 John 5:1: Everyone who believes that Jesus is the Christhas been born of God.
No Perfection, No DefectionOne of the mistaken effects of all those tests of life wouldbe to overwhelm us with the sense that John might possiblybe saying: If youre born again, youre perfect. If youre bornagain, you dont sin at all. There is no defeat in the Christianlife. There is only victory. That would be a serious misreadingof the letter.Another mistaken effect that these tests might have on our mindsis to make us think we can lose our salvation. They might make usthink that we can be born again for a while and then begin to fail inthese tests and die and lose the spiritual life that we were given in thenew birth. That would be another serious mistake.John is very aware that his words could be taken in thesetwo wrong ways. So he is as explicit as any writer in the New128
Testament that this is not the case: Christians are not sinless,and born-again people cannot lose the new birth and be lost.He says in 1 John 1:810, If we say we have no sin [presenttense], we deceive ourselves, and the truth is not in us. If weconfess our sins [present tense], he is faithful and just to forgiveus our sins and to cleanse us from all unrighteousness. If wesay we have not sinned, we make him a liar, and his word isnot in us. So John is at pains to say that walking in the light(1:7) does not mean walking flawlessly. It means that, when youstumble, the light of Christ causes you to see your stumbling assin and hate it and confess it and receive forgiveness and moveforward with Christ.And John is just as jealous to make sure we dont infer fromthese tests of life that we can be born again and then later loseour life and be lost. 1 John 2:19 is one of the clearest statements inthe Bible that there is another way to understand what happenswhen a person abandons the church. It says, They went outfrom us, but they were not of us; for if they had been of us, theywould have continued with us. But they went out, that it mightbecome plain that they all are not of us.Notice three things John says to protect us from misunderstanding. 1) Those who seemed to be born again and forsookthe faith never were born againthey never were of us. Theywent out from us, but they were not of us. In other words, theexplanation is not that they lost their new birth. They never hadit. 2) Those who are truly born again (who are of us) willpersevere to the end in faith. Verse 19: If they had been of us,they would have continued with us. Endurance is not the causeof the new birth. The new birth is the cause of endurance, andendurance is the evidence of new birth. 3) God often makesplain who the false Christians are in the church by their eventualrejection of the truth and the people of God. Verse 19: They129
went out, that it might become plain that they all are not of us.It became plain. So today it often becomes plain who are ofus.You recall that one of the tests of life in 1 John 4:6 was thatthose who truly know God listen to the apostolic teaching. Theylove it, and they cling to it. Whoever knows God listens to us;whoever is not from God does not listen to us. These peoplelistened for a while. The seed of the word sprang up, perhapseven with joy (Luke 8:13), and it looked as though they weretruly born again. But then hard times came and the cares andriches and pleasures of life swept them away, and they showedthat they had never been born again.A Three-Link Chain in 1 John 5:34Now briefly consider 1 John 5:34, and let it set the stage for a fullertreatment in the next chapter. Consider the way these thoughtsfit together. Heres a three-link chain of thought: [Link One]For this is the love of God, that we keep his commandments.And his commandments are not burdensome. [Link Two] Foreveryone who has been born of God overcomes the world. [LinkThree] And this is the victory that has overcome the worldourfaith.Link One: Love for God is expressed in obedience to hiscommandments with a spirit that does not act burdensomely.Verse 3: For this is the love of God, that we keep his commandments. And his commandments are not burdensome. The markof love for God is willing, joyful obedience, not begrudgingobedience.Link Two: The basis of this unbegrudging obedience is thepower of the new birth to overcome the world. Verse 4: For[signifying the basis of what went before!] everyone who has
130
been born of God overcomes the world. Our love for Godobeys him freely and joyfully because in the new birth the spellof the world is broken and it loses its power. When the worldloses its powerful attraction because of the new birth, God andhis holy will become attractive. Not burdensome. How doesthis work?Link Three: This world-defeating power that breaks the spellof sin and makes the will of God beautiful, not burdensome, isour faith. Verse 4: And this is the victory that has overcome theworldour faith.Gospel, New Birth, Faith, and Obedience with JoySo the chain of thought goes like this: The new birth happensas we are brought into contact with the living and abiding word,the gospel. The first effect of this new birth is that we see andreceive God and his Son and his work and his will as supremelybeautiful and valuable. Thats faith. This faith overcomes theworld, that is, it overcomes the enslaving power of the world tobe our supreme treasure.Faith breaks the enslaving spell of the worlds allurement. Inthat way, faith leads us into obedience with freedom and joy.God and his holy will look beautiful and not burdensome. Thenew birth has taken the blinders off. We see things for what theyreally are. We are free to obey with joy.May God confirm your spiritual realityyour new birthby overcoming the seductive power of the world in your life.Everyone who has been born of God overcomes the world. Andthis is the victory that has overcome the worldour faith.
131
11Regeneration, Faith, LoveIn That OrderIn this chapter, we pick up on the very important text, 1 John 5:15,which we began to unpack in the last chapter. There is so muchmore. One of my aims here is to show that our ability to loveothers imperfectly is based on our assurance that in Christ wealready love them perfectly. In other words, I want you to see foryourselves that, even when you fail to love as you ought, Christsperfection stands before God in place of that failure. And I wantyou to see that faith in Christ, not love for people, is the way youenjoy that union with Christ. Therefore, faith must come firstand be the root of love and be different from love. Otherwise,love will be destroyed.If you dont come at love this way, your failures will probablyoverwhelm you with guilt and hopelessness. If that happens,you will give way either to hardworking legalism or fatalisticimmorality.Lets start where we left off at the end of the previous chapter,namely, with the chain of thought in 1 John 5:34. The reason133
desiring him with such ardency and authenticity that his will isour delight and is not burdensome.Which Commandments?Before we go to the next link in the chain of 1 John 5:34, letsbe sure that we know what commandments of God the apostleJohn especially has in mind when he speaks about keeping thecommandments of God as an expression of loving him. Itspretty obvious if we follow the train of thought from 4:20forward. John says in 4:20, If anyone says, I love God, andhates his brother, he is a liar; for he who does not love his brotherwhom he has seen cannot love God whom he has not seen. Andthis commandment we have from him: whoever loves God mustalso love his brother. So it appears that the primary obediencethat John has in mind which would show we love God is lovingothers, especially other believers.He stays on this point in 1 John 5:1: Everyone who loves theFather loves whoever has been born of him. So there it is again:The sign that you love God is that you love others, especiallyother believers. Then verse 2 turns it around and says that lovingGod is the sign that you love his children: By this we know thatwe love the children of God, when we love God and obey hiscommandments. I think the point of this is to guard againstsentimental reinterpretations of what love isreinterpretationsthat leave God and his commandments totally out of account.John is saying: Dont do that. You dont love anybody if youdont love God. You may think you do. But John says in verse 2,By this we know that we love the children of God, when welove God.If you dont love God, you cant do anybody any ultimategood. You can feed them and clothe them and house them andkeep them comfortable while they perish. But in Gods mind,135
that by itself is not what love is. Love does feed and clothe andhouseand keeps the commandments that include helpingothers know and love God in Christ. But if you dont love God,you cant do that. So if you dont love God, you cant love peoplein the way that counts for eternity.So we have our answer: When John says, This is the love ofGod, that we keep his commandments. And his commandmentsare not burdensome, he mainly means the commandmentssummed up in loving other people, especially believers, andloving them in a way that counts forever. So we could paraphraseverse 3 like this: This is the love of God, that we love others,especially his children, and that this life of sacrificial Christ-likelove is not burdensome. Its what we most deeply desire to do asan expression of our love for the Father.The Second Link: The New BirthNow the second link in the chain of thought in 1 John 5:34 isthe first part of verse 4: For everyone who has been born ofGod overcomes the world. Notice the word for at the beginning.John says that he is now going to explain why loving God bydoing his commandmentsthat is, by loving other peopleisnot burdensome. Its not burdensome, he says in verse 4,because everyone who has been born of God overcomes theworld. How is that an argument?We are able to love God and love others because in the newbirth we have conquered the world. Everyone who has beenborn of God conquers the world. This must mean that thereare forces in the world that work to make us not love God andnot love each other. And in the new birth these forces have beenovercome.What would those forces be? Lets go to 1 John 2:1517 for theclearest answer in this letter:136
Here are the forces in the world that have to be overcome (v. 16):the desires of the flesh and the desires of the eyes and pride inpossessions. That could be summed up as desires for what wedont have, and pride in what we do have. When we dont havewhat we want, the world corrupts us with covetousness. Andwhen we do have what we want the world corrupts us with pride.This is what keeps us from loving God and loving each other.We love stuff. And when we dont have it, we crave it. And whenwe do have it, we love to talk about it incessantly, and waste timeon it. And where is God in all that? At best, hes there as thecosmic Sugar Daddy. We may even thank him for all our stuff.But there is a kind of gratitude that proves that the gift, and notthe Giver, is our god.The main reason we dont love God and fi nd it burdensometo love people is that our cravings are for the things of the world.They may be good things. They may be bad things. They maybe material things. They may be relational. Whatever their form,they are not God. And when we crave them above God, they areidols. They replace love for God and love for people. Thats theuniversal problem of the world. Whats the solution?Johns answer is in 1 John 5:34. He says that the reason lovingGod and loving people is not burdensome (v. 3) is that wehave been born again, and this new birth conquers the world:Everyone who has been born of God overcomes the world.Now we can see what that means. It means that the new birth137
severs the root of those cravings for the world. Overcoming theworld means that the desires of the flesh and the desires of theeyes and the pride in possessions dont rule us anymore. Theirpower is broken.The Third Link: Faith in JesusHow does that work? Thats what the last half of verse 4 tellsus (the third link in the chain): And this is the victory thathas overcome the worldour faith. The reason the new birthconquers the desires of the flesh and the desires of the eyes andthe pride in possessions is that it creates faith.The most immediate and decisive work of God in the newbirth is that the new life he creates sees the superior value ofJesus over all else (2 Cor. 4:4, 6). And with no lapse of time atall, this spiritual sight of the superior value of Jesus results inreceiving Jesus as the Treasure that he is. That is faith: receivingJesus for all that he is because our eyes have been opened to seehis truth and beauty and worth.That is why faith conquers the world. The world held us inbondage by the power of its desires. But now our eyes have beenopened by the new birth to see the superior desirability of Jesus.Jesus is better than the desires of the flesh, and better than thedesires of the eyes, and better than the riches that strangle uswith greed and pride (Mark 4:19).The Order: New Birth, Faith, LoveNow we are in a position to answer our original question aboutthe relationship between regeneration, faith in Christ, and lovingpeople. Heres what we can say and why its so important.We can say, first, that regeneration is the cause of faith. Thatsplain in 1 John 5:1: Everyone who believes [that is, has faith] thatJesus is the Christ has been born of God. Having been born of138
141a practice of sinning also practices lawlessness; sin islawlessness. You know that he appeared to take awaysins, and in him there is no sin. No one who abides inhim keeps on sinning; no one who keeps on sinninghas either seen him or known him. Little children, letno one deceive you. Whoever practices righteousnessis righteous, as he is righteous. Whoever makes apractice of sinning is of the devil, for the devil has beensinning from the beginning. The reason the Son of Godappeared was to destroy the works of the devil. No oneborn of God makes a practice of sinning, for Gods seedabides in him, and he cannot keep on sinning becausehe has been born of God. By this it is evident who arethe children of God, and who are the children of thedevil: whoever does not practice righteousness is not ofGod, nor is the one who does not love his brother.
1 John 3:110
12Freedom fromthe Practice of SinningThe question we will tackle in this chapter is: How do people whohave experienced the miracle of the new birth deal with their ownsinfulness as they try to live in the full assurance of their salvation?That is, how do we deal with the conflict between the realityof the new birth, on the one hand, and our ongoing sin, on theother hand? How do we balance the danger of losing assuranceof salvation and the danger of being presumptuous that we areborn again when we may not be? How can we enjoy the assuranceof being born again, and yet not take lightly the sinfulness ofour lives that is so out of step with being born again?God Calls Us to Full AssuranceThe First Epistle of John, more than any other book in the Bible,seems to be designed to help us in this practical, daily battle.Consider 1 John 5:13: I write these things to you who believe inthe name of the Son of God that you may know that you have143
These false teachers disconnected Christ and the flesh. We see thatin verse 2. John insisted on the very thing some were denying:Every spirit that confesses that Jesus Christ has come in the flesh isfrom God. They did not like the idea of the preexistent Christbeing united with human flesh.Bad Christology Yields Bad MoralityHere is the reason thats relevant for our question in this chapter.This view of the person of Christ not being united to physicalflesh evidently had a practical, moral effect on the way these falseteachers viewed the Christian life. Just as they disconnected theperson of Christ from ordinary physical life, so they disconnectedbeing a Christian from ordinary physical life.One of the clearest places to see this is here in our text: 1 John 3:7.John says, Little children, let no one deceive you [so he hasthe false teachers in view]. Whoever practices righteousness isrighteous, as he is righteous. Whats he saying? He is saying.Beware of the false teachers because what they say is that youcan be righteous and not practice righteousness. Let no onedeceive you. Whoever practices righteousness is righteous.In other words, John opposes not only their view of Christ,that they disconnect his person from his ordinary bodily life ofdoing things, but he also opposes their view of the Christian lifewhen they disconnect our person from our ordinary bodily lifeof doing things. The flesh didnt really matter for Jesus, thefalse teachers say. What matters is that somehow, in a spiritual145
physical doing, or else the spiritual being is simply not real. Thatswhat we saw in 1 John 3:7: Little children, let no one deceive you.Whoever practices righteousness is righteous, as he is righteous.The deceivers were saying: You can be righteous and yet not practicerighteousness. John says: The only people who are righteous arethe ones who practice righteousness. Doing confirms being.That is what John says over and over again in this letter. Forexample, in 1 John 2:29, he says, If you know that he is righteous,you may be sure that everyone who practices righteousness hasbeen born of him. In other words, the doing of righteousnessis the evidence and confirmation of being born again.Or consider 1 John 3:9: No one born of God makes a practiceof sinning, for Gods seed abides in him, and he cannot keep onsinning because he has been born of God. The practice of sinis the evidence and confirmation that one is not born of God.Doing confirms being. Not practicing sin is the evidence andconfirmation of being born again.And the reason the new birth inevitably changes the life ofsinning, John says, is that when we are born again, Gods seedabides in us, and we cannot keep on sinning. Thats how realthe connection between the new birth and daily physical life is.The seed here may be the Spirit of God or the word of God orthe nature of Godor all three. Whatever it is specifically, Godhimself is at work in the new birth so powerfully that we cannotkeep on practicing sin. Gods new presence cannot make peacewith a pattern of sinful behavior.These false teachers who think they can separate who theyare spiritually from who they are physically do not understandeither the incarnation or regeneration. In the incarnation, thepreexistent Christ is really united with a physical body. Andin regeneration, the new creation in Christ has real, inevitableeffects on our physical life of obedience.147
148
should pray for that. All wrongdoing is sin, but there is sinthat does not lead to death.Notice that last clause: There is sin that does not lead to death.This is why you can see your brother committing sin. He is yourbrother. He is born again. And he is sinning. How can this be?Because there is sin that does not lead to death. I dont thinkJohn has particular kinds of sins in view, but rather degrees ofrootedness and habitual persistence. There is a point of confirmedsinning which may take you over the line of no return and youwill be like Esau who sought repentance with tears and couldnot find it (Heb. 12:1617). He could not repent. If he could have,there would have been forgiveness. But the heart can become sohardened by sin that even its desires to repent are counterfeit.Dealing with Our Ongoing SinNow we come to the question we raised at the beginning: Howdo people who have experienced the miracle of the new birth dealwith their own sinfulness as they try to live in the full assuranceof their salvation? My answer is: You deal with it by the way youuse Johns teaching. John warns against hypocrisy (claiming tobe born again when your life contradicts it), and John celebratesthe Advocacy and Propitiation of Christ for born-again sinners.The question is: How do you use these two truths? How doyou use the warning that you might deceive yourself? How doyou use the promise, If we do sin, we have an Advocate? Theevidence of your new birth lies in how these two truths functionin your life.Heres the way they function if you are born again:Fleeing Presumption, Flying to the AdvocateOne common scenario for believers is drifting toward sinful presumption. You are slipping into a lukewarm, careless, presumptuous149
150
151
13Loving Others with the Love of GodThe aspect of the new birth we will focus on in this chapteris the fact that the new birth creates the connection betweenGods love for us and our love for each other. If anyone ever asks,How does the fact that God loves you result in your loving others? theanswer is: The new birth creates that connection. The new birthis the act of the Holy Spirit connecting our dead, selfish heartswith Gods living, loving heart so that his life becomes our lifeand his love becomes our love.This is clearly seen in 1 John 4:712. John shows the link intwo ways: First, he shows that Gods nature is love, so that whenwe are born again by him we share that nature; and second, heshows that the manifestation of that nature in history was thesending of his Son so that we might have eternal life throughhim. Lets take these one at a time and notice how they areconnected to the new birth.Gods Nature Is LoveFirst, verses 78: Gods nature is love. Beloved, let us love oneanother, for love is from God, and whoever loves has been born153
of God and knows God. Anyone who does not love does notknow God, because God is love. Notice it says two things.Verse 7 says that love is from God. And verse 8 at the end says,God is love. These are not at odds, because when John says thatlove is from God, he doesnt mean its from him the way lettersare from a mailman, or even from a friend. He means that love isfrom God the way heat is from fire, or the way light is from thesun. Love belongs to Gods nature. Its woven into what he is. Itspart of what it means to be God. The sun gives light because it islight. And fire gives heat because it is heat.So Johns point is that in the new birth, this aspect of thedivine nature becomes part of who you are. The new birth is theimparting to you of divine life, and an indispensable part of thatlife is love. Gods nature is love, and in the new birth that naturebecomes part of who you are.Notice verse 12: No one has ever seen God; if we love oneanother, God abides in us and his love is perfected in us. Whenyou are born again, God himself is imparted to you. He dwellsin you and sheds abroad in your heart his love (Rom. 5:5). Andhis aim is that this love be perfected in you. Notice the phrasehis love in verse 12. The love that you have as a born-againperson is no mere imitation of the divine love. It is an experienceof the divine love and an extension of that love to others.So the first way John links Gods love for us and our love forpeople is by focusing on Gods nature as love and how the newbirth connects us to that.Gods Love Revealed in Sending His SonThen, second, consider 1 John 4:911, where John focuses onthe main manifestation of that divine love in history.In this the love of God was made manifest among us, thatGod sent his only Son into the world, so that we might live154
156
157
He says three things about love here, and they are increasinglyspecific. First, he says that love does practical things for people.Verse 18: Little children, let us not love in word or talk but indeed and in truth. He doesnt mean that talk is not an importantway of loving people. The tongue is full of potential for love andhate. What he does mean is that where deeds of practical helpare called for, dont settle for talk. Do practical things for eachother.Then he tells us something about how seriously we shouldtake this. Verse 16: We ought to lay down our lives for thebrothers. Christ loved us by laying down his life for us. Whenwe were born again, this love became our love. There is in theborn-again person a deep impulse to die to self that others mightlive. The presence of Christ in the born-again person is the presence of a servants heart. A sacrificial spirit. A readiness to godown that others might go up. Love does not want to prosperat the expense of others. Love wants others to prosper, and if itcosts us our life, thats okay. Jesus will take care of us.So the first thing John says is that love is practical and doesgood for others. And the second thing he says is that we will dothis even if it is very costly. He laid down his life for us, and weought to lay down our lives for the brothers.Third, he says that this will mean very practical sacrifices inorder to give people the things they need. Verse 17: If anyonehas the worlds goods and sees his brother in need, yet closeshis heart against him, how does Gods love abide in him? Themain way John has in mind for us to lay down our lives foreach other is that we share what we have. Love doesnt thinkpossessively. Love knows that everything belongs to God. Weare only managers of his possessions. Everything we have is athis disposal. And God is love. And when we were born again, hislove became our love. And now his love governs his possessionsin our hands.160
161
Part FiveHow Can We Help OthersBe Born Again?
163
14Tell Peoplethe Good News of Jesus ChristThe biblical truth that saving faith is possible only because Godcauses unbelievers to be born again (1 John 5:1) may make usfeel empowered and encouraged and bold and hopeful in ourpersonal evangelism, or it may make us feel fatalistic, pointless,unmotivated, and paralyzed in our evangelism. If we feelfatalistic and pointless and unmotivated and paralyzed in ourwitness to unbelievers, our feelings are out of sync with thetruth, and we should ask the Lord to change our feelings.This is the way I live my life every dayseeking to bring myvagrant feelings into line with ultimate reality. My feelings arenot God. God is God. My feelings do not define truth. Godsword defines truth. My feelings are echoes and responses towhat my mind perceives. And sometimesmany timesmyfeelings are out of sync with the truth. When that happensandit happens every day in some measureI try not to bend thetruth to justify my imperfect feelings, but rather, I plead with
165
166
flourish for a moment and give joy that lasts for a moment. Thenthey are gone, and the life they sustained is gone. But the wordof God is not like that. The life it creates lasts forever because thelife-creating and life-sustaining word lasts forever.Then Peter tells us exactly what he is referring to with thisphrase the word of God. He says in the last part of verse 25,And this word is the good news that was preached to you. Thegood news preached to youthats the imperishable seed; thatsthe living and abiding word of God through which you wereborn again. So the way God brings about the new birth in dead,unbelieving hearts is by the gospel, the good news.The Greatest News in the WorldAnd the news is this: Christ, the Son of God, died in our placebecame our substituteto pay the price for all our sins, andto accomplish perfect righteousness, and to endure and removeall of Gods wrath, and rise from the dead triumphant overdeath for our eternal life and joy in his presenceand all of thisoffered freely through faith alone in Jesus Christ alone. Thatsthe good news. To this day, two thousand years later, it remainsthe greatest news in the world. And there are millions (near andfar) who do not know this news.So heres the pointand it is immensely important if thereis anyone you love (or any thousands you love) and want to seeborn again to a living hope: If people are to be born again, itwill happen by hearing the word of God, centered in the gospelof Jesus Christ. They will be born again through the living andabiding word of Godthe gospel. Gods work and your workcome together like this: God causes the new birth through the seed of the word, thegospel.169
God brings about the new birth through your telling peoplethe gospel. God regenerates people through the news about who Christis and what he has done on the cross and in the resurrection. God gives new life to dead hearts through your words whenyou speak the gospel.Giving Life with the GospelSo, going back to our original question: What should we be doingto help unbelievers be born again? Answer: Tell people the good newsof Christ from a heart of love and from a life of service. Well saymore about the heart of love and the life of service later. Butfocus here for a moment on this amazing fact: The seed thatsaves is the word of Godthe gospel preached. The seed thatcreates new life is the gospel in the mouths of believers, spokento unbelievers. The surgical instrument that opens the eyes ofthe blind is your words telling and explaining the gospel.How can this become for us not just a conviction but a passion?I pray that God will use his own word in this chapter to wakenthis passion. So consider more of his word. James 1:18: Of hisown will he brought us forth by the word of truth. There it is inthe words of James, the Lords brother: by the word of truth.That was how he brought us forth. And this reference is to thenew birth.In 1 Peter 2:9, just nine verses later than our text in 1:2325(born again through the living and abiding word, the gospel),Peter says, You are a chosen race, a royal priesthood, a holynation, a people for his own possession, that you may proclaimthe excellencies of him who called you out of darkness into hismarvelous light.God brought you out of darkness and into his marvelouslight by the word of God, the gospel (1:23, 25). And now in this170
marvelous light what are we to do? Why are we here? One utterlycrucial reason while this age remains: that you may proclaimthe excellencies of him who called you out of darkness into hismarvelous light. We are in the marvelous light of the love andpower and wisdom of Christ so that our joy in that marvelouslight might be filled up through proclaiming the excellencies ofChrist.Why? Because thats how others will be born againby hearing this good news. And when they are born again, they movefrom darkness to marvelous light and see Christ for who he is,and treasure him for who he is, and therefore magnify him forwho he is. And our joy is completed in their joy in him.What Will It Take Today?What will it take so that thousands of Christians in our churchesbecome passionate about telling the gospel to unbelievers? Oneof the reasons we dont do it as much as we should is that life inAmerica is so entertaining that thoughts about desperate, eternal,spiritual need are hard for us to feel, let alone talk about. Theworld is just too interesting and entertaining. It feels awkwardto make ourselves or others uncomfortable with thoughts aboutperishing people. Its heavy. But life in America is light.So perhaps what God will choose to do is what he did for thechurch in Jerusalem. They were not moving out from Jerusalemto Judea, Samaria, and the uttermost parts of the world inevangelism the way Jesus told them to in Acts 1:8. So Stephenwas raised up to bear such irresistible testimony (Acts 6:10) thatthe only way his adversaries could handle him was to kill him(Acts 7:60).And when they did, the persecution spilled over onto all theChristians in Jerusalem. And there arose on that day a greatpersecution against the church in Jerusalem, and they were all171
174
15I Am Sending Youto Open Their EyesWere ending this book on the ground. On the street. In thecar. At Starbucks. In the back yard. In school. At work. Overlunch. On the phone. On Facebook and MySpace. And textmessaging. And Skyping. And blogging. And airplanes. Anda hundred ordinary conversations. Were ending with personalevangelisman old-fashioned commitment in new contexts forthe sake of the new birth in thousands of spiritually dead peoplefor the glory of Jesus Christ.We have affirmed repeatedly the biblical truth of 1 Peter 1:23,You have been born againthrough the living and abiding wordof Godfollowed by the explanation in verse 25: This word isthe good news that was preached to you. In other words, Godbrings about the new birth through the gospelthe good newsthat God sent his Son into the world to live a perfect life, die forsinners, absorb the wrath of God, take away our guilt, providethe gift of righteousness, and give eternal joy in Christ throughfaith alone apart from works of the law.
177
People are born again through hearing that news, and neverborn again without it. Faith comes from hearing, and hearingthrough the word of Christ (Rom. 10:17). So when we asked,What should we do to help people be born again? the biblical answerwas plain: Tell people the good news from a heart of love and alife of service.In this final chapter, the aim is to underline that main pointwith a couple of new texts and then give some encouragementsand practical helps.God Makes Light Shine in Our Hearts2 Corinthians 4:4 pinpoints the condition people are in withoutChrist. Verse 4: In their case the god of this world has blindedthe minds of the unbelievers, to keep them from seeing thelight of the gospel of the glory of Christ, who is the image ofGod. People who dont believe in Christ are blind. They cantsee Christ as supremely valuable, and so they wont receive himas their Treasure and so they are not saved. A work of God isneeded in their lives to open their eyes and give them life so theycan see and receive Christ as Savior and Lord and Treasure oftheir lives. That work of God is called the new birth.Then look at the solution to this condition of blindness andperishing. Verse 6: For God, who said, Let light shine outof darkness, has shone in our hearts to give the light of theknowledge of the glory of God in the face of Jesus Christ.This is a description of the new birth, even though that termis not used. The God who created light in the beginning doesthe same thing in the human heart. Only this time, the light isnot physical light, but the light of the knowledge of the gloryof God in the face of Christ. Or as verse 4 calls it: the light ofthe gospel of the glory of Christ, who is the image of God.178
He causes the human heart to see the truth and beauty andworth of Christthe glory of Christ. And when we see himfor who he really is, we receive him for who he is. And to asmany as received him, he gave power to become the children ofGod (John 1:12). Thats what we want for our childrenat sixor sixteen or twenty-sixand for our parents and our spousesand our neighbors and colleagues and our friends at school. Wewant the light to shine in their hearts so they see and receiveChrist. We want them to be born again.God Sends You to Open Their EyesLook at the human means God uses to make this happen.2 Corinthians 4:5: What we proclaim is not ourselves, butJesus Christ as Lord, with ourselves as your servants for Jesussake. Pauls role was to proclaim Christ from a heart of loveand a life of service. That proclamation is called the gospel inverse 3: Even if our gospel is veiled, it is veiled only to thosewho are perishing. Its the gospel that spiritually blind peoplecant see and spiritually deaf people cant hear. So our answerto the question What should we do to help people be born again? is:Tell them the good news of Christ from a heart of love and a lifeof service.Here is an astonishing picture of human agency in the newbirth. In Acts 26, Paul is telling King Agrippa about his conversion and his call to the ministry. He reports the spectacularencounter with Christ on the Damascus Road. Then he reportsthe commission that Christ gave him. The words of the commission are amazing. Paul says that Jesus told him;I am Jesus whom you are persecuting. But rise and standupon your feet, for I have appeared to you for this purpose,to appoint you as a servant and witness to the things in
179
180
meals. So dont let the fact that you cant cause the new birthstop you from telling the gospel. That is how people are bornagainthrough the living and abiding word, the good news ofJesus Christ.Ten Encouragements for Gospel-TellingSo here are a few encouragements that I hope will help you.1. Know This: God Uses Clay PotsBack to the context of 2 Corinthians 4:46. The next verse iscrucial. We dont usually read it in context. Verse 6 has just saidthat the God who created light in the universe does the same kindof thing in the hearts of blind sinners like us. He gives the light ofthe knowledge of the glory of God in the face of Christ. In verse 4,this light is called the light of the gospel of the glory of Christ.Thats the context. Now heres verse 7: But we have thistreasure in jars of clay, to show that the surpassing power belongsto God and not to us. We have this treasure. What treasure?The knowledge of the glory of God in the face of Christ. Or,the light of the gospel of the glory of Christ. In short: We havethe gospel with its light-giving power.Now the encouragement is this: We have this treasure injars of clay. Jars of clay is a reference to us. We are the jars ofclay. Compared to the treasure that is in us, we are clay. Weare not gold. The gospel is gold. We are not silver. The newsabout Christ is silver. We are not bronze. The power of Christis bronze.This means that if you feel average or below average in yourfitness to share the gospel treasure, you are closer to the truththan someone who feels powerful and wise and self-sufficient.Paul wants us to realize that we are clay pots. Not gold or silver
181
or bronze. He wants us to realize that from the most sophisticated to the most average, we are all clay pots when it comesto containing and sharing the gospel. It is so valuable and sopowerful that any thought of its container being somethingcomparable is foolish.How does Paul talk about himself and Apollos, two of themost fruitful Christians in the first century? What then isApollos? What is Paul? Servants through whom you believed, asthe Lord assigned to each. I planted, Apollos watered, but Godgave the growth. So neither he who plants nor he who waters isanything, but only God who gives the growth (1 Cor. 3:57).Whats the point of being a clay pot? Back to 2 Corinthians 4:7:We have this treasure in jars of clay, to show that the surpassingpower belongs to God and not to us. Gods aim is that hisown power through the gospel, not ours, be exalted. Whichmeans that if you feel average or less than average in your senseof fitness to tell the gospel, you are the person God is lookingfora clay pot, who simply shares the treasure of the gospel,not the glitzy intellect, not the glitzy eloquence, not the glitzybeauty or strength or cultural cleverness. Then God will do hiswork through the gospel, and the surpassing power will belongto him and not to us.Be encouraged, ordinary Christian. You are appointed, preciselyin your ordinariness, for the greatest work in the world: openingthe eyes of the blind and showing the Treasure of Christ.2. Get Resources to ShareGiving away good Christian literature is one way of extendingyour personal witness about the gospel. At try to make evangelistic booklets available as inexpensively as
182
possible or for whatever price you can afford.23 There are dozensof other very useful materials available.The point is: Think this way. Think: Wherever I can, I wantto commend Christ. I want to tell the story that God uses togive people life. Put something in your pocket, your purse,your briefcase, your car. And pray every day, Lord, make me aninstrument of gospel-spreading today. Use me to open the eyesof the blind.3. Know that God May Use Many InfluencesKeep in mind that what you say to someone about Jesus may besupplemented by a half dozen others that God is providentiallylining up to speak to this person as God pursues him forsalvation. You may feel your word was wasted. It is never wasted(1 Cor. 15:58). Your word may be the beginning of the influences.Or it may be the fi nal, decisive word that God uses to bringa person to faith. Speak your word. The smallest word aboutChrist is not wasted.A young woman told the story as she was joining our churchof how Christ saved her. She said that she knew a good bitabout Christianity because of her parents but had thrown it allaway as a teenager and was on her own. One day she and herfriends were walking down the beach as several handsome guysapproached. Her thought was to impress them and be thoughtattractive and cool. As the guys passed, one of them called out,Praise Jesus!Now probably later that night those guys said to themselves,That was a lame witness. Why didnt we stop and talk? Littledid they know that this simple word, Praise Jesus, pierced her23 Two examples would be the booklet For Your Joy and the tract The Quest for Joy.
183
heart and sent her later to her knees and to the Savior. There areno wasted testimonies.4. Be a Lavish GiverBe known as a generous person, not a stingy person. Jesus said,Lend, expecting nothing in return (Luke 6:35). I mean this ingeneral about all that you own. Stingy people make Jesus lookunimportant and unsatisfying. But more specifically I mean: Belavish in your giving of good booksif you know unbelieverswho are readers. Give a Christian book that cost you ten orfifteen or thirty dollars. Offer it as a gift and tell them what itmeant to you and that you would love to talk about it some time.If you dont know the person, ask for their permission to givethem a book that meant a lot to you.This is what I regularly do on the plane. Sometimes conversations are easy to get into about Christ because I am a pastor.Other times theyre not. But in either case, I often say, I wrotea book that I would love to give to you. May I give you one?People almost never say no. I put different books in my briefcaseto give away. The most common ones are Seeing and SavoringJesus Christ, Fifty Reasons Why Jesus Came to Die, Desiring God,and When the Darkness Will Not Lift. I also keep some of thesein the drawer by our front door at home in case there is anopportunity to give one to someone at the door. Choose a fewshort books that you have read that have helped your faith, andkeep a stash of them in key places. Develop the habit of thinkingthis way: How can I commend Christ today? Be lavish in yourgiving.And, of course, give away the Bible. I happened to open abiography of the missionary Henry Martyn recently and readthis about the author, B. V. Henry: Henry came to personalfaith in Christ at the age of 17 through reading a New Testament
184
Yet, most of us dont think this way. The gods bore us, and wereturn to our video games. Very few people are interested inothers. If you really fi nd their story interesting, and care aboutthem, they may open up to you and want to hear your storyChrists story.24 B. V. Henry, Forsaking All for Christ: A Biography of Henry Martyn (London:Chapter Two, 2003), 167.25 You can buy the entire Bible in the English Standard Version at Desiring Godfor under $4.00. C. S. Lewis, The Weight of Glory (Grand Rapids, MI: Eerdmans, 1949), 1415.
185
speak to others about Christ (1 Pet. 2:9), but some have a gift ofprophecy and exhortation and teaching (Rom. 12:7).The point is: We are all in this together, but some are gifted oneway and some another. Find where you fit, and stoke the flamesof your effectiveness there. Grow in every area, but dont paralyzeyourself because you are not like someone else. God made youand means to use youthe unique youin evangelism.9. Read Books on EvangelismHere are two older books and one newer one: Will MetzgersTell the Truth; J. I. Packers Evangelism and the Sovereignty of God;and Mark Devers The Gospel and Personal Evangelism.27 Thereare, of course, dozens of books worthy of your attention. Mypoint is simply to encourage you to think this wayto includein your mindset the desire to be instructed and inspired by whatothers have written on personal evangelism.10. Pray for BoldnessIt is remarkable to notice that most of the prayers relating toevangelism in the New Testament relate to prayers for the gospeltellers, not the gospel-hearers. Romans 10:1 is an exception tothat: Brothers, my hearts desire and prayer to God for them isthat they may be saved. But mostly we read things like Pray forus, that the word of the Lord may speed ahead and be honored(2 Thess. 3:1). Pray also for us, that God may open to us a doorfor the word, to declare the mystery of Christ (Col. 4:3). Keepalert with all perseverance, making supplication forme, that27 Metzger, Tell the Truth: Whole Gospel to the Whole Person by the Whole People,third ed. (Downers Grove, IL: InterVarsity Press, 202, orgi 1981); Packer,Evangelism and the Sovereignty of God (Downers Grove, IL: InterVarsity Press,2009, orig. 1961); Dever, The Gospel and Personal Evangelism (Wheaton, IL:Crossway Books, 2007).
187
188
ConclusionThe New Birthand the New WorldJesus words You must be born again (John 3:7) go to theheart of the worlds problems. There will be no final peace, nofinal justice, no triumph over hate and selfishness and racismwithout this profound change in human nature.All other diagnoses and remedies are superficial. They mayeven be valuablelike laws that restrain people from doing theirworst. But without the new birth, people are not changed at theroot, and that is where the problem lies. If human beings arenot changed at the root, then our innate selfishness will spoilevery dream.Jesus remedy fits the depths of our disorder. If we only didbad things because of bad circumstances, then there mightbe hope that changing the circumstances would change ourbehavior. But our problem is not simply that we do bad thingslike slandering others, and cheating in private, and neglecting
192
Scripture IndexPsalms19:12 .................... 4640:8 ....................13451:5 ....................... 49119:24 ..................134119:35 ...................134119:92 ..................134143:2 ................... 190Isaiah40:6-8 ................ 16865:17 ..................... 8866:22 .................... 88Jeremiah17:9 ............... 46, 19031:31-34 ................. 3933:8 ....................... 41Ezekiel16:4-8 ...................4836:24-28 .......... 39-4236:25-27 ........... 91-9236:26 ..........19, 50, 56Matthew1:18 .......................661:20 ......................664:4 ...................... 173
5:16 ....................... 217:11 ..................... 1907:16-17 ................ 1908:11-12 ..................10110:29-30 ............... 9312:34 .............190, 19116:26.......................219:28 ..................... 8822:37 ..................... 5823:15 ..................25-2623:25 .................... 19123:27 .................... 19123:33 .................25-2625:41 ..................... 6125:46 ...................101Mark1:24 ......................304:19 ..................... 1387:13 ..................... 16810:45 ..................... 82Luke2:52 .......................666:35 ..................... 1846:36 .....................1868:13 ......................1309:60 .....................2910:16 ..................... 72
15:24 .....................2922:20 .................... 39John1:1 ............111, 115, 1681:1-14 ...................1101:11-13 ............. 60, 1161:12 .......... 42, 62, 1791:12-13 ............ 111, 1181:13 ...................... 1171:14 ......... 74, 116, 1681:14-16 .................. 713 ........................... 913:1-3 ...................... 283:1-10 ..............24, 343:2 ........................303:3 .. 20, 21, 25, 29, 33,......35, 46, 60, 61, 62,.... 77, 78, 90, 101, 1923:5 ......... 31, 33, 37, 47,................. 51, 91, 1043:6 ........31, 36, 41, 1173:7 .... 2, 9, 20, 22, 29,.... 35, 46, 62, 189, 1903:7-8 .......................73:8 ...... 9, 31, 33, 38-393:10....................... 393:15 ....................... 383:16 ....................... 38
193
Scripture IndexJohn (cont.)3:18 ....................... 383:19-20............. 50, 563:36.............25, 33, 694:20 .................... 1355:23 ....................... 725:24 ....................1445:40 .................... 1926:35 ....................... 326:37 ................. 19, 526:44 ........19, 52-53,566:51 ....................... 716:63 ....... 31, 33, 36-37,...................... 47, 92,6:65 ............. 52-53, 5610:28.....................4811:43 ......... 68, 79, 8414:6 ......32, 36, 92, 19214:15.....................13415:1-17.................... 3217:3 .......................6218:24....................10120:31 ........... 32, 33, 37
1:26 ...................... 821:28 ....................... 825:1 ......................... 615:5 ........................1546:6 ....................... 406:11 ...................... 406:17 ...................56-576:20-21 ................. 616:23 ...................... 617:4-6 .................... 617:18 ................... 58-598:1 ........................ 618:3 .................. 82, 1558:7-8 .................51, 568:9 .........................518:15 ....................... 198:20-23 ............ 88-898:23.......................898:28 ...................... 858:29 .................... 1468:30 ...................... 198:33-34 ................1409:6...................... 16810:1 ......................18710:17 ......106, 114, 17812:7 ............... 186, 18712:8 ......................18613:13-14 ..................1115:16 ...................... 61
Acts1:8 ....................... 1712:41 .....................1724:31......................1885:28 ......................1865:31 ...................... 1196:10 ..................... 1717:60 ..................... 1718:1 ................. 171-1728:4 .......................1728:4-5 ....................17213:48 .................... 11915 ........................ 10715:9 ..................... 10716:14 ...............19, 11916:31 ............ 103, 10718:27 .................... 11926:15-18 ......... 179-18026:18 ................... 180
1 Corinthians1:2 ........................ 611:21 ......................1861:22-24 ............ 84-852:14 ............. 51-52, 563:5-7 .....................18212:3 .................. 52, 5613:12 ...................... 1715:1-2 ....................10315:1-5 .................... 11315:2 ...................... 11315:11 ............... 113-11415:58 ..................... 183
Romans1:16 ...................... 1191:18 ....................... 501:21 ....................... 821:24 ...................... 82
2 Corinthians4......................... 1804:1-7 ....................1764:3 .......................1794:4 .......... 27, 138, 178
194
Finally Alive2 Thessalonians1:8 ...................... 1042:13 ....................... 613:1 ........................1871 Timothy1:5 ....................... 1041:14 ...................... 602 Timothy1:3 ........................ 602:24-26 ............. 57-582:25-26 ................. 119Titus3 .......................... 903:1-8 ......................863:3 ....................... 903:3-5 ...................... 913:4 .................. 90, 933:4-5 ...........91, 92-933:4-6................93-943:5 ........ 87, 89, 91-92,................94-96, 1043:7 ....................... 90Hebrews4:15 .......................6611:3 ..................... 16812:16-17 ............... 149James1:18 ........ 114, 119, 1701 Peter1:2 ........................ 611:3 ....................26, 811:3-4 ...........80, 82-831:3-25 ...............79-801:13-25 ............. 76, 981:14-15 ................... 831:18 ....................... 811:18-19 ............. 80, 821:22 ............... 107, 1171:22-2:3 ............... 1641:22-23 ..... 102-108, 1161:22-25 .......... 167-169
195
Persons Index
ever, Mark..........................187Dyson, Hugo ............................11
197
Subject Index
Baptism...................... 3840, 96
Calling,
199
Subject index
200
am my problem .................... 49Imperishability ................... 8081Incarnation . 6566, 7074, 8283,.................94, 146147, 156Institutes of the Christian Religion ..45
..................................... 111mantra........... 111112, 114116, 119Marriage ....................... 13, 58, 191Means, God-appointed, for new birth................ 1718, 2122, 179Mercy of God ... 22, 2627, 44, 47,......53, 55, 67, 74, 78, 80, 82,.... 8687, 89, 9193, 9596,..........107, 150, 176, 186, 188Miracle ..... 10, 12, 18, 22, 30, 47, 55,......58, 78, 112, 114, 143, 149Monica, mother of Augustine ... 10Moral cannot ........................ 52MySpace ................................. 177
201
Subject index3 reasons Jesus teaching is unsettling ........................ 2627and the new world........ 189192effects of ........................121161happens to us, not by us ..18, 26,.................................27, 77how can we help others . 163188being sent to open their eyes,.............................. 177188tell people the good news ofJesus....................... 165174how does the new birth comeabout?.......................... 75119from Gods side............7996our involvement .........101108how the born again love .157161humbly rejoicing in the goodness of others ..........158159meeting others needs, even atgreat cost................ 159161much about it in the Bible ..... 17our condition apart from new birth......................................4862dead in trespasses and sins............................... 4849by nature children of wrath..................................... 49love darkness and hate light ...50hearts hard like stone ..........50unable to submit to or pleaseGod ................................ 51unable to accept the gospel.................................. 5152unable to come to Christ orembrace him as Lord .. 5253slaves to sin ....................56 57slaves of Satan ................ 5758no good thing dwells in us.................................. 5859our involvement in .. 78, 101108radically changes people .........15term born again . 12, 13, 14, 16, 17through the word of God ...... 18
202
Finally AliveRegeneration, see New birthRelevance ......................... 99100Repentance............. 5758, 149, 158Resurrection see Jesus
203
One Thing:Developing a passion for the beauty of GodSam StormsThe goal of our creation was not simply that we might be happy,but happy in appreciating Gods own glory. We were made toglorify God and enjoy him forever. Nothing is more importantthan understanding this truth. This inspiring work helps ussee that beauty has the power to convince the inquiring mindof truth. The souls contact with Gods beauty elicits love andforges in us a new affection that no earthly power can overcome.Enjoying God in the revelation of his beauty is the solution toour struggle with sin, the catalyst for substantive and lastingchange and is the souls satisfaction, with which no rival pleasurecan hope to compete.So what is it about God that when known, seen and experiencedempowers the human soul to feel sickened in the presence of sinand satisfied in the divine embrace? That word again: Beauty.Apatheism affects not just those outside the church but thoseinside the church who cant be bothered with their own religionlet alone someone elses.The more I ponder the source and ground of all our lasting joy,the more convinced I become that Sam Storms is right. Its theBeauty of God. In all his gifts we are to see him. Especially inthe gospel. Let Sam Storms guide you biblically and wakenyour heart to the Treasure of Christ who is the image of theBeauty of God.
John PiperSam Storms is Pastor of Bridgeway Church, Oklahoma City,Oklahoma and founder of Enjoying God Ministries.ISBN 978-1-85792-952-2
If you would like to further explore the vision of God and lifepresented in this book, we at Desiring God would love to serveyou. We have hundreds of resources to help you grow in yourpassion for Jesus Christ and help you spread that passion toothers. At our website, desiringGod.org, youll find almost every-thing John Piper has written and preached, including morethan thirty books. Weve made over twenty-five years of his sermons available free online for you to read, listen to, download,and in some cases watch.In addition, you can access hundreds of articles, find out whereJohn Piper is speaking, learn about our conferences, dis-cover ourGod-centered childrens curricula, and browse our online store.John Piper receives no royalties from the books he writes and nocompensation from Desiring God. The funds are all reinvestedinto our gospel-spreading efforts. Desiring God also has a whatever-you-can-afford policy, designed for individuals with limiteddiscretionary funds. If youd like more information about thispolicy, please contact us at the address or phone number below.We exist to help you treasure Jesus Christ and his gospel aboveall things because he is most glorified in you when you are mostsatisfied in him. Let us know how we can serve you!
Desiring GodPost Office Box 2901Minneapolis, Minnesota 55402888.346.4700 mail@desiringGod.org
STAYING FAITHFULIn dependence upon God we seek to help make His infallibleWord, the Bible, relevant. Our aim is to ensure that the LordJesus Christ is presented as the only hope to obtain forgivenessof sin, live a useful life and look forward to heaven with Him.REACHING OUTChrists last command requires us to reach out to our world withHis gospel. We seek to help fulfil that by publishing books thatpoint people towards Jesus and help them develop a Christ-likematurity. We aim to equip all levels of readers for life, work,ministry and mission.Books in our adult range are published in three imprints.Christian Focus contains popular works including biographies, commentaries, basic doctrine and Christian living.Our childrens books are also published in this imprint.Mentor focuses on books written at a level suitable for BibleCollege and seminary students, pastors, and other seriousreaders. The imprint includes commentaries, doctrinal studies, examination of current issues and church history.Christian Heritage contains classic writings from the past.Christian Focus Publications LtdGeanies House, Fearn, Ross-shire,IV20 1TW, Scotland, United Kingdominfo@christianfocus.com
Mult mai mult decât documente.
Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori.Anulați oricând. | https://ro.scribd.com/document/315057686/Buku-Finally-Alive-John-Piper | CC-MAIN-2020-10 | refinedweb | 23,895 | 72.56 |
Library code snippets
Dynamic thumbnail images from ASP.NET
I have had this sampe code of dynamic thumbnail generation kicking around for some time, so I've finally gotten the time to post it here.. This really shows how cool (and useful, of course)
IHttpHandler is. Here's the gist of the implementation:
public class ImageHandler : IHttpHandler
{
// the max size of the Thumbnail
const int MaxDim = 120;
public void ProcessRequest(HttpContext ctx)
{
// let's cache this for 1 day
ctx.Response.ContentType = "image/jpeg";
ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
ctx.Response.Cache.SetExpires(DateTime.Now.AddDays(1));
// find the directory where we're storing the images
string imageDir = ConfigurationSettings.AppSettings["imageDir"];
imageDir = Path.Combine(
ctx.Request.PhysicalApplicationPath, imageDir);
// find the image that was requested
string file = ctx.Request.QueryString["File"];
file = Path.Combine(imageDir, file);
// load it up
using (Image img = new Bitmap(file))
{
// do some math to resize the image
// note: i know very little about image resizing,
// but this just seemed to work under v1.1. I think
// under v2.0 the images look incorrect.
// *note to self* fix this for v2.0
int h = img.Height;
int w = img.Width;
int b = h > w ? h : w;
double per = (b > MaxDim) ? (MaxDim * 1.0) / b : 1.0;
h = (int)(h * per);
w = (int)(w * per);
// create the thumbnail image
using (Image img2 =
img.GetThumbnailImage(w, h,
new Image.GetThumbnailImageAbort(Abort),
IntPtr.Zero))
{
// emit it to the response strea,
img2.Save(ctx.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public bool IsReusable
{
get { return true; }
}
private bool Abort()
{
return false;
}
}
This was originally published on Brock Allen's Blog.
If you call the GetThumbnailImage() method, as stated in the documentation, it will return the thumbnail image EMBEDDED IN THE IMAGE resized to the size you requested.
In many cases, this isn't what you want. For example, let's say I take a photo from my Minolta 7D, it is 2000x3006 pixels, with an 100x150 embedded thumbnail.
I now request a "thumbnail" image that is 400x600. It will take the 100x150 image and blow it up to be 400x600. It will not take the large image and scale it.
To do that, you need to create another image, and draw the large image on to it and save the new image.
The only case where this will work is if the image you want is smaller than the one that is embedded, or if there is no embedded image. If you are using this generically, then you need to consider someone uploading a 2K x 3K image with a 16x16 embedded thumbnail.. Not pretty when you blow it up to 100x150 or whatever.
If you want to confirm this problem, just blow up an image to the original size using this method. Depending on the make of the camera you used to get the image, it will either look good or look like crud.
Chert
We have verified that its use crashes asp.net worker processes.
Wow, unbeatable!
-
That's what I needed for my photo gallery! Thanks a lot guys.
Take a look at their beta version ... *I-Load 1.5 Beta *
The easiest way to upload and resize an image to the internet is I-Load.
This component also create an unlimited number of thumbnails from the original image with the required size.
I-Load is a FREE ASP.NET web control with numerous benefits and features.
You can download I-Load (it's FREE!) and view an online demo here:
This thread is for discussions of Dynamic thumbnail images from ASP.NET. | http://www.developerfusion.com/code/4688/dynamic-thumbnail-images-from-aspnet/ | crawl-002 | refinedweb | 597 | 67.96 |
The blog of the F# team at Microsoft:
GET --> the JSON value ["value1","value2"]
GET --> the JSON value 5
POST --> does nothing by default, but you can adjust to write to a backend service
PUT --> again, does nothing by default, but you can adjust to write to a backend service
DELETE --> again, does nothing by default, but you can adjust to write to a backend service
To start, create a New Project in Visual Studio 2012 and choose the Online section of the New Project dialog, as shown below.
Next, choose the "F# C# MVC 4" template. For me, this is the first template on the list.
Give the solution project a name, then create the solution. This will download and install the project template. Accept the MS-PL license conditions, and then choose the "WebAPI" project kind. If desired, include a project for tests.
Your solution will have three projects:
The first, "...WebApi" is a standard C# Web site project to act as a service API host for your service code (which is written in F#). You can apply all standard C# ASP.NET Web API programming techniques here.
The second, "...WebAppApi" is your F# implementation of your Web API.
The third, "...WebAppTests" contains tests for your Web API.
You can now run your solution by hitting F5, deploying to localhost. This starts the C# Web site project:
You can now use HTTP requests directly to access the data returned by the Web API. For example, try accessing directly from your browser
This will give a download of either JSON or XML text. If JSON it will contain the data:
["value1","value2"]
This data is derived from the F# code for implementing the "ValueController" controller which governs everything returned by and any subordinate requests such as. These permissible HTTP requests form the WebAPI you have implemented.
The F# code that implements the various HTTP actions is in ValueController.fs and is as follows:
namespace FsWeb.Controllers open System.Webopen System.Web.Mvcopen System.Net.Httpopen System.Web.Http type ValuesController() = inherit ApiController() // GET /api/values member x.Get() = [| "value1"; "value2" |] |> Array.toSeq
// GET /api/values/5 member x.Get (id:int) = "value"
// PUT /api/values/5 member x.Put (id:int) ([<FromBody>] value:string) = ()
// DELETE /api/values/5 member x.Delete (id:int) = ()
This F# type has a specific form that is expected by the ASP.NET Web API. The mappinng is somewhat obvious: the Get methods implement the HTTP GET actions, the GET method with a parameter implements the api request .../values/5 where an integer parameter is given, and so forth. In the case of Get(), the return values are presented as a sequence (IEnumerable) of strings, which is automatically marshalled to XML or JSON.
This shows how simple it is to get started with an HTTP Web API implementation in F#. The start page for the ASP.NET application you have created gives further links to documentation on the ASP.NET Web API which you can use to get started with writing more detailed controllers. Most the documentation will be in C#, but it is simple to translate the documentation on controllers into F#.
If you're interested in contributing to more samples of using ASP.NET and F# together, the F# MVP Ryan Riley is working on a Web API Koans project, and working on porting the ASP.NET MVC4 samples (see and ). One place to discuss things with Ryan is on the email lists of the FSharpx project.
There are endless possibilities for what you can do from here such as
Thanks to Dan Mohl for this great template.
Enjoy!
The F# Team
I think that it would be really neat to see a full F# Razor implementation so that ASP.NET MVC projects might be entirely handled in F#. FsRazor (on GitHub, IIRC) seemed an interesting start but it lacks the "compiler smarts" to feel like a first class implementation of F# in the Razor template language, and it hasn't been updated to F# 3.0 last I checked. | http://blogs.msdn.com/b/fsharpteam/archive/2012/09/04/exploring-the-online-templates-creating-a-web-api-with-f-and-asp-net.aspx | CC-MAIN-2014-15 | refinedweb | 677 | 65.52 |
It shouldn't be that difficult to build a standalone Weblogic WS-Security enabled client for invoking JAX Web Services, but the reality is that it is. Let's find out why.
JAX-RPC Using a Stand-Alone Client JAR File When Invoking Web Services.Processing SOAP messagesUsing client-side SOAP message handlersUsing MTOMInvoking JAX-RPC Web servicesUsing SSL
The stand-alone client JAR file does not, however, support invoking Web services
that use the following advanced features:
Web services reliable SOAP messagingMessage-level security (WS-Security)ConversationsAsynchronous request-responseBufferingJMS transport
JAX-WSYou can invoke a Web service from any Java SE or Java EE application running on WebLogic Server (with access to the WebLogic Server classpath). Support for stand-alone Java applications that are running in an environment where WebLogic Server libraries are not available is not available in this release of JAX-WS.
Furthermore :
Learn how to create the wlfullclient.jar using the WebLogic JarBuilder tool along with cryptoj.jar with client applications. The wlfullclient.jar and cryptoj.jar must be kept in the same directory as the wlfullcient.jar references cryptoj.jar in its manifest Class-Path.Add the wlfullclient.jar to the client application's classpath.
What is recurring in the above passages is 'classpath' and the need for the Weblogic Server libraries to be available to it.Thing is I don't want to go through setting up a WebLogic instance just to get to those libraries, or build a client that depends on the classpath as well as the machine's or host OS's intricacies.Furthermore, any setup would have to be multiplied by 10, the number of machines looking to access the same web service.
In any case my Java client should always call into a Weblogic, well, 'client' library in order to consume the necessary functionality.Turns out that choosing the appropriate one is convoluted:
Do I need wlfullclient.jar, wlthint3client.jar, wlclient.jar, wljmsclient.jar, wlclient.jar, or maybe wlsafclient.jar? Also, don't forget wljmsclient.jar, wljmxclient.jar and wseeclient.jar.Spoiler alert, the one I used was wlsafclient.jar.
Terminology is not of much help either.You see, the manuals use the term 'standalone client' in a vague way, as in the JAX-RPC section we saw earlier, with The stand-alone client JAR file does not, however, support invoking Web services that use the following advanced features.But what is meant by that;is it referring to the 'standalone' Java 'client' I'm looking to build? Turns out that by 'client' is meant the jar that my Java client should call into in order to invoke the web service.In JAX-RPC's occasion this is wseeclient.jar.
But from now on and for the purposes of this article, 'client' will always mean 'my Java client' in either source or packaged form.
What prompted this quest was being handed a copy of a program's source, aka the 'client', that invokes a message level WS-Security Weblogic powered web service.This client software is expected to be receiving HL7 messages from another application and forward them to the Weblogic (JAX-WS) service.This setup then had to be replicated across 10 CentOS Linux production machines.eing
Going back to square one I wasn't particularly fond of this replication and the technical glitches I might have to confront.Instead I needed a solution able to work anywhere and under any environment with the minimum requirements possible, something that mostly boiled down to locating and importing the necessary library dependencies at runtime in a portable way.In other words, take care of those pesky import statements:
package com.wlogic.client;
import weblogic.xml.crypto.wss.WSSecurityContext;
import weblogic.xml.crypto.wss.provider.CredentialProvider;.wsee.security.util.CertUtils;
import weblogic.security.SSL.TrustManager;
import javax.annotation.Generated;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceRef;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World with WebLogic dependencies!" );
}
}
(Note that in order to keep the example simple, the rest of the body's code was removed)
So to simplify matters and be truly portable, I needed, on each machine, to:
In other words no strings attached, portability being the prime target. It sounded like the perfect scenario for an all-inclusive fat jar client.
Talking about limitations imposed by IDEs, in trying to run the client from source from within JDeveloper on Windows, I had a close encounter with the dreadful CreateProcess error=206, The filename or extension is too long error.
The same error but under a different code, 87, was filed as an Eclipse bug back in 2012, and as it seems still at large in year 2017 and on Jdeveloper on Windows 7.The following extract from the original bug filing thread reveals the issue behind it:
The bug here describes that the junit or java launcher can not be used in case the classpath or command line arguments exceed the limitation of the operating system. To solve that problem outside of eclipse is a total different story and should be discussed on another platform (stack overflow or whatever).
Your post is about two issues, one is how to find out the generated commandline and the other one is how to get the process running inside eclipse.
To find out how the command line gets generated, I suggest the following:
To get your application inside eclipse running, you need to reduce the command line. As mentioned there are different strategies. You need to find out which one is the best for you:
So although not an Eclipse/Jdeveloper issue per se but more prevalent to the command line limitations of Windows, the point is that JDeveloper failed me and as discovered down the same thread, this constituted a reason for abandoning Eclipse all together :
I thought I would give some information regarding this bugs impact on the use of the Eclipse product as I am a faithful Eclipse user. This bug has caused the entire engineering department at Expedia.com (approax. 200 devs) to move to a paid product, IDEA intellij, due to their inability to use the IDE for debugging or running JUnits.
and
As an employee for expedia.com, I can say that we support both Eclipse and IntelliJ and we currently have developers using both. Some developers have switched to IntelliJ and this bug was a contributing factor. I use and prefer IntelliJ for several reasons, and have been using it since before we knew about this issue.
This situation nicely paves the way to laying forward my objection, that is, that nowadays all if not most Java development is done on IDEs which hide the underlying procedures and complexities, to the point of questioning the Java notion of 'openness', as you're now attached to these massive toolkits instead of the tool versions of the command line.
Of course since in reality this is a Windows OS problem, firing CLI tools like Maven or Gradle would also be prone to the very same issue, but at least you are in control therefore enabled to respond better, also hinted by the tools' switches verbose output;Maven's -e -X or Gradle's --debug.It's all about control, IDEs for Automatic driving vs CLI for Manual...
Surprisingly some of the proposed solutions do involve packing a "pathing jar" on the command line, as seen here and here:
The Windows command line is very limiting in this regard. A workaround is to create a 'pathing jar'. This is a jar containing only a Manifest.mf file, whose Class-Path specifies the disk paths of your long list of jars, etc. Now just add this pathing jar to your command line classpath. This is usually more convenient than packaging the actual resources together.
As I recall, the disk paths can be relative to the pathing jar itself. So the Manifest.mf might look something like this:
Class-Path: this.jar that.jar ../lib/other.jar
If your pathing jar contains mainly foundational resources, then it won't change too frequently, but you will probably still want to generate it somewhere in your build. | https://www.i-programmer.info/programming/java/11142.html | CC-MAIN-2022-40 | refinedweb | 1,381 | 54.63 |
“Shed Skin is an experimental Python-to-C++ compiler. It accepts pure Python programs, and generates optimized C++ code. This means that, in combination with a C++ compiler, it allows for translation of Python programs into highly efficient machine language. For a set of 16 non-trivial test programs, measurements show a typical speedup of 2-40 over Psyco, about 12 on average, and 2-220 over CPython, about 45 on average. Shed Skin also outputs annotated source code.”
Shed Skin Python-to-C++ Compiler 0.0.8 Released
About The Author
Thom Holwerda
Follow me on Twitter @thomholwerda
32 Comments
2006-05-04 4:07 pmsrepmub
right, it (currently) doesn’t work for arbitrary programs. I am not building a ‘magic’ compiler, but something that is mostly useful for developing computationally intensive code. btw, it is of course possible to only compile parts of your program, so you can get very good performance for that part (much better than using Psyco), while still being able to use the full Python in the rest of your program.
2006-05-04 4:39 pmameasures
Firstly, it is great to have information directly from the author of such an innovative tool.
Secondly I am in the process of writing a translator/ cross compiler in Python. After the pain of Lex + Yacc; the joy of YAPPS was a blessed relief. Will take a look at your work with much interest.
Speed of development with Python is phenomenal compared with C++ or Java; however the pain of recompiling the interpreter to gain additional libraries makes it awkward at times for most folk.
Good luck with progressing your project; it sounds good.
2006-05-04 8:03 pmrlewczuk
Interesting indeed. Ability to speed up hot parts of a program without rewriting it in C(++) is really, really valuable.
First I’ve thought looking at the source tarball is why isn’t it implemeted in python (performance may somwaht suffer but development might be hell lot easier). Not that i’m criticizing this tool as it seems to be a great one if it achieves production quality (maybe it already has ? still haven’t run it on my linux box but I’m going to try it now
. I’m just curious of your opinion about pros and cons of C++ versus Python implementation.
Regards,
rle
2006-05-04 8:48 pmsrepmub
Shed Skin is fully written in Python (ss.py, about 6000 lines). I wouldn’t dare otherwise.. 🙂 it doesn’t compile itself, because it uses several (dynamic) libraries, but I am thinking of compiling the type inference part (which takes 90%+ of the time). all the ?pp files you see are C++ implementations of the builtins and some (parts of) library modules, that are linked with generated code to produce the result.
2006-05-04 8:50 pmsrepmub
oh no, it’s far from production quality (version 0.0.8 kind of indicates this
). it’s really an academic exercise at this moment, partly just to show that it is possible. I am hoping other people will contribute parts, bug reports etc. so that in many months it might work for arbitrary ‘largish’ Python programs (of course, respecting the limitations imposed by using SS).
I know has some information about a Python in Python that implements a backend in C and another backend in LLVM. I’m primarily interested in this as a multiplatform environment so Psyco is no use to me.
2006-05-04 5:16 pmsrepmub
I have tried to read their website a few times, but it seems they are trying a lot of things at the same time. Shed Skin is really much simpler (only 6000 lines!), and has one clear goal: to be *really* fast for algorithmic-like code, at the cost of some flexibility. also, I am not sure if PyPy will ever accept *pure* code, without any annotations, and if it will ever generate as fast code as Shed Skin does.
!!!
It looks a good stuff to me…
I hope it will soon leave the alpha to be more usable (don’t know exactly how usable it is?)
It is a piece of work anyway. Making a compiler that translate into a different language is not an easy thing, I can imagine. And one guy only.
My only worry is if it may help to leave an excelent “Free” language as Python is…
!!!
i’ve always wondered why the cpython interpreter hasn’t been rewritten, we’re always hearing how slow it is compared with jython, ironpython, psyco etc.
pypy sounds like going in the wrong direction (implementing the interpreter in python would be slower than c, which is already slow enough) shedskin looks promising though.
i seem to recall that the parrot implementation for python had been abandoned too.
2006-05-04 7:02 pmma_d
psyco doesn’t run python code, it translates python functions to 386 asm. It’s not exactly fully capable, and it’s limited to one architecture. It’s also incompatible with some code.
CPython is largely fine, and it works. It’s slow, but usually that doesn’t matter.
You pretty much just have to put your more complex code in c.
Ironpython also isn’t finished.
I think speedups are actually soon on the todo list for python. I think they’re planning on reworking things for efficiency in python 3, but maybe that’s a rumor?
2006-05-04 7:53 pmschala
The point of pypy, as I understand it, is to implement all of the core Python language in Python so that it is extensible. The bytecode interpreter would still be written in C, if not assembler, so it would be plenty fast. Ideally, it would even be faster than CPython is now, since you could focus all your optimization on the bytecode interpreter, and the language itself would be optimized too.
2006-05-05 11:54 pmsubterrific
You’ve misunderstood. The point of PyPy is a reimplementation of all of CPython in pure-Python. The point being that it is much easier to experiment with Python code than C code.
2006-05-04 8:55 pmsrepmub
@wkleunen:
sure, true dynamic typing can be useful at times. but I really almost never use it myself. a _lot_ of serious programs are written in C++, without much need for dynamic typing. the real value of Python, as I see it, is that you can _leave out type declarations_, and the high-level syntax and datatypes. Shed Skin maintains all these advantages.
2006-05-05 8:18 amwkleunen
@srepmub:
Indeed, many staticly typed programs are written in C++. Personally i prefer 2 languages: c++ and python. So when you take out dynamic typing from python, i would personally prefer programming in c++.
My personal opinion would be: if you do it, do it fully, like pypy tries to do. If i really am concerned with speed, i will use a staticly typed language.
of many such projects, with ever improving C++ quality.
One of the promises of .NET was the ability to write a project in multiple languages without the heartburn and performance hit of FFI’s. That’s never really materialized, and I have to suspect that MS’s apparent indifference to their own languishing creation is a trick to gain mindshare until they’re ready to slap on the royalties and lawsuits.
Maybe someday it will be practical to glue generated C++ files, even in weird dialects, together.
2006-05-05 6:45 pmsrepmub
because C++ is much closer to Python. for example, the Python list type can be mapped to the C++ STL vector type. then you have namespaces, exceptions etc.. C++ just has so many abstractions, which makes translation much easier. (this is one of the reasons why the compiler is only 6000 lines :-))
Is that % speedup, or x speedup? If the average Python program now runs in 1/12th the time it takes in the interpreter, that’s quite an improvement. | https://www.osnews.com/story/14515/shed-skin-python-to-c-compiler-008-released/ | CC-MAIN-2019-51 | refinedweb | 1,336 | 64.2 |
CRUD Template
- Features
- Install
- Preparation
- Proposed usage scheme
- SQLAlchemy Support
- Relational Joins
- Extensions for the basic skeleton
- Building the CRUD interface manually
Basic model admin interfaces (create, read, update, delete, a.k.a, CRUD) are frequently used in creating web applications.
Here's the tgcrud basic template generator which helps you to create an admin interface (the create, read, update and delete functions).(or do it in your way)
- Takes advantage of TurboGears form widgets and validation. you'd hardly need to modify the HTML.
Install
The tgcrud command extension is available from the Python CheeseShop and the TurboGears Subversion repository. You can use setuptools to install tgcrud with following command:
$ easy_install tgcrud
or download the source code and install it manually. Or, just copy the code from this page into your project (see below).
Preparation
- Start a TurboGears project with tg-admin quickstart. We'll name our example "project".
- Define the model in model.py. We'll name our data class BookMark.
- Create a database with the tg-admin sql create command.
- Now we can start to create the admin interface.
Proposed usage scheme
Once you've defined your model, you can use the tg-admin crud command to generate the crud package. The syntax is:
$ tg-admin crud [model class name] [package name]
for example, if the model name is BookMark and the package name is BookMarkController, the command is:$ tg-admin crud BookMark BookMarkController
Then the BookMarkController package (folder) is generated. You just need to take a few minutes to customize the widget formfield to have a proper crud interface.
tgcrud generates plain TurboGears code, so you can do whatever you want on these package.
- Customize the form field in BookMarkController/controllers.py.
First, you have to customize the widget fields:from bookmark.model import BookMark from turbogears import widgets class BookMarkFields(widgets.WidgetsList): # if we have a SQLObject model with 4 fields: name, url, excerpt, memo name = widgets.TextField(label="Name") url = widgets.TextField(label="URL") excerpt = widgets.TextField(label="Excerpt") memo = widgets.TextField(label="Leave Memo")If you are not familiar with widgets yet, check out the Widgets Overview page.
All available form widgets are listed in the WidgetBrowser (tg-admin toolbox).
And you may want to add a schema for form validation as well (optional):class BookMarkSchema(validators.Schema): name = validators.String(not_empty=True, max=30) url = validators.URL(add_http=True, check_exists=True) # append the following validators
For a referene of available validators, refer to the FormEncode documentation.
You see that you can even use the existing schemas without pain. You don't really need to customize the form validation schema, but it's good to know that you have the option.
Read the widgets documentation for detailed information on validator usage.
To use the admin interface, you need import the package to your controllers.py with a line like this:
from BookMarkController import BookMarkController
and add a sub-controller to your Root controller class:
foo = BookMarkController()
This way, the class BookMarkController will be mounted to the Root controller.
- Start the server and open the URL to use the customizable interface.
SQLAlchemy Support
tgcrud 1.0 supports both SQLObject and SQLAlchemy models, By default tgcrud will detect the proper ORM for you. In cases you can specify the -s option to the tg-admin crud command for SQLAlchemy support, similar to the -s option of the tg-admin quickstart command. Example:
$ tg-admin crud -s BookMark BookMarkController
The generated templates will use 'id' as the default primary key. While SQLObject use 'id' as it's primary key, it works well with SQLObject models. But if we take SQLAlchemy models into consideration, SQLAlchemy provide the flexibility to use variety names as primary keys. Thus tgcrud allows you to specify the "-i(id)" option, which is denoting to your model's primary key, to the tg-admin crud command. Example:
$ tg-admin crud -i user_id User usermin
Relational Joins
tgcrud generates 'no-magic', plain TurboGears code. It is not an automatic admin tool such as Catwalk in TurboGears or the admin interface in Django. tgcrud's aim is to save you time for basic CRUD interface design decisions (in TurboGears) and generate the skeleton code for production. You have to handle the advanced model relationships by your self. Fortunately we can provide a strategy guide for using relational joins.
Before doing Relational Joins, you should open the tg-admin shell(or use Catwalk if you are using SQLObject) and make sure you can do the basic operations around your USER -Group models.
Then, apply the same operation on the (hand made/generated by tgcrud) interface. That would be:
One-to-one Relationships
For relation joins you'd assign 'object' instead of plain parameters.
My approach is using SelectField in the widget form and overwrite the parameters in the save method.
For example, in widgets.py:
.... + book = widgets.SingleSelectField(label="book", + options=[(entry.id, entry.title) for entry in book] + )
In controllers.py:
def save(self, id=None, **kw): #update kw + if kw['book']: + kw['book'] = Book.get(int(kw['book'])) #update .... #create ....
It's an interesting Python trick, we overwrite the kw['book'] value in the kw dictionary with the object with the id referred to by the value.
If you don't like it, you can customize the joins in a normal way.
One-to-many Relationships
Try CheckBoxList, MultipleSelectField or the SelectCheck widget plugin.
Take User-Group relationship generated by identity for example. You have two steps to do:
- Form the selected groups to a group check list (or something else)
- process the select group
My approach is using CheckBoxList in the widget form and overwrite the parameters in the save method.
For example, in controllers.py (step 1):
def show(....): .... + record = User.get(int(id)) + check= widgets.CheckBoxList(label = "Groups", name= "user_groups", + options=[(entry.id, entry.group_name) for entry in groups], + default=[entry.group_id for entry in record.groups] + )
In ``controllers.py``(step 2):
def save(self, id=None, **kw): #update kw + try: + groups = list(kw['user_groups']) + except: + groups = [] + hub.begin() + record = User.get(int(id)) + for group in record.groups: + record.removeGroup(group) + for group_id in groups: + record.addGroup(Group.get(int(group_id))) + hub.commit() ....
BTW, the example is suited for many-to-many relationships too.
Many-to-many Relationships
You can try the SelectShuttle widget plugin to generate a selection form for many-to-many relationships. But in this example I'll be using SelectField instead.
In controllers.py:
def save(self, id=None, **kw): #update kw + if kw['authors']: + # assume there's only one author + obj_id = User.get(int(kw['authors'])) + del kw['authors'] #update else: record = Book.get(int(id)) + record.addUser(obj_id) .... #create if not id: record = Book(**kw) + record.addUser(obj_id) ....
Extensions for the basic skeleton
Secure your CRUD interface with identity
You can protect whole of your CRUD interface with one line of code. Just append a line in the main project's controllers.py:
foo = BookMarkController() + foo = identity.SecureObject(foo,identity.has_permission('admin'))
Now only users with permission admin can access the foo CRUD interface.
Or you can protect specific methods with a @identity.require() decorator:
.... @expose() @identity.require(identity.in_group("admin")) def method.....
Check the TurboGears documentation about identity for details.
Paginate your lists
Search for 'paginate' in controllers.py. The pagination support code appears in the import section and just above the list method.
Uncomment the two lines. That's all you need to do for pagination support in controllers.py:
+ from turbogears import paginate .... @expose(template='kid:dnidoc.manage.templates.list') + @paginate('records') def list(self, **kw): ....
then check template/list.kid, there's a commented paginate panel:
<span py: <a py:${page}</a> <b py:${page}</b> </span>
Now you have solid pagination support for your list pages.
Check the TurboGears documentation about the paginate decorator for details.
tgcrud skeleton uses id as the default primary key in templates, but SQLAlchemy can use variable key names. So if you are using SQLAlchemy, you may need to change the id parameter manually. Luckily there're just 3 templates need to deal with:
- list
- form
- show
For example, if you want a crud interface of the User model class, all you need to do is to replace id with user_id in these pages.
Building the CRUD interface manually
If you don't want to use the tg-admin crud command , you can also integrate the CRUD code manually.
The latest template is available here:
This has also optional support for identity, paginate..., etc.
The following is the basic skeleton of the admin interface.
- Create a folder to contain the code. We take BookmarkController as an example.
- The structure is the following
#project/BookmarkController/ __init__.py controllers.py templates/__init__.py master.kid list.kid form.kid show.kid
When you first enter the interface, it will list all info in list page. You can create a new record by clicking the 'New BookMark' link. This will lead you to the new page. Similarly, when you click 'edit' or 'show', this will lead you to the 'edit' or 'show' page. Since the differences between 'new' and 'edit' pages are wrapped in widgets, these two pages share the same 'form' template. The basic operations of tgcrud are a full clone of the scaffold implementation in Ruby on Rails.
Importing the CRUD controller
Add the following lines in your project's controllers.py:
from BookmarkController import BookMarkController .... class Root(controllers.RootController): main= BookMarkController()
The controllers.py source
The full controller code is here:
from turbogears import controllers, expose, redirect from turbogears import validate, flash, error_handler from bookmark.model import BookMark from turbogears import widgets, validators class BookMarkFields(widgets.WidgetsList): """fields definitions. Replace to your Fields""" # take name and url field for short example name = widgets.TextField(label="Name") url = widgets.TextField(label="URL") class BookMarkSchema(validators.Schema): """ define validation schema that involves field dependency or logical operators """ name = validators.String(not_empty=True, max=30) url = validators.URL(add_http=True, check_exists=True) class BookMarkForm(widgets.TableForm): """form builder""" #name="BookMark" fields = BookMarkFields() #validator = BookMarkSchema() # define schema outside of BookMarkFields #method="post" #submit_text = "Create" model_form = BookMarkForm() class BookMarkController(controllers.Controller): """Basic model admin interface""" modelname="BookMark" @expose() def default(self, tg_errors=None): """handle non exist urls""" raise redirect("list") @expose() def index(self): """handle front page""" raise redirect("list") @expose(template='bookmark.BookmarkController.templates.list') def list(self, **kw): """List records in model""" records = BookMark.select() return dict(records = records, modelname=self.modelname) @expose(template='bookmark.BookmarkController.templates.show') def show(self,id, **kw): """show record in model""" record = BookMark.get(int(id)) return dict(record = record) @expose(template='bookmark.BookmarkController.templates.form') def new(self, **kw): """Create new records in model""" return dict(modelname = self.modelname, form = model_form, page='new') @expose(template='bookmark.BookmarkController.templates.form') def edit(self, id, **kw): """Edit record in model""" try: record = BookMark.get(int(id)) except: flash = "Not valid edit" return dict(modelname = self.modelname, page='edit' record = record) @validate(model_form) @error_handler(new) @expose() def save(self, id=None, **kw): """Save or create record to model""" #update kw if id: #update """ record = BookMark.get(int(id)) record.set(name = self.name, url = self.url) or for attr in kw: setattr(record, attr, kw[attr]) """ for attr in kw: setattr(record, attr, kw[attr]) flash("Bookmark was successfully updated.") raise redirect("../list") else: #create """ assign the attrs one by one: self.name = kw['name'] self.url = kw['url'] or for attr in kw: setattr(self, attr, kw[attr]) """ #BookMark(name = self.name, url = self.url) BookMark(**kw) @expose() def destroy(self, id): record = BookMark.get(int(id)) record.destroySelf() flash("${modelname} was successfully destroyed.") raise redirect("../list")
You need to customize the following for your project:
- The BookMarkFields class
The Templates source
list.kid:
<body> <h1>Listing ${modelname}</h1> <table> <tr> <th> name </th> <th> url </th> <th> excerpt </th> <th> memo </th> </tr> <tr py: <td>${record.name}</td> <td>${record.url}</td> <td>${record.excerpt}</td> <td>${record.memo}</td> <td><a href="show/${record. id}">Show</a></td> <td><a href="edit/${record. id}">Edit</a></td> <td><a href="destroy/${record. id}" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href; f.submit(); };return false;">Destroy</a></td> </tr> </table> <br/> <a href="new">New ${modelname}</a> </body>
You need to customize the following for your project:
- Column cells and labels
form.kid:
<body> <h1>Editing ${modelname}</h1> <div py: ${form(action='save', ${form(value=record, action=tg.url('../save/%s'%str(record.id)), <a href="${tg.url('../show/%s'%record.id)}">Show</a> | <a href="${tg.url('../list')}">Back</a> </div>
You need to customize the following for your project:
- None
show.kid:
<body> <table> <tr> <th> name: </th> <td>${record.name}</td> </tr> <tr> <th> url: </th> <td>${record.url}</td> </tr> <tr> <th> excerpt: </th> <td>${record.excerpt}</td> </tr> <tr> <th> memo: </th> <td>${record.memo}</td> </tr> </table> <br/> <a href="../edit/${record. id}">Edit</a> | <a href="../list">Back</a> </body>
You need to customize the following for your project:
- Column cells and labels | http://docs.turbogears.org/1.0/CRUDTemplate | crawl-002 | refinedweb | 2,195 | 51.55 |
I have to write a program that the user enters the number of disks from tower 1 to tower 3. The rules are: only one disk can be moved at any time and no disk can be placed on top of a disk with a smaller diameter. All i have left to do is change my code so that it for each move it says e.g. disk 1 from tower 1 to tower 3. Also I need to print out how many moves it took. If you can help me, then thank you. Here is what I have:
#include <stdio.h>
void tower(int, int, int, int);
main()
{
int n;
printf("Enter the starting number of disks: ");
scanf("%d", &n);
tower(n, 1, 3, 2);
return 0;
}
void tower(int c, int start, int end, int temp)
{
if (c == 1) {
printf("%d --> %d\n", start, end);
return;
}
tower(c - 1, start, temp, end);
printf("%d --> %d\n", start, end);
tower(c - 1, temp, end, start);
} | https://cboard.cprogramming.com/c-programming/5882-towers-hanoi.html | CC-MAIN-2017-09 | refinedweb | 166 | 85.93 |
The following is code that demonstrates using HubKey's Client-side API for SharePoint. This API wraps many of SharePoint Server 2007's Web Services (Lists Web Service, Webs Web Service, etc.) to provide a familiar object model that can be used on remote client machines without having to process XML requests and responses. In this case the code from the MSDN article How to: Upload a File to a SharePoint Site from a Local Folder was copied verbatim, and it compiles and runs successfully on a client computer, even though the SharePoint DLLs are not referenced or installed.
Update: You can download a demo copy of the API - click here for information.
Update II: The API now includes a demo application - see this post for details.
using System;
using System.IO;
// Using HubKey.Web.Services.SharePoint in place of Microsoft.SharePoint
using HubKey.Web.Services.SharePoint;
namespace HubKey.DevelopmentHole
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.RunDemo();
}
public void RunDemo()
{
string webUrl = "";
SPSite site = new SPSite(webUrl);
SPWeb web = site.OpenWeb();
//create a new document library
Guid id = web.Lists.Add("Temp Doc Lib", "A temp document library.", SPListTemplateType.DocumentLibrary);
SPList list = web.Lists[id];
//add a field
list.Fields.Add("Upload Source", SPFieldType.Text, false);
list.Update();
string fileUrl = webUrl + "/Temp Doc Lib/New Folder/test.txt";
string localFileName = @"D:\Temp\test.txt";
string localFileContents = "A temp file uploaded by HubKey's SharePoint client-side API.";
File.WriteAllText(localFileName, localFileContents);
//Upload the file using the API code from 'How to: Upload a File to a SharePoint Site from a Local Folder'
//see
UploadFile(localFileName, fileUrl);
SPFile file = web.GetFile(fileUrl);
file.CheckOut();
//update the title and new upload source field by using the file's SPListItem property...
file.Item["Title"] = "A temp title";
file.Item["Upload Source"] = "HubKey's SharePoint client-side API.";
file.Item.Update();
//Check in
file.CheckIn("Checked in by HubKey's SharePoint client-side API");
//Get the file contents
string serverFileContents = web.GetFileAsString(fileUrl);
System.Diagnostics.Debug.Assert(string.Equals(localFileContents, serverFileContents));
//Tidy up
list.Delete();
}
public void UploadFile(string srcUrl, string destUrl)
{
if (!File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}
SPWeb site = new SPSite(destUrl).OpenWeb();
FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
EnsureParentFolder(site, destUrl);
SPFile file = site.Files.Add(destUrl, contents);
SPFolder folder = file.ParentFolder;
}
public string EnsureParentFolder(SPWeb parentSite, string destinUrl)
{
destinUrl = parentSite.GetFile(destinUrl).Url;
int index = destinUrl.LastIndexOf("/");
string parentFolderUrl = string.Empty;
if (index > -1)
{
parentFolderUrl = destinUrl.Substring(0, index);
SPFolder parentFolder
= parentSite.GetFolder(parentFolderUrl);
if (!parentFolder.Exists)
{
SPFolder currentFolder = parentSite.RootFolder;
foreach (string folder in parentFolderUrl.Split('/'))
{
currentFolder = currentFolder.SubFolders.Add(folder);
}
}
}
return parentFolderUrl;
}
}
}
12 comments:
Very nice work.
Is the api free? Where to download the api?
Yeah, what Tony said.
Thanks - we're still working through some additional functionality and testing, but it's likely we'll have something available for download soon. If you're interested in participating in testing, drop us a line at info@hubkey.com or choose "HubKey SharePoint API" as your interest on HubKey's Contact Us form.
You can now download a beta copy of the API - choose "HubKey SharePoint API" as your interest on HubKey's Contact Us form.
Is it possible to retrieve information on the libraries on sharepoint with this api? For example of what type the metadata fields in the library are. (Checkbox, dropdownlist and so on).
"A person wants to upload a document. The client has to show metadata in the way it is shown on sharepoint."
Hi!
Two more questions..
Is form based authentication possible with this api?
Is the source code available?
thanks!
I need to get the type of the metainfo column on sharepoint with Frontpage RPC. Can anybody help me?
Toni - you'll need to use the Web Services (e.g. the Lists.GetList method) provided by SharePoint to accomplish this. HubKey's SharePoint API uses these web services to provide an object model that replicates some of the features of Microsoft's API - including providing a SPFieldCollection for objects like SPList (e.g. list.Fields) and SPListItem (e.g. file.Item.Fields["Division Code"].TypeAsString). It currently does not support forms authentication however - until it does you'll need to hand code the processing of the service requests and xml formatted results.
Ok. Thanks for the answer.
It would be great if you could send me source code. Then I could add my little hack, if not I wait for you to add form-based authentication. Good work!
a nice work
i'm looking for web service to list database informations for a web application and to list web applications of a sharepoint server, could you advice me?
thanks
Hi! The question of form based authentication again.. To work around the problem, is it possible to set the header of the requests in the api? Then I can post the cookie in that header.
Best regards,
Toni
Hi Toni
It's not supported, but the web services are public properties of SPSite, so you might be able to set the CookieContainer property for example. You'd also need to pass the authentication cookie to the Web's WebClient (FrontPageRPC object) object.
You can get the authentication cookie by using the authentication web service.
We have a commercially licensed release of the API that will be available soon that includes support for FBA among other features (e.g. adding new webs). It will also include source code so that you can customize and extend the library as needed. | http://geek.hubkey.com/2008/11/sharepoint-api-client-side-object-model.html | CC-MAIN-2020-29 | refinedweb | 943 | 52.76 |
18 November 2011 07:18 [Source: ICIS news]
By Quintella Koh
SINGAPORE (ICIS)--Offers for 2-ethylhexanol (2-EH) cargoes in east Asia this week hit a fresh 23-month low, with spot prices likely to continue falling as traders unload deep-sea cargoes, industry sources said Friday.
A large-scale northeast Asian buyer said it received an offer this week for a parcel of 2-EH European origin, scheduled for delivery on 10 December, at $1,450/tonne (€1,073/tonne) CFR (cost and freight) ?xml:namespace>
The last time cargoes were transacted at below $1,450/tonne CFR East Asia was on 22 January 2010, according to ICIS.
On 11 November, 2-EH CFR East Asia, which is subjected to import duty, was assessed at $1,460-1,500/tonne 22 January 2010, ICIS data shows.
The buyer of the bulk-sized 2-EH cargo from
In the regional market, a Japanese trader said that it was prepared to offer Japanese-origin spot cargoes at $1,450/tonne CFR East Asia. The trader said that it is currently in negotiations with its customers for bulk-parcels of 1,000 tonnes.
Producers and traders polled on Friday said that continued weak demand from the downstream dioctyl phthalate (DOP) sector is placing strong downward pressure on Asian 2-EH spot prices.
DOP, a plasticiser, is added into polyvinyl chloride (PVC) to increase the flexibility of the polymer. PVC is used heavily in the construction sector for the manufacture of door frames, window frames and piping.
Fears of a property bubble that is developing in
Average home prices in the country's 100 major cities fell for the second consecutive month in October to yuan (CNY) 8,856/square metre ($1,395/square metre), down 0.23 percent from September, according to the latest report from the China Index Academy, the China Daily reported.
And price cuts in first-tier cities like
($1 = €0.74 / $1 = CNY6 | http://www.icis.com/Articles/2011/11/18/9509465/asia-2-eh-offer-at-23-month-low-buyers-insist-on-lower-prices.html | CC-MAIN-2015-06 | refinedweb | 326 | 57.3 |
combines two graphs More...
#include <vtkMergeGraphs.h>
combines two graphs
vtkMergeGraphs combines information from two graphs into one. Both graphs must have pedigree ids assigned to the vertices. The output will contain the vertices/edges in the first graph, in addition to:
The output will contain the same attribute structure as the input; fields associated only with the second input graph will not be passed to the output. When possible, the vertex/edge data for new vertices and edges will be populated with matching attributes on the second graph. To be considered a matching attribute, the array must have the same name, type, and number of components.
Definition at line 58 of file vtkMergeGraphs.h.
Definition at line 62 of file vtkMergeGraphs.
This is the core functionality of the algorithm.
Adds edges and vertices from g2 into g1.
Whether to use an edge window array.
The default is to not use a window array.
The edge window array.
The default array name is "time".
The time window amount.
Edges with values lower than the maximum value minus this window will be removed from the graph. The default edge window is 10000.
This is called by the superclass.
This is the method you should override.
Reimplemented from vtkGraphAlgorithm.
Fill the input port information objects for this algorithm.
This is invoked by the first call to GetInputPortInformation for each port so subclasses can specify what they can handle.
Reimplemented from vtkGraphAlgorithm.
Definition at line 108 of file vtkMergeGraphs.h.
Definition at line 109 of file vtkMergeGraphs.h.
Definition at line 110 of file vtkMergeGraphs.h. | https://vtk.org/doc/nightly/html/classvtkMergeGraphs.html | CC-MAIN-2021-17 | refinedweb | 263 | 69.99 |
Forum:Plan of action for user rights and moderation
I am the Operations Manager of the RWF, and of this website. I am the closest thing there is to someone being in charge. I also have a long history of making decisions, and of proving my positive intents to this website and its users. I am now going to use both this actual authority, and defacto moral authority, to deal with a situation that is out of hand. I am going to put a solution in place via fiat eventually. But I do want everyone’s feedback in order to make it as palatable to everyone as possible, and give it the best chance to succeed.
At the moment things like sysops, and crats are just labels, with extra buttons that many people don’t even know what to do with. The back and forth rights battles reminds me of The Sneetches by Dr. Seuss. So my first major proposal is the complete removal of bureaucrat as a user group. It’s gone. Instead there will be three groups with different rights spread out:
- Sysops-patrol, auto-patrol, delete, restore, semi-protect, vandal bin, and blocking for spammers and obvious vandalism and for fun, can make and remove sysops rights.
- Tech-Bigdelete, edit MW and JS, interwiki tables, etc. Things needed for tech reasons on the wiki.
- Moderators-full protect, full rights grant and removal, blocking for trolling/disruption, hide/view revisions.
The sysops group and continue as it is, a fun group that spread around useful tools to people that have been here a little while. The purpose of letting sysops add or remove the sysops right is so that people can continue to grant the privilege to new users, but if someone starts abusing it badly, say deleting tons of pages they can be removed without having to wait for someone further up the chain to act.
The sysops will not have the moral authority to block anyone but for short periods for either the typical “fun” blocks, or for obvious vandalism or spam. Blocking for any other reason is grounds for removal of that right.
The tech group will be for those who are doing things in the cogs and wheels of the wiki and need to edit and do things most users won’t. It keeps those powers with the people that need them but doesn’t confuse things by giving them authority over the wiki.
The moderators group will be an elected position. Elected using the same criteria and extension that the board of trustees uses. Since the sole purpose of the moderators is to deal with trolling, or disruption we don’t need tons of them. A mere handful of trusted users, that are given the authority and the tools to respond to situations that are disrupting the wiki. They can temporarily block people, remove rights, or protect pages. Tmtoulouse (talk) 15:59, 17 May 2011 (UTC)
Contents
- 1 Feedback here
- 2 Idears (braindrizzling)
- 3 Loya Jirga
- 4 Sysops
- 5 Tech
- 6 Moderators
- 7 Abolish Chicken Coop
- 8 Moving forward with step 1
- 9 Dispute resolution
- 10 Support Trent's proposal
- 11 Reject Trent's proposal
- 12 Restoration of Sysops
- 13 So what next?
- 14 Working out details
Feedback here[edit]
- could we edit our own vector.js files? To add mark as patrolled hot vandal, etc. ? ТyTalk. 16:04, 17 May 2011 (UTC)
- Editing JS in your own user space should remain intact. Tmtoulouse (talk) 16:05, 17 May 2011 (UTC)
- Thank you for explaining. ТyTalk. 16:06, 17 May 2011 (UTC)
- This looks like a good idea to me. Nebuchadnezzar (talk) 16:07, 17 May 2011 (UTC)
- I like this idea. It's simple. Simple is good. Senator Harrison (talk) 16:11, 17 May 2011 (UTC)
- Notwithstanding the disheartening bullshit that happened yesterday, I don't believe the political process is over yet or that it's necessary for you to intervene. Some of the disruptive reactive types are running out steam and bile (I am referring to a tiny few shit stirring motherfuckers here - you assholes know who you are) and leaving space for those with good ideas who nonetheless got dragged into this miasma of atomized diarrhea but are inclined to cool the fuck down to get some good work done. Please give everyone a few more days to get some cream for that butthurt and drink their anger into submission. Nutty Roux (talk) 16:18, 17 May 2011 (UTC)
- I am not doing it right this second. I am leaving plenty of time for people to state their ideas and suggestions and to build off this framework. Tmtoulouse (talk) 16:22, 17 May 2011 (UTC)
- I was overstating my confidence in this community. I sometimes let my cheeriness get the best of my impeccable judgment. Do what you think is best. Nutty Roux (talk) 16:24, 17 May 2011 (UTC)
- Generally looks good. I suggest that it be specifically spelled out that sysops are not allowed to do moderator blocks, or undo a desysop from the moderators. Doing so would automatically earn themselves a moderator desysop and block as punishment, no questions or trial or HCM necessary. And that moderators are specifically directed to enforce the Community Standards, and not arbitrary personal reasons. (Meaning: each desysop/block should have an indication of what Community Standard was violated.) --Eira OMTG! The Goat be Praised. 16:48, 17 May 2011 (UTC)
- It's time to give fascism a chance - David Gerard (talk) 17:09, 17 May 2011 (UTC)
I don't like the look of what's been going on in the last few days, but the suggestions above look reasonable. My biggest concern is about authority rather than abilities, as I think the site should remain essentially egalitarian. So I think it's important to establish whether Moderators would actually hold more authority than other users, or just more abilities.
My own opinion is that the things Moderator abilities should be used for (except hiding revisions for privacy reasons) should be decided by the community, much as they are now, rather than an individual. Giving another user Moderator rights would only be done when the user is elected, and removing rights or issuing a lengthy block to a troublemakers should only be done when agreed at the Chicken Coop. Hence it would then be the Moderator's role simply to enact the community decision rather than making the decision themselves. It should be emphasised that a Moderator's opinion on any issue carries no more weight than any other user's. ΨΣΔξΣΓΩΙÐ
Methinks it is a Weasel 17:48, 17 May 2011 (UTC)
- The whole issue of this is that most disruption needs a quick but temporary response, and the "mob" moves very slowly and usually with a heavy hammer when it strikes. By empowering a small number of individuals to take actions to break up heated fights/disruption we decrease the HCM issues. Moderators can lock a page, or block a user on a temporary basis till things cool. Permanent blocking or the like could still be left up to community cluster fuck. Tmtoulouse (talk) 18:14, 17 May 2011 (UTC)
- How would that, for example, to use a real example, have helped the mess that Blue and I got ourselves mired in last week? To use a real world example of something I assume we are trying to solve? What would the new process potentially look like? ħuman
03:06, 19 May 2011 (UTC)
- Having actual rules that you guys could use to support your positions would have lead to a better discussion than "I like human, so I support him" and "I like Blue so I support her". We could have had a reasoned argument about which rules apply, and how. And before a bunch of people who are invested in the site rather than the entire mob of concern trolls. --Eira OMTG! The Goat be Praised. 03:59, 19 May 2011 (UTC)
- Reasonable compromise to me. Weaseloid's question still remains un answered though... would moderators be considered to "hold authority"? I believe your response implies "yes". (But then I am a pedantic bitch, I like things explicit.) --Eira OMTG! The Goat be Praised. 18:25, 17 May 2011 (UTC)
- Question: Has anyone ever recieved a permaban (who didn't return has a sock, etc) in RW? even TK never recieved more than a two year block, I think. nobsViva la Revolucion! 20:40, 17 May 2011 (UTC)
- I think permabans are mostly reserved for blatant and unfunny vandalism (single-purpose accounts) and spambots, and even then, they're pretty rare since we also got the bin and escalating blocks. Check out Special:BlockList for the list if you're curious. But I guess the answer to your actual question would be "No." --Sid (talk) 22:42, 17 May 2011 (UTC)
- I like the suggestions.--BobSpring is sprung! 19:35, 17 May 2011 (UTC)
- Not bad ideas. But Technical Power != Social Power. Everyone here is obsessing over UserRights, when the problem has never been the technical one of which users are in which groups, it has been the social one of who has authority and whether those having authority are willing to show good leadership. A "Moderators" group is a good idea, but giving it extra technical rights compared to others is not the point. The point is to give it social authority — this requires both others to respect the group, and the group and its members to conduct themselves in such a way so as to retain the respect of others. If you want to mark membership of this group, a Wiki page would work just as well as a UserRights group. (((Zack Martin)))™ 19:45, 17 May 2011 (UTC)
- I mostly agree with what I think is your main point: The distinguishing feature of the Mods will be their crisis-time authority and not some fancy wiki power. But (and I'm not sure if I'm disagreeing with you, filling in another angle of your idea, or just phrasing your thoughts in a different way) social and technical power should be linked: Don't give nukes to people with lacking leadership qualities (like foresight and a cool head), and also don't establish an institution with authority without giving said institution some way to actually exercise said authority. Limiting the Full Rights Alteration user-right (which is basically the only Mod-only technical power of interest here) to a select few people with authority both limits the fallout of HCM (just look at the User Rights log of the last few days...) and gives the people in charge another tool to use against wikilawyering trolls. It won't define the group, but it'll help. --Sid (talk) 22:27, 17 May 2011 (UTC)
- Oh I agree some sort crat authority (ability to control other's user rights) needs to be restricted to people who can be trusted not to abuse it, and needs to exist so people abusing lesser rights can quickly be dealt with. But the old system was mostly fine by that - only crats could change user rights. The recent HCM started because the crats themselves lacked sufficiently clear and respected and enforced guidelines as to how to use that power. Really, all these people arguing about who should be a crat or a sysop, when that wasn't actually the problem to begin with. (((Zack Martin)))™ 08:50, 18 May 2011 (UTC)
It looks pretty good actually. It doesn't seem radically different from what we're trying to get done now, but cratship is so tainted that it might be a good idea to nuke it altogether and give it a different form. EddyP Great King! Disaster! 22:35, 17 May 2011 (UTC)
Strange women lying in ponds distributing swords is no basis for a system of government. Occasionaluse (talk) 19:53, 18 May 2011 (UTC)
Idears (braindrizzling)[edit]
The lowest level "sysop," half of these will be able to block, but not unblock; the other half of the group will have the keys to unblock but no handcuffs. Members of this group would be in the group about a month lernin' what's kosher blocking vs what ain't. [This level would be for future sysops-to-be; people who are already here probably already know these things, could also be used as a punishment level short of full user privileges being axed.] 17:09, 17 May 2011 (UTC) C®ackeЯ
- I think we should forgo block rights for common users in favor of vandal bin rights.--
-brxbrx 17:57, 17 May 2011 (UTC)
- To avoid a janitor (I'd like to keep the old vocabulary, it was fun to read about) cancelling the promotion of a troll or vandal done by a moderator, I propose you create a second group with the same rights as a normal user. You could name that a "on probation" group. Janitors could move people between the normal users and janitors group, as suggested, but only moderators could move people to and from the "on probation" group. dx (talk) 20:37, 18 May 2011 (UTC)
Loya Jirga[edit]
Would we still need them? Have we ever actually needed them? Can we scrap the LJ? Wéáśéĺóíď
Methinks it is a Weasel 19:43, 17 May 2011 (UTC)
- LJ should be scrapped and replaced with mods. Tmtoulouse (talk) 22:58, 17 May 2011 (UTC)
- Now that's a good idea OzdemocracyTalk! 01:49, 18 May 2011 (UTC)
- See Forum:Order_or_No_Order#I.27d_just_like_to_mention for some off-topic drifting to this topic. Trent, I think you should wait until the mob forms an opinion. This isn't like you, and lest you forget, you gave up ownership a while ago. Not the respect and moral authority, but ownership. If people with server access can unilaterally redefine this site (ok, I know you have asked for input and all...), then we are in a weird place, especially regarding recent history. ħuman
05:56, 18 May 2011 (UTC)
- As I understand it Trent has asked for comments on his suggestions before implementation. That is, I suppose, why we are commenting on this page. Under the process above the LG would seem to have no function.--BobSpring is sprung! 20:33, 18 May 2011 (UTC)
- But I see no alternate versions of the ideas here, despite various commentary besides "it's perfect". There aren't header that say "alternate text or ideas". It seems like it is all about Trent evaluating the "commentary" and deciding what to do based on that. But I suppose any of us could add sections. Some of his sections are rather opaque, though, especially the tech one. ħuman
05:15, 22 May 2011 (UTC)
- You know what that sounds like to me? People implicitly agreeing that the text is acceptable. Trent isn't calling for anything nutso here at all, and so I don't think it's unreasonable that people are only calling for minor tweaks, and changes. --Eira OMTG! The Goat be Praised. 05:19, 22 May 2011 (UTC)
- Yeah, the main purpose the LJ served was as a kind of security blanket - at least in my opinion. It got formed, but was never really needed after that particularly biblical HCM died-out. Concernedresident omg!!! ponies!!! 15:44, 22 May 2011 (UTC)
The role & authority of the Loya Jirga was never sufficiently well defined anyway. The one time they were invoked, they were supposed to be dealing with one specific user (MC) & the problems he was creating, & the outcome was LJ making a decision about site policy (the talk-page revert rule), something which I & some other users thought they had no authority to do. This is why I think we need to agree very clearly about the Moderator role & what kinds of authority it involves before electing anyone to this position. Wėąṣėḷőįď
Methinks it is a Weasel 15:55, 22 May 2011 (UTC)
- Yeah, it was unfortunate it was formed during a shitstorm. Kind of like having to design a parachute after an engine has already failed. I think we're slightly better organised now, and it'll be easier to define the New World Order without the emotional baggage that was being flung around. Concernedresident omg!!! ponies!!! 16:01, 22 May 2011 (UTC)
Sysops[edit]
These will work almost exactly the same as they currently work on the wiki. It provides useful tools to manage and deal with the day-to-day issues of the wiki such as deleting articles or dealing with spam. The major difference is that sysops can add and remove people from the sysops group. Adding people should follow the current set of guidelines we use (been here a little while, mostly harmless), removing people should only be done if that individual is doing something that needs immediate action. Such as mass deletion of pages, or mass revoking of user rights.
Syops will be able to block and vandal bin people, but will ‘’not’’ have the authority to do this to anyone except for obvious vandalism or spam. Fun blocks of other sysops can continue as they are, well, fun.
Sysops can also semi-protect pages up to autoconfirmed users if something is getting repeatedly hit by spam bots or something. Sysops will have no added authority in any dispute or dispute moderation when compared with any other users.
Feedback on sysops[edit]
I don't think the "mostly harmless" rule was working well, since people were being sysopped almost on sight. I'd set the bar slightly higher - at least a couple weeks with a couple dozen decent edits. But then, I may be glorifying the "old days" when I used to "consider" before doing it. ħuman
04:26, 18 May 2011 (UTC)
- My suggestion over at some other page was to set edit count criteria for the user class that's supposed to make up the bulk of the editors, mostly as a way of determining who should be given the right to vote, which could then be made a sysop ability. I'd still set it rather low (like 100 edits total, 50 mainspace), so newbies could be quickly integrated, but high enough as to require some effort before users can get their sockpuppets to sysop rank. Röstigraben (talk) 06:39, 18 May 2011 (UTC)
(((Zack Martin)))™ 08:51, 18 May 2011 (UTC)
- The "rule" I used back in the day was if I felt no need to go check an edit unless I was curious what was being written, I'd sysop the user. That was my rule of thumb for "trusted/useful". It rather defies simple enumeration as a rule, but made sense and was easy to implement. But then, I was also here about 27/8 back then... ħuman
03:02, 19 May 2011 (UTC)
- Leave it at the new ruling class's discretion to demote - with the understanding that they'd need a decent reason not to. i.e. no point in demoting someone who racks up the time and edits, yet is acting the arse. Concernedresident omg!!! ponies!!! 16:05, 22 May 2011 (UTC)
- I must say, though, that the sooner sysops lose the power to make sysops, the better IMO. I think giving sysops that much power permanently will only cause much greater problems than we have now. The Punk Symphony of Noise Your mental puke relief 09:09, 7 June 2011 (UTC)
Patrolling edits[edit]
This features has always seemed to me much more user-unfriendly than it is useful. Could we just drop it? Ŵêâŝêîôîď
Methinks it is a Weasel 20:22, 19 May 2011 (UTC)
- +1 - David Gerard (talk) 20:22, 19 May 2011 (UTC)
- I dunno, I always thought I was being user-friendly when I marked an edit "patrolled", or further edited the article. ħuman
05:08, 22 May 2011 (UTC)
- Human is useful. I like having the patrol thing running as a prompt to keep an eye on the edits of newbies and BoNs. Those red exclamations are pretty eye-catching and purdy. Concernedresident omg!!! ponies!!! 16:07, 22 May 2011 (UTC)
- Maybe we could just have a probationary period. Should the wiki grow further, there may come a time where looking for red exclamation points is the only way to spot noobs.--"Shut up, Brx." 16:11, 22 May 2011 (UTC)
- Sometimes even without the red marks we can tell who they are... ħuman
09:24, 7 June 2011 (UTC)
- If autoconfirmed users were automatically patrolled it wouldn't be so bad, but since the mass desysoping there are veteran users showing up red in RC. Also the fact that if you re-edit or revert a noob's comment, you still have to patrol it to make the red ! disappear is pretty annoying. Wẽãšẽĩõĩď
Methinks it is a Weasel 12:47, 7 June 2011 (UTC)
Tech[edit]
Given out to people that have a reason and a need for the tools it provides. Basically the ability to edit any of the site wide scripts or settings, as well as MW namespace, big delete, and interwiki tables.
Because of the potential security issues this invokes tech users will need to request this user right from mods or other tech users and give reasons why they need it, what their plans are, etc.
There is no authority for community or content management with this user right. Its purely a nuts and bolts thing.
Feedback on tech[edit]
So only Techs can edit the MW stuff? We have made this place so much cooler by everybody (as far as I know, I usually had a gold badge) being able to customize the MW things. ħuman
04:23, 18 May 2011 (UTC)
- I think that this user group is a good idea. Especially since people who edit the MediaWiki space and make changes to the Wiki itself should be held to a high level of trust here. Lord Goonie Hooray! I'm helping! 15:14, 18 May 2011 (UTC)
- The MW things haven't changed in a very long time, they are customized, and if someone wants to add or change something and they are not in the tech group there is the talk page. Tmtoulouse (talk) 15:18, 18 May 2011 (UTC)
- Yeah, tech guys is a good idea.--Colonel Sanders (talk) 17:26, 18 May 2011 (UTC)
- Fine as long as they're using their abilities for things the site/community needs or wants them to do & not just following personal whims. Would techies also be eligible for sysop &/or Mod positions, or is it an either/or deal? ₩€₳$€£ΘĪÐ
Methinks it is a Weasel 19:36, 18 May 2011 (UTC)
- Maybe I misunderstood what this meant. As some know, there is a huge list of MW default pages or templates or whatever they are - like the text used for the bar across the top ("fossil record"). I guess Trent didn't mean that stuff? He meant the extensions, the custom stuff? If so I stand corrected. ħuman
05:02, 22 May 2011 (UTC)
- When RW moved to Trent's home, Jeeves used some js hackery to take over several other accounts on the old server. So before giving someone the ability to edit MW space, think about that. -- Nx / talk 05:13, 22 May 2011 (UTC)
I would also add, regarding "there is always the talk page", that 2 out of 3 people with the tech group currently hate me with a burning passion. That's a bit intimidating. ħuman
05:05, 22 May 2011 (UTC)
- I would also add... and what if they just do what they want based on wiki-politics? Are they accountable in any way? ħuman
05:10, 22 May 2011 (UTC)
- Which two? -- Nx / talk 05:13, 22 May 2011 (UTC)
- You and somebody else. You have trying to drive me off the wiki for almost eight months now. It might not be intentional on your part, of course, it could be a language issue. ħuman
02:30, 23 May 2011 (UTC)
- Wait, I thought this wasn't yet implemented. Who has the tech group? Uke Blue 03:51, 23 May 2011 (UTC)
- It's just Human's paranoia. Apparently he still thinks that Pi has access to the server. -- Nx / talk 04:00, 23 May 2011 (UTC)
- I keep forgetting that, yes. There are two, and one hates me with an ignorant passion. And abuses their access any time they feel like it. ħuman
04:30, 25 May 2011 (UTC)
- Oh, for Pete's sake. Human, in the unlikely event that Nx acts maliciously with the server, I suspect that at least one of the other editors would lodge a complaint with the Board of Trustees.
ListenerXTalkerX 04:53, 25 May 2011 (UTC)
- It's not unlikely; it happens all the time. Wasn't it only a couple of days ago we had checkuser installed without warning? & Users should be accountable to the community, not the Board. See my suggestion below. Wẽãšẽĩõĩď
Methinks it is a Weasel 06:20, 25 May 2011 (UTC)
- I do not think Nx did that with malicious intent.
ListenerXTalkerX 06:28, 25 May 2011 (UTC)
- Malicious intent is not the only reason to hold techs responsible... they should ensure that all their server access is used responsibly. (I could care less for their wiki edits, but they shouldn't abuse their server access to delete everyone's user rights, or install CheckUser, just because they can.) --Eira OMTG! The Goat be Praised. 06:33, 25 May 2011 (UTC)
- Whether it was done maliciously, for a joke, to prove a point or just to show off is immaterial; whatever the motive, it was an unjustified use of server access to unilaterally dictate site policy & practice, which is a gross assumption of authority. It's hardly the first time we've seen this, but it would be nice if it was the last. Site users of all user rights levels should be help accountable to the community. Wėąṣėḷőįď
Methinks it is a Weasel 12:27, 25 May 2011 (UTC)
- What a joke. At best if someone does something really bad, we have a huge HCM and maybe they get a slap on the wrist and they promise not to do it again. And then we go on our merry way like nothing happened. Hell, Human hates me and he wants to convince the board to remove my server access and yet I still have it. I even got away with installing checkuser. -- Nx / talk 07:05, 26 May 2011 (UTC)
- I don't hate you, I am sick of you. There's a difference. Who leaked private Board discussions to you? And the Checkuser thing has yet to be dealt with. ħuman
08:06, 26 May 2011 (UTC)
- No one leaked private discussions to me, you said it yourself. Hey, maybe you can convince the board to remove Trent's access as well, since he's also using it for political ends, and then give you access to the server, so you can finally run this cesspit the way you like. -- Nx / talk 08:29, 26 May 2011 (UTC)
Accountability of tech users[edit]
Tech users should be accountable to the community (like all other admins). Aside from routine maintenance and emergency fixes, anything they do should have been discussed first. Using their abilities to do anything controversial at the site without appropriate prior discussion should be regarded as an abuse of privileges & dealt with as such (i.e. at the Chicken Coop or equivalent). ωεαşεζøίɗ
Methinks it is a Weasel 12:51, 24 May 2011 (UTC)
- As the techs have server access, they will need to answer to the Board, since the Foundation maintains the server. Having their actions approved by the community can be a separate process.
ListenerXTalkerX 06:28, 25 May 2011 (UTC)
Moderators[edit]
This is the big one, the new one. This will be a set number of individuals elected by the users following the guidelines set forth on board elections. Let’s say 7 people. They are empowered as ‘’individuals’’ to act to prevent or stop disruptive activities on the wiki. We have a set of rules/guildlines in place that can be used and followed. But I don’t want to create a complex script or algorithm for the mods. Instead the goal would be to elect clear minded people who we trust to make the right decisions as individuals on issues that can’t be addressed by the “mob”.
Moderators should see themselves as what the name implies: moderators of dispute. The first step should be conversation, and trying to encourage people to calm down or refocus their energies. If action needs to be taken beyond that it should be all about the minimal action needed to resolve the situation. Perhaps a 2 hour block, or just a 2 hour page protection.
Other issues moderators might be called upon to deal with are posting of personal information, or libelous statements. Moderators are empowered by the community, and answerable to that community. There will be an election, and a term of position, let’s say 6 months. If a moderator is seriously abusing the position the other moderators can act to remove the rights. An impeachment procedure could be useful to draft up but I don’t think it’s something we have to prioritize.
Basic common sense should apply, moderators should not act as moderators in disputes they are involved in, keep actions to a minimum, talk first, act as a last resort, etc. Hopefully we won’t have a need to use the tools very often, most of our issues are far and few between and become only a major hassle because we have to start up the argument about how we don’t have a way to deal with it.
Feedback on moderators[edit]
"When you do things right, people won't be sure you've done anything at all." 00:48, 19 May 2011 (UTC) C®ackeЯ
Revision delete[edit]
Is probably the one key tool that must be used in a timely fashion - removing personal information, say, from the bar or twigoCP. If delayed, it is much harder and messier, and also more embarrassing. Having "just a few" people with this might be an issue. I estimate it takes about 20 or so users to adequately keep an eye on the wiki 24/7. JMHO. ħuman
04:22, 18 May 2011 (UTC)
- Seven is far too few for this. ħuman
04:22, 18 May 2011 (UTC)
- Also, regarding rarely-used "powers" like this, we should have a "crat school" (or will it be "mod school"? Secondary Modern?) where they practice what to do in a pinch? ħuman
07:19, 18 May 2011 (UTC)
- I re-assert my original (before all the shit was mascerated) proposal of 12 'crats. Lily Inspirate me. 09:24, 18 May 2011 (UTC)
- Crats are gone, no more, their is very little the mods need to do that requires action right this second. We need quality over quantity here. If we set this number too high their might not even be enough volunteers to fill all the spots, and if we don't allow the site to vote and select amongst volunteers they won't have the moral authority or we might wind up with individuals that shouldn't have the job and have it only because they volunteered when others didn't. Tmtoulouse (talk) 15:20, 18 May 2011 (UTC)
- A problem with a having a small fixed number of Mods is that, once elected to the position, most Mods will probably want to stay in it & the community will probably be happy to keep them in office, barring any cases of abuse. So it will become an oligarchy of sorts, while new editors will have very slim chances of ever achieving the position of Moderator. I think it would be better for all volunteers who receive more than a threshold number of votes to be elected as Mods rather than keeping a fixed number of positions to fill. & If we end up with 20-odd Mods, so what? I don't see why that would be a problem. Wèàšèìòìď
Methinks it is a Weasel 17:50, 18 May 2011 (UTC)
-
- But if moderators have to moderate disputes, then having too many just re-created HCM. Imagine a Supreme Court of 55 people. I think your points are good, however, and that there is a legitimate concern that moderators would become an entrenched cabal. Maybe they could be elected to a one year term, and then not stand for election again for another year, or something like that? (Just sort of thinking out loud here.) DickTurpis (talk) 17:56, 18 May 2011 (UTC)
- Human's points about the timeliness of revisiondelete are excellent. Revisiondelete is best suited for sysops. Occasionaluse (talk) 19:21, 18 May 2011 (UTC)
-
- For moderators, the most important quality would be their ability to resolve disputes. Not just "not cause them" - which would apparently already exceed the old cratship criteria - but actual competence in stopping editors from ripping each other apart. If there were 20 people like that here, the latest HCM wouldn't have happened in the first place. i'd go with a smaller number, but it doesn't have to be a fixed one either: over at the old crat election page, there were some suggestions on how to make their number proportional to that of active editors, so the administration could grow with the community. Röstigraben (talk) 19:29, 18 May 2011 (UTC)
- Perhaps we could do with a pool of mods, say 25: 11 being needed to "adjudicate" any one issue, done on a first come-first (to) serve basis, if more than 14 demur the case is placed on hold until the 11 can mustered. 20:20, 18 May 2011 (UTC) C®ackeЯ
- One way to think about it is if you have 12 moderators, they "ought" to be on the wiki 2 hours a day, but only if you need them constantly. I also think that you could have ad hoc groups to mediate conflicts: you don't need all 55 of a time. Although, I suppose there are potential problems with factionalism. steriletalk 00:58, 19 May 2011 (UTC)
- It's hard keeping up with all the proposals and potential change ideas, but if RD is handled at the non-mod level, then a small number of mods is fine with me. As Rosty said, if we had 20 people good at this, the place would be much smilier. I see the mod "job" as similar to the trustee one - activity is not necessary, but 100% commitment to turn up for the job when called is. ħuman
02:58, 19 May 2011 (UTC)
- That's the way I was thinking about it... what could really be so serious that we need to ensure that there is a mod here 24/7? With a lot of sysops most problems can be cut off super fast. The mods are supposed to be there to handle things that sysops can't handle (because the sysops might be the problem). --Eira OMTG! The Goat be Praised. 03:56, 19 May 2011 (UTC)
- KISS, 3 mods, with 2 alternates in case of an incapacity. 2 may act by unanimous consent in case of incapacity of 3 others. If 4 are incapacited, special elections called. If need for more, add them later. Most important responsibility is on the voters to elect a balance of views and temperment, else what's the purpose of a committe of clones rubberstamping each views? nobsViva la Revolución! 22:05, 7 June 2011 (UTC)
Moderator suggestion[edit]
I entirely support Trent's ideas. Any reduction in bureaucracy is an excellent idea, and a reduction in number of titles - and their perceived importance - is overdue. Re. the Mods, why not email a Mod if they haven't made an edit in more than, say, three months and ask them if they want to continue to be a Mod. If yes, they stay, if no, go to a pool of editors who have been regular editors for at least the previous year for candidates and let just the existing Mods vote someone new in. There's no risk that Mods will become a set-in-stone cabal - we've lost so many senior members over the years - and there's only been four years. In internet time, that's an Ice Age. Please, just do something, ANYTHING to stop the laughable bureaucracy creation - it's hideously embarrassing and utterly pathetic. DogP (talk) 01:38, 19 May 2011 (UTC)
- I agree. The mods need to be active; not just someone who gets a title, swans off for a while and then returns expecting to continue with their same position.
ГенгисIs the Pope a Catholic? 23:13, 21 May 2011 (UTC)
Moderator elections[edit]
Will we be able to vote against users as well as for them, as we've done with bureaucrat elections, or just vote in favour of users, like with the LJ & RWF board elections? I think we should should be able to vote against users if we want to, since it's pretty obvious that many users have strong views about who they don't want in office as well as who they do. Wēāŝēīōīď
Methinks it is a Weasel 07:15, 20 May 2011 (UTC)
- That is both an excellent and terrible idea. I support it. TrickyDickTurpis (talk) 14:50, 20 May 2011 (UTC)
- Yeah, makes sense. We should at a minimum have open discussions on pros and cons as part of the process - even if not literal for and against voting. Concernedresident omg!!! ponies!!!
Abolish Chicken Coop[edit]
Chicken coop doesn't help, it just makes things worse.
Suggest to replace it with the following structure:
- The complaintant approaches the Moderators collectively, to ask them to appoint a Moderator (uninvolved in the original dispute)
- The assigned Moderator attempts to mediate privately between the parties
- If mediation fails, then a public dispute resolution process can follow
- Moderators can collectively make a binding decision at end of public process (similar to WP ArbCom process)
Hopefully, by requiring private mediation before public disputation, the temperature will go down rather than up. (((Zack Martin)))™ 13:11, 19 May 2011 (UTC)
- I agree!--Colonel Sanders (talk) 13:38, 19 May 2011 (UTC)
- Private mediation first is a very good idea. Then we don't have to get everyone and their mothers involved with every petty squabble. --Eira OMTG! The Goat be Praised. 14:14, 19 May 2011 (UTC)
- Moderators would seem to make the concept of the Chicken Coup redundant.--BobSpring is sprung! 15:07, 19 May 2011 (UTC)
- I don't think so. As I raised further up the page, I don't think Mods should have authority to make executive decisions about the site or users. They should just have the abilities to use when required. Decisions, including on conflicts or cases of abuse, should still be made by the community. Weaseloid
Methinks it is a Weasel 19:07, 19 May 2011 (UTC)
Moving forward with step 1[edit]
Step one will consist of nuking the crat position, restructuring the sysops position as documented and creation of the tech user group. Other random user groups like irrational number will also be nuked. I still haven't decided the best way to deal with "ninja" whether keeping it the same or some other option. The status quo can continue on that for now.
I will also create the mod positions with corresponding rights but wont add anyone to it. We can then move forward with the getting the specifics of the mod group finalized and setting up elections. Tmtoulouse (talk) 01:09, 20 May 2011 (UTC)
- I like the Ninja user group, because it allows people to bot themselves and thus perform category work without spamming RC if you have bot work disabled. Perhaps giving it a different name like "Botable" or something more clear like that would be a good idea. This argument is based on the way Blue worked... for a long time she had crat just so she could bot/debot herself... seems like a more or less pointless waste of passing a lot of wiki rights for a narrow scope. --Eira OMTG! The Goat be Praised. 01:15, 20 May 2011 (UTC)
- Some people have a separate account which has bot status, and they use that for the boring stuff. the main drawback I see is having to log in and out, unless they have two browsers. Real first name and last initialTalk, talk, talk skim my contributions 13:23, 20 May 2011 (UTC)
- Logging in and out isn't that big a deal. If you are doing work requiring a bot status, you are used to tedium. Aboriginal Noise What the hell is that thing? 13:29, 20 May 2011 (UTC)
- what I mean is if you have to log in and out, you might as well get ninja rights, it's probably just as many clicks. Real first name and last initialTalk, talk, talk skim my contributions 13:31, 20 May 2011 (UTC)
- Ninja works better IMHO. ТyTalk. 15:09, 20 May 2011 (UTC)
-
- Having a ninja bit also isn't that big of a deal. If you're the type of tedious bastard who does bot work, we should make it as easy for you as possible. Occasionaluse (talk) 15:18, 20 May 2011 (UTC)
- There are a few other tedious bastards like me here. ТyTalk. 15:20, 20 May 2011 (UTC)
- Perhaps we name it "BotWorker" then to get rid of the "coolness" factor in the word Ninja? So that people aren't scrambling to get it, just because they think it would have to be cool? (Why else would they name it something cool like "Ninja"?) --Eira OMTG! The Goat be Praised. 16:20, 20 May 2011 (UTC)
For us ignorant ones, what does the ninja group do again? TrickyDickTurpis (talk) 15:57, 20 May 2011 (UTC)
- Allows people to "bot themselves". Occasionaluse (talk) 15:58, 20 May 2011 (UTC)
- Kinky! TrickyDickTurpis (talk) 16:12, 20 May 2011 (UTC)
- Installing checkuser for mods too? If your going to do fascism, may as well do it properly. Nightwish (talk) 16:37, 20 May 2011 (UTC)
As you have laid out here, Trent, I support implementation. We do need to sort out the authority of and procedure surrounding the moderators, though. Uke Blue 03:50, 23 May 2011 (UTC)
Dispute resolution[edit]
As there is some ambiguity re the authority of the new Moderators, and some users are suggesting that we abolish the Chicken Coop & let Mods make all decisions about abuse/conflict/trolling, which I do not find very mobocratic, I suggest we agree now on how these cases should be resolved. My own suggestion is:
- If necessary, a Moderator should take emergency action to defuse or contain the situation. This may mean temporarily blocking a user or users, locking a page, or removing a user's Sysop or Moderator rights. It should only be done if the situation demands it, e.g. deletion sprees, mass blocking, wheel warring, etc.
- The case should be brought before the Chicken coop & everyone given a chance to comment, including any involved or accused parties (hence why any block at this stage should be short-term only).
- If the community agrees that long-term action should be taken - e.g. a lengthy block or removal of admin abilities - a Moderator should take the necessary action.
-.
- In all other areas of decision-making (e.g. article content disputes, site policy discussions, etc.) Moderators should have no more authority than any other member of the community.
Feedback & alternative suggestions welcome. Ŵêâŝêîôîď
Methinks it is a Weasel 16:58, 22 May 2011 (UTC)
- What is this "community" you talk of? It must be something nazist since it is supposed to be in "agreement". --85.78.24.238 (talk) 17:06, 22 May 2011 (UTC)
- And if we take these suggestions, we don't actually solve the problem of issues being public, and everyone putting in their two cents. I mean, if we want to keep solving our problems by invoking shit storms, then sure... why not. But that's kind of the reason that all those people LANCB... --Eira OMTG! The Goat be Praised. 00:43, 23 May 2011 (UTC)
- I agree. --85.78.55.247 (talk) 01:00, 23 May 2011 (UTC)
- The site is a mobocracy. That means issues being public and everyone putting in their two cents, so I don't see that as a problem that needs solving. Most of those people who left have already come back, & I see no reason why less people would LANCB if decisions were imposed from above; if anything, it would be more likely to cause resentments. Wëäŝëïöïď
Methinks it is a Weasel 00:56, 23 May 2011 (UTC)
- I know what this site has been, and I like it operating as such. But some people have gotten seriously abusive over things, and it happens in every single goatdamn coop. You literally cannot stand up any assert any position without someone abusively attack you. Thus, as long as people assert that members of the board of trustees have to be above all this bullshit, leaves board members with one and only one solution: don't be active on this wiki at all. --Eira OMTG! The Goat be Praised. 01:22, 23 May 2011 (UTC)
- I am every other poster in this thread, thus representing a majority opinion of the wiki. --85.78.55.247 (talk) 01:00, 23 May 2011 (UTC)
- This is always how it's worked:
- Step 1: Dispute is brought to the community
- Step 2: Everyone adds their 2 cents
- Step 3: ?????
- Step 4: RESOLUTION!
- That's how I see it. TrickyDickTurpis (talk) 01:05, 23 May 2011 (UTC)
- Well... as long as you remove Step 4 from that list, yes, that is exactly how everything has been going... --Eira OMTG! The Goat be Praised. 01:23, 23 May 2011 (UTC)
." I agree with this in terms of language, but probably not in spirit. The trouble is that there is nobody to determine what a "deadlock" might look like, to say "Now we should transfer this case to the moderators." To say "use common sense" is pointless, because most of our trouble has been helped by people having very different definitions of "common sense." Who would decide when to bring in this panel of moderators, Weaseloid? Would their decision mean anything if they can't legitimately take over a case? Seme Blue 03:43, 23 May 2011 (UTC)
- Personally, I think that if a dispute goes to the coop, onlky the moderators should be allowed to vote on the outcome. Everyone should be able to make their case, and say what they like, but ultimately, only a select group of people should have the final say. Of course if the dispute involves 1 or more of the moderators, they should recuse themselves for the period of the coop proceeding (although they would be able to present their arguments as they see fit). DamoHi 03:49, 23 May 2011 (UTC)
- I strongly agree. Uke Blue 04:57, 23 May 2011 (UTC)
- Sorry for jumping in without being part of it, but isn't the problem that everyone puts in their 2 cents or whatever?? How do you know when everyone has put that in and how do you know that their being paid attention too?? People end up with more say if their pessistant or loud about it so its not fair.
11:34, 23 May 2011 (UTC)
- Not really. Cf recent Coop cases. Being loud & persistent doesn't guarantee the support of the community. Ŵêâŝêîôîď
Methinks it is a Weasel 12:54, 24 May 2011 (UTC)
Dispute "moderation," moved from above[edit]
Beyond trolling and other disruptive behavior, how would these moderators be empowered to moderate disputes between users? Would they form a sort of arbitration committee and vote on guilt and/or penalties? Seme Blue 03:54, 23 May 2011 (UTC)
- They would need checkuser and could then block people and their IPs and their proxies. ħuman
02:36, 6 June 2011 (UTC)
Support Trent's proposal[edit]
- I support Trent's proposal to the letter.
- The fact that Trent had to take unilateral action on this illustrates, to my mind, the need for a regular procedure and system of voting to settle questions of changes to Wiki policy.
ListenerXTalkerX 05:30, 24 May 2011 (UTC)
- Let's get this going already. - π 11:44, 24 May 2011 (UTC)
- yeah why not
11:59, 24 May 2011 (UTC)
- Phase one is complete. (evil laugh) ТyTalk. 12:00, 24 May 2011 (UTC)
- Sounds good to me, though some details still need to be worked out. TrickyDickTurpis (talk) 12:02, 24 May 2011 (UTC)
- Aye. --Sid (talk) 12:32, 24 May 2011 (UTC)
- EddyP Great King! Disaster! 12:47, 24 May 2011 (UTC)
- I was convinced by MC larronsicut fur in nocte 12:56, 24 May 2011 (UTC)
- NDSP 13:36, 24 May 2011 (UTC)
- Are we already voting on this? If so, how about a two-step process: first vote on Trent's proposal versus the status quo, then discuss and vote on amendments along the lines of the suggestions above. That ought to satisfy both those who're tired of debates without conclusions and those who have specific objections. Röstigraben (talk) 18:34, 24 May 2011 (UTC)
- Trent seems to be saying that the mob is not voting on this, but commenting on it.
ListenerXTalkerX 18:38, 24 May 2011 (UTC)
- Then how will the final version be decided? Seems to me there's a general preference for reform with this as the baseline - so far so good, but there are also lots of open questions and comments that contradict each other, so there's no apparent consensus on specifics. Röstigraben (talk) 18:47, 24 May 2011 (UTC)
- We could start discussing the regular voting procedure I mentioned. If that could be put in place, there is a chance that we could hammer out the remaining specifics for ourselves without it being derailed by a bout of HCM. Another benefit is that it might obviate the need for Trent to take this kind of unilateral action again.
ListenerXTalkerX 18:55, 24 May 2011 (UTC)
- We could already hammer out the specifics without HCM. That's what this page is for & I don't see much HCM on it. Neither is there a pressing need for unilateral action until the boundaries of the proposed roles have been clearly drawn. At present there are more questions than answers on this page, & only a few editors have commented. It's too soon to implement. Wēāŝēīōīď
Methinks it is a Weasel 19:04, 24 May 2011 (UTC)
- Well, parts of it are already being implemented. And I can also understand those who are wary of neverending debates, although I'm not one of them. That's why I suggested a vote now to create the necessary legitimacy for any change to the ststus quo, and then take some time to discuss details and smaller changes. If those debates get nowhere, there's the original proposal to fall back on. It would also offer everyone a clear choice - if you're satisfied with the current system, vote nay now; if you want reform, vote yes; if you'd like some changes to Trent's proposal, vote on them afterwards. Röstigraben (talk) 19:20, 24 May 2011 (UTC)
- I am certainly not opposed to voting as a refelection of expressing community support or disapproval. I have sought community consensus and feedback as well as consensus and feedback from the RWF. It certainly helps legitimize the action as more than just my whim by fiat. At the moment I am focusing on the technical aspects of implementing the plan. Once the infrastructure is firmly in place we can hammer out some of the social and community details more firmly. Tmtoulouse (talk) 19:06, 24 May 2011 (UTC)
ListenerXTalkerX 19:14, 24 May 2011 (UTC)
- Kiss-arse Bondurant (talk) 19:16, 24 May 2011 (UTC)
- I see no changes based on input, the proposal is still exactly as you first typed it, grammatical errors and all. This is not the way to do this. But if it be done, then it be done. Server access = Complete Control. As we have seen with Nx' recent hijinks. ħuman
04:28, 25 May 2011 (UTC)
- As you yourself said above, "I see no alternate versions of the ideas here, despite various commentary besides 'it's perfect'." The suggestions that have appeared are more addenda to Trent's plan than alternatives to it.
ListenerXTalkerX 04:40, 25 May 2011 (UTC)
- And none of the suggestions seem to have been incorporated. So anyway, we are now going to try the "control from the top down" method of running the wiki? I'm sure trent is as curious as I am to how that will work out. ħuman
04:45, 25 May 2011 (UTC)
- Cats are dogs. --85.78.199.96 (talk) 06:48, 25 May 2011 (UTC)
I support Trent's plan wholeheartedly, although I'm done here anyway. I really can't be arsed to be part of a community that prefers rules over content. DogP (talk) 19:30, 24 May 2011 (UTC)
- I support the plan--"Shut up, Brx." 20:25, 24 May 2011 (UTC)
- Ahh, what the hell. --ǓḤṂ³ 22:22, 24 May 2011 (UTC)
- I don't have the whole history, but I'd like this community to get back to adding content. Having Trent put a basic structure in place looks good to stop the political bitching. We can discuss the modification we'd like later. dx (talk) 21:15, 25 May 2011 (UTC)
- --BobSpring is sprung! 21:28, 25 May 2011 (UTC)
- Aboriginal Noise What the hell is that thing? 22:47, 25 May 2011 (UTC)
- Most certainly, I support this proposal. The Punk Symphony of Noise Your mental puke relief 22:50, 25 May 2011 (UTC)
- Enough of this endless saga already. Also, ban users named after Conservapedia in-jokes. Real first name and last initialTalk, talk, talk skim my contributions 09:41, 26 May 2011 (UTC)
- I put my sig here, right? Seme Blue 16:10, 26 May 2011 (UTC)
- PACODOGwoof, bitches 16:13, 26 May 2011 (UTC)
- --OompaLoompa (talk) 16:21, 26 May 2011 (UTC)
- Voices in head say yes. Concernedresident omg!!! ponies!!! 08:38, 27 May 2011 (UTC)
- Aye.--Bertran (talk) 17:40, 2 June 2011 (UTC)
- Still think 7 Mods is too bureacratic who will either reinforce each others prejudices or deadlock by talking things to death, but it's a start. nobsViva la Revolución! 19:54, 17 June 2011 (UTC)
- It is worth a try although I would call the sysops, "bureaucrats", because they can promote/demote and this way newcomers would be like "Whoa, everybody gets to be bureaucrats here!?!?! I pledge allegiance to RatWiki, with liberty and justice for all." I'll have to see what actually happens before actually voting. ~ Lumenos (talk) 04:30, 20 December 2011 (UTC)
- Jesus Fucking Christ Lumenos, could you be any later to the party? We are about to have the second mod elections. - π
04:47, 20 December 2011 (UTC)
- It was Lumenos? Ah, I'd been wondering why this thread got bumped.
Radioactive afikomen Please ignore all my awful pre-2014 comments. 22:19, 25 December 2011 (UTC)
Reject Trent's proposal[edit]
- I have outlined my reasons for opposing his proposal on his talk page, for which he has not responded. I feel this will grant draconian powers to a new moderating class who will abuse their powers and will persecute all site dissidents who respectfully disagree with both the aims and the inherent hypocrisy of this website. Dissent should be valued and should not lead to accusations of trollery and blocking. MarcusCicero (talk) 11:49, 24 May 2011 (UTC)
- Idiot. Your fascist abuse of this site sickens me. Are you an aspie? Fascist. I shall write an essay on your abuse of the system. Idiot. Are you an aspie? Idiot. fascist. Idiot. Censorship. Pretentious waffle about ancient Rome. Idiot. Fascist. Are you an aspie? Idiot. I wrote a play about you which shows in a really bad light. Fascist. Look at me, I'm really intelligent and you're all idiots. Idiot. Fascist. Are you an aspie? I have started the Save RationalWiki From Fascist Censorship society, written in bad mock-intellectual English. — Unsigned, by: 213.1.33.1 / talk / contribs
- Are we voting here on the autocratic imposition that was never adapted to incorporate suggestions or answer critiques and has already been implemented by fiat? NAY. ħuman
02:35, 6 June 2011 (UTC)
Restoration of Sysops[edit]
Since Trent's proposal seems to be being implemented... and since it involves retaining "Sysops" much as it was before... does that mean the people who used to be Sysops will get their Sysop back? (((Zack Martin)))™ 10:37, 27 May 2011 (UTC)
- This is a good example of why sysop-ships shouldn't be handed out like candy. --OompaLoompa (talk) 11:00, 27 May 2011 (UTC)
- You've now got yours back, Maratrean. I doubt that anybody's going to go through the logs & resysop everybody who lost their rights, but if people ask for them back & there's no good reason not to, they might as well be a sysop again. Wėąṣėḷőįď
Methinks it is a Weasel 18:10, 27 May 2011 (UTC)
Any chance I could be demoted again? I feel the urge to block someone for 3.141 seconds. —Tom Morris (talk) 20:48, 11 July 2011 (UTC)
So what next?[edit]
The mob seems to have spoken, and with only 2 demurs the consensus is strongly in favor of this proposal. This seems pretty typical of RW. 1) someone proposes something, 2) most of the mob agrees, 3) nothing happens as everyone waits around for someone to actually do something. At times like this some sort of small hierarchy could come in handy; people who are authorized or obligated to put things into effect when they have been decided on. So, is this happening? TrickyDickTurpis (talk) 12:50, 6 June 2011 (UTC)
- 4) someone actually does something, and then a HCM breaks out because not everyone was asked/not everyone agreed to do this. -- Nx / talk 06:51, 7 June 2011 (UTC)
- The tech group seems to have been implemented, that's it. Anyone willing to kick-start this back into gear? ТyTalk. 12:52, 6 June 2011 (UTC)
- Trent seems to have taken point on this, so it seems to me it's kind of incumbent on him to get it rolling. If he doesn't want to, appointing someone else would be good. Generally in these sorts of cases it's legit for anyone to set up the proper pages and get the ball rolling, but this is sort of a delicate situation, and for any random editor to do it might seem presumptuous. TrickyDickTurpis (talk) 12:57, 6 June 2011 (UTC)
- Nobody wants to risk their neck. We still need to find out how many moderators there will be etc. Anybody got an expendable sock? ТyTalk. 13:01, 6 June 2011 (UTC)
- From what I can gather they seem to be looking into ways for mods to be able to block sysops without the sysop unblocking themselves in such a way that it doesn't require either a) a hack that would need to be redone on every update, or b) a patch that would require MediaWiki to actually respond to a request. I am given to understand that in the past major errors were pointed out by Nx to MediaWiki that were promptly ignored and still persist to this day. - π 13:12, 6 June 2011 (UTC)
- That seems to be a technical issue that doesn't warrant holding up everything else, especially since there are ways around that. At WP a sysop unblocking themselves is a big deal that gets them demoted permanently, I think. Also, a sysop could have their sysopness revoked for the duration of their block. As for the number of moderators, that's a good point. Someone should instigate a vote or whatever on that. TrickyDickTurpis (talk) 13:25, 6 June 2011 (UTC)
- But sysops can sysop and desysop other sysops here, won't be long before there is wheel-warring again. There seems to be a new mute group, might be something to do with it. - π 13:27, 6 June 2011 (UTC)
-
- i agree - seems to be too complex. If a sysop has screwed up and needs to be blocked, then demoting him for the duration of the block isn't going to hurt. It's not like he can edit anyway. By the way - who moderates the mods? --OompaLoompa (talk) 13:29, 6 June 2011 (UTC)
- I still think we can get around this without significant tech changes. For example, if a sysop gets blocked, promote him to user for the duration. Put a template on his userpage or whatever alerting the mob that this user is blocked and should not be demoted or unblocked for the duration. A link to the relevant discussion and decision would be a good idea as well. Anyone who demotes or unblocks gets reverted with a warning, and continuation results in that user getting the same treatment. Considering we have very few non-fun blocks of legit editors I doubt this will happen terribly often. TrickyDickTurpis (talk) 13:43, 6 June 2011 (UTC)
- There is always someone around here that will stickup for the "rights" of a vandal/troll/whatever, that will denounce the decisions as unfair/censorship/whatever and go ahead and ignore such a decision. Basically Trent/Nx want to take this out of the hands of everyone. As a rather loose analogy, imagine a prison for which everyone but the prisoners has key. How long do you think the prisoners would remain in that prison? - π 02:23, 7 June 2011 (UTC)
- IMHO, a simpler solution would be to just not give out sysopship like candy, but whatever. This is a disaster waiting to happen, especially since sysops can now demote as well as promote sysops. -- Nx / talk 06:50, 7 June 2011 (UTC)
- On the first point, I stand vindicated. On the second, I stand corrected. ħuman
09:06, 7 June 2011 (UTC)
- Well, that is the HCM this is meant to replace, and if some actual rules are put in place we may be able to keep that to a minimum. In the past people could do whatever they want because for all intents and purposes this site has had no rules, so anyone can make a somewhat fair claim that they haven't broken any. All one could do is try to enact some ex post facto ruling, which doesn't serve anyone's interest. Haphazardly made blocks could be haphazardly reversed. What I think we're looking to do is eliminate haphazard blocks made by any random sysop (i.e. anyone on this site), with the exception of blatant vandalism and fun blocks. Introducing due process would make blocks of established users rarer and more legitimate, as well as make claims of unfairness a bit more impotent. It seems to me blocks are rare as it is, so I'm not sure this will necessarily be such a problem. If someone goes around reversing blocks because they think blocking any user is fascism, regardless of the will of the community, that user can risk losing their ability to block and unblock as well. (Perhaps we could have a position that is the same as current sysop, but without blocking powers, which we could promote such troublesome users to?) At some point this site needs a few rules spelled out. "Everyone be nice" is a great concept, but no country has ever been able to write a constitution that concise. The site's gotten too big and there is too much disagreement for the old "let things work themselves out; we all get along pretty well here" concept that used to work for a while. Actual policies, specifically on blocking and promotion/demotion, are needed. Demotion to sysop is still a minor enough issue, and with bureaucrats gone and replaced by a set number of elected moderators we can hopefully solve the the latter issue, and due process should put to rest some fears of abusive blocking. That's my thought anyway. TrickyDickTurpis (talk) 03:12, 7 June 2011 (UTC)
- What specific due process are you talking about? & What actual policies & rules? I find it disappointing that people have been called on to vote aye or nay & now apparently to implement a plan that still has so many holes in it. It really makes this whole feedback exercise a waste of time. It wasn't waiting around for something to happen that killed discussion on this page; it was a premature vote that seems to have made people think this was an all or nothing deal & that a motion has been carried when actually very little has actually been decided. Weaseloid
Methinks it is a Weasel 06:52, 7 June 2011 (UTC)
- I agree. Almost everyone voted for the "feel good plan of daddy taking care of us" but no one read the swiss cheese of the fine print. ħuman
09:08, 7 June 2011 (UTC)
[edit]
- It doesn't seem to me this proposal is a final one - it's a bit brief for that - but rather a way to get a general idea as to whether this sort of idea is acceptable. There's no point in taking the time to write a detailed proposal if it's immediately clear everyone hates the entire concept. People seem to like this basic plan, so a few details should be worked out, and if those are also acceptable, then the plan should be put into action. No one likes tons of rules, so while this proposal should be expanded on before a final decision is made it should still be kept rather succinct.
- While Nx's proposal that sysops shouldn't be made in such a willy-nilly manner has merit, it seems to me that the community is not entirely in agreement on that. Even when people agree with Nx in principle, I see no support for a Wikipedia-style RFA or such. I believe we still want to keep rules to a minimum, so proposing new standards and rules for sysops might open up an unpleasant can of worms. The point has been made a few times that there's nothing a sysop can do that can't easily be undone, so there is little harm in the system as it currently is there. The exception is re-demotion of sysop who had their powers removed for violations of rules/standards, as Pi points out above. We should be able to deal with this without a huge shakeup in tech aspects and such. Or at least we can try. Since I don't suspect we'll see promotion being necessary too often, I don't forsee a big problem. We can always adjust later.
- Now, if I recall correctly, the primary catalyst for the current crisis was the controversy over Human and Blue taking away bureaucrat rights of other users, which is seen as a bigger deal than sysop rights. The general lack of guidelines for who gets to be a crat has always been problematical, and the latest shitstorm is a case in point. Removing crats entirely and replacing them with elected moderators solves this problem.
- The specifics of what moderators do and how many there will be is what really needs to be worked out. Trent describes the position as having "the authority and the tools to respond to situations that are disrupting the wiki", which I assume means deciding if a block or promotion is necessary, as well as serving as arbitrators for disputes between users and resolving edit wars. I'd certainly prefer if actions involving rights of others were decided by majority vote of moderators, and they are not given authority to decide such things unilaterally. Again, details to be worked out.
- The next quandary is community input for working out the specifics, now that the general idea has been deemed acceptable to the large majority (of those who showed any interest at all). This will likely involve 20,000 more comments by everybody and their uncle, all of which will have to be taken into account and out of this mess someone will have to extract something that can be close to being regarded as a general consensus. The fact that no one on the site currently has specific authority to do such a thing is why so much goes unresolved. That's something that needs fixing. TrickyDickTurpis (talk) 13:59, 7 June 2011 (UTC)
- The biggest issues re the new roles would seem to be authority, accountability, and due process. Personally, I don't support mods being arbitrators. Mods responding to situations that are getting out of hand by taking temporary measures is fair enough, but how a dispute is settled or a troublemaker is dealt with should still be a community decision. Wëäŝëïöïď
Methinks it is a Weasel 18:44, 7 June 2011 (UTC)
- Why? It's just as arbitrary. --85.78.194.49 (talk) 19:04, 7 June 2011 (UTC)
- Not really. The site only exists because of its community of editors, & decisions made collectively by as much of the community as possible are more likely to reflect the community's interests than decisions made by a few übermensch. Wèàšèìòìď
Methinks it is a Weasel 19:56, 7 June 2011 (UTC)
- But then what would stop the utterly massive HCM that happens when that laudable community happens to disagree vehemently within itself over disputes? Nothing. And the fight would escalate like it did just a few weeks ago, because there is literally nothing with the power to actually make a legitimate decision. Yes, everyone should be able to put their two cents in for Coop cases and the like. But we'll have not actually achieved any progress if there ends up being no arbitration body smaller than the mob at large, because HCM and general dysfunction will continue to proliferate. Seme Blue 21:14, 7 June 2011 (UTC)
- The point has been made a few times that there's nothing a sysop can do that can't easily be undone That was before sysops could promote and demote sysops. A vandal could remove everyone's sysop rights if they're fast enough, and then we'd have to wait for a moderator or a tech to fix it. -- Nx / talk 19:18, 7 June 2011 (UTC)
- That's the funniest thing I've read on RW for a long time. Does that make you and Armodikov vandals for doing exactly that? ħuman
04:01, 8 June 2011 (UTC)
-
- Nx, sysops can only promote. Not demote. RWisms aside (also, pl0x bot ninja me, thank you)--"Shut up, Brx." 04:05, 8 June 2011 (UTC)
- No bricks, it's been changed. Sysops can now make sysops and unmake them. It's a brave new world! ħuman
05:23, 8 June 2011 (UTC)
- that just seems like a dumb idea.--"Shut up, Brx." 05:56, 8 June 2011 (UTC)
- Why? Tmtoulouse (talk) 06:08, 8 June 2011 (UTC)
- Because it enables gratuitous rights wars, although the moderator class could stem that (is that what stem means? Apart from a bit of plant).--"Shut up, Brx." 06:16, 8 June 2011 (UTC)
- Dunno where this myth of sysops only being able to make & not unmake other sysops comes from, when it says clearly at the top of this page that sysops "can make and remove sysops rights". Ŵêâŝêîôîď
Methinks it is a Weasel 07:21, 8 June 2011 (UTC)
- That's a good point. Is this sysop demotional power a permanent thing, or is it still in trial mode? I personally don't have a problem with being slightly more discriminating than the "everybody's a sysop" thing, but I don't think anyone wants an onerous procedure for demotion, particularly when we tend to pride ourselves on granting these powers liberally. Trying to change the sysop policy in any way is going to create another huge discussion which will likely sidetrack everything else, and will still probably not lead to any clear decision. Which brings me to Weaseloid's comment about community decisions. I agree in principle, but a group of 100+ editors is unlikely to reach a decision; in most discussions there is going to be a diversity of opinions, and trying to sort them out into a rough consensus isn't always going to be easy. Even in the best scenarios, someone still needs to "certify" the result and implement it, and it's better if that person is seen to have some sort of authority, and not just the first person to come along and say "I'm calling this one for Editor-X". This will be more important in cases wherein there is no clear decision by the community, and calls have to be made on sockpuppets, disingenuous votes or comments, or just working out a compromise between 3 or 4 different, somewhat evenly split results. Too often we have a range of opinions/comments by diverse users and in the end, after everyone's commented, people look around and basically say "OK, um, now what?" There should be someone authorized to take the next step. I see moderators filling that role. TrickyDickTurpis (talk) 20:16, 7 June 2011 (UTC)
- I have no problem with the idea of working out more structured process for dispute resolution or with moderators officiating it in some way e.g. "certifying" the outcome of a vote or discussion & putting it into action, but don't like the idea proposed by some that it should be mods alone voting on disputes & coop cases. That seems overly hierarchical. Wẽãšẽĩõĩď
Methinks it is a Weasel 20:30, 7 June 2011 (UTC)
- You're not exactly harmless either...I wonder what we should do with you? Occasionaluse (talk) 20:01, 7 June 2011 (UTC)
-
- Moderate him? --85.78.158.55 (talk) 20:20, 7 June 2011 (UTC)
- I know. People like Nx need to be reminded of "no perfect solution" fallacies, just like all techies. Occasionaluse (talk) 20:38, 7 June 2011 (UTC)
Working out details[edit]
I think we're getting somewhere here, and it seems it's time for us as a community to try to work out details. 3 of the biggest issues as I see them are:
- Ability of sysops to demote/promote sysops, and the possibility of abuse
- The specifics of the roles of moderators
- How many moderators there will be
The final question is probably the easiest to address, as there's been relevant polls elsewhere, so perhaps that should be addressed first (although it might make more sense to address specifically what they'll do before we settle on a number, it would also be nice to get something settled for once; we have a general idea of what they'll be doing anyway). A recent poll on Bureaucrats (which moderators will effectively replace) showed 7 to be the clear frontrunner. How about a further poll with 3 choices: 7, more than 7, less than 7? If the mores or the lesses win then we have further discussion/polling to pinpoint an exact number. What do people think? TrickyDickTurpis (talk) 12:55, 8 June 2011 (UTC)
- Just noticed Forum:Moderators, which is a discussion of some of these very issues. So we can ignore this section for now, and instead use it as a plug for Forum:Moderators. So go to Forum:Moderators for discussion. TrickyDickTurpis (talk) 15:32, 8 June 2011 (UTC) | https://rationalwiki.org/wiki/Forum:Plan_of_action_for_user_rights_and_moderation | CC-MAIN-2019-30 | refinedweb | 12,753 | 69.52 |
#include <CGAL/interpolation_functions.h>
CGAL::cpp98::unary_function< Map::key_type, std::pair< Map::mapped_type, bool > >.
The struct
Data_access implements a functor that allows to retrieve data from an associative container.
The functor keeps a reference to the container. Given an instance of the container's key type, it returns a pair of the container's value type and a Boolean indicating whether the retrieval was successful.
This class can be used to provide the values and gradients of the interpolation functions.
Parameters
The class
Data_access has the container type
Map as template parameter.
If there is an entry for
p in the container
map, then the pair of
map.find(p) and
true is returned.
Otherwise, the Boolean value of the pair is
false. | https://doc.cgal.org/latest/Interpolation/structCGAL_1_1Data__access.html | CC-MAIN-2021-49 | refinedweb | 123 | 50.43 |
Recent changes to bugs missed in finally block2004-02-29T21:34:36Z2004-02-29T21:34:36ZBrett Favre<div class="markdown_content"><p>I'm using Gretel to build a nice test-coverage report<br /> on my unit<br /> tests. It would be nice to get 100% test-coverage so<br /> that I can<br /> show that every line of the code get's executed. Some<br /> part of my<br /> code has a finally statement in it, like this simple<br /> example:</p> <p>01 package example;<br /> 02<br /> 03 public class FinallyExample {<br /> 04 public static void main(String args[]) {<br /> 05 int i=10;<br /> 06 try {<br /> 07 i++;<br /> 08 } finally {<br /> 09 System.out.println("i is "+i);<br /> 10 }<br /> 11 System.out.println("end.");<br /> 12 }<br /> 13 }</p> <p>When I run this code, the line 9 is always marked as<br /> "mixed".<br /> The percentage of complete test-coverage never get's 100%.</p> <p>Can I get 100% coverage in code with finally statements? </p></div> | https://sourceforge.net/p/gretel/bugs/feed.atom | CC-MAIN-2018-05 | refinedweb | 176 | 52.8 |
isation of exceptions is a natural outcome of the class hierarchy. Java
exceptions must be instances of Throwable or any Throwable descendant. As for.
InvalidIndexException, ElementTypeException, and NoSuchElementException
are all leaf classes.
Each one represents a specific type of error that can occur when
manipulating an array. One way a method can catch exceptions is to catch only those that
are instances of a leaf class. For example, an exception handler that handles only invalid
index exceptions has a catch statement like this:
catch (InvalidIndexException e) {
. . .
}
ArrayException is a node class and represents any error that can occur when
manipulating an array object, including those errors specifically represented by one of its
subclasses. A method can catch an exception based on its group or general type by specifying
any of the exception's superclasses in the catch statement.
For example, to catch all
array exceptions regardless of their specific type, an exception handler would specify an
ArrayException argument:
catch (ArrayException e) {
. . .
}
This handler would catch all array exceptions including InvalidIndexException,
ElementTypeException, and NoSuchElementException. You can find out precisely which
type of exception occurred by querying the exception handler parameter e. You could even set
up an exception handler that handles any Exception with this handler:
catch (Exception e) {
. . .
}
Exception handlers that are too general, such as the one shown here, can make your
code more error prone by catching and handling exceptions that you didn't anticipate and
therefore are not correctly handled within the handler. We don't recommend writing general
exception handlers as a rule.
As you've seen, you can create groups of exceptions and handle exceptions in a general
fashion, or you can use the specific exception type to differentiate exceptions and handle
exceptions in an exact fashion.
The following error message is one of two similar error messages you will see if you try
to compile the class InputFile, because the InputFile class contains calls to methods that
throw exceptions when an error occurs:
InputFile.java:8: Warning: Exception java.io.FileNotFoundException
must be caught, or it must be declared in throws clause of this
method.
in = new FileReader(filename);
The Java language requires that methods either catch or specify all checked exceptions
that can be thrown within the scope of that method. If the compiler detects a method, such as
those in InputFile, that doesn't meet this requirement, it issues an error message like the
one shown above and refuses to compile the program.
Let's look at InputFile in more detail and see what's going on.
The InputFile class wraps a FileReader and provides a method, getWord, for reading
a word from the current position in the reader.
// Note: This class won't compile by design!
import java.io.*;
public class InputFile {
private FileReader in;
public InputFile(String filename) {
in = new FileReader(filename);
}
public String getWord() {
int c;
StringBuffer buf = new StringBuffer();
do {
c = in.read();
if (Character.isWhitespace((char)c))
return buf.toString();
else
buf.append((char)c);
} while (c != -1);
return buf.toString();
}
}
The compiler prints the first error message because of the bold line in the above code
listing. The bold line creates a new FileReader object and uses it to open a file whose name
is passed into the FileReader constructor.
So what should the FileReader do if the named file does not exist on the file system?
Well, that depends on what the program using the FileReader wants to do. The implementers
of FileReader have no idea what the InputFile class wants to do if the file does not exist.
Should the FileReader kill the program? Should it try an alternate filename? Should it just
create a file of the indicated name?
There's no possible way the FileReader implementers
could choose a solution that would suit every user of FileReader. So, they punted, or rather,
threw, an exception. If the file named in the argument to the FileReader constructor does
not exist on the file system, the constructor throws a java.io.FileNotFoundException. By
throwing an exception, FileReader allows the calling method to handle the error in whatever
way is most appropriate for it.
As you can see from the code, the InputFile class completely ignores the fact that
the FileReader constructor can throw an exception. However, as stated previously, the Java
language requires that a method either catch or specify all checked exceptions that can be
thrown within the scope of that method. Because the InputFile class does neither, the
compiler refuses to compile the program and prints an error message.
In addition to the first error message shown above, you also see the following similar
error message when you compile the InputFile class:
InputFile.java:15: Warning: Exception java.io.IOException must be
caught, or it must be declared in throws clause of this method.
while ((c = in.read()) != -1) {
The InputFile class's getWord method reads from the FileReader that was opened
in InputFile's constructor. The FileReader read method throws a java.io.IOException
if for some reason it can't read from the file. Again, the InputFile class makes no attempt to
catch or specify this exception. Thus you see the second error message.
At this point, you have two options. You can either arrange to catch the exceptions
within the appropriate methods in the InputFile class, or the InputFile methods can "duck"
and allow other methods further up the call stack to catch them. Either way, the InputFile
methods must do something, either catch or specify the exceptions, before the InputFile
class can be compiled. For the diligent, there's a class, InputFileDeclared, that fixes the
bugs in InputFile by specifying the exceptions.
RSS feed Java FAQ News | http://javafaq.nu/java-article1184.html | CC-MAIN-2017-43 | refinedweb | 949 | 55.54 |
Search the Community
Showing results for tags 'roguelike'..!
- Hey guys! I am coding simple roguelike dungeon crawler: Live version. I have this issue with collisions, whenever a player is positioned like this: ( the lighter tiles are floor tiles and the darker walls obviously ) When he presses down arrow and left arrow at once, he can move on wall tile. This is how I handle input: onKeyDown( event ){ switch ( event.key ){ case 'ArrowUp': this.nextStep( 0, -1 ); break; case 'ArrowDown': this.nextStep( 0, 1 ); break; case 'ArrowLeft': this.nextStep( -1, 0 ); break; case 'ArrowRight': this.nextStep( 1, 0 ); } } nextStep( playerDirectionX, playerDirectionY ){ if ( !this.canMove( this.player, playerDirectionX, playerDirectionY ) ){ return; } this.player.x += playerDirectionX * TILE_SIZE; this.player.y += playerDirectionY * TILE_SIZE; } canMove( unit, dirX, dirY ){ const targetTileX = ( unit.body.x / TILE_SIZE ) + dirX; const targetTileY = ( unit.body.y / TILE_SIZE ) + dirY; return ( this.map.isInBounds( targetTileX, targetTileY ) && !this.map.isWall( targetTileX, targetTileY ) ); } Here's the whole project's code: Can somebody help me please ?] Super-W-Hack!
Ahmed Khalifa posted a topic in Game ShowcaseDescription: Links: Amidos: Newgrounds: Kongregate: Itch.io: GameJolt:
Shiny Gauntlet: Now on Steam Green Light
How do I implement Hexagonal Tilemaps
Felix posted a topic in Phaser 2Hi, I want to make my first Phaser game, a graphical Roguelike on a hexagonal grid. I know, a square grid would be easier, but let me try it anyway. How can I reuse as much code possible from the Phaser libraries (e.g. Tilemap) as possible? I would like, for example, to use the functionality of these examples: Depth Sort example Tilemap Ray Cast CSV Map (scrolling) If I can use existing libraries, I would have less work, less bugs, and better performance. Performance isn't critical though and I might have less work if I implement everything myselft, rather than shoehorning the libraries to do something they weren't intended to. Collision detection isn't an issue (the player and the enemies are always standing in the middle of a cell).I would like to express North, North-East, South-East, South, South-West, and North-West as tuples of +1, -1 and 0.Here is a doodle I made which explains how I could use isometric or rectangular grid "technology" (I hope it was worth the time to create it!). (I wrote the x-coordinate first. I'm not sure if that's normal.) Did anyone of you make a game with hex grid? How did you do it? What would you recommend to me? Is this the right forum? Do you have questions?
[WIP] Bad Transaction
shadowagent posted a topic in Game ShowcaseI just stumbled across the site while researching HTML5 game topics, and I thought I'd post a project I'm currently working on using canvas. I'm currently developing a dystopian roguelike game called Bad Transaction. It's a single player game with a custom 2D engine, and a custom node server backend. I've been working on it for a little over a year now, and I'm really hoping to have a very, very, early alpha ready at some point this year. Here's the latest development progress video:.
Overriding default drawing for a Roguelike FOV calculation
YardGnomeNinja posted a topic in Phaser 2To start, I'll say, there may be a better way than what I'm thinking, so I'm very open to suggestions. I'm making a Roguelike. I have rooms with attaching tunnels, a player that can move to free spaces, the VERY basics. I've reached the point of implementing an FOV (Field of View). I've got it in place for the most part. When the map is drawn, only the visible spaces within the player's FOV display their tiles, however when it comes to updating the display I'm getting nowhere, very...very... slowly. I've tried calling my "recalculateFOV" function in the Phaser "update" state, only to be fired when the player moves, then redrawing the entire map based on the results. This is agonizingly slow for some reason I can't quite decipher and just doesn't work properly. Then I thought maybe I needed to overwrite how Phaser handles drawing to get the job done. I Googled for any help on how to go about that and came up empty. I've read a couple of Phaser tutorials on creating a Roguelike, however the ones I've found left out handling FOV. Any help or suggestions would be greatly appreciated. Thanks!
.
Random Map Generation for Roguelikes in Phaser?
Muckluck posted a topic in Phaser 2.
A simple rogue like based on a tutorial
eugenioclrc posted a topic in Game ShowcaseHi! i have just make a rogue like game (small demo) Here is the link; Here is the source; I hope you like it!! Code and ideas were taken from;
The art of waiting...
FlashbackJon posted a topic in Phaser 2Long story short: new to Phaser, making a roguelike. Turn-based movement on a tilemap grid, etc. Obviously this ground has been covered before, but it seems that every example of a roguelike or RPG that I've found has basically just set the x/y of the sprite every time a movement occurs, and I'd like to be animating it. I want to wait for user input, then shut off listening for input, and wait for the chosen action/move (if valid) to finish before the game continues processing the turn. I've got it tweening well, but I'm not sure, conceptually, what the best practice is for "waiting." A few games I've seen that use turn-based structure set a variable and then check time in update() to see if sufficient time has passed. I tried using a timer at first, but ran into unexpected behavior (I'm sure I could fix it, but I'm more interested in knowing what I ought to do)... What I have now (experimenting with the former), but not overly enamored with it: function update() { if (acceptInput) { if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { acceptInput = false; moveTimer = game.time.time; game.add.tween(player.body).to({ x: '-' + TILEWIDTH }, MOVEDURATION, Phaser.Easing.Linear.None, true); } else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { acceptInput = false; moveTimer = game.time.time; game.add.tween(player.body).to({ x: '+' + TILEWIDTH }, MOVEDURATION, Phaser.Easing.Linear.None, true); } else if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) { acceptInput = false; moveTimer = game.time.time; game.add.tween(player.body).to({ y: '-' + TILEHEIGHT }, MOVEDURATION, Phaser.Easing.Linear.None, true); } else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { moveTimer = game.time.time; acceptInput = false; game.add.tween(player.body).to({ y: '+' + TILEHEIGHT }, MOVEDURATION, Phaser.Easing.Linear.None, true); } } else { if (game.time.time > moveTimer + MOVEDURATION) { acceptInput = true; } }}Thoughts?
Tull [RPG]
jucarave posted a topic in Game ShowcaseHello everyone, this is the second game that i post in this page, and is my first complete html5 game, i did it for the trials of oryx 2013, i developed it in about a month and was done using javascript from the scratch. The game is Tull, a very simple rpg with some roguelikes elements like the permadeath and randomnes, there is also food consumption and the weapons, armours, magic and food can be only bought in the town, there is also a hotel in the town so you can regenerate your health. There is only one Dungeon but it has 20 levels, each one more difficult than the previous, there are 3 sub bosses and 1 final boss (Ias) which is the target of the game. Anyway, here it is the link, i hope you like it. You will probably find some "engrish" problems, let me know about the ones you find. Greetings
rot.js - A Roguelike Toolkit for JS
rich posted a topic in Coding and Game Designrot.js is a set of JavaScript libraries, designed to help with a roguelike development in browser environment. | https://www.html5gamedevs.com/tags/roguelike/ | CC-MAIN-2022-40 | refinedweb | 1,324 | 65.62 |
An easy solution to design reports using OpenOffice
Project description
Introduction
py3o is an elegant and scalable solution to design reports using LibreOffice or OpenOffice. py3o.template is the templating component that takes care of merging your data sets with a corresponding templated OpenOffice document.
It is plateform independent and does not require LibreOffice/OpenOffice itself to generate an ODF file.
If you want to generate a PDF or any other supported output format you will then need to have a server with either LibreOffice or OpenOffice and to install the py3o.renderserver on it. We also provide a docker image on the docker hub
If you want to have templating fusion & document conversion in one single web service usable from any language with just HTTP/POST you can install py3o.fusion server. Which also exists as a docker image
Python 3 support
- py3o.fusion is python3 ready. But, yes there is a but… alas!, you’ll need
to install a trunk version of Genshi:
$ # activate your python env... $ svn checkout genshi_trunk $ cd genshi_trunk $ python setup.py build $ python setup.py install
We tested this with revision 1271. When genshi 0.8 is released we can officially say we support Python3 out of the box.
Full Documentation
We provide a documentation for this package. If anything is not correctly explained, please! create a ticket in our ticketing system
Example Usage
Below is an example that you can find in the source code inside the examples directory.
from py3o.template import Template t = Template("py3o_example_template.odt", "py3o_example_output.odt") t.set_image_path('logo', 'images/new_logo.png') class Item(object): pass) t.render(data)
Changelog
0.9.1 Jun. 3 2015
- Fixed parser to read from the var name instead of its description, if you dont use the helper tool to introspect your reports this release is of no importance to you as it only fixes this particular point.
0.9 Jan. 8 2015
- Added support for soft page breaks
0.8 Nov. 19 2014
- Added better unit tests
- Fixed corner cases in the variable introspection mechanism
- Better handling of “ignore_undefined” that now also allows undefined images
0.7 Oct. 15 2014
- Added Python3 support
- Fixed a problem with validity of output in case the template contains a text:list inside a for loop
- Added new public methods to help report servers introspect the template data dictionary
- Added real unit tests (96% coverage ATM, way to go test team!)
Contributors
By order of contribution date:
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/py3o.template/0.9.1/ | CC-MAIN-2018-51 | refinedweb | 438 | 56.05 |
Hi all,
Can you use the Fox Pro libraries to compress files in Lianja?
Example
There are other ways for Lianja?
Thanks
Ario
Hi all,
Can you use the Fox Pro libraries to compress files in Lianja?
Example
There are other ways for Lianja?
Thanks
Ario
Hi Ario,
You should specify target OS. For Windows you can use COM/Activex.
Also look for corresponding libs in Python or PHP: can use the EXECPYTHON ( ) built-in function.
There is also the same functionality available with PHP using EXECPHP( ).
Lianja can integrate Python, PHP and JavaScript code in with VFP code.
Josip
Last edited by josipradnik; 2017-10-10 at 05:19.
Hi Ario,
The chilkat extension for Lianja is available for Windows, Linux and MacOS.
There are many feature rich classes specifically built for Lianja including zip/unzip and other compression libraries.
Last edited by barrymavin; 2017-10-10 at 05:43.
Principal developer of Lianja, Recital and other products
Follow me on:
Twitter:
Hi Ario,
we use the Chikat libraries for a number of purposes in VFP and Lianja. The integration with Lianja is particularly smooth (and described well on the Lianja site). The Zip options available are very handy in various scenarios.
Hank
online casino using Lianja and this could really help in setting up everything. Any update on this would be greatly appreciated. Cheers!
Hi Ben,
No. An FLL is a Fox-specific file.
I use Chilkat controls in VFP and in Lianja.
If you go with Chilkat, I have some wrapper routines in Lianja that I use to work with Chilkat (so fewer steps are required). Let me know and I'll get them to you.
Hank
Hi benrayburn,
I posted a two minute video on how you can easily zip files in Lianja with a call to python.
You do not need to know anything about python to get it to work.
Here is the link
Here is the python code:
from zipfile import ZipFile
def zipmyfile(filetozip,zipfilename):
ZipFile(zipfilename,'w').write(filetozip)
Here is the call from lianja:
This is just how I would do it.This is just how I would do it.filetozip = "c:\\lianja\\apps\\zip\\test.txt"
zipfilename = "c:\\lianja\\apps\\zip\\test.zip"
o = loadlibrary("lianja_python_zip.py")
execpython("zipmyfile('"+filetozip+"','"+zipfilena me+"')")
Let me know if you have any questions.
Herb
Last edited by hmischel@diligentsystems.com; 2020-07-15 at 11:32.
Very nice, Herb.
Did you use a bit of Python in your flagship app for image manipulation?
Hank
Hi Hank,
I use the python opencv libraries extensively for the image manipulation and use that in tandem with scikit-learn (sklearn) for the support vector machines (which in my case has proven more precise than random forest) along with scipy, numpy and the rest of the data science toolkits.
With my ability to glue all of that together with Lianja, I can have fast local persistent storage, fast image displays and a central hub that lets me move efficiently between all the objects and displays.
The speed at which I am able to respond to clients needs for enhancements is unparalleled.
I simply can't imagine how I could have built this application without Lianja.
The heads of every major lab and most studios in hollywood have heard of this system.
Have a look at the promo we updated. You will notice it is all in Lianja.
Herb
That is fantastic.
Bookmarks | https://www.lianja.com/community/showthread.php?3898-Compressing-files-zip-utility&s=4c45e337233b3316ce8df3787b038b0e&p=21918 | CC-MAIN-2021-25 | refinedweb | 575 | 75.81 |
KDEUI
#include <kgesture.h>
Detailed Description
Definition at line 152 of file kgesture.h.
Constructor & Destructor Documentation
Create a new invalid rocker gesture.
Definition at line 416 of file kgesture.cpp.
Creates a new gesture consisting of given buttons.
- Parameters
-
Definition at line 422 of file kgesture.cpp.
Creates a new gesture from a string description.
- Parameters
-
Definition at line 429 of file kgesture.cpp.
Copies the given gesture.
- Parameters
-
Definition at line 464 of file kgesture.cpp.
Destructor.
Definition at line 470 of file kgesture.cpp.
Member Function Documentation
Write the button combination to hold and thenPush.
Definition at line 506 of file kgesture.cpp.
Return an opaque value for use in hash tables.
Definition at line 602 of file kgesture.cpp.
Return true if this gesture is valid.
Definition at line 544 of file kgesture.cpp.
Return a user-friendly name for the mouse button button.
Definition at line 513 of file kgesture.cpp.
Return the opposite of operator==()
Definition at line 597 of file kgesture.cpp.
Set this gesture to the other gesture.
Definition at line 584 of file kgesture.cpp.
Return whether this gesture is equal to the other gesture.
Definition at line 592 of file kgesture.cpp.
Return a user-friendly name of the button combination.
Definition at line 532 of file kgesture.cpp.
set button combination to trigger
Definition at line 476 of file kgesture.cpp.
Return a string representation of this gesture.
Return an empty string if invalid. This function is mainly for use with config files.
- See also
- rockerName()
Definition at line 550 of file kgesture. | https://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/classKRockerGesture.html | CC-MAIN-2019-30 | refinedweb | 264 | 55 |
The nemesis package
a rake like task management tool
Properties
Modules
Downloads
- nemesis-2009.8.4.tar.gz [browse] (Cabal source package)
- Package description (included in the package)
Maintainers' corner
For package maintainers and hackage trustees
Readme for nemesis-2009.8.4
Nemesis: a rake like task management tool for haskell
Demo
nemesis = do clean [ "**/*.hi" , "**/*.o" , "manifest" ] task "dist" $ do sh "cabal clean" sh "cabal configure" sh "cabal sdist" task "i" (sh "ghci -isrc src/System/Nemesis.hs") task "manifest" $ do sh "find . | grep 'hs$' > manifest"
Tutorial
Install
cabal update; cabal install nemesis
DSL
Put the following code into a file named
Nemesis
nemesis = do -- desc is optional, it gives some description to the following task desc "Hunter attack macro" -- syntax: task "keyword: dependencies" io-action task "attack: pet-attack auto-attack" (putStrLn "attack macro done!") desc "Pet attack" task "pet-attack: mark" $ do sh "echo 'pet attack'" desc "Hunter's mark" task "mark" $ do sh "echo \"casting hunter's mark\"" desc "Auto attack" task "auto-attack" $ do sh "echo 'auto shoot'"
Run
run
nemesis
attack : Hunter attack macro auto-attack : Auto attack mark : Hunter's mark pet-attack : Pet attack
run
nemesis attack
casting hunter's mark pet attack auto shoot attack macro done!
Namespace
Suppose you have the following tasks
nemesis = do namespace "eat" $ do task "bread: salad" $ putStrLn "eating bread" task "salad: /drink/coke" $ putStrLn "nice salad" namespace "drink" $ do task "coke" $ putStrLn "drinking coke"
then
nemesis bread => .nemesis: bread does not exist! nemesis eat/bread => drinking coke nice salad eating bread
Advance usage
Use LANGUAGE
Use a separator below language extensions, e.g.
{-# LANGUAGE QuasiQuotes #-} -- Nem nemesis = do task "i" (sh "ghci -isrc src/System/Nemesis.hs")
currently the separator
-- Nem is hard coded
Build it yourself
If you don't want
nemesis to compile
Nemesis through intermediate
nemesis-tmp.hs file, rename your
Nemesis to
Nemesis.hs, then start with this template.
import System.Nemesis (run) import System.Nemesis.DSL nemesis = do task "i" (sh "ghci -isrc src/System/Nemesis.hs") main = run nemesis
The logic is that whenever
main is defined in
Nemesis.hs,
nemesis will act as
ghc --make wrapper, so you can get nice error messages.
That's it!
OK, she's actually mnemosyne, a cool goddess none the less. | https://hackage.haskell.org/package/nemesis-2009.8.4 | CC-MAIN-2015-40 | refinedweb | 379 | 53.41 |
Manual for version 1.5.2 Written by Dimitri van Heesch c 1997-2007 CONTENTS 1 Contents I User Manual 4 1 Installation 4 2 Getting started 9 3 Documenting the code 14 4 Lists 23 5 Grouping 25 6 Including formulas 29 7 Graphs and diagrams 30 8 Preprocessing 33 9 Automatic link generation 36 10 Output Formats 40 11 Linking to external documentation 40 12 Frequently Asked Questions 42 13 Troubleshooting 45 II 47 Reference Manual 14 Features 47 15 Doxygen History 49 16 Doxygen usage 51 17 Doxytag usage 52 18 Doxywizard usage 54 19 Installdox usage 55 20 Configuration 56 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 CONTENTS 2 21 Special Commands 76 22 HTML Commands 110 23 XML Commands 114 III Developers Manual 115 24 Doxygen’s Internals 115 25 Perl Module output format documentation 119 26 Internationalization 121 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 CONTENTS Introduction ‘abuse’. Automatic link generation shows how to put links to files, classes, and members in the documentation. • Section Output Formats shows how to generate the various output formats supported by doxygen.: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 1 CONTENTS • Section Features presents an overview of what doxygen can do. • Section Doxygen History shows what has changed during the development of doxygen and what still has to be done. • Section Doxygen usage shows how to use the doxygen program. • Section Doxytag usage shows how to use the doxytag program. • Section Doxywizard usage shows how to use the doxywizard program. • Section Installdox usage shows how to use the installdox script that is generated by doxygen if you use tag files.. • Section XML Commands shows an overview of the C# style XML-2007 by Dimitri van Heesch.. User examples Doxygen supports a number of output formats where HTML is the most popular one. I’ve gathered some nice examples (see) of real-life projects using doxygen. These are part of a larger list of projects that use doxygen (see). If you know other projects, let me know and I’ll add them. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 2 CONTENTS Future work Although doxygen is used successfully by a lot of people already, there is always room for improvement. Therefore, I have compiled a todo/wish list (see) of possible and/or requested enhancements. Talin for adding support for C# style comments with XML markup. • Petr Prikryl for coordinating the internationalisation support. All language maintainers for providing translations into many languages. • Gerald Steffens of E-trend for financial support. • The band Porcupine Tree for providing hours of great music to listen to while coding. • many, many others for suggestions, patches and bug reports. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 3.5.2, written by Dimitri van Heesch 1997-2006-3.2.x or higher and doxy.5.2, written by Dimitri van Heesch 1997-2006 core. Bison problems Versions 1.31 to 1.34 of bison contain a ”bug” that results in a compiler errors like this: ce parse.cpp:348: member ‘class CPPValue yyalloc::yyvs’ with constructor not allowed in union This problem has been solved in version 1.35 (versions before 1.31 will also work)..5.2, written by Dimitri van Heesch 1997-2006 It appears that doxygen doesn’t work properly if it is compiled with Sun’s C++ WorkShop Compiler. I cannot verify this myself as I do not have access to a Solaris machine with this compiler. With GNU compiler it does work.) c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 7 1.4 Compiling from source on Windows. For doxygen 1.4.7 or higher it is recommended to use GraphViz 2.8 or higher to avoid font issues. Red Hat 9.0 problems If you get the following error after running make tmake error: qtools.pro:70: Syntax error then first type export LANG= before running make. 1.4 Compiling from source on Windows From version 1.5.0 onwards, build files are provided for Visual Studio 2005. Also the free ”Express” version of Developer Studio can be used to compile doxygen. Alternatively, you can compile doxygen the Unix way using Cygwin or MinGW. Before you can compile doxygen you need to download and install the C++ compiler of Visual Studio. Since Microsoft apparently wants to lure everyone into using their .NET stuff, you need to do some manual steps in order to setup a proper working environment for building native win32 applications. Once your environment is setup, you can download the source distribution of doxygen and unpack it. If you don’t have a tool like WinZip, then I suggest to download unxutils and untar the archive from within a command box using tar zxvf doxygen-version.src.tar.gz Inside the archive you will find a winbuild directory containing a Doxygen.sln file. Just open this file in Visual Studio. You can now build the Doxygen, Doxytag, and Doxywizard projects for Release or Debug to compile the executables. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 8 1.5 Installing the binaries on Windows Note that compiling Doxywizard currently requires a commercial license for Qt 3. Also read the next section for additional tools you may need to install. 1.5 Installing the binaries on Windows Doxygen comes as a self-installing archive, so installation is extremely simple. Just follow the dialogs. After installation it is recommended to also download and install GraphViz (version 2.8 or better is highly recommended). Doxygen can use the dot tool of the GraphViz package to render nicer diagrams, see the HAVE DOT option in the configuration file. If you want to produce compressed HTML files (see GENERATE HTMLHELP) in the config file, then you need the Microsoft HTML help workshop. You can download it from Microsoft. In order to generate PDF output or use scientific formulas you will also need to install LaTeX and Ghostscript. For LaTeX a number of distributions exists. Popular onces that should work with doxygen are MikTex and XemTex. Ghostscript can be downloaded from Sourceforge. After installing LaTeX. 1.6 Tools used to develop doxygen Doxygen was developed and tested under Linux & MacOSX using the following open-source tools: • GCC version 3.3.6 (Linux) and 4.0.1 (MacOSX) • GNU flex version 2.5.33 (Linux) and 2.5.4 (MacOSX) • GNU bison version 1.75 • GNU make version 3.80 • Perl version 5.8.1 • VIM version 6.2 • Firefox 1.5 • Troll Tech’s tmake version 1.3 (included in the distribution) • teTeX version 2.0.2 • CVS 1.12.12 2 Getting started The executable doxygen is the main program that parses the sources and generates the documentation. See section Doxygen usage for more detailed usage information. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 9 2.1 Step 1: Creating a configuration file 10 The executable doxytag is only needed if you want to generate references to external documentation (i.e. documentation that was generated by doxygen) for which you do not have the sources. See section Doxytag): Doxywizard Your application XML files generate/edit read custom output doxmlparser lib Config file Doxyfile make ps read generate/update Latex files + Makefile postscript latex make pdf PDF read Sources Doxygen read read generate Man pages Custom − headers − footers Tag file(s) − images Windows only refman.rtf import MS−Word doc generate HTML pages Doxytag read chm HTML Help Workshop parse Figure 1: Doxygen information flow 2.1 Step 1: Creating a configuration file> c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 2.2 Step 2: Running doxygen ∗.cpp ∗.h). Only files that match one of the patterns will be parsed (if the patterns are omitted a list of source extensions is used).. If a file has an .idl or .odl extension it is treated as an IDL file. If it has a .java extension it is treated as a file written in Java. Files ending with .cs are treated as C# files and the .py extension selects the Python parser. Finally, files with the extensions .php, .php4, .inc or .phtml are treated as PHP sources. Any other extension is parsed as if it is a C/C++ file, where files that end with .m are treated as Objective-C source files. analyse). 2.2 Step 2: Running doxygen To generate the documentation you can now enter: doxygen <config-file> Depending on your settings doxygen will create html, rtf, latex, xml and/or man directories inside the output directory. As the names suggest these directories contain the generated documentation in HTML, RTF, LATEX, XML and Unix-Man page format. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 11 2.2 Step 2: Running doxygen, and MAN OUTPUT tags of the configuration file. If the output directory does not exist, doxygen will try to create it for you (but it will not try to create a whole path recursively, like mkdir -p does). 2.2.1 HTML output The generated HTML documentation can be viewed by pointing a HTML browser to the index.html file in the html directory. For the best results a browser that supports cascading style sheets (CSS) should be used (I’m using Mozilla, Safari, Konqueror, and sometimes IE6 to test the generated output). Some of the features the HTML section (such as GENERATE TREEVIEW) require a browser that supports DHTML and Javascript. If you plan to use the search engine (see SEARCHENGINE), you should view the HTML output via a PHP-enabled web server (e.g. apache with the PHP module installed). 2.2.2 LaTeX output The generated LATEX documentation must first be compiled by a LATEX compiler (I use a recent teTeX distribution). To simplify the process of compiling the generated documentation, doxygen writes a Makefile into the latex directory.. 2.2.3 RTF output Doxygen combines the RTF output to a single file called refman.rtf. This file is optimized for importing into the Microsoft Word. Certain information is encoded using field. To show the actual value you need to select all (Edit - select all) and then toggle fields (right click and select the option from the drop down menu). 2.2.4 XML output. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 12 2.3 Step 3: Documenting the sources) 2.2.5 Man page output. 2.3 Step 3: Documenting the sources Although documenting the sources (unless the word is preceded by a %; then the word will not be linked and the % sign is removed). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 13 14. 3 Documenting the code 3.1 Special documentation blocks A special documentation block is a C or C++ style comment block with some additional markings, so doxygen knows it is a piece of documentation that needs to end up in the generated documentation. For Python code there is a different comment convention, which can be found in section Special documentation blocks in Python c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 3.1 Special documentation blocks //! //!... text ... //! 4. Some people like to make their comment blocks more visible in the documentation. For this purpose you can use the following: ///////////////////////////////////////////////// /// ... text ... ///////////////////////////////////////////////// c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 15 3.1 Special documentation blocks 16 //!. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 3.1 Special documentation blocks /*! Details. */ int publicVar; //! A function variable. /*! Details. */ int (*handler)(int a,int b); }; The one-line comments contain a brief description, whereas the multi-line comment blocks contain a more. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 17 3.2 Putting documentation after members */ ˜Test(); /** * a normal member taking two arguments and returning an integer value. * @param a an integer argument. * @param s a constant character pointer. * @see Test() * @see ˜Test() * . 3.2 Putting documentation after members If you want to document the members of a file, struct, union, class, or enum, and you want to put the documentation for these members inside the compound, c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 18 3.3 Documentation at other places int var; //!< Detailed description after the member //!< or int var; ///< Detailed description after the member ///< Most often one only wants to put a brief description after a member. This is done as follows: int var; //!< Brief description after the member. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 19 3.3 Documentation at other places: /*! \class Test \brief A test class. A more detailed class description. */ Here the special command \class is used to indicate that the comment block contains documentation for the class Test. Other structural commands are: • \struct to document a C-struct. • \union to document a union. • \enum to document an enumeration type. • \fn to document a function. • \var to document a variable or typedef or enum value. • \def to document a #define. • \typedef to document a type definition. • \file to document a file. • \namespace to document a namespace. • \package to document a Java package. • \interface to document an IDL: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 20 3.3 Documentation at other places /*! . c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 21 3.4 3.4 Special documentation blocks in Python Special documentation blocks in Python For Python there is a standard way of documenting the code using so called documentation strings. Such strings are stored in # Documentation for this module. # # More details. ## Documentation for a function. # # More details. def func(): pass ## Documentation for a class. # # More details. class PyClass: ## The constructor. def __init__(self): self._memVar = 0; ## Documentation for a method. # @param self The object pointer. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 22 23 def PyMethod(self): pass ## A class variable. classVar = 0; ## @var _memVar # a member variable Since python looks more like Java than like C or C++, you should set OPTMIZE OUTPUT JAVA to YES in the config file. 4 Lists Doxygen provides and is based on indentation of the items. Here is an example: /*! * A list of events: - mouse events * -# mouse move event * -# mouse click event\n * More info about the click event. * -# for indentation within lists, please make sure that TAB SIZE in the configuration file is set to the correct tab size. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 24 consist of multiple paragraphs. Here is the above example with HTML commands: /*! * * * * * * * * * * * * * * * * */ A list of events: <ul> <li> mouse events <ol> <li>mouse move event <li>mouse click event\n More info about the click event. <li>mouse double click event </ol> <li> keyboard events <ol> <li>key down event <li>key up event </ol> </ul> More text here. Note: In this case the indentation is not important. Using \arg or @li For compatibility with the Troll Tech’s internal documentation tool and with KDoc, doxygen has two commands that can be used to create simple unnested lists. See \arg and \li for more info. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 25 5 Grouping Doxygen has three mechanisms to group things together. One mechanism works at a global level, creating a new page for each group. These groups are called ’modules’ in the documentation. The second mechanism works within a member list of some compound entity, and is refered to as a ’member groups’. For pages there is a third grouping mechanism referred to as subpaging. */ /*@{*/ c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 5.1 Modules /** last command is exactly like \addtogroup with a lower priority. It was added to allow ”lazy” grouping definitions: you can use commands with a higher priority in your .h files to define the hierarchy and \weakgroup in .c files without having to duplicate the hierarchy exactly. Example: /** */ /** c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 26 5.2 Member Groups * @ingroup group2 * @brief class C3 in group 2 */ class C3 {}; /** @ingroup group2 * @brief class C4 in group 2 */ class C4 {}; /** @ingroup group3 * @brief class C5 in @link group3 the third [email protected] */ class C5 {}; /** @ingroup group1 group2 group3 group4 * namespace N1 is in four groups * @sa @link group1 The first [email protected], */ /** @} */ // end of group5 /** @addtogroup group1 * * More documentation for the first group. * @{ */ /**. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 27 5.2 Member Groups A member group is defined by a //@{ ... //@} block or a /*@{*/ ... /*@}*/ block if you prefer C style comments. Note that the members of the group should be physcially inside the member group’s body. Before the opening marker of a block a separate comment block may be placed. This block should contain the @name (or \name) command and is used to specify the header of the group. Optionally, the comment block may also contain more detailed information about the group. Nesting of member groups is not allowed. If all members of a member group inside a class have the same type and protection level (for instance all are static public members), then the whole member group is displayed as a subgroup of the type/protection level group (the group is displayed as a subsection of the ”Static Public Members” section for instance). If two or more members have different types, then the group is put at the same level as the automatically generated groups. If you want to force all member-groups of a class to be at the top level, you should put a \nosubgrouping command inside the documentation of the class. Example: /** */ c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 28 5.3 Subpaging 29 //@{ //!). 5.3 Subpaging Information can be grouped into pages using the \page and \mainpage commands. Normally, this results in a flat list of pages, where the ”main” page is the first in the list. Instead of adding structure using the approach decribed in section modules it is often more natural and convienent 1.0 distribution. • dvips: a tool to convert DVI files to PostScript files I have used version 5.92b from Radical Eye software for testing. • gs: the GhostScript interpreter for converting PostScript files to bitmaps. I have used Aladdin GhostScript 8.0 for testing. There are three . 2. Unnumbered displayed formulas that are centered on a separate line. These formulas should be put between \f[ and \f] commands. An example: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 |I2 | = ψ(t) u(a, t) − c(ξ)ut (ξ, t) dξ dt 0 k(θ, t) γ(t) a 3. Formulas or other latex elements that are not in a math environment can be specified using \f{environment}, where environment is the name of the LATEX environment, the corresponding end command is \f}. Here is an example for an equation array \f{eqnarray*} g &=& \frac{Gm_2}{rˆ2} \\ &=& \frac{(6.673 \times 10ˆ{-11}\,\mbox{m}ˆ3\,\mbox{kg}ˆ{-1}\, \mbox{s}ˆ{-2})(5.9736 \times 10ˆ{24}\,\mbox{kg})}{(6371.01\,\mbox{km})ˆ2} \\ &=& 9.82066032\,\mbox{m/s}ˆ2 \f} which results in: g = = = Gm2 r2 (6.673 × 10−11 m3 kg−1 s−2 )(5.9736 × 1024 kg) (6371.01 km)2 9.82066032 m/s2 For the first two commands one should make sure formulas contain valid commands in LATEX’s math-mode. For the third command the section should contain valid command for the specific environment. Warning: Currently, doxygen is not very fault tolerant in recovering from typos in formulas. It may have to be necessary to remove the file formula.repository that is written and can be found at If you have the ”dot” tool available in the path, you can set HAVE DOT to YES in the configuration file to let doxygen use it. Doxygen uses the ”dot” tool to generate the following graphs: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 31 •.). • if CALL GRAPH is set to YES, a graphical call graph is drawn for each function showing the functions that the function directly or indirectly calls. • if CALLER GRAPH is set to YES, a graphical caller graph is drawn for each function showing the functions that the function is directly or indirectly called by. The elements in the class diagrams in HTML and RTF have the following meaning: • A yellow box indicates a class. A box can have a little marker in the lower right corner to indicate that the class contains base classes that are hidden. For the class diagrams the maximum tree width is currently 8 elements. If a tree is wider some nodes will be hidden.. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 32 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 33: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 44 TAGFILES = b.tag=b.chm:: or you can use installdox to set the links as follows: installdox [email protected]::! 10. How can I exclude all test directories from my directory tree? Simply put an exclude pattern like this in the configuration file: EXCLUDE_PATTERNS = */test/* 11. Doxygen automatically generates a link to the class MyClass somewhere in the running text. How do I prevent that at a certain place? Put a % in front of the class name. Like this: %MyClass. Doxygen will then remove the % and keep the word unlinked. 12. My favourite programming language is X. Can I still use doxygen? No, not as such; doxygen needs to understand the structure of what it reads.). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 45 13. Help! I get the cryptic message ”input buffer overflow, can’t enlarge buffer because scanner uses REJECT”, unless the option BUILTIN STL SUPPORT is turned on. 16. I have problems getting the search engine to work with PHP5 and/or windows Please read this for hints on where to look. 17. Can I configure doxygen from the command line? Not via command line options, but doxygen can read from stdin, so you can pipe things through it. Here’s an example how to override an option in a configuration file from the command line (assuming a unix environment): ( cat Doxyfile ; echo "PROJECT_NUMBER=1.0" ) | doxygen - If multiple options with the same name are specified then doxygen will use the last one. To append to an existing option you can use the += operator. 18.”). 19.... 13 Troubleshooting Known problems: • If you have problems building doxygen from sources, please read this section first. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 46. • It is not possible to insert a non-member function f in a class A using the \relates or \relatesalso. • PHP only: Doxygen requires that all PHP statements (i.e. code) is wrapped in a functions/methods, otherwise you may run into parse problems..5.2, written by Dimitri van Heesch 1997-2006 47 How to report a bug Bugs are tracked in GNOME’s bugzilla database. Before submitting a new bug, first check if the same bug has already been submitted by others. If you believe you have found a new bug, please file file for easier processing. When reporting a new bug you’ll get a chance to attach a file to it immediately after opening the bug. [email protected] if you prefer not to send them via the bug tracker or mailing list. For patches please use ”diff -uN” or include the files you modified. If you send more than one file please tar or zip everything, so I only have to save and download one file. Part II Reference Manual 14 Features • Requires very little overhead from the writer of the documentation. Plain text will do, but for more fancy or structured output HTML tags and/or some of doxygen’s special commands can be used. • Supports C/C++, Java, (Corba and Microsoft) Java, Python, IDL, C#, Objective-C and to some extent D and PHP sources. • Supports documentation of files, namespaces, packages, classes, structs, unions, templates, variables, functions, typedefs, enums and defines. • JavaDoc (1.1), Qt-Doc, and ECMA-334 (C# spec.) compatible. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 48 • Automatically generates class and collaboration diagrams in HTML (as clickable image maps) and LATEX (as Encapsulated PostScript images). • Uses the dot tool of the Graphviz tool kit to generate include dependency graphs, collaboration diagrams, and graphical class hierarchy graphs. • Flexible comment placement: Allows you to put documentation in the header file (before the declaration of an entity), source file (before the definition of an entity) or in a separate file. • Generates. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 49 Although doxygen can be used in any C or C++ project, initially!. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 50 PHP based search engine that allows you to search through the generated documentation. • A configuration file instead of command-line options. A default configuration file can be generated by doxygen. • Added an option to generate output for undocumented classes. • Added an option to generate output for private members. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 51.: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 52 If you need non-default options (for instance to use pdflatex) you need to make a config file with those options set correctly and then specify that config file as the forth argument.. 17 Doxytag usage Doxytag is a small command line based utility. It. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 53 Important: If you use tag files,). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 54: doxytag -t qt.tag $QTDIR/doc/html 18 Doxywizard usage Doxywizard is a GUI front-end for configuring and running doxygen.. Wizard Click this button to quickly configure the most important settings and leave the rest of the options to their defaults. Expert Click this button to to gain access to the full range of configuration options. Load Click this button to load an existing configuration file from disk.. The Wizard Dialog LaTeX there are additional options. Doxygen can produce a number of diagrams. Using the diagrams tab you can select which ones to generate. For most diagrams the dot tool of the GraphViz package is needed (if you use the binary packages for Mac or Windows this tool is already included). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 55 Expert dialog The Expert dialog has a number of tab fields, ‘∗’ button that, when pressed, replaces the selected item in the list with the string entered in the edit field. • For file and folder entries, there are special buttons that start a file selection dialog. The get additional information about the meaning of an option, click on the ”Help” button at the bottom right of the dialog and then on the item. A tooltip with additional information will appear. Menu options The GUI front-end has a menu with a couple of useful items Open... This is the same as the ”Load” button in the main window and allows to open a configuration file from disk. Save as.. This is the same as the ”Save” button in the main window and can be used to save the current configuration settings to disk. Recent configurations Allow to quickly load a recently saved configuration. Set as default... Stores the current configuration settings as the default to use next time the GUI is started. You will be asked to confirm the action. Reset... Restores the factory defaults as the default settings to use. You will be asked to confirm the action. 19. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 56. 20 20.1 Configuration Format A configuration file is a free-form ASCII text file with a structure that is similar to that of a Makefile, with the $(ENV VARIABLE NAME).: @INCLUDE_PATH = my_config_dir The configuration options can be divided into several categories. Below is an alphabetical index of the tags that are recognized followed by the descriptions of the tags grouped by category. ABBREVIATE BRIEF 20.2 BRIEF MEMBER DESC ALIASES 20.2 CALL GRAPH 20.17 CALLER GRAPH 20.17 ALLEXTERNALS 20.16 20.2 ALPHABETICAL INDEX 20.7 CASE SENSE NAMES 20.2 ALWAYS DETAILED SEC 20.2 CHM FILE 20.8 BINARY TOC 20.8 CLASS DIAGRAMS 20.17 BUILTIN STL SUPPORT 20.2 CLASS GRAPH 20.17 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 20.1 Format COLLABORATION GRAPH 57 20.17 FILTER SOURCE FILES 20.5 20.2 COLS IN ALPHA INDEX 20.7 FULL PATH NAMES COMPACT LATEX 20.9 GENERATE AUTOGEN DEF COMPACT RTF 20.10 20.13 GENERATE BUGLIST 20.3 CPP CLI SUPPORT 20.2 GENERATE CHI 20.8 CREATE SUBDIRS 20.2 GENERATE DEPRECIATEDLIST 20.3 DETAILS AT TOP 20.2 GENERATE HTML 20.8 GENERATE HTMLHELP 20.8 20.9 DIRECTORY GRAPH 20.17 DISABLE INDEX 20.8 GENERATE LATEX DISTRIBUTE GROUP DOC 20.2 GENERATE LEGEND 20.17 DOT GRAPH MAX NODES 20.17 GENERATE MAN 20.11 DOT IMAGE FORMAT 20.17 GENERATE PERLMOD 20.14 DOT MULTI TARGETS 20.17 GENERATE RTF 20.10 DOT PATH 20.17 GENERATE TAGFILE 20.16 DOT TRANSPARENT 20.17 GENERATE TESTLIST 20.3 DOTFILE DIRS 20.17 GENERATE TODOLIST 20.3 ENABLE PREPROCESSING 20.15 GENERATE TREEVIEW 20.8 ENUM VALUES PER LINE 20.8 GENERATE XML 20.12 ENABLED SECTIONS 20.3 GRAPHICAL HIERARCHY 20.17 EXAMPLE PATH 20.5 GROUP GRAPHS 20.17 EXAMPLE PATTERNS 20.5 HAVE DOT 20.17 EXAMPLE RECURSIVE 20.5 HHC LOCATION 20.8 EXCLUDE 20.5 HIDE FRIEND COMPOUNDS 20.3 EXCLUDE PATTERNS 20.5 HIDE IN BODY DOCS 20.3 EXCLUDE SYMLINKS 20.5 HIDE SCOPE NAMES 20.3 EXPAND AS DEFINED 20.15 HIDE UNDOC CLASSES 20.3 EXPAND ONLY PREDEF 20.15 HIDE UNDOC MEMBERS 20.3 EXTERNAL GROUPS 20.16 HIDE UNDOC RELATIONS 20.17 EXTRA PACKAGES 20.9 HTML ALIGN MEMBERS 20.8 EXTRACT ALL 20.3 HTML FOOTER 20.8 EXTRACT LOCAL CLASSES 20.3 HTML HEADER 20.8 EXTRACT LOCAL METHODS 20.3 HTML OUTPUT 20.8 EXTRACT PRIVATE 20.3 HTML STYLESHEET 20.8 EXTRACT STATIC 20.3 IGNORE PREFIX 20.7 FILE PATTERNS 20.5 IMAGE PATH 20.5 FILE VERSION FILTER 20.5 INCLUDE GRAPH 20.17 FILTER PATTERNS 20.5 INCLUDE PATH 20.15 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 20.1 Format 58 INHERIT DOCS 20.2 REFERENCED BY RELATION 20.6 INLINE INFO 20.3 REFERENCES RELATION 20.6 INLINE INHERITED MEMB 20.2 REFERENCES LINK SOURCE 20.6 INLINE SOURCES 20.6 REPEAT BRIEF 20.2 INPUT 20.5 RTF EXTENSIONS FILE 20.10 INPUT ENCODING 20.5 RTF HYPERLINKS 20.10 INPUT FILTER 20.5 RTF OUTPUT 20.10 INTERNAL DOCS 20.3 RTF STYLESHEET FILE 20.10 JAVADOC AUTOBRIEF 20.2 SEARCH INCLUDES 20.15 LATEX BATCHMODE 20.9 SEARCHENGINE 20.18 LATEX CMD NAME 20.9 SEPARATE MEMBER PAGES 20.2 LATEX HEADER 20.9 SHORT NAMES 20.2 LATEX HIDE INDICES 20.9 SHOW DIRECTORIES 20.3 LATEX OUTPUT 20.9 SHOW INCLUDE FILES 20.3 SHOW USED FILES 20.3 MACRO EXPANSION MAKEINDEX CMD NAME 20.15 20.9 SKIP FUNCTION MACROS 20.15 MAN EXTENSION 20.11 SORT BRIEF DOCS 20.3 MAN LINKS 20.11 SORT MEMBER DOCS 20.3 MAN OUTPUT 20.11 SOURCE BROWSER 20.6 STRIP CODE COMMENTS 20.6 STRIP FROM INC PATH 20.2 MAX INITIALIZER LINES MSCGEN PATH 20.3 20.17 MULTILINE CPP IS BRIEF 20.2 STRIP FROM PATH 20.2 OPTIMIZE OUTPUT FOR C 20.2 SUBGROUPING 20.2 OPTIMIZE OUTPUT JAVA 20.2 TAB SIZE 20.2 OUTPUT DIRECTORY 20.2 TAGFILES 20.16 OUTPUT LANGUAGE 20.2 TEMPLATE RELATIONS 20.17 PAPER TYPE 20.9 TOC EXPAND 20.8 PDF HYPERLINKS 20.9 TREEVIEW WIDTH 20.8 PERL PATH 20.16 UML LOOK 20.17 PERLMOD LATEX 20.14 USE HTAGS 20.6 PERLMOD PRETTY 20.14 USE PDFLATEX 20.9 PERLMOD MAKEVAR PREFIX 20.14 USE WINDOWS ENCODING 20.2 PREDEFINED 20.15 VERBATIM HEADERS 20.6 PROJECT NAME 20.2 WARN FORMAT 20.4 PROJECT NUMBER 20.2 WARN IF DOC ERROR 20.4 QUIET 20.4 WARN IF UNDOCUMENTED 20.4 RECURSIVE 20.5 WARN LOGFILE 20.4 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 20.2 Project related options 59 WARN NO PARAMDOC 20.4 XML OUTPUT 20.12 WARNINGS 20.4 XML PROGRAMLISTING 20.12 XML SCHEMA 20.12 XML DTD 20.2 20.12 Project related. CREATE SUBDIRS If the CREATE SUBDIRS tag is set to YES, then doxygen will create 4096 subdirectories . OUTPUT LANGUAGE, Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, Italian, Japanese, Korean, Lithuanian, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. USE WINDOWS ENCODING). BRIEF MEMBER DESC If the BRIEF MEMBER DESC tag is set to YES (the default) doxygen will include brief member descriptions after the members that are listed in the file and class documentation (similar to JavaDoc). Set to NO to disable this. REPEAT BRIEF. ABBREVIATE BRIEF”. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 20.2 Project related options INC. CASE SENSE NAMES advised to set this option to NO. SHORT NAMES If the SHORT NAMES tag is set to YES, doxygen will generate much shorter (but less readable) file names. This can be useful is your file systems doesn’t support long names like on DOS, Mac, or CD-ROM.. BUILTIN STL SUPPORT. CPP CLI SUPPORT If you use Microsoft’s C++/CLI language, you should set this option to YES to enable parsing support. DISTRIBUTE GROUP DOC. MULTILINE CPP IS BRIEF. Note that setting this tag to YES also means that rational rose comments are not recognized any more. DETAILS AT TOP If the DETAILS AT TOP tag is set to YES then Doxygen will output the detailed description near the top, like JavaDoc. If set to NO, the detailed description appears after the member documentation. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 60 20.3 Build related options INHERIT DOCS If the INHERIT DOCS tag is set to YES (the default) then an undocumented member inherits the documentation from any documented member that it re-implements. SEPARATE MEMBER PAGES If the SEPARATE MEMBER PAGES tag is set to YES, then doxygen will produce a new page for each member. If set to NO, the documentation of a member will be part of the file/class/namespace that contains it. TAB SIZE the TAB SIZE tag can be used to set the number of spaces in a tab. Doxygen uses this value to replace tabs by spaces in code fragments. ALIASES. OPTIMIZE OUTPUT FOR C JAVA Set the OPTIMIZE OUTPUT JAVA tag to YES if your project consists of Java or Python sources only. Doxygen will then generate output that is more tailored for that language. For instance, namespaces will be presented as packages, qualified scopes will look different, etc. SUBGROUPING. 20.3 Build related options.5.2, written by Dimitri van Heesch 1997-2006 61 20.3 Build related options EXTRACT LOCAL METHODS This flag is only useful for Objective-C code. When set to YES local methods, which are defined in the implementation section but not in the interface are included in the documentation. If set to NO (the default) only methods in the interface are included.. INTERNAL DOCS The INTERNAL DOCS tag determines if documentation that is typed after a \internal command is included. If the tag is set to NO (the default) then the documentation will be excluded. Set it to YES to include the internal documentation. HIDE SCOPE NAMES If the HIDE SCOPE NAMES tag is set to NO (the default) then doxygen will show members with their full class and namespace scopes in the documentation. If set to YES the scope will be hidden. SHOW INCLUDE FILES If the SHOW INCLUDE FILES tag is set to YES (the default) then doxygen will put a list of the files that are included by a file in the documentation of that file. INLINE INFO If the INLINE INFO tag is set to YES (the default) then a tag [inline] is inserted in the documentation for inline members... GENERATE BUGLIST The GENERATE BUGLIST tag can be used to enable (YES) or disable (NO) the bug list. This list is created by putting \bug commands in the documentation. ENABLED SECTIONS The ENABLED SECTIONS tag can be used to enable conditional documentation sections, marked by \if <section-label> ... \endif and \cond <section-label> ... \endcond blocks. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 62 20.4 Options related to warning and progress messages. SHOW USED FILES Set the SHOW USED FILES tag to NO to disable the list of files generated at the bottom of the documentation of classes and structs. If set to YES the list will mention the files that were used to generate the documentation. SHOW DIRECTORIES If the sources in your project are distributed over multiple directories then setting the SHOW DIRECTORIES tag to YES will show the directory hierarchy in the documentation. 20 NO PARAMDOC. 20.5. the libiconv documentation for the list of possible encodings. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 63 20.5 Input related options ∗.php ∗.php3 ∗.inc ∗.m ∗.mm FILE VERSION FILTER. Example of using a shell script as a filter for Unix: </HEAD> <BODY BGCOLOR="#FFFFFF"> If the tag is left blank doxygen will generate a standard header. The following commands have a special meaning inside the header: $title, $datetime, $date, $doxygenversion, $projectname, and $projectnumber. Doxygen will replace them by respectively the title of the page, the current date and time, only the current date, the c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 66 20.8 HTML related options version number of doxygen, the project name (see PROJECT NAME), or the project number (see PROJECT NUMBER). If CREATE SUBDIRS is enabled, the command $relpath$ can be used to produce a relative path to the root of the HTML output directory, e.g. use $relpath$doxygen.css, to refer to the standard style sheet. See also section Doxygen usage for information on how to generate the default header that doxygen normally uses. HTML FOOTER The HTML FOOTER tag can be used to specify a user-defined HTML footer for each generated HTML page. To get valid HTML the footer file should contain at least a </BODY> and a </HTML> tag. A minimal example: </BODY> </HTML> If the tag is left blank doxygen will generate a standard footer. The following commands have a special meaning inside the footer: ). See also section Doxygen usage for information on how to generate the default on Windows. The HTML Help Workshop contains a compiler that can convert all HTML output generated by doxygen into a single compressed HTML file (.chm). Compressed. CHM FILE. HHC LOCATION. GENERATE CHI If the GENERATE HTMLHELP tag is set to YES, the GENERATE CHI flag controls if a separate .chi index file is generated (YES) or that it should be included in the master .chm file (NO). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 67 20.9 LaTeX related options panel EXTRA_PACKAGES = times c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 68 20.10 RTF related options If left blank no extra packages will be included. LATEX HEADER)..10 RTF related options GENERATE RTF If the GENERATE RTF tag is set to YES doxygen will generate RTF output. The RTF output is optimized reader that support those fields. note: WordPad (write) and others do not support links. RTF STYLESHEET FILE Load stylesheet definitions from file. Syntax is similar to doxygen’s config file, i.e. a series of assignments. You only have to provide replacements, missing definitions are set to their default value. See also section Doxygen usage for information on how to generate the default style sheet that doxygen normally uses. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 69 20.11 Man page related options RTF EXTENSIONS FILE Set optional variables used in the generation of an RTF document. Syntax is similar to doxygen’s config file. A template extensions file can be generated using doxygen -e rtf extensionFile. 20.11.12. XML PROGRAMLISTING If the XML PROGRAMLISTING tag is set to YES Doxygen will dump the program listings (including syntax highlighting and cross-referencing information) to the XML output. Note that enabling this will significantly increase the size of the XML output. 20.13.14 PERLMOD related options GENERATE PERLMOD If the GENERATE PERLMOD tag is set to YES Doxygen will generate a Perl module file that captures the structure of the code including all documentation. Note that this feature is still experimental and incomplete at the moment. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 70 20.15 Preprocessor related options PERLMOD LATEX If the PERLMOD LATEX tag is set to YES Doxygen will generate the necessary Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI output from the Perl module output. PERLMOD PRETTY MAKEVAR PREFIX. 20.16 External reference options TAGFILES The TAGFILES tag can be used to specify one or more tagfiles. See section Doxytag usage for more information about the usage of tag files. Optionally an initial location of the external documentation can be added for each tagfile. The format of a tag file without this location is as follows: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 71 20.17 Dot options .17 Dot options CLASS DIAGRAMS If the CLASS DIAGRAMS tag is set to YES (the default) doxygen will generate a class diagram (in HTML. MSCGEN PATH You can define message sequence charts within doxygen comments using the \msc command. Doxygen will then run the msgen tool) to produce the chart and insert it in the documentation. The MSCGEN PATH tag allows you to specify the directory where the mscgen tool resides. If left empty the tool is assumed to be found in the default search path.. GROUP GRAPHS If the GROUP GRAPHS and HAVE DOT tags are set to YES then doxygen will generate a graph for groups, showing the direct groups dependencies. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 72 20.17 Dot options UML LOOK If the UML LOOK tag is set to YES doxygen will generate inheritance and collaboration diagrams in a style similar to the OMG’s Unified Modeling Language.. CALL GRAPH If the CALL GRAPH and HAVE DOT tags. CALLER GRAPH If the CALLER GRAPH and HAVE DOT tags are set to YES then doxygen will generate a caller dependency graph for every global function or class method. Note that enabling this option will significantly increase the time of a run. So in most cases it will be better to enable caller graphs for selected functions only using the \callergraph command. GRAPHICAL HIERARCHY If the GRAPHICAL HIERARCHY and HAVE DOT tags are set to YES then doxygen will graphical hierarchy of all classes instead of a textual one. DIRECTORY GRAPH If the DIRECTORY GRAPH, SHOW DIRECTORIES and HAVE DOT options are set to YES then doxygen will show the dependencies a directory has on other directories in a graphical way. The dependency relations are determined by the #include relations between the files in the directories. DOT GRAPH MAX NODES The MAX will always show the root nodes and its direct children regardless of this setting.). DOT TRANSPARENT Set the DOT TRANSPARENT tag to YES to generate images with a transparent background. This is disabled by default, which results in a white background. Warning: Depending on the platform used, enabling this option may lead to badly anti-aliased labels on the edges of a graph (i.e. they become hard to read). DOT MULTI TARGETS. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 73 20.18 Search engine options.18 Search engine options SEARCHENGINE The SEARCHENGINE tag specifies whether or not the HTML output should contain a search facility. Possible values are YES and NO. If set to YES, doxygen will produce a search index and a PHP script to search through the index. For this to work the documentation should be viewed via a web-server running PHP version 4.1.0 or higher. (See for installation instructions). = = = = = = = = = QdbtTabular html YES examples/examples.doc src *.cc *.h examples qt.tag /usr/local/bin/perl YES To regenerate the Qt-1.44 documentation from the sources, you could use the following config file: PROJECT_NAME OUTPUT_DIRECTORY HIDE_UNDOC_MEMBERS HIDE_UNDOC_CLASSES ENABLE_PREPROCESSING MACRO_EXPANSION EXPAND_ONLY_PREDEF SEARCH_INCLUDES FULL_PATH_NAMES STRIP_FROM_PATH = = = = = = = = = = Qt qt_docs YES YES YES YES YES YES YES $(QTDIR)/ c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 74 20.18 Search engine options PREDEFINED INPUT FILE_PATTERNS INCLUDE_PATH RECURSIVE = USE_TEMPLATECLASS Q_EXPORT= \ QArrayT:=QArray \. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 75 76 21 Special Commands 21.1 Introduction All commands in the documentation start with a backslash (\) or an at-sign (@). If you prefer you can replace all commands starting with a backslash below by their counterparts that start with an at-sign..86 \dontinclude 21.77 \addindex 21.67 \dot 21.92 \dotfile 21.94 \addtogroup 21.2 \anchor 21.68 \e 21.95 \arg 21.87 \else 21.42 \attention 21.35 \elseif 21.43 \author 21.36 \em 21.96 \b 21.88 \endcode 21.97 \brief 21.37 \endcond 21.44 \bug 21.38 \enddot 21.98 \c 21.89 \endhtmlonly 21.100 \callgraph 21.3 \endif \callergraph 21.4 \endlatexonly \category 21.5 \endlink \class 21.6 \endmanonly \code 21.90 \endmsc \cond 21.39 \endverbatim 21.103 \copydoc 21.91 \endxmlonly 21.104 \date 21.40 \enum 21.10 \def 21.7 \example 21.11 \defgroup 21.8 \exception 21.46 \deprecated \dir 21.45 21.101 21.69 21.102 21.99 21.41 \f$ 21.105 21.9 \f[ 21.106 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 21.1 Introduction \f] 77 21.107 \privatesection (PHP only) 21.126 \file 21.12 \property \fn 21.13 \protected (PHP only) 21.126 \hideinitializer 21.14 \protectedsection (PHP only) 21.126 \htmlinclude 21.85 \protocol \htmlonly 21.108 21.25 21.26 \public (PHP only) 21.126 21.126 \if 21.47 \publicsection (PHP only) \ifnot 21.48 \ref 21.71 \image 21.109 \relates 21.27 \include 21.78 \relatesalso 21.28 \includelineno 21.79 \remarks 21.55 \ingroup 21.15 \return 21.56 \internal 21.17 \retval 21.57 \invariant 21.49 \sa 21.58 \interface 21.16 \section 21.73 \latexonly 21.110 \see 21.59 \li 21.112 \showinitializer 21.29 \line 21.80 \since 21.60 \link 21.70 \skip 21.81 \mainpage 21.18 \skipline 21.82 \manonly 21.111 \struct 21.30 \subpage 21.72 \subsection 21.74 \msc \n 21.93 21.113 \name 21.19 \subsubsection 21.75 \namespace 21.20 \test 21.61 \nosubgrouping 21.21 \throw 21.62 \note 21.50 \todo 21.63 \overload 21.22 \typedef 21.31 21.114 \union 21.32 \package 21.23 \until 21.83 \page 21.24 \var 21.33 \par 21.51 \verbatim \paragraph 21.76 \verbinclude 21.84 \param 21.52 \version 21.64 \post 21.53 \warning 21.65 \pre 21.54 \weakgroup 21.34 \p \private (PHP only) 21.126 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 \xmlonly 21.115 21.116 21.2 \addtogroup <name> [(title)] 78 \xrefitem 21.66 \∼ 21.119 \$ 21.121 \< 21.123 \@ 21.118 \> 21.124 \\ 21.117 \# 21.122 \& 21.120 \% 21.125. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 \callergraph 21.4 21.4 \callergraph When this command is put in a comment block of a function or method and HAVE DOT is set to YES, then doxygen will generate a caller graph for that function (provided the implementation of the function or method calls other documented functions). The caller graph will generated regardless of the value of CALLER GRAPH. Note: The completeness (and correctness) of the caller graph depends on the doxygen code parser which is not perfect. 21.5 \category <name> [<header-file>] [<header-name>] For Objective-C only: Indicates that a comment block contains documentation for a class category with name <name>. The arguments are equal to the \class command. See also: section \class. 21.7 \def <name> Indicates that a comment block contains documentation for a #define macro. Example: /*! \file define.h \brief testing defines This is to test the documentation of defines. */ /*! \def MAX(x,y) c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 79 \defgroup <name> (group title) 21.8.8 .9 \dir [<path fragment>] Indicates that a comment block contains documentation for a directory. The ”path fragment” argument should include the directory name and enough of the path to be unique w.r.t. the other directories in the project. The SHOW DIRECTORIES option determines whether or not the directory information is shown and the STRIP FROM PATH option determines what is stripped from the full path before it appears in the output. 21.10 . c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 80 \example <file-name> 21.11 */ /*! \enum Test::TEnum * A description of the enum type. */ /*! \var Test::TEnum Test::Val1 * The description of the first enum value. */ 21.11 \example <file-name> Indicates that a comment block contains documentation for a source code example. The name of the source file is <file-name>. The text of this file will be included in the documentation, just after the documentation contained in the comment block. All examples are placed in a list. The source code is scanned for documented members and classes. If any are found, the names are cross-referenced with the documentation...12 \file [<name>] Indicates that a comment block contains documentation for a source or header file with name <name>. The file name may include (part of) the path if the file-name alone is not unique. If the file name is omitted c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 81 21.13 \fn (function declaration) (i.e. the line after \file is left blank) then the documentation block that contains the \file command will belong to the file it is located in.; Note: In the above example JAVADOC AUTOBRIEF has been set to YES in the configuration file. 21.13 . c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 82 21.14 \hideinitializer See also: section \var and \typedef. 21.15 .16 \interface <name> [<header-file>] [<header-name>] Indicates that a comment block contains documentation for an interface with name <name>. The arguments are equal to the \class command. See also: section \class. 21.17 \internal This command writes the message ‘For internal use only’ to the output and all text after an \internal command until the end of the comment block or the end of the section (whichever comes first) is marked as ”internal”. If the \internal command is put inside a section (see for example \section) all subsection after the command are considered to be internal as well. Only a new section at the same level will be visible again. You can use INTERNAL DOCS in the config file to show or hide the internal documentation. 21.18 _sec Introduction * c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 83 21.19 \name (header) * This is the introduction. * * \section install_sec Installation * * \subsection step1 Step 1: Opening the box * * etc... */ You can refer to the main page using \ref index (if the treeview is disabled, otherwise you should use \ref main). See also: section \section, section \subsection and section \page. 21.19 \name (header) This command turns a comment block into a header definition of a member group. The comment block should be followed by a //@{ ... //@} block containing the members of the group. See section Member Groups for an example. 21.20 \namespace <name> Indicates that a comment block contains documentation for a namespace with name <name>. 21.21 \nosubgrouping This command can be put in the documentation of a class. It can be used in combination with member grouping to avoid that doxygen puts a member group as a subgroup of a Public/Protected/Private/... section. 21.22 . c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 84 21.23 \package <name> Example: class Test { public: void drawRect(int,int,int,int); void drawRect(const Rect &r); }; void Test::drawRect(int x,int y,int w,int h) {} void Test::drawRect(const Rect &r) {} /*! .23 \package <name> Indicates that a comment block contains documentation for a Java package with name <name>. 21.24 . c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 85 21.25 \property (qualified property name) See also: section \section, section \subsection, and section \ref. 21.25 \property (qualified property name) Indicates that a comment block contains documentation for a property (either global or as a member of a class). This command is equivalent to \var and \fn. See also: section \fn and \var. 21.26 \protocol <name> [<header-file>] [<header-name>] Indicates that a comment block contains documentation for a protocol in Objective-C with name <name>. The arguments are equal to the \class command. See also: section \class. 21.27 \relates <name> This command can be used in the documentation of a non-member function <name>. It puts the function inside the ‘related function’ section of the class documentation. This command is useful for documenting.28 \relatesalso <name> This command can be used in the documentation of a non-member function <name>. It puts the function both inside the ‘related function’ section of the class documentation as well as leaving its normal file docc User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 86 21.29 \showinitializer umentation location. This command is useful for documenting non-friend functions that are nevertheless strongly coupled to a certain class. It only works for functions. 21.29 .30 \struct <name> [<header-file>] [<header-name>] Indicates that a comment block contains documentation for a struct with name <name>. The arguments are equal to the \class command. See also: section \class. 21.31 \typedef (typedef declaration) Indicates that a comment block contains documentation for a typedef (either global or as a member of a class). This command is equivalent to \var and \fn. See also: section \fn and \var. 21.32 \union <name> [<header-file>] [<header-name>] Indicates that a comment block contains documentation for a union with name <name>. The arguments are equal to the \class command. See also: section \class. 21.33 \var (variable declaration) Indicates that a comment block contains documentation for a variable or enum value (either global or as a member of a class). This command is equivalent to \typedef and \fn. See also: section \fn and \typedef. 21.34 \weakgroup <name> [(title)] Can be used exactly like \addtogroup, but has a lower priority when it comes to resolving conflicting grouping definitions. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 87 21.35 \attention { attention text } See also: page Grouping and \addtogroup. Section indicators 21.35 .36 . \warning This class may explode in your face. \warning If you inherit anything from this class, you’re doomed. class WindowsNT {}; 21.37 .38 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 88 21.39 \cond [<section-label>] ends when a blank line or some other sectioning command is encountered. See section \author for an example. 21.39 \cond [<section-label>] Starts a conditional section that ends with a corresponding \endcond command, which is typically found in another comment block. The main purpose of this pair of commands is to (conditionally) exclude part of a file from processing (traditionally this could only be achieved using C processor commands). The section between \cond and \endcond commands can be included by adding its section label to the ENABLED SECTIONS configuration option. If the section label is omitted, the section will be excluded from processing unconditionally. For conditional sections within a comment block one should use a \if ... \endif block. Conditional sections can be nested. In this case a nested section will only be shown if it and its containing section are included. Here is an example showing the commands in action: /** An interface */ class Intf { public: /** A method */ virtual void func() = 0; /// @cond TEST /** A method used for testing */ virtual void test() = 0; /// @endcond }; /// @cond DEV /* * The implementation of the interface */ class Implementation : public Intf { public: void func(); /// @cond TEST void test(); /// @endcond /// @cond /** This method is obsolete and does * not show up in the documentation. */ void obsolete(); /// @endcond }; /// @endcond The output will be different depending on whether ENABLED SECTIONS is empty, TEST, DEV, or DEV TEST. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 89 21.40 \date { date description } 21.40 .41 \deprecated { description } Starts a paragraph indicating that this documentation block belongs to a deprecated entity. Can be used to describe alternatives, expected life span, etc. 21.42 \else Starts a conditional section if the previous conditional section was not enabled. The previous section should have been started with a \if, \ifnot, or \elseif command. See also: \if, \ifnot, \elseif, \endif. 21.43 .44 \endcond Ends a conditional section that was started by \cond. See also: \cond. 21.45 \endif Ends a conditional section that was started by \if or \ifnot For each \if or \ifnot one and only one matching \endif must follow. See also: \if, and \ifnot. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 90 21.46 \exception <exception-object> { exception description } 21.46 .47 . Note that for C# code, this command is equivalent to \code. • </CODE> End a <CODE> section. Note that for C# code, this command is equivalent to \endcode. • <DD> Starts an item description. • <DFN> Starts a piece of text displayed in a typewriter font. • </DFN> Ends a <DFN> section. • <DIV> Starts a section with a specific style (HTML only) • </DIV> Ends a section with a specific style (HTML only). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 112 <SPAN> Starts an inline text fragment with a specific style (HTML only) • </SPAN> Ends an inline text fragment with a specific style (HTML only). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 113: • © the copyright symbol • &tm; the trade mark symbol • ® the registered trade mark symbol • < less-than symbol • > greater-than symbol • & ampersand • ' single quotation mark (straight) • " double quotation mark (straight) • ‘ left single quotation mark • ’ right single quotation mark • “ left double quotation mark • ” right double quotation mark • – n-dash (for numeric ranges, eg. 2–8) • — m-dash (for parenthetical punctuation — like this). ß) to the output. • &?cedil; where ? is one of {c,C}, writes a c-cedille (like ç). c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 114 • &?ring; where ? is one of {a,A}, writes an a with a ring (like å). • a non breakable space. Finally, to put invisible comments inside comment blocks, HTML style comments can be used: /*! <!-- This is a comment with a comment block --> Visible text */ 23 XML Commands: • <c> Identifies inline text that should be rendered as a piece of code. <tt>text</tt>. Similar to using • <code> Set one or more lines of source code or program output. Note that this command behaves like \code ... \endcode for C# code, but it behaves like the HTML equivalent <code>...</code> for other languages. • <description> Part of a <list> command, describes an item. • <example> Marks a block of text as an example, ignored by doxygen. • <exception cref="member"> Identifies the exception a method can throw. • <include> Can be used to import a piece of XML from an external file. Ignored by doxygen at the moment. • <item> List item. Can only be used inside a <list> context. • <list type="type"> Starts a list, supported types are bullet or number. A list consists of a number of <item> tags. • <para> Identifies a paragraph of text. • <param name="paramName"> Marks a piece of text as the documentation for parameter ”paramName”. Similar to using \param. • <paramref name="paramName"> Refers to a parameter with name ”paramName”. Similar to using \a. • <permission> Identifies the security accessibility of a member. Ignored by doygen. • <remarks> Identifies the detailed description. • <returns> Marks a piece of text as the return value of a function or method. Similar to using \return. • <see cref="member"> Refers to a member. Similar to \ref. • <seealso cref="member"> Starts a ”See also” section referring to ”member”. Similar to using \sa member. • <summary> Identifies the brief description. Similar to using \brief. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 115 • <value> Identifies a property. Ignored by doxygen. Here is an example of a typical piece of code using some of the above commands: /// ; } } Part III Developers Manual 24 Doxygen’s Internals Doxygen’s internals Note that this section is still under construction! The following picture shows how source files are processed by doxygen. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 116.5.2, written by Dimitri van Heesch 1997-2006 117.5.2, written by Dimitri van Heesch 1997-2006 118.5.2, written by Dimitri van Heesch 1997-2006 119 print STDERR "Error: opening file Makefile.libdoxygen for writing\n"; exit 1; } print "Processing Makefile.libdoxygen...\n"; while (<F>) { if ( s/\(LEX\) -P([a-zA-Z]+)YY -t $file/(LEX) -d -P\1YY -t $file/g ) { print "Enabling debug info for $file\n"; } elsif ( s/\(LEX\) -d -P([a-zA 25. 25.5.2, written by Dimitri van Heesch 1997-2006 25. 25. 25.5.2, written by Dimitri van Heesch 1997-2006 120 25.3 Perl Module documentation format. This should generate a doxylatex.pdf with the documentation in PDF format. 5. Run: make dvi This should generate a doxylatex.dvi with the documentation in DVI format. 25. 25. 26 Internationalization Support for multiple languages Doxygen has built-in support for multiple languages. This means that the text fragments, generated by doxygen, can be produced in languages other than English (the default). The output language is chosen through the configuration file (with default name and known as Doxyfile). Currently (version 1.5.2), 33 languages are supported (sorted alphabetically): Afrikaans, Arabic, Brazilian Portuguese, Catalan, Chinese, Chinese Traditional, Croatian, Czech, Danish, Dutch, English, Finnish, c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 121 122 French, German, Greek, Hungarian, Indonesian, Italian, Japanese (+En), Korean (+En), Lithuanian, Norwegian, Persian,. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 123 Language Afrikaans Arabic Brazilian Portuguese Catalan Chinese Chinese Traditional Croatian Czech Danish Dutch English Finnish French German Greek Hungarian Indonesian Italian Japanese JapaneseEn Korean KoreanEn Lithuanian Norwegian Persian Polish Portuguese Romanian Russian Serbian Slovak Slovene Spanish Swedish Ukrainian Maintainer Johan Prinsloo Moaz Reyad Fabio ”FJTC” Jun Takada Chino Maximiliano Pin Albert Mora Li Daobing Wei Liu Daniel YC Lin Paul Gessos Ákos Kiss Földvári György Hendy Irawan Alessandro Falappa Ahmed Aldo Faisal Ryunosuke Satoh Kenji Nagamatsu Iwasa Kazmi see the Japanese language SooYoung Jung Richard Kim see the Korean language Tomas Simonaitis Mindaugas Radzius Aidas Berukstis Lars Erik Jordet Ali Nadalizadeh Bartomeu Francisco Oltra Thennet Mikael Hallin Olexij Tkatchenko Contact address [email protected] [email protected] [email protected] [email protected] Status 1.4.6 1.4.6 up-to-date up-to-date [email protected] [email protected] up-to-date [email protected] [email protected] 1.4.6 [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] olli.korhonen [email protected] [email protected] [email protected] [email protected] [email protected] up-to-date up-to-date up-to-date up-to-date up-to-date obsolete up-to-date up-to-date up-to-date 1.4.6 foldvari [email protected] [email protected] [email protected] 1.4.6 up-to-date [email protected] [email protected] up-to-date [email protected] [email protected] [email protected] English based 1.4.6 [email protected] [email protected] English based 1.4.6 [email protected] [email protected] [email protected] [email protected] [email protected] 1.4.6 1.4.6 1.4.6 g [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] 1.3.3 1.4.1 up-to-date 1.4.1 1.2.18 1.4.6 up-to-date [email protected] [email protected] [email protected] 1.4.6 1.4.1. c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 124 Adding a new language to doxygen This short HOWTO explains how to add support for the new language to Doxygen: use. #define preprocessor commands at the beginning of the file). in the #ifndef and: c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 125 –) c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 126). Looking at the base class of the language translator, the script guesses also the status of the translator – see the last column of the table with languages above. The translator.py c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 127 newer translator adapter. Run the translator.py script occasionaly.5.2, written by Dimitri van Heesch 1997-2006 Index \#, 109 \$, 109 \&, 109 \<, 110 \>, 110 \\, 109 \%, 110 \a, 101 \addindex, 96 \addtogroup, 78, 87 \anchor, 96 \arg, 101 \attention, 88 \author, 88 \b, 102 \brief, 88 \bug, 88 \c, 102 \callergraph, 79 \callgraph, 78 \category, 79 \class, 79 \code, 102 \cond, 89 \copydoc, 102 \date, 90 \def, 79 \defgroup, 80 \deprecated, 90 \dir, 80 \dontinclude, 98 \dot, 103 \dotfile, 104 \e , 104 \else, 90 \elseif, 90 \em , 104 \endcode, 105 \endcond, 90 \enddot, 105 \endhtmlonly, 105 \endif, 90 \endlatexonly, 105 \endlink , 96 \endmanonly, 105 \endmsc, 105 \endverbatim, 105 \endxmlonly, 106 \enum, 80 \example, 81 \exception, 91 \f$, 106 \f[, 106 \f], 106 \file, 81 \fn, 82 \hideinitializer, 83 \htmlinclude, 101 \htmlonly, 106 \if, 91 \ifnot, 92 \image, 106 \include, 99 \includelineno, 99 \ingroup, 83 \interface, 83 \internal, 83 \invariant, 92 \latexonly, 107 \li, 108 \line, 100 \link, 96 \mainpage, 83 \manonly, 107 \msc, 103 \n, 108 \namespace, 84 \nosubgrouping, 84 \note, 92 \overload, 84 \p, 108 \package, 85 \page, 85 \par, 92 \paragraph, 98 \param, 93 \post, 93 \pre, 93 \property, 86 \protocol, 86 \ref, 96 \relates, 86 \relatesalso, 86 \remarks, 94 \return, 94 \retval, 94 \sa, 94 \section, 97 \see, 94 \showinitializer, 87 \since, 94 \skip, 100 INDEX \skipline, 100 \struct, 87 \subpage, 97 \subsection, 98 \subsubsection, 98 \test, 95 \throw, 95 \todo, 95 \typedef, 87 \union, 87 \until, 100 \var, 87 \verbatim, 108 \verbinclude, 101 \version, 95 \warning, 95 \xmlonly, 109 \xrefitem, 95 \∼, 109 ABBREVIATE BRIEF, 59 acknowledgements, 3 ALIASES, 61 ALLEXTERNALS, 72 ALPHABETICAL INDEX, 66 ALWAYS DETAILED SEC, 60 BINARY TOC, 68 bison, 4 BRIEF MEMBER DESC, 59 browser, 12 BUILTIN STL SUPPORT, 60 CALL GRAPH, 73 CALLER GRAPH, 73 CASE SENSE NAMES, 60 CHM FILE, 67 CLASS DIAGRAMS, 72 CLASS GRAPH, 72 COLLABORATION GRAPH, 72 COLS IN ALPHA INDEX, 66 COMPACT LATEX, 68 COMPACT RTF, 69 CPP CLI SUPPORT, 60 CREATE SUBDIRS, 59 DETAILS AT TOP, 60 DIRECTORY GRAPH , 73 DISABLE INDEX, 68 DISTRIBUTE GROUP DOC, 60 Doc++, 3 DOT CLEANUP, 74 DOT GRAPH MAX NODES, 73 DOT IMAGE FORMAT, 73 129 DOT MULTI TARGET, 73 DOT PATH, 73 DOT TRANSPARENT, 73 DOTFILE DIRS, 73 ENABLE PREPROCESSING, 71 ENABLED SECTIONS, 62 ENUM VALUES PER LINE, 68 EXAMPLE PATH, 64 EXAMPLE PATTERNS, 64 EXAMPLE RECURSIVE, 64 EXCLUDE, 64 EXCLUDE PATTERNS, 64 EXCLUDE SYMLINKS, 64 EXPAND AS DEFINED, 71 EXPAND ONLY PREDEF, 71 EXTERNAL GROUPS, 72 EXTRA PACKAGES, 68 EXTRACT ALL, 61 EXTRACT LOCAL CLASSES, 61 EXTRACT LOCAL METHODS, 62 EXTRACT PRIVATE, 61 EXTRACT STATIC, 61 features, 47 FILE PATTERNS, 64 FILE VERSION FILTER, 64 FILTER PATTERNS, 65 FILTER SOURCE FILES, 65 flex, 4 FULL PATH NAMES, 60 GENERATE AUTOGEN DEF, 70 GENERATE BUGLIST, 62 GENERATE CHI, 67 GENERATE DEPRECATEDLIST, 62 GENERATE HTML, 66 GENERATE HTMLHELP, 67 GENERATE LATEX, 68 GENERATE LEGEND, 74 GENERATE MAN, 70 GENERATE PERLMOD, 70 GENERATE RTF, 69 GENERATE TAGFILE, 72 GENERATE TESTLIST, 62 GENERATE TODOLIST, 62 GENERATE TREEVIEW, 68 GENERATE XML, 70 GPL, 2 GRAPHICAL HIERARCHY, 73 GROUP GRAPHS, 72 HAVE DOT, 72 HHC LOCATION, 67 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 INDEX HIDE FRIEND COMPOUNDS, 62 HIDE IN BODY DOCS, 62 HIDE SCOPE NAMES, 62 HIDE UNDOC CLASSES, 62 HIDE UNDOC MEMBERS, 62 HIDE UNDOC RELATIONS, 73 HTML ALIGN MEMBERS, 67 HTML FILE EXTENSION, 66 HTML FOOTER, 67 HTML HEADER, 66 HTML OUTPUT, 66 HTML STYLESHEET, 67 IGNORE PREFIX, 66 IMAGE PATH, 65 INCLUDE GRAPH , 73 INCLUDE PATH, 71 INCLUDED BY GRAPH , 73 INHERIT DOCS, 61 INLINE INFO , 62 INLINE INHERITED MEMB, 60 INLINE SOURCES, 65 INPUT, 63 INPUT FILTER, 65 installation, 4 INTERNAL DOCS, 62 JAVADOC AUTOBRIEF, 60 LaTeX, 12 LATEX BATCHMODE, 69 LATEX CMD NAME, 68 LATEX HEADER, 69 LATEX HIDE INDICES, 69 LATEX OUTPUT, 68 LATEX PDFLATEX, 69 license, 2 MACRO EXPANSION, 71 make, 4 MAKEINDEX CMD NAME, 68 MAN LINKS, 70 MAN OUTPUT, 70 MAX EXTENSION, 70 MAX INITIALIZER LINES, 63 MSCGEN PATH, 72 MULTILINE CPP IS BRIEF, 60 OPTIMIZE OUTPUT FOR C, 61 OPTIMIZE OUTPUT JAVA, 61 output formats, 40 OUTPUT DIRECTORY, 59 OUTPUT LANGUAGE, 59 PAPER TYPE, 68 130 parsing, 13 PDF HYPERLINKS, 69 perl, 4 PERL PATH, 72 perlmod, 119 PERLMOD LATEX, 71 PERLMOD MAKEVAR PREFIX, 71 PERLMOD PRETTY, 71 PREDEFINED, 71 PROJECT NAME, 59 PROJECT NUMBER, 59 Qt, 4 QUIET, 63 RECURSIVE, 64 REFERENCED BY RELATION, 65 REFERENCES LINK SOURCE, 65 REFERENCES RELATION, 65 REPEAT BRIEF, 59 RTF, 12 RTF HYPERLINKS, 69 RTF OUTPUT, 69 RTF STYLESHEET FILE, 69 SEARCH INCLUDES , 71 SEARCHENGINE, 74 SEPARATE MEMBER PAGES, 61 SHORT NAMES, 60 SHOW DIRECTORIES, 63 SHOW INCLUDE FILES, 62 SHOW USED FILES, 63 SKIP FUNCTION MACROS, 71 SORT BRIEF DOCS, 62 SORT MEMBER DOCS, 62 SOURCE BROWSER, 65 STRIP CODE COMMENTS, 65 STRIP FROM INC PATH, 60 STRIP FROM PATH, 60 SUBGROUPING, 61 TAB SIZE, 61 TAGFILES, 71 TEMPLATE RELATIONS, 73 TOC EXPAND, 68 TREEVIEW WIDTH, 68 UML LOOK, 73 USE HTAGS, 65 USE WINDOWS ENCODING, 59 VERBATIM HEADERS, 65 WARN FORMAT, 63 WARN IF DOC ERROR, 63 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 INDEX WARN IF UNDOCUMENTED, 63 WARN LOGFILE, 63 WARN NO PARAMDOC, 63 WARNINGS, 63 XML, 12 XML DTD, 70 XML OUTPUT, 70 XML PROGRAMLISTING, 70 XML SCHEMA, 70 c User Manual for Doxygen 1.5.2, written by Dimitri van Heesch 1997-2006 131
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project | https://manualzz.com/doc/7168172/manual-for-version-1.5.2-written-by-dimitri-van-heesch-c-. | CC-MAIN-2020-40 | refinedweb | 12,273 | 68.77 |
If you’ve ever looked at even small amounts of CIL, you’ll notice that two different instructions are used to call methods: “call” and “callvirt”. My goal in this post is to introduce these two methods and provide a general understanding of how they are used.
call – The basics
Call provides basic method calling functionality in CIL. Let’s jump right into an example to see how it works.
class Program { static void Main(string[] args) { Printer.Print("Hello World"); } } public class Printer { public static void Print(string message) { Console.WriteLine(message); } }
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Hello World" IL_0005: call void ConsoleApplication1.Printer::Print(string) IL_000a: ret } // end of method Program::Main
.method public hidebysig static void Print(string message) cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void [mscorlib]System.Console::WriteLine(string) IL_0006: ret } // end of method Printer::Print
There isn’t actually anything too complicated going on here. When we execute Main, “Hello World” is loaded onto the stack, and then the Print method, which takes a single string parameter, is called using the “call” instruction. Notice that the call instruction itself takes as a descriptor a reference to the method to call. (This reference is actually a metadata token, but going into details about metadata is a topic for another day.) When call executes, it pops the number of arguments of the stack that the method being called requires, and passes them as zero-indexed arguments to the method. We can see this in action at line IL_0000 of the Print method, where we load “argument 0” onto the stack so that it can be passed to the Console.WriteLine method by another “call” invocation. In our case the Print method doesn’t return anything, but if it did the return value would simply be pushed onto the stack before the final “ret” call of the method.
callvirt – The basics
Perhaps the easiest way to distinguish call from callvirt is to refer to their different descriptions in the CIL spec. While call is simply used to “call a method”, “callvirt” is used to “call a method associated, at runtime, with an object”. To understand how the notion of an object impacts a method call, take this function.
public static void Print(object thingy) { Console.WriteLine(thingy.ToString()); }
As we learned back in this post, the behaviour that this method will exhibit is entirely dependent on what type “thingy” really is, due to the fact that ToString() is a virtual method. But how can the runtime know what implementation of “ToString” to call if it calls it on a simple object? Well, this is where callvirt really starts to make sense. Callvirt takes into account the type of the object on which the method is being called in order to provide us with the polymorphic behaviour that we expect from such cases. All that is required in order to execute a callvirt instruction is to pass a pointer to the object on which the method is being called. We can see this if we look at the IL of the ToString() call in the Print method.
.method private hidebysig instance void Print(object thingy) cil managed { // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.1 IL_0001: callvirt instance string [mscorlib]System.Object::ToString() IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: ret } // end of method Printer::Print
The override of ToString() that we are calling doesn’t take any parameters, however before calling it, argument at index 0 is loaded onto the stack. Argument at index 0 is of course “thingy”, whatever it happens to be. When callvirt is executed to call the ToString() method, it first verifies that “thingy” isn’t null, and then goes on to determine the type of “thingy” before locating the correct instance of ToString() to call by walking up the inheritance tree until it finds a valid ToString() implementation.
When callvirt replaces call…
So far the distinction that we have made between call and callvirt has been simple: call provides simple method calling functionality, while callvirt provides support for virtual methods and polymorphism. However, if you begin to examine the IL of your own C# programs you’ll notice that callvirt is also used to call nonvirtual instance methods. But why would the C# compiler do this? Off the top of my head I can think of two advantages:
- Nonvirtual methods can be made virtual without recompiling calling assemblies.
- Developers don’t need to keep track of which methods are virtual and can therefore be called on null references (because of callvirt’s integrated null check). This “feature” is limiting, but simplifies coding. It is also important to understand that calling nonvirtual methods with callvirt doesn’t impact performance as much as one may think. While the null reference check integrated into callvirt is still performed on nonvirtual calls, if the jitter knows that a given method is nonvirtual it won’t bother searching through the inheritance tree to find the correct method implementation. It’ll go straight to the correct implementation just as call would. This makes callvirt almost as fast as call when calling nonvirtual instance methods.
When call replaces callvirt…
Despite the fact that it doesn’t have “virt” in the name, call can still be used to call nonvirtual methods. It simply calls them nonvirtually, invoking the method declared on the type of the variable instance as it appears in the calling scope. An example of when this occurs is when an overriding method calls a base implementation. Were the call to be made with callvirt, the runtime would end up re-calling the derived implementation which would then re-call the base implementation and so on and so forth until a stack overflow occurred.
Final word
Hopefully by now you’ll have a decent understanding of the call and callvirt instructions. This understanding will be important in several upcoming articles, so stay tuned to make use of what we’ve discussed. | http://www.levibotelho.com/development/call-and-callvirt-in-cil/ | CC-MAIN-2018-34 | refinedweb | 1,017 | 61.77 |
Python Examples on github
Good evening.
I have downloaded a few of the python examples from the Onion GitHub page to try out. The first one I tried to use PWM.py just kicked out an error as follows:
root@Omega-172E:/Python-PWM/onion# python PWM.py
Traceback (most recent call last):
File "PWM.py", line 5, in <module>
from onion import I2C
ImportError: No module named onion
Am I missing something? Is there a module I have to download before using the examples?
Thanks in advance for any info.
Hi @Daniel-Wright, we have updated our python libraries. Please view instruction here: on how to use it to control the PWM Expansion.
Cheers!
@B.
Hi @Daniel-Wright, Ah, I see what you are looking for. The reason that we have shown instructions on how to turn servo to a given angle is because we have found out that each servo has different settings, and would requite different duty cycle to get to a given angle. So with the old python library, unless you are using the same servo motor that we were using, you would still need to adjust the duty cycle to get to the angle that you want. This will also depend on the type of servo you choose to use (180 degrees, 360 degrees, or continuous). The library mentioned in the dependency error you posted is. However, the main problem is that this package depends on a package on OpenWRT called
smbus, which has been broken for the current release of OpenWRT.
I think the best option for your project might be to test out the servo motor that you are planning to use with the PWM Control Console App. Try adjusting the values to the angles that you wish to use, and setting those duty cycles using the new python libraries. On our end we might also be able to add a couple of functions to directly set the angles for the most commonly used servo motors.
Good morning @Boken-Lin,
Thank you for your reply. That i helpful. My experience has mainly been with the Arduino platform and the PicAxe platform so all this python programing and stuff is fairly new to me… I'm learning though.
I can't wait for the Cloud thing to be available and see what kind of info and projects end up on there.
Any tips on learning python and stuff easier???
Thanks again.
! | http://community.onion.io/topic/321/python-examples-on-github/ | CC-MAIN-2019-39 | refinedweb | 407 | 71.75 |
2.1.1 ?IMPORT?
Quirks Mode, IE7 Mode, IE8 Mode, and IE9 Mode (All Versions)
A processing instruction that imports a tag definition from an element behavior. Two attributes are required:
The value of an XMLNS attribute that has been defined in the HTML tag must correspond to the value of the namespace attribute defined in the IMPORT processing instruction (PI). Otherwise, the imported tag definition cannot be used.
An imported tag will not render if the value of the implementation attribute is not valid. When using an HTC file, the file must comply with the same security rules as all behaviors. For more information, see Introduction to DHTML Behaviors [MSDN-DHTMLBehaviors].
The IMPORT PI must be placed before the first instance of a custom element that uses the imported tag definition. If the IMPORT PI is placed after the custom element, the behavior does not attach to the custom element. This also means that the document.write method should not be used to add the IMPORT PI to a document.
The IMPORT PI is only processed during the initial parsing of the document. Therefore, a document that uses an element behavior must include the IMPORT PI in the HTML file. Provided that the IMPORT PI is specified in the primary document, the document.write method can be used to add the custom element and attach to the behavior. | https://msdn.microsoft.com/en-us/library/ff628832(v=vs.85) | CC-MAIN-2017-13 | refinedweb | 229 | 55.24 |
In addition to Python’s built-in data types, Jython has the benefit of using Java collection classes by importing the java.util package. The following code describes the classes given below −
import java.util.ArrayList as ArrayList arr = ArrayList() arr.add(10) arr.add(20) print "ArrayList:",arr arr.remove(10) #remove 10 from arraylist arr.add(0,5) #add 5 at 0th index print "ArrayList:",arr print "element at index 1:",arr.get(1) #retrieve item at index 1 arr.set(0,100) #set item at 0th index to 100 print "ArrayList:",arr
The above Jython script produces the following output −
C:\jython27\bin>jython arrlist.py ArrayList: [10, 20] ArrayList: [5, 20] element at index 1: 20 ArrayList: [100, 20]
Jython also implements the Jarray Object, which allows construction of a Java array in Python. In order to work with a jarray, simply define a sequence type in Jython and pass it to the jarrayobject along with the type of object contained within the sequence. All values within a jarray must be of the same type.
The following table shows the character typecodes used with a jarray.
The following example shows construction of jarray.
my_seq = (1,2,3,4,5) from jarray import array arr1 = array(my_seq,'i') print arr1 myStr = "Hello Jython" arr2 = array(myStr,'c') print arr2
Here my_seq is defined as a tuple of integers. It is converted to Jarray arr1. The second example shows that Jarray arr2 is constructed from mySttr string sequence. The output of the above script jarray.py is as follows −
array('i', [1, 2, 3, 4, 5]) array('c', 'Hello Jython') | https://www.tutorialspoint.com/jython/jython_using_java_collection_types.htm | CC-MAIN-2021-43 | refinedweb | 272 | 58.28 |
Check Python version using Python Script
In this article, we will learn the command to check the version of Python using Python script. Let's first have a quick look over what is a Python script.
Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing the python script has the extension
‘.py’ or can also have the extension
‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.
Check Python Version
Like much other software, Python too has several different versions released to date. After Python or any installation, one should check the version of the software that is running the script. Python uses
version keywords to check the Python version. The python script is a simple code that can be run in different modes such as using a Python interpreter, on a command line, or using any Python editor. Let us look over the commands to check the Python version.
There are different versions of Python, but the two most popular ones are Python 2 and Python 3. When looking at the version number, there are usually three digits to read:
- the major version
- the minor version
- the micro version
Let us look over the commands to check the Python version.
Check Python Version in Linux
Most modern Linux distributions come with Python pre-installed. To check the version installed, open the Linux terminal window and enter the given command:
python ––version
Check Python Version in Windows
Most out-of-the-box Windows installations do not come with Python pre-installed. However, it is always a good practice to check the version. To check the version installed, open Windows Powershell or any Python editor, and enter the given command:
python ––version
Check Python Version in MacOS
If you are using a macOS, check the Python version by entering the given command in the terminal:
python –version
In all the three version checks, you will an output somewhat like Python 3.5.2. As discussed above 3 is the major version, 5 is the minor version and 2 is the micro version.
Use sys module to check Python version
import sys print("Python version") print (sys.version) print("Version info.") print (sys.version_info)
Python version
3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609]
Version info.
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
Use platform module to check Python version
from platform import python_version print(python_version())
3.5.2
Conclusion
In this article, we learned to use a simple command
python --version to check the version of Python on any Python script whether it is an editor, interpreter, or a command line. We saw the other two ways i.e.
sys.version and
python_version to check the Python version. | https://www.studytonight.com/python-howtos/check-python-version-using-python-script | CC-MAIN-2022-21 | refinedweb | 492 | 72.26 |
Quick links
Name: Mutex locked twice
Description: Calling the lock method of a mutex twice in succession might cause a deadlock.
ID: cpp/twice-locked
Kind: problem
Severity: error
Precision: low
/** * @name Mutex locked twice * @description Calling the lock method of a mutex twice in succession * might cause a deadlock. * @kind problem * @id cpp/twice-locked * @problem.severity error * @precision low * @tags security * external/cwe/cwe-764 * external/cwe/cwe-833 */ import cpp import semmle.code.cpp.commons.Synchronization import LockFlow /** * Holds if `call` locks `v`, via the access `a`, but `v` might already * be locked when we reach `call`. The access `a` might be in a function * which is called indirectly from `call`. */ cached private predicate twiceLocked( FunctionCall call, Variable v, VariableAccess a) { lockedOnEntry(v.getAnAccess(), call) and lockedInCall(a, call) } /* * When this query finds a result, there are often multiple call sites * associated with one instance of the problem. For this reason, we do not * include `call` in the result. However, it is sometimes helpful to * include `call.getLocation()` in the result, because it can help to find * the control flow path which might be responsible. */ from FunctionCall call, Variable v, VariableAccess access2 where twiceLocked(call, v, access2) and v = access2.getTarget() and // If the second lock is a `try_lock` then it won't cause a deadlock. // We want to be extra sure that the second lock is not a `try_lock` // to make sure that we don't generate too many false positives, so // we use three heuristics: // // 1. The call is to a function named "try_lock". // 2. The result of the call is used in a condition. For example: // if (pthread_mutex_lock(mtx) != 0) return -1; // 3. The call is a condition. Because the analysis is interprocedural, // `call` might be an indirect call to `lock`, so this heuristic // catches some cases which the second heuristic does not. not (trylockCall(access2, _) or tryLockCondition(access2, _, _) or call.isCondition()) select access2, "Mutex " + v + " might be locked already, which could cause a deadlock."
Mutexes come in two flavors: recursive and non-recursive. For example,
the C++ mutex library provides both
std::mutex
and
std::recursive_mutex. A non-recursive mutex cannot
be locked until it has been unlocked by its previous owner, even if it
is already owned by the current thread. Deadlock is often caused by a
thread attempting to lock the same mutex twice, usually in a recursive
algorithm.
If a recursive method needs to acquire a lock, then split it into two methods. The first method is public and is responsible for locking and unlocking the mutex. It delegates the rest of the work to a second private method. The second method does not need to lock or unlock the mutex because that is done by the first method.
In this example, the method
f is recursive, so it causes
a deadlock by attempting to lock the mutex twice.
class C { std::mutex mutex; public: // BAD: recursion causes deadlock. int f(int n) { mutex.lock(); int result = (n == 0) ? 1 : n*f(n-1); mutex.unlock(); return result; } };
In this second example, the recursion is delegated to an internal method so the mutex is only locked once.
class C { std::mutex mutex; int f_impl(int n) { return (n == 0) ? 1 : n*f_impl(n-1); } public: // GOOD: recursion is delegated to f_impl. int f(int n) { mutex.lock(); int result = f_impl(n); mutex.unlock(); return result; } }; | https://help.semmle.com/wiki/display/CCPPOBJ/Mutex+locked+twice | CC-MAIN-2019-26 | refinedweb | 568 | 58.58 |
Created on 2011-03-04 05:47 by casevh, last changed 2014-08-03 06:18 by haypo. This issue is now closed.
Python 3.2 fails when printing long strings.
C:\Python32>python
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("a"*66000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 12] Not enough space
>>>
Some observations:
1) 3.2 on Linux prints just fine.
2) 2.7.1 and 3.1.3 on Windows x64 are fine
3) The 32-bit interpreter for 3.2 also fails.
4) On 32-bit Windows, a length of 62733 works correctly but 62734, and higher, fail.
5) On 64-bit Windows, the output is visibly corrupted when the length reaches 62801 but the error does not occur until the length reaches 65536.
6) While experimenting with various lengths, I was able to crash the interpreter once.
Likewise, this fails with 3.2::
import os
os.write(1, b"a" * 66000)
It's probably a Windows limitation regarding the number of bytes that can be written to stdout in one write.
As for the difference between python versions, what does
python -c "import sys; print(sys.getsizeof('a'))" return ?
no, it works with 3.2b2 (r32b2:87398), and fails with 3.2 final (r32:88445)
Extract of issue #1602:
<< WriteConsoleW has one bug that I know of, which is that it <a href="">fails when writing more than 26608 characters at once</a>. That's easy to work around by limiting the amount of data passed in a single call. >>
I suppose that os.write(1) does indirectly write into the Windows console which has this limit.
Extract of the WriteConsole Function:
<< The storage for this buffer is allocated from a shared heap for the process that is 64 KB in size. The maximum size of the buffer will depend on heap usage. >>
Ah ah, that's funny, "depend on heap usage" :-)
This changed with r87824
> This changed with r87824
Yes, I changed Python to open all files in binary mode. With Python < 3.2, you can open sys.std* streams in binary mode using -u command line option (u like unbuffered, not Unicode ;-)).
Indeed, Python3.1 fails with the -u option.
Before r87824, the C call to write() performed CRLF conversion. In the implementation of MSVCRT, a local buffer is used (1025 chars in vs8.0, 5*1024 in vs10.0), so WriteFile is called with small sizes.
Since r87824 (or with -u), no such conversion occurs, and WriteFile is called with the full buffer.
Anyway, use os.write() to write unicode into the Windows console is not the right thing to do. We should use WriteConsoleW(): #1602 is the correct fix for this issue.
I'm writing bytes here: os.write(1, b"b" * 66000)
And WriteConsole has the same issue.
> And WriteConsole has the same issue.
print() (sys.stdout and sys.stderr) should use WriteConsoleW() and use small chunks (smaller than 64 KB, I don't know the safest size).
IIUC, this is a Windows bug? Is there any easy workaround for us?
It may be a windows bug, but it's also an a python regression!
A fix is to limit the number of chars:
===================================================================
--- D:/py3k/Modules/_io/fileio.c (revision 87824)
+++ D:/py3k/Modules/_io/fileio.c (copie de travail)
@@ -712,6 +712,8 @@
errno = 0;
len = pbuf.len;
#if defined(MS_WIN64) || defined(MS_WINDOWS)
+ if (len > 32000 && isatty(self->fd))
+ len = 32000;
if (len > INT_MAX)
len = INT_MAX;
n = write(self->fd, pbuf.buf, (int)len);
On my system, errors start at ~52200 (why?). I hope that 32K is low enough... MSVCRT's write() (version vs10.0) uses a buffer of 5K.
print("a"*66000)
works (after some delay) running from an IDLE edit window (but see #144249). Works means that I get a working prompt back with no errors.
Unlike IDLE, the Command Prompt Windows keeps a limited number of lines in its buffers (default: 4x50), and may have a total size limit.
I'm adding a test that will reproduce the crash.
And a patch for the test + fix.
> Indeed, Python3.1 fails with the -u option.
I'm also attaching another test to reproduce the crash with '-u' option.
I did some tests: os.write(1, b'X'*length) does always fail with length >= 63842. It does sometimes fail with length > 35000. The maximum looks completly random: as written in Microsoft documentation, "The maximum size of the buffer will depend on heap usage"...
32000 looks arbitrary. I would prefer 2^15-1 (32767) because it looks less magical :-)
Remarks about test_wconsole_binlarge.patch:
- I don't know if isatty() is cheap or not. Is it a system call? If it might be slow, it should be only be called once in the constructor. On Windows, I don't think that isatty(fd) evoles.
-?
Other remarks about test_wconsole_binlarge.patch:
- the patch doesn't apply on Python 3.3
- I would prefer 32767 instead of 32000 for the maximum length
Suggestion for the comment in fileio.c:
* Issue #11395: not enough space error (errno 12) on writing
into stdout in a Windows console if the length is greater than
66000 bytes. */
Thanks for the comment. It's my first patch. :-)
> - the patch doesn't apply on Python 3.3
That latest patch file I generated against the tip of 3.1 branch. Should I create two separate patches for 3.1 and 3.2+ (which will apply on 3.3, as well)? Actually, this crash will reproduce on (from my testing) 2.7 with "-u" option on, as well...
> -?
I have a few ideas to work around this and still have a unit test...
Attached a modified patch that should work against 3.2+ heads:
- Added `isatty` bit field in isatty that's evaluated during its
construction. This should eliminate the need to call `isatty()` on
every write.
- Cap buffer length to 32767 (4 * 1024 - 1) when writing to a tty.
- Test this by supplying `CREATE_NEW_CONSOLE` to `subprocess.call`, so
we do not flood regrtest's console output.
These changes are conditionally compiled on Windows only.
Should a similar patch be made for 2.7+ (maybe earlier)?
On Windows, isatty() is a cheap call: a simple lookup in the _ioinfo structure. And dup2() can still change the destination of a file descriptor, so the new attribute can be out of sync...
I suggest to call isatty() on every write.
FWIW, here's the Microsoft's source for isatty (in VC\crt\src\isatty.c):
/***
*int _isatty(handle) - check if handle is a device
*
*Purpose:
* Checks if the given handle is associated with a character device
* (terminal, console, printer, serial port)
*
*Entry:
* int handle - handle of file to be tested
*
*Exit:
* returns non-0 if handle refers to character device,
* returns 0 otherwise
*
*Exceptions:
*
*******************************************************************************/
int __cdecl _isatty (
int fh
)
{
#if defined (_DEBUG) && !defined (_SYSCRT)
/* make sure we ask debugger only once and cache the answer */
static int knownHandle = -1;
#endif /* defined (_DEBUG) && !defined (_SYSCRT) */
/* see if file handle is valid, otherwise return FALSE */
_CHECK_FH_RETURN(fh, EBADF, 0);
_VALIDATE_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, 0);
#if defined (_DEBUG) && !defined (_SYSCRT)
if (knownHandle == -1) {
knownHandle = DebuggerKnownHandle();
}
if (knownHandle) {
return TRUE;
}
#endif /* defined (_DEBUG) && !defined (_SYSCRT) */
/* check file handle database to see if device bit set */
return (int)(_osfile(fh) & FDEV);
}
Attached a version of the last patch without `.isatty` caching.
I tried to commit io_write.patch, but I had problems with Mercurial :-) I will commit it later.
This last patch looks good, except that the comments "if stdout mode is binary (python -u)" are incorrect: since r87824, all files are opened in binary mode.
> This last patch looks good, except that the comments "if stdout mode
> is binary (python -u)" are incorrect: since r87824, all files are
> opened in binary mode.
I plan to commit the patch to 3.1 and then forward port to 3.2 and 3.3. Yes, I will adapt the comment (remove "(python -u)") for 3.2 and 3.3.
New changeset 8939a21bdb94 by Victor Stinner in branch '3.2':
Issue #11395: io.FileIO().write() clamps the data length to 32,767 bytes on
New changeset 4b3472169493 by Victor Stinner in branch 'default':
(merge) Issue #11395: io.FileIO().write() clamps the data length to 32,767
I realized that it was a little more difficult to port the fix on 3.1 because 3.1 doesn't have the fix for Windows 64 bits. So I only fixed Python 3.2 and 3.3, also because nobody reported failure for Python 3.1 on Windows with -u flag.
I tested my fix: the test fails without the fix, and it pass correctly with the fix. So let's close the last regression that I introduced in Python 3.2!
If I understand the bug in the Windows console functions correctly, a limit of 32767 bytes might not always be small enough. The problem is that if two or more threads are concurrently using any console functions (which all use the same 64 KiB heap), they could try to allocate up to 32767 bytes plus overhead at the same time, which will fail.
I wasn't able to provoke this by writing to sys.stdout.buffer (maybe there is locking that prevents concurrent writes), but the following code that calls WriteFile directly, does provoke it. GetLastError() returns 8 (ERROR_NOT_ENOUGH_MEMORY; see), indicating that it's the same bug.
# Warning: this test may DoS your system.
from threading import Thread
import sys
from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
from ctypes.wintypes import BOOL, HANDLE, DWORD, LPVOID, LPCVOID
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))
WriteFile = WINFUNCTYPE(BOOL, HANDLE, LPCVOID, DWORD, POINTER(DWORD), LPVOID) \
(("WriteFile", windll.kernel32))
GetLastError = WINFUNCTYPE(DWORD)(("GetLastError", windll.kernel32))
STD_OUTPUT_HANDLE = DWORD(-11)
INVALID_HANDLE_VALUE = DWORD(-1).value
hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
assert hStdout is not None and hStdout != INVALID_HANDLE_VALUE
L = 32760
data = b'a'*L
def run():
n = DWORD(0)
while True:
ret = WriteFile(hStdout, data, L, byref(n), None)
if ret == 0 or n.value != L:
print(ret, n.value, GetLastError())
sys.exit(1)
[Thread(target=run).start() for i in range(10)]
The buffer size only needs to be capped if WINVER < 0x602. This issue doesn't apply to Windows 8 since it uses the ConDrv device driver instead of LPC.
Prior to Windows 8, WriteFile redirects to WriteConsoleA when passed a console handle. This makes an LPC call to conhost.exe (csrss.exe before Windows 7), which copies the buffer to a shared heap. But a Windows 8 console process instead has actual File handles provided by the ConDrv device:
stdin \Device\ConDrv\Input
stdout \Device\ConDrv\Output
stderr \Device\ConDrv\Output
For File handles, ReadFile and WriteFile simply call the NT system functions NtReadFile and NtWriteFile. The buffer size is only limited by available memory.
This issue is closed. You should reopen it or open a new one. | http://bugs.python.org/issue11395 | CC-MAIN-2014-49 | refinedweb | 1,845 | 77.23 |
From: jokke_at_[hidden]
Date: 1999-11-14 14:09:20
Hello
I have some problems installing dir_it and I would be very thankful for
any help.
I am using linux (slackware 7.0 with glibc) and running unzip and
./configure is not a problem but when I run make I get following errors:
$ make
Makefile:121: make.depend: No such file or directory
c++ -M > make.depend -I. src/directory.cpp
c++ -c -o src/directory.o -I. -g -O2 -Wall -pedantic -ansi
src/directory.cpp
boost/directory.h:54: sorry, not implemented: `namespace_decl' not
supported by dump_type
In file included from src/directory.cpp:20:
boost/directory.h:54: no class template named `iterator' in `'
boost/directory.h:54: confused by earlier errors, bailing out
make: *** [src/directory.o] Error 1
Is it anyone that knows how to solve this problem?
Regards
Jokke
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/1999/11/0934.php | CC-MAIN-2020-05 | refinedweb | 166 | 54.18 |
I have a list of items, coming from one object which are of type A, and a library that operates on object of type B.
I would like to convert A to B, and later call B's function in a pythonic way. What I have come up with so far:
def convert_A_to_B(A):
return B(A.something, A.something_else)
def doStuff(a_list):
converted_to_b = list(map(convert_A_to_B, a_list)
return list(map(B.function, converted_to_b))
return list(map(combine(convert_A_to_B, B.function)))
from functools import partial, reduce combine = lambda *xs: partial (reduce, lambda v,x: x(v), xs)
The function is usable such as
combine (A.foo, A.bar) (x) with is equivalent to
A.bar(A.foo (x)).
combine will accept a variadic number of functions, and return a new function that accepts a single value. This value will then be passed through every previously mentioned function (in chain) until a final result is yield.
map (combine (convert_A_to_B, B.function), a_list) | https://codedump.io/share/1QMLHXBJMbvw/1/combine-functions-to-later-use-in-map | CC-MAIN-2017-47 | refinedweb | 161 | 65.93 |
Content
Created
3 May 2011
Requirements
The Spark Form container lays out its children in three ways:
- Horizontal layout, which is the default
- Stacked layout, and
- Customized using a grid-based constraint layout
This exercise will focus on the stacked layout. The constraint layout is outside the scope of this course.
In this exercise you will style the Employee Portal: Vehicle Request Form application that you created and customized in the first three days of this series (see Figure 1).
Figure 1. Preview the application.
In this exercise, you will learn how to:
In this section, you will use the stacked layout skin in your form.
- Download the ex5_04_starter.zip file if you haven't already and extract the file ex5_04_starter.fxp to your computer.
- Open Flash Builder.
- Import the ex5_04_starter.fxp file.
- Open the ex5_04_starter.mxml file.
- Run the application.
You should see the application that you created in Exercise 3.6: Validating form data. Notice that the Form is set in the default horizontal layout (see Figure 2).
Figure 2. The form is in the default horizontal layout.
- Return to the ex5_04_starter.mxml file.
- Below>
- After the namespace definitions, add a CSS style selector for the Spark
FormItemcontainer.
s|FormItem { }
- In the.
- Save the file and run the application. You should get an error because you also have to apply the stacked skin to the FormHeading control so that the columns match the stacked FormItem controls.
- Return to the ex5_04_starter.mxml file.
- Before the selector for the Form and FormItem controls, add a selector for the Spark FormHeading control.
- In the FormHeading selector block, use the
skinClassproperty to reference the
StackedFormHeadingSkin.
s|FormHeading { skinClass:ClassReference("spark.skins.spark.StackedFormHeadingSkin"); }
- Save the file and run the application.You should see that the FormItem labels appear above the input controls in the stacked layout (see Figure 3).
- Click the Submit Request.
Figure 3. The Form is now set in the stacked layout.
- After the namespace definitions and before the selector for the FormHeading control, add a CSS style selector for the Spark Form container.
s|Form { }
In the Form selector block, use the
skinClassproperty to reference the StackedFormSkin class.
s|Form { skinClass:ClassReference("spark.skins.spark.StackedFormSkin"); }
- Save the file and run the application. You should see that the application is exactly the same as in Figure 3.
- Click the Submit Request button. You should see that the errors now display at the top of the form.
In this section, you will add sequence labels which are displayed to the left of
FormItemcontainers.
- Return to Flash Builder.
- From the components package, open the VehicleRequestForm.mxml file.
- Locate the Employee
FormItemcontainer.
- To the opening
FormItemtag, add the
sequenceLabelproperty with a value of
1).
<s:FormItem
- To the opening tag for the Office Phone
FormItemcontainer, add the
sequenceLabelproperty with a value of
2).
<s:FormItem
- To the opening tag for the Mobile Phone FormItem container, add the sequenceLabel property with a value of 3).
<s:FormItem
- To the opening tag for the Pickup Date
FormItemcontainer, add the
sequenceLabelproperty with a value of
4).
<s:FormItem
- To the opening tag for the Return Date
FormItemcontainer, add a
sequenceLabelproperty with a value of
5).
<s:FormItem
- Save the file and run the application.You should see the sequence numbers in front of each
FormItemlabel (see Figure 4).
Figure 4. The sequence labels are added to each FormItem control.
In this section, you will add text prompts to the form to describe the input controls. The
promptproperty is supported by the Spark
TextInputand
TextAreacontrols.
- Return to the VehicleRequestForm.mxml file in Flash Builder.
- Locate the
phone TextInputcontrol in the Office Phone
FormItemtag block.
- To the
TextInputcontrol, add the
promptproperty with a value of Select employee.
<s:TextInput
- Save the file and run the application. You should see the text prompt in the Office Phone text field (see Figure 5).
Figure 5. The text prompt in the Office Phone field.
- 5.Click in the Office Phone input control area. The prompt disappears when the input gets focus.
- Leave the Office Phone input control area black and click in the Mobile Phone input control. Note that the text prompt reappears when the input control loses focus and no value is entered.
The Spark
FormItemcontainer supports customization of the required and error fields. You can use a custom icon image and change the background color and text properties. In this section, you will customize the required and error icon images.
- Return to VehicleRequestForm.mxml file in Flash Builder.
- To the opening tag of the Mobile Phone
FormItemcontainer, add the
requiredIndicatorSourceproperty and assign the value to
assets/required.png.
<s:FormItem
- Save the file and run the application.You should see the newly customized required icon (see Figure 6).
Figure 6. The customized required icon.
- Without entering a value in the Mobile Phone field, click the Submit Request button. Note the yellow triangle with the exclamation point. This is the default error icon (see Figure 7).
Figure 7. The default error icon.
- Return to the VehicleRequestForm.mxml file.
- To the opening Mobile Phone
FormItemtag, add the
errorIndicatorSourceproperty and assign the value to
assets/invalid.png.
<s:FormItem
- Save the file and run the application.
- Without entering a value in the Mobile Phone field, click the Submit Request button.You should see the newly customized error icon (see Figure 8).
Figure 8. The customized error icon.
In this exercise you styled the Employee Portal: Vehicle Request Form application that you created and customized in the first three days of this series.. | https://www.adobe.com/devnet/flex/newcontent/videotraining/exercises/ex5_04_new.html | CC-MAIN-2018-09 | refinedweb | 921 | 60.21 |
Hello
I'm trying to use the "Making programmatic calls from a dialog node" () details in order to start implementing my web services into watson assistant Dialog nodes
So I have tried this (with a very basic sample ws available on the web) :
{ "context": { "sCurrency": "USD", "sRateDate": "2018-11-05" }, "output": { "generic": [ { "values": [ { "text": "Test Currency Rate WS <? $sCurrency ?> <? $sRateDate ?> => <? $WSresult ?>" } ], "response_type": "text", "selection_policy": "sequential" } ] }, "actions": [ { "name": "", "type": "client", "parameters": { "Currency": "<? $sCurrency ?>", "RateDate": "<? $sRateDate ?>" }, "result_variable": "$WSresult" } ] }
But, when I call this node with Watson Assistant "Try It Out", I only get this output below and $WSResult variable (as result_variable) is not set
Test Currency Rate WS USD 2018-11-05 =>
What's wrong with this example ? I think I haven't understood these implementation rules well ... please help !
Thank you a lot for your help
Laurent
Answer by MitchMason (5336) | Nov 08, 2018 at 10:10 AM
Watson Assistant will not run any external callouts for you. So there is no way to use type:client in your callout in the tryout panel.
When building a chatbot, there is some code that connects the Watson API to your front end. This is called an orchestration layer. If you use type:client for your callout, you are telling Watson that your orchestration will run the callout and let Watson know what response you get by filling that response variable.
If you choose type:server, then we have built a connection to IBM cloud functions that can run custom code for you, but you still have to write the wrapper code to make the call to that URL.
Answer by stephen-broadhurst (1082) | Nov 08, 2018 at 02:08 PM
Hi @LaurentTCT what @Mitchmason says it right, but actually I think it is telling you in the bit where he mentions the server intergration that you can do what you want to. I.e you can call a webservice from Watson in the Try-It-Out pane.
There are a couple of steps to this which aren't very intuitive, but when you've got them down you can do with very little code. As an aside server is now called cloud_function although the old term still works
Here is a worked example. I replaced the webservice you were using with which I found a lot nicer, and does the same thing, you can get a free key and use the full example I've given below
The bits you need to do to make this work is:
Use a very light IBM Cloud Function to wrap the webservice you want to call
manage your credentials for the webservice and your Cloud Function account in a private context variable in the Try-It-Out Window so it doesn't end up in the Watson logs
Use two nodes, one to get the value, and a second jump to, to display the value
1 Create your cloud function go here (Bluemix AKA IBM Cloud, OpenWhisk AKA IBM Cloud Functions)
Create an action give it a package of "getcurrencypackage" and an action name of "getcurrencyaction"
This is the code you need to wrap the fixer.io URL. All we are doing is telling it we want JSON, handling the parameters and returning the result. Literally just paste this into the box and save.
let rp = require('request-promise') function main(params) { const options = { uri: "" + params.access_key + "&symbols=" + params.symbols, json: true } return rp(options) .then(res => { return { response: res } }) }
Then you need your namespace and credentials for IBM Cloud Functions. Annoyingly "CF Credentials" could stand for Cloud Foundry or Cloud Functions. Here it stands for Cloud Functions
Go here
Note your namespace, and your username and password are called an API-KEY the username is the first bit until the : and the password is the second bit after the :. Stick them somewhere for later when you need to configure them in the try-it-out pane in a private variable.
2 Configure your two nodes.
The first node needs this set in the JSON editor - don't forget to REPLACE YOUR NAME SPACE This node is going to clear your output context variable so there is nothing kicking about from a previous call (easy to get confused in Try-It-Out if you don't do this), then call the webservice for you. It doesn't actually output anything as the webservice needs to execute, so do any processing and display in a second node you jump to.
{ "context": { "fixerobj": "" }, "output": { "generic": [ { "values": [ { "text": "" } ], "response_type": "text", "selection_policy": "sequential" } ] }, "actions": [ { "name": "**<IBMID@YOURDOMAIN.COM_BETA>**/getcurrencypackage/getcurrencyaction", "type": "cloud_function", "parameters": { "access_key": "$private.credentials.access_key", "symbols": "USD" }, "credentials": "$private.credentials", "result_variable": "context.fixerobj" } ] }
Create your second node and the jump to. Use a jump to response, so the first outputs blank and the second response just appears without evaluating anything. If you keep these second sort of nodes below anything_else it's neat and tidy and they won't get in the way of anything else, but anywhere will actually do. All the second node needs to do is output $fixerobj so you see it on screen
3 Set your context for credentials
Got to Try-It-Out pane.
Use Manage Context Create a variable $private (This won't be stored in your Watson logs) Configure it to be (all one line)
{"credentials":{"user":"<CLOUDFUNCTIONUSERNAME>","password":"<CLOUDFUNCTIONPASSWORD>","access_key":"<FIXERACCESSKEY>"}}
Now test it out.
In try it out, use whatever utterance you are using to trigger your first node. you should see something like.
{ "success": true, "timestamp": 1519296206, "base": "EUR", "date": "2018-11-08", "rates": { "USD": 1.03432231 } }
This is a big long response. Actually once you have the framework down it's very easy to throw new API values in and manipulate. Your credentials typically stay the same for cloud functions, often the same for the external API group you want to use. You just create a Cloud Function wrapper around each end point you want (or pass it into a generic function). Handle the parameters and call it from your flows.
In production you are definitely going to have an orchestration layer managing the credentials and interaction between your user interface, Watson and other backend end points, for you, so it is arguable whether it is better to do in your own orchestration. But you can do it all in Watson (using cloud functions callouts) and Try-It-Out if you want.
This is basically your currency query without the SPEL processing (which you can add on in the second node).
It's just an amalgamation of these two pages
But it's an end to end example around what you were trying to do. I've used a cloud_function node rather than a web_action, and there are lot of different ways of storing your credentials, but this is an end to end working example. There will be other variations on this that work I'm sure, but here is an end to end example.
All the best
Answer by stephen-broadhurst (1082) | Nov 08, 2018 at 10:20 AM
I struggled to recreate your call at all with that web-service.
It failed to come back a number of times, and is really fussy about the date format without specifying clearly what the date format should be.
For it to work in Watson you're going to need to make sure you're passing the variables in, in the right way, and then getting something out Watson can work with as a JSON object.
Can you paste an example using curl of the call you are trying to make?
Getting your call going right in curl in a way which responds with a suitable value that can be passed into a Watson context variable object/array/number/string is going to make working out what's happening a lot easier.
Answer by DavidSeager (881) | Nov 11, 2018 at 09:12 AM
Be aware that Assistant can only call to a Cloud Function in the same region, and that Cloud Functions only seem to be available in US-South and Germany regions. Therefore your Assistant service must be in either of those regions, and your Cloud Function must be in the same region.
Otherwise it's all in @StephenH. detailed answer.
Answer by MitchMason (5336) | Nov 08, 2018 at 09:58 AM
So if you choose type:client then your client application layer needs to go run whatever arbitrary code is needed for that action, and then send the results back to Watson in a following message that fills in that $WSResult variable.
Im guessing that you assumed Watson would ping that URL... but that is not the case. You either use cloud functions and write the code to call the URL there, which would be type:server, or if you choose type:client then your client application has to go do the work.
Answer by Laurent Dhaisne (20) | Nov 08, 2018 at 10:03 AM
Hello @MitchMason
Sorry, to be honest/transparent with you, I don't catch your answer
Could you please develop your answer ?
Thank you a lot Sorry for my understanding
Laurent
Answer by Laurent Dhaisne (20) | Nov 08, 2018 at 10:12 AM
Thank you @MitchMason
I confirm that I was expecting Watson to call this url so I was totally wrong
Thank you very much for your answer
Laurent
Answer by Laurent Dhaisne (20) | Nov 08, 2018 at 10:50 AM
Hello @stephen-broadhurst
Sorry, I don't catch you This web service is an example one, just found on the web, to illustrate my issue If you have another to use that it is more adapted, of course you can submit it
I'm just trying to call an external web service with parameters and get back an answer (as a typical web service call)
But, as mentioned by @MitchMason, it seems that I didn't understood the details of this article and it is not possible to do this kind of ws call directly from a dialog node as Watson will not call the ws url
If you have an idea, i'm totally open
Laurent
Answer by PythonBiter (1) | Apr 24 at 07:29 AM
Hi,
@stephen-broadhurst : I don't really get how to manage the whole process. I am connected to the Speech-To-Text on Bluemix and to Node-Red. So how can the action help me get the questions I ask the Chatbot answered correcty? My database is stored in a .csv file. I followed this guide. But somehow it gets to fuzzy right now.
I hope to get some enlightment here.
150 people are following this question.
Watson Assistant - How to select Multiple predefined Options? 1 Answer
how do you handle authentication via web service connections in your environement 1 Answer
Can dynamic training break normal (Watson assistant) service processing? 1 Answer
Deployed bot marks irrelevant messages (entities mostly) as an intent every time (mostly #Greeting). Causes conversation to jump to "Hello" if the wrong thing is said at the wrong time. 2 Answers
Unable to see response from Cloud Function inside Watson Virtual Assistant 2 Answers | https://developer.ibm.com/answers/questions/479521/web-service-i.html?childToView=479597 | CC-MAIN-2019-35 | refinedweb | 1,855 | 64.95 |
How to Find Saddle Point of a Matrix in Java
Today we are going to learn how to find the saddle point of a matrix in Java. As we all know a matrix is a 2-Dimensional array and in it, Saddle point is that element of the matrix which is lowest in its row but the highest in its column.
Saddle Point of a Matrix in Java
There are many ways to solve this problem, One of the solutions is provided here.
Following are the steps to follow-
1. Traverse the row and find the smallest number. Save its column number in a variable.
2. Now traverse the same column check if the row ‘s smallest number is greatest in its column.
3. If yes print the number , if no check for next row.
4. If no such point is there in the array, print no saddle point.
here is the code for the same.
import java.util.Scanner; /** * @author darshna * */ public class Saddle_point { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("enter the size of 2d matrix"); int n = s.nextInt(); int arr[][] = new int[n][n]; System.out.println("enter the array:-"); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { arr[i][j] = s.nextInt(); } int col_max = 0; for (int i = 0; i < n; i++) { int row_min = arr[i][0]; //smallest of row int col = 0; for (int j = 1; j < n; j++) { if (arr[i][j] < row_min) { row_min = arr[i][j]; col = j; } } for (int k = 0; k < n; k++) { if (row_min < arr[k][col]) { col_max = 0; break; } else col_max = row_min; } if (col_max != 0) System.out.println("saddle point " + col_max); } } }
Output:-
enter the size of 2d matrix 3 enter the array:- 1 2 3 4 5 6 7 8 9 saddle point 7
Hope you understand the code.
You may also read: | https://www.codespeedy.com/how-to-find-saddle-point-of-a-matrix-in-java/ | CC-MAIN-2019-47 | refinedweb | 319 | 71.04 |
CGTalk
>
Software Specific Forums
>
Autodesk Maya
>
Maya Programming
> refresh UI during a running script
PDA
View Full Version :
refresh UI during a running script
kzax
03-19-2009, 02:05 PM
Hi,
I'm using a python script to create render layers, put objects selected in them, and at the end I have to change the shaders of objects in the different render layers. By hand it's working well, but within the script it's not working at all. Render layers are created but the shaders are not changed. If I cut the script in two parts, the first to create render layers and the second one to change the shaders it's ok if I launch the first and then the second one when the first one is finished, but not within one script.
I think it's because the render layers window is not refreshed during the execution of the script, but can I force the refresh during the running script?
Or is there a way to change by script the shader of a specific object in a specific render layer?
Thanks a lot,
Philippe.
HapG
03-19-2009, 04:28 PM
use the refresh command :)
kzax
03-19-2009, 05:38 PM
unfortunately refresh isn't working...
this is my code
def f1():
mc.select('head_HR',r=1)
sel = mc.ls(sl=1)
for l in range(1,9):
nameRL=('RL_%d' %l)
mc.createRenderLayer (sel, name=nameRL, noRecurse=1)
def f2():
for i in range(1,9):
nameRL = 'RL_%d' %i
mel.eval('layerEditorLayerButtonSelect 0 ' + nameRL)
mc.select('head_HR', r=1)
if i==5:
mc.sets(forceElement='dgs_material1SG' )
else:
mc.sets(forceElement='importedMaterial_blackhole_shdSG' )
mc.select(clear=1)
f1()
mc.refresh(cv=0, f=1)
for j in range (1,100): print j
f2()
#during the loop after the refresh command I can see that the render layers window is not refreshed at all :(
Do you see what's wrong?
HapG
03-19-2009, 05:47 PM
I've never tried refresh in a python script. I have had some some success using eval(), as it calls the script differently.
Keilun
03-19-2009, 06:40 PM
I don't believe there is any way to easily force the Render Layers panel to refresh. You would need to have a look at how the Render Layers panel is setup and hope to find a method that you can invoke on it that will update its elements.
The refresh command only controls the viewports. Calling the refresh after having changed the shader for an object in a given render layer should still update in the viewport if the change was made in the active render layer.
CGTalk Moderation
03-19-2009, 06. | http://forums.cgsociety.org/archive/index.php/t-743639.html | CC-MAIN-2013-48 | refinedweb | 455 | 63.39 |
'...'. You can also read and write data starting at the current file position, and seek() through the file to different positions.
A memory-mapped file is created by the mmap constructor,).
Note
If you want to create a memory-mapping for a writable, buffered file, you should flush() the file first. This is necessary to ensure that local modifications to the buffers are actually available to the mapping.
For both the Unix and Windows versions of the constructor, access may be specified as an optional keyword parameter. access accepts one of three values: ACCESS_READ, ACCESS_WRITE, or ACCESS_COPY to specify read-only,.
To map anonymous memory, -1 should be passed as the fileno along with the length.
(Windows version) Maps length bytes from the file specified by the file handle fileno, and creates a mmap object. If length is larger than the current size of the file, the file is extended to contain length bytes. If length is.
offset may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. offset defaults to 0. offset must be a multiple of the ALLOCATIONGRANULARITY.
(Unix version) Maps length bytes from the file specified by the file descriptor fileno, and returns a mmap object. If length is 0, the maximum length of the map will be the current size of the file when mmap is called..
offset may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. offset defaults to 0. offset must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.
To ensure validity of the created memory mapping the file specified by the descriptor fileno is internally automatically synchronized with physical backing store on Mac OS X and OpenVMS.
This example shows a simple way of using mmap:
import mmap # write a simple example file with open("hello.txt", "wb") as f: f.write is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 on failure.
Flushes changes made to the in-memory copy of a file back to disk. Without use of this call there is no guarantee that changes are written back before the object is destroyed. If offset and size are specified, only changes to the given range of bytes will be flushed to disk; otherwise, the whole extent of the mapping is flushed.
(Windows version) A nonzero value returned indicates success; zero indicates failure.
(Unix version) A zero value is returned to indicate success. An exception is raised when the call failed.
Copy the count bytes starting at offset src to the destination index dest. If the mmap was created with ACCESS_READ, then calls to move will raise a TypeError exception.
Return a, and advances the file position by 1.
Returns a single line, starting at the current file position and up to the next newline.
Resizes the map and the underlying file, if any. If the mmap was created with ACCESS_READ or ACCESS_COPY, resizing the map will raise a TypeError exception.
Returns the highest index in the object where the subsequence sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 on failure.
Set the file’s current position. whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file’s end).
Return the length of the file, which can be larger than the size of the memory-mapped area.
Returns the current position of the file pointer.
Write the bytes in. | https://wingware.com/psupport/python-manual/3.3/library/mmap.html | CC-MAIN-2015-22 | refinedweb | 631 | 67.15 |
getting "ACPI Invalid PBLK Length 5" - message on Hardy Alpha 5
Bug Description
I am getting an error message on the Hardy Alpha 5 Alternate CD version 32 bit.
The error message is: ACPI Invalid PBLK length 5
This message occurs both during the integrity check function of the CD and also during the very initial stages of the actual installation process of installing from the CD to the hard drive.
Let me know if you need any further information.
Thanks.
Hi wpshooter,
Do you already checked if exist a BIOS upgrade for your computer?
Thank you!
I suggest looking at https:/
Try booting with the "acpi=off" kernel parameter
* This will disable ACPI support. If the error is the same with acpi enabled and disabled, this may not be an ACPI issue.
Alessio:
This is an ASUS P4G8x deluxe motherboard. The BIOS is already at the latest version. Board is no longer supported, so there will be no more BIOS updates.
If this is a problem related to ACPI, why would I get this very same message when running the CD integrity check from the Ubuntu initial boot menu ?? Is the running of that integrity check dependent on ACPI settings, etc. ?
Thanks.
P. S. - I don't get this message when using the Gutsy version on this same computer.
Therefore, that sort of leads me to believe that the problem is with Hardy, not the computer.
Thanks.
I am still getting the "ACPI Invald PBLK Length 5" message on the Hardy BETA version Alternate CD.
I only get this message on a computer that I built that is using an ASUS P4G8X motherboard.
I have tried the same CD on 2 other computers that I built using other ASUS model motherboards and also on some older IBM Netvista computers that I have and I do NOT get the message on any of those computers.
What needs to be fixed in the Hardy O/S so that this message is not displayed on the ASUS P4G8X computer ? Like I said in a previous posting, I don't think there is anything wrong with this computer because I do NOT get this message when using the Gutsy version of Ubuntu.
Thanks. downloaded Intrepid Alpha 5 ALTERNATE CD version and I still get this same message both when I run the CD integrity check function from the Ubuntu initial boot menu screen and also when I go into the INSTALL menu option.
Thanks.
Google search suggests that it's predominantly users with Asus motherboards/
I recently installed the release version of Intrepid on the P4G8X ASUS motherboard computer and I still get the same error message.
If I can run Gutsy on this motherboard without getting this message, then the integrity of Hardy and Intrepid is very doubtful in my mind. This leads me to think that someone is changing things in this O/S without taking into account ALL of the consequences.
Thanks.
I also get this error sometimes when booting up Acer 4530 laptop running Ubuntu Intrepid AMD64. It doesn't always occur, though. I haven't tried putting acpi=off because it doesn't occur often.
I am seeing this error at boot with Ubuntu 9.04.
I get the same error on my Kubuntu 9.04 with ASUS P4S8X-X in a clean install.
I am seeing this error at boot with Ubuntu 9.04. I have followed the instructions at https:/
acpi=off results in different errors appearing at boot as well as no response from my ethernet controller.
acpi=ht same as above
pci=noacpi results in above as well as seeing the error "Invalid PBLK length [5]"
acpi=noirq same as above
pnpacpi=off results in just the Invalid PBLK length error (ethernet works fine)
noapic same as above
nolapic same as above
My motherboard: ASUS P4S800 ACPI BIOS Revision 1011beta
I just noticed that my original report of this bug was over a year ago now (in March 2008).
And this still has not been fixed ???
Hi,
I'm a Ubuntu newbie. I noticed this error for the first time. Last week I moved to 9.04 on my old Asus laptop. So indeed it has not been fixed.
Don't know if it hurts, don't know if there is really something wrong (I don't see a problem...)
I'm seeing this problem as well ("Invalid PBLK length [5]").
Stats:
Mobo: Asus A7A266
Ubuntu 9.04
kernel 2.6.28-13
Recently (possibly after last kernel package update?) started getting random kernel panics. I suppose it could be aging hardware... and I never really noticed whether I was getting this error message before, since I only reboot this box for distro & kernel upgrades :-)
Same problem, followed by:
[3.445580] IO APIC resources could bet not allocated
I can login to desktop, but after few seconds the monitor became black and then the system return in the graphic login prompt, again, infinitely.
System: Pentium 3 1Ghz, 512Mb RAM, M.B. Asus CUSL2-C with latest BIOS, hard disk 200Gb, DVD drive.
I tried a clean installation with Ubuntu 9.04 from original CD desktop version. I made a manual partitioning to prevent Grub error 18:
sda1 1gb ext3 mounted with /boot
sda5 rest_of_space ext3 mounted with /
Can you supply me a copy of the ACPI dsdt from your machine. To do so, please do the following:
sudo cat /proc/acpi/dsdt > dsdt.dat
and attach this binary file to the bug report. I will disassemble it and see why the BIOS is making ACPI complain about the PBLK. Thanks!
I'm also seeing this Invalid PBLK Length error on an ASUS board, a P4PE to be exact.
I have attached my dsdt.dat.
Hello Colin
Here is the file you requested sent correctly.
Thank you once again for all the help and time your putting into to this problem I'm having.
Regards,
chico
@chico,
I require just a little more information now, can you please run the following command:
sudo acpidump > acpi.dat
and attach the acpi.dat to the bug report. Thanks!
The warning is because of a problem with the Processor declaration in the _PR root namespace of your ACPI DSDT:
Scope (\_PR)
{
Processor (\_PR.CPU0, 0x00, 0x0000E410, 0x05) {}
Processor (\_PR.CPU1, 0x01, 0x00000000, 0x00) {}
}
The syntax of the Processor declaration is as follows:
Processor (ProcessorName, ProcessorID, PBlockAddress, PblockLength)
Section 18.5.93 of the ACPI specification states that the PBlockLength is the length of the processor register block, in bytes and is either 0 (for no P_BLK) or 6. In your case, the it's been set to 0x05 in the first Processor declaration which is definetly not compliant with the specification, hence the kernel warning message. The ACPI specification can be downloaded from http://
As it is, this is not a kernel bug, but a warning from the kernel that your BIOS is buggy and needs fixing. I suggest informing the manufacturer so that they can fix the BIOS.
I shall therefore mark this as "Won't Fix".
Since most of the motherboards that are exhibiting this error/warning message are fairly old and it is HIGHLY unlikely that the M/B manufacturer is going to fix this BIOS problem, is there any actual negative consequences to installing and running Ubuntu on a computer that is using one of these motherboards ?
Thanks.
@wpshooter, from my understanding, if the kernel detects a problem with the PBLK length then it will not configure up the ACPI CPU throttling. So, basically, you lose the ability to do CPU throttling. Since this is under ACPI control and the BIOS has been found to contain errors in this configuration, the kernel chooses to disable this functionality rather than risk using incorrect configuration, which seems to me like the least risky option for the kernel to make.
I think the user has to change their display card to agp from pci in the bios, and then install again the system. I think. I got that error too, but I dont get errors from other dists incl ubuntu and knoppix, i.e. mythbuntu and LinHES.
I am not sure where I stand here in this regard, and this is a year on from the last comment.
Install of MythDora, 12.23 mythtv
A quick Google of this obscure error message leads me to believe that you are not that first to be confused by it and it should really be worded into something that makes sense to normal people like you and me at least. | https://bugs.launchpad.net/ubuntu/+source/linux/+bug/197267 | CC-MAIN-2015-27 | refinedweb | 1,430 | 70.63 |
Joining is easy.
Subscribe to our announce list. We'll send you a confirmation email in reply. Come back, enter the confirmation password, and you're done!
On the way to the X Developer’s Conference in Nuremberg, Eric and I chatted about how the DRI2 extension wasn’t really doing what we wanted. We came up with some fairly rough ideas and even held an informal “presentation” about it.
We didn’t have slides that day, having come up with the content for the presentation in the hours just before the conference started. This article is my attempt to capture both that discussion and further conversations held over roast pork dinners that week.A brief overview of DRI2
Here’s a list of the three things that DRI2 currently offers.Application authentication.
The current kernel DRM authentication mechanism restricts access to the GPU to applications connected to the DRM master. DRI2 implements this by having the application request the DRM cookie from the X server which can then be passed to the kernel to gain access to the device.
This is fairly important because once given access to the GPU, an application can access any flink’d global buffers in the system. Given that the application sends screen data to the X server using flink’d buffers, that means all screen data is visible to any GPU-accessing application. This bypasses any GPU hardware access controls.Allocating buffers.
DRI2 defines a set of ‘attachment points’ for buffers which can be associated with an X drawable. An application needing a specific set of buffers for a particular rendering operation makes a request of the X server which allocates the buffers and passes back their flink names.
The server automatically allocates new buffers when window sizes change, sending an event to the application so that it knows to request the new buffers at some point in the future.Presenting data to the user.
The original DRI2 protocol defined only the DRI2CopyRegion request which copied data between the allocated buffers. SwapBuffers was implemented by simply copy data from the back buffer to the front buffer. This didn’t provide any explicit control over frame synchronization, so a new request, DRI2SwapBuffers, was added to expose controls for that. This new request only deals with the front and back buffers, and either copies from back to front or exchanges those two buffers.
Along with DRI2SwapBuffers, there are new requests that wait for various frame counters and expose those to GL applications through the OMLsynccontrol extensionWhat’s wrong with DRI2?
DRI2 fixed a lot of the problems present with the original DRI extension, and made reliable 3D graphics on the Linux desktop possible. However, in the four years since it was designed, we’ve learned a lot, and the graphics environment has become more complex. Here’s a short list of some DRI2 issues that we’d like to see fixed.
InvalidateBuffers events. When the X window size changes, the buffers created by the X server for rendering must change size to match. The problem is that the client is presumably drawing to the old buffers when the new ones are allocated. Delivering an event to the client is supposed to make it possible for the client to keep up, but the reality is that the event is delivered at some random time to some random thread within the application. This leads to general confusion within the application, and often results in a damaged frame on the screen. Fortunately, applications tend to draw their contents often, so the damaged frame only appears briefly.
No information about new back buffer contents. When a buffer swap happens and the client learns about the new back buffer, the back buffer contents are always undefined. For most applications, this isn’t a big deal as they’re going to draw the whole window. However, compositing managers really want to reduce rendering by only repainting small damaged areas of the window. Knowing what previous frame contents are present in the back buffer allows the compositing manager to repaint just the affected area.
Un-purgable stale buffers. Between the X server finishing with a buffer and the client picking it up for a future frame, we don’t need to save the buffer contents and should mark the buffer as purgable. With the current DRI2 protocols, this can’t be done, which leaves all of those buffers hanging around in memory.
Driver-specific buffers. The DRI2 buffer handles are device specific, and so we can’t use buffers from other devices on the screen. External video encoders/cameras/encoders can’t be used with the DRI2 extension.
GEM flink has lots of issues. The flink names are global, allowing anyone with access to the device to access the flink data contents. There is also no reference to the underlying object, so the X server and client must carefully hold references to GEM objects during various operations.
Given the three basic DRI2 operations (authentication, allocation, presentation), how can those be improved?Eliminate DRI/DRM magic-cookie based authentication
Kristian Høgsberg, Martin Peres, Timothée Ravier & Daniel Vetter gave a talk on DRM2 authentication at XDC this year that outlined the problems with the current DRM access control model and proposed some fairly simple solutions, including using separate device nodes—one for access to the GPU execution environment and a separate, more tightly controlled one, for access to the display engine.
Combining that with the elimination of flink for communicating data between applications and there isn’t a need for the current magic-cookie based authentication mechanism; simple file permissions should suffice to control access to the GPU.
Of course, this ignores the whole memory protection issue when running on a GPU that doesn’t provide access control, but we already have that problem today, and this doesn’t change that, other than to eliminate the global uncontrolled flink namespace.Allocate all buffers in the application
DRI2 does buffer allocation in the X server. This ensures that that multiple (presumably cooperating) applications drawing to the same window will see the same buffers, as is required by the GLX extension. We suspected that this wasn’t all that necessary, and it turns out to have been broken several years ago. This is the traditional way in X to phase out undesirable code, and provides an excellent opportunity to revisit the original design.
Doing buffer allocations within the client has several benefits:
No longer need DRI2 additions to manage new GL buffers. Adding HiZ to the intel driver required new DRI2 code in the X server, even though X wasn’t doing anything with those buffers at all.
Eliminate some X round trips currently required for GL buffer allocation.
Knowing what’s in each buffer. Because the client allocates each buffer, it can track the contents of them.
Size tracking is trivial. The application sends the GL the of the viewport, and the union of all viewports should be the same as the size of the window (or there will be undefined contents on the screen). The driver can use the viewport information to size the buffers and ensure that every frame on the screen is complete.
The new DMA-buf infrastructure provides a cross-driver/cross-process mechanism for sharing blobs of data. DMA-buf provides a way to take a chunk of memory used by one driver and pass it to another. It also allows applications to create file descriptors that reference these objects.
For our purposes, it’s the file descriptor which is immediately useful. This provides a reliable and secure way to pass a reference from an underlying graphics buffer from the client to the X server by sending the file descriptor over the local X socket.
An additional benefit is that we get automatic integration of data from other devices in the system, like video decoders or non-primary GPUs. The ‘Prime’ support added in DRI version 2.8 hacks around this by sticking a driver identifier in the driverType value.
Once the buffer is available to the X server, we can create a request much like the current DRI2SwapBuffers request, except instead of implicitly naming the back and front buffers, we can pass an arbitrary buffer and have those contents copied or swapped to the drawable.
We also need a way to copy a region into the drawable. I don’t know if that needs the same level of swap control, but it seems like it would be nice. Perhaps the new SwapBuffers request could take a region and offset as well, copying data when swapping isn’t possible.Managing buffer allocations
One trivial way to use this new buffer allocation mechanism would be to have applications allocate a buffer, pass it to the X server and then simply drop their reference to it. The X server would keep a reference until the buffer was no longer in use, at which point the buffer memory would be reclaimed.
However, this would eliminate a key optimization in current drivers— the ability to re-use buffers instead of freeing and allocating new ones. Re-using buffers takes advantage of the work necessary to setup the buffer, including constructing page tables, allocating GPU memory space and flushing caches.Notifying the application of idle buffers
Once the X server is finished using a buffer, it needs to notify the application so that the buffer can be re-used. We could send these notifications in X events, but that ends up in the twisty mess of X client event handling which has already caused so much pain with Invalidate events. The obvious alternative is to send them back in a reply. That nicely controls where the data are delivered, but causes the application to block waiting for the X server to send the reply.
Fortunately, applications already want to block when swapping buffers so that they get throttled to the swap buffers rate. That is currently done by having them wait for the DRI2SwapBuffers reply. This provides a nice place to stick the idle buffer data. We can simply list buffers which have become idle since the last SwapBuffers reply was delivered.Releasing buffer memory
Applications which update only infrequently end up with a back buffer allocated after their last frame which can’t be freed by the system. The fix for this is to mark the buffer purgable, but that can only be done after all users of the buffer are finished with it.
With this new buffer management model, the application effectively passes ownership of its buffers to the X server, and the X server knows when all use of the buffer are finished. It could mark buffers as purgable at that point. When the buffer was sent back in the SwapBuffers reply, the application would be able to ask the kernel to mark it un-purgable again.A new extension? Or just a new DRI2 version?
If we eliminate the authentication model and replace the buffer allocation and presentation interfaces, what of the existing DRI2 protocol remains useful? The only remaining bits are the other synchronization requests: DRI2GetMSC, DRI2WaitMSC, DRI2WaitSBC and DRI2SwapInterval.
Given this, does it make more sense to leave DRI2 as it is and plan on deprecating, and eventually eliminating, it?
Doing so would place a support burden on existing applications, as they’d need to have code to use the right extension for the common requests. They’ll already need to support two separate buffer management versions though, so perhaps this burden isn’t that onerous?.
Related posts:
In today’s online beat, you’ll see reports of a 25 year old man who’s been picked up by the police for questioning on a Facebook post of his. The Star covers it. As does The Malaysian Insider.
Some facts that we know from the above two reports:
How do we go from a Facebook posting to people finding his house? I decided to do a little sleuthing while sitting in the airport lounge.
The first post mentioning his name (Gopinath Jayaratnam) that Twitter search can find was made at 4.58pm on 25 September 2012. Its clear from his Facebook profile he lives in Klang. The first post providing information about where he lives came from Ariff Amran at 7.44pm on 25 September 2012. It also includes his identity card (IC) number. It didn’t take long before the masses were united under a hashtag: the KL traffic update hashtags #kltu & #klrb. First posting that was retweeted came at 9.35pm (this includes an image of the original Facebook posting which has since been removed – now all that exists is an apologetic message), followed by 9.57pm with his IC & home address.
At 10.09am today (26 September), a user has uploaded a photo of Gopinath’s damaged house. Its clear it was taken the night before. Another gem is at 8.58am today morning, they decided to talk about his car as well.
I find all these acts unwarranted and unjustified.
I don’t know what will happen in this scenario as its too early to tell. I am not going to comment on the law with the exception that I was under the impression that the Sedition Act was to be repealed. A lawyer in KL, Foong Cheng Leong was quick to jump on the fact that even though Gopinath claims he had been hacked, the new evidence act amendments, section 114A applies.
The Twitter stream has nothing but nasty comments towards Gopinath. There are Facebook posts that have 20,000 likes talking about him. At 25, I’m sure he has a bright future ahead of him. After all, I can think of many politicians that violate Section 298A of the Penal Code.
My advice to users of the web: be careful of your passwords. Be careful about being broken into. Be careful about having your personal devices stolen. Also be wary about your personal information that you have available on the Web. And never assume that Facebook status update is private.
Related posts:
On the 15th I wondered what would Google do? On the 17th, it was clear that Google buckled and blocked the video to Malaysians. To be fair, it did the same in Singapore and many other nations. That did not stop angry protestors to hang out in front of the US Embassy in Kuala Lumpur on the 21st.
But on the Internet, one cannot stop the free flow of information.
This is something Malaysian censors have to come to grips with. After all, even the chief censor in Myanmar has decided to call it a day.
That’s why the offending clip is still online as reported on the 18th. People, citizens of the world, have made copies of the offending video (it is a no brainer to download the video from YouTube) and have re-uploaded it. So now it becomes a cat & mouse game to find the video for the Malaysian authorities and report it to Google. I have no doubt that at least 3.8 people in some government department is working on this task.
Only way for the Malaysian government to ensure that Malaysians never see this content? Block YouTube. I’m sure that would be hugely unpopular. Besides, isn’t there Vimeo and plenty of other services?
Malaysian Government: 0 Internet: 1
Related posts:? screen size might be too small to watch TV on, but we’ll see.
Related posts:
Watch An Entrepreneur’s Life: Gary Vaynerchuk. It is a little less than 8 minutes long, but it is awesome. Some quick points:
Related posts:!
Related posts:
This year linux.conf.au, Australia’s premier open source conference, has broken with tradition and released their draft programme () and partner’s programme () schedules before registrations open on 1 October.
The conference will feature six streams of talks across five days. The first two days will be for miniconferences, with the rest of the conference dedicated to eighty-four talks and six tutorials, on topics ranging from software engineering to systems administration. This year, there is a heavy focus on deep technical content, including many talks on the Linux kernel, and various hardware platforms. The conference also boasts four keynotes from pivotal industry figures, which will be announced in the next few months.
The partner’s programme has become a traditional element of linux.conf.au, but this is the first year to announce a draft schedule before tickets for the programme go on sale. The partner’s programme consists of a family friendly tour of tourist attractions around Canberra.
Conference Director Michael Still said “releasing the schedule for the conference is a significant milestone and I’m very pleased that we hit it ahead of our internal timeline. We are also proud to have a series of simply fantastic presenters this year, and expect to be presenting a solid conference that offers great value for money.”
Early bird registrations for the conference open on 1 October, and discounted tickets will be available until sold out. The number of early bird tickets is strictly limited, and they usually sell out very quickly. Delegates will need to get in quickly after 1 October to make sure they get the best deal.
“Mozillians are people who make things. Moving people from consumption to creation is Mozilla’s goal.” - Mitchell Baker, Mozilla Chair and Chief Lizard Wrangler
This is a brilliant goal. To build a generation of webmakers. Getting people to create more than just consume.
It is widely stated that 1% create, 10% curate, the rest consume (quote from Fred Wilson). Imagine if the tables were turned.
Related posts:.
People to follow: Zeffri Yusof on Twitter is @zeffri. There’s also @GoogleMsia. Google+ account for +Google Malaysia.
Related posts:!
Related posts:
linux.conf.au, Australia’s premier open source conference, have announced the final miniconferences for 2013, all of which address open source programming. Miniconfs are day-long sessions on a specific topic. As the name suggests, they are expected to be run as a miniature conference, with a formal schedule published ahead of time listing speakers and sessions for the day.
Underpinning all open source development is one single thing: programming. Open source programming tools are fast becoming the language of choice for many developers. According to one study*, Python is consistently listed within the top ten languages by popularity.
Open Programming: This miniconference provides an opportunity for application developers to share their techniques and practices for development with free and open source tools. It provides an opportunity to discuss programming techniques, best practices, and developer values across all open source programming languages.
Developer Automation and Continuous Integration: The Developer Automation miniconference discusses the current state of the art of open source developer tooling and testing automation. It will cover tools like Jenkins or Buildbot, build event triggers like Zuul or Tarmac, and code review systems like Gerrit or Launchpad.
Browser: The humble web browser is a key component of the modern internet. The browser miniconference is focused on the capabilities of browsers, and how to provide web developers with new and open technologies to deliver web users an experience like never before.*
Bdale and I are pleased to announce the release of AltOS version 1.1.
AltOS is the core of the software for all of the Altus Metrum products. It consists of cc1111-based micro-controller firmware and Java-based ground station software.
We’ve spent the last flying season chatting with people flying TeleMetrum and TeleMini boards and they came up with some great ideas to add to the system.AltOS Firmware — Features and fixes
There are bug fixes in both ground station and flight software, so you should plan on re-flashing both units at some point. However, there aren’t any incompatible changes, so you don’t have to do it all at once.
New features:
Apogee-lockout timer. For situations where the normal apogee determination algorithm could be fooled, we’ve added a timeout value to prevent premature firing of the apogee charge. Normal flights won’t need this, but a couple of users asked for this feature.
RSSI value for Monitor Idle mode. The TeleDongle firmware has been updated to report signal strength information for data received from the altimeter. This allows the user to see how well the radio is working without having to switch to flight mode.
Force the radio to 434.550MHz. This is useful with TeleMini devices where the only way to talk to the device is through the radio. If you don’t know the frequency, it’s really hard to make that work.
Bug fixes:
AltosUI has also seen quite a bit of work for the 1.1 release. There aren’t any huge new features, but some activities are restructured to make them easier to navigate. And, of course, we’ve fixed a bunch of bugs.
New features:
Configure Ground Station activity. This provides a way to set the default radio frequency for each TeleDongle. This replicates the frequency menu present in the Monitor Flight activity, but doesn’t also bring up that giant window.
Support the apogee lockout timer. This just adds another entry in the dialog for configuring the altimeter to configure the new timer. By default, the timer is disabled, allowing the apogee detection code in the flight computer to operate normally.
Add imperial units option. When enabled, this uses imperial units (feet and miles) for all values on the screen and in the voice announcements.
User interface changes:
Make the look-n-feel configurable. Java offers many different user interface styles on each platform. This exposes the available set and lets the user pick one. By default, we continue to use the native platform appearance.
Add an ‘Age’ element to the Monitor Flight UI. This shows how long it has been since the last valid telemetry packet was received, making it easy to tell when communications are lost.
Change flight data downloading. Instead of selecting which to download and which to delete at the same time, the interface now has separate steps for downloading and then deleting files. This makes it easier to verify that the files were downloaded before deleting flights from the on-board memory.
Re-compute boost and landing times. Given the whole flight history, it’s easy to find the time when the rocket started and stopped flying. Having these get recomputed means the boost time, acceleration values and main descent rates are computed more accurately.
Bug fixes:
Wait for 10 valid GPS messages before marking GPS as ready. Before this fix, GPS was marked as ready when 10 valid packets were received from the flight computer after the first valid GPS data arrived. This waits for 10 valid GPS packets instead.
Fix Google Earth file export. The format requirements for Google Earth files became more strict in recent releases; this patch changes how the files are formatted to make them work again.
Make AltosUI run on Mac OS X “Lion”. Apple changed the default heap size for Java applications with this release, dramatically reducing the memory available to applications. This would cause map tiles to fail to load and other random problems.
Improve COM port handling on Windows. This eliminates the need to wait 5 seconds between closing and re-opening devices, and also eliminates other spurious errors when opening devices.
It’s been a couple of weeks since we closed the for Call for Presentations, and the papers committee has been working really hard to review all of your submissions. We had well over 300 proposals to read, and even with a team of twenty people to review them all, there were some days where it just didn’t feel as though we would be able to make it. In the end, we did it, though. It took us four weeks, and we made over 3000 reviews all up. That’s a lot of reviews!It turns out that that wasn’t even the hard part though. The hard part was where members of the papers committee came from all around Australia and New Zealand to do the final cut, and create a program. It was a long weekend, and everyone needed a beer or three once we were done, just to get over the shock of it all. But the good news is that we’ve come up with something that we think is really awesome. Like, REALLY awesome. LCA in Canberra next year is going to be AMAZING.
So now we’re busy contacting everyone who has been accepted to make sure that they can actually come and give their talk. This is happening in stages and it might take us a little while. So if you haven’t heard from us yet, DON’T PANIC. We’ll get through the list soon, and everyone will know if they’ve been accepted or not before too long. This is partly because we want to make sure our system doesn’t break down from overload, and partly so that our speaker liaisons don’t break down from overload and set the system on fire. Or something.
But, once all that has happened, and assuming nothing gets set on fire, we open early bird regos on 1 October and the real fun starts. So make sure you know where your party shoes are, you’re gonna need them real soon now ...Read this post on our blog
Found.
No related posts..
Update: Rafael Ortiz writes, “For the record previous non-webkit versions of browse only got 187 points on html5test, my beta chrome has 400 points, so it’s a great advance!” | http://luv.asn.au/aggregator?page=369 | CC-MAIN-2015-48 | refinedweb | 4,288 | 63.39 |
Service Dynamics: the lazy man's way
- |
-
-
-
-
-
-
Read later
My Reading List
There is little doubt that the hardest topic in OSGi is how to deal with service dynamics. In this article we will explore in depth the fundamental nature of the problem and than present some innovative strategies to solve it. Although basic familiarity with OSGi is assumed readers new to the technology should find this an entertaining read as well. The discussion will be based directly on the OSGi API and can serve as an informal introduction to the OSGi service layer. At the end of the article we will present some frameworks that capture the API patterns we have developed and thus free the developers from having to deal with OSGi directly.
The Problem
There are two key factors that make service dynamics fiendishly hard to get right.
Concurrency
Before we delve deeper we should digest one basic and somewhat startling fact: the OSGi framework in practice does not run threads of it's own! It is merely a "dead" threadsafe object structure on the heap. The "main" thread is used to setup this structure and start the initial set of bundles. Than it goes to sleep - it's function to merely prevent the JVM from shutting down due to lack of living threads. The "main" thread is typically awaken only at the end of the framework shutdown sequence when all other threads are supposed to be dead. It is used to perform some final cleanup before it also dies and lets the JVM exit. This means that all useful work must be done by threads started from bundles during that initial startup sequence. Let's call these "active bundles". The majority of bundles are usually "passive bundles". I.e. they don't start threads from their BundleActivator.start() method. Instead they setup the imports of some service objects, which are than composed into new service objects, which are finally exported. After the
start() call returns the bundle just sits there and waits for a thread to call it's exported services. As elegant and lightweight all this might be it also means that the OSGi framework does not enforce any threading model - it steps aside and lets the bundles sort it all out between themselves. The framework object structure acts as a "passive bundle" (a bundle with ID 0 in fact) getting animated only when a thread from an "active bundle" calls in to perform some interaction with another bundle or with the framework itself. Because at any time a random number of threads can call into the OSGi core the framework implementers have their work cut out for them. We as an application coders are also not exempt from the suffering.
The concurrency factor is is than this: at all times an OSGi application is subjected simultaneously to two independent control flows. We'll call these the "business logic flow" and the "dynamic management flow". The first one represents the useful work done by the app and has nothing to do with OSGi. Here we choose the design (thread pools, work queues etc) and code our bundles to follow the rules. The second control flow however is entirely out of our hands. Generally it takes place when a management application running concurrently to our own plays with the lifecycle of the bundles (this includes installing and uninstalling). Often there are more than one such applications - each with it's own threading rules just like our app. Some examples include provisioning over HTTP, management and monitoring over JMX, even a telnet console interface. Each of these can reach through the OSGi core, call BundleActivator.stop() on a bundle we depend on, and cause the withdrawal of a service we require. When this happens we must be ready to cooperate in the release of the service object. This odd arrangement is explained with the second factor mentioned earlier.
Direct service references
The second factor has to do with the way objects are exchanged between bundles. Here again OSGi is non-intrusive and lightweight: an importing bundle holds a direct reference to the object owned by the exporting bundle. The chief benefit of this design is that OSGi does not introduce method call overhead between bundles - calling a service is just as fast as calling a privately owned object. The downside is that the importing bundle must cooperate with the exporting bundle to properly release the service. If an importer retains a reference to the dead service at least two harmful effects take place:
- Calls to the stale service are likely to crash.
Because the service is no longer backed by a bundle, calling it will likely result in an exception due to unavailable required services or other resources. I.e. the importer will never work properly because of it's unwillingness to drop the stale service and try to get a new working one.
- Memory leaks because of
ClassLoaderretention.
The
ClassLoaderof the exporter bundle will remain in memory even though the bundle is uninstalled. Obviously each object on the heap must have a concrete implementing class, which in this case is provided by the dead bundle's
ClassLoader. This leak will happen even if the importer sees the service object through an interface loaded from a third library bundle.
All this means that the importer must track the availability of the service and guarantee the release of all references to the service object in finite time after it has received a service unregistration event. Conversely when the service goes back online it must be picked up and propagated to the points within the bundle where it is used.
The solution
So far we went to great pains to describe..err..the pain of service dynamics. Now that we are hurting let us discuss the remedy. For the moment we have exhausted the subject of the correct importer policy. Now let's add to this a service export policy. The sum of an import and an export policy should form a complete doctrine about service dynamics. We will explore two export policies with their corresponding doctrines.
Eager
This school of though shoots for safe service calls. It's motto is:
To export a service is to announce it is ready for use
Consider what this means for services that are composed from imported objects. Such objects are called "required services". A service can also be "optional - e.g. logging. Under the eager motto when a required service goes down the export is no longer usable. So it must also be withdrawn from the OSGi service registry. This goes the other way too - when the required service comes back the composite service must be registered once more. This results in cascades of service registrations and unregistrations as chains of dependent services come together and fall apart. Implementing this flickering behavior varies from hard to exceptionally hard. The problem is that the imports and the exports have to be tracked inside common objects with the proper synchronization. Also quite often this dynamic dependency management is further compounded by the need to track events from non-service sources. For example we track a dynamic configuration waiting for it to become valid.
Let us suppose we manage to write all of the boilerplate for each of our bundles. Now imagine how a thread races through the OSGi container when it executes the business control flow (i.e. useful work). It will start it's path from the active bundle that drives the particular application. As soon as it calls a service object it will leave it's "home" bundle and enter the bundle that exports the service. If that service is in turn implemented via other services the thread will hop into the bundle of each one and so on. For the original service call to succeed each and every hop must also succeed. Turns out we are trying to achieve a kind of transactional behavior - a call to a chain (or more generally a tree) of services either fully succeed or can not be made in the first place because the root service is not registered. Under such strong guarantees the active bundle knows ahead of time (or eagerly) that a certain activity can't be performed and can take alternative actions. E.g. rather than react to an error it proactively performs the respective error handling.
The safety promised by the Eager model hinges on the particular way the OSGi framework delivers service status events. Service tracking is done by hooking a ServiceListener to the OSGi service registry. For better or worse the OSGi framework calls these listeners synchronously - i.e. within the management control flow that performs the actual service unregistration. This gives a chance for the management and application control flows to meet inside the importer bundle. The importer can than synchronize both flows against the same private lock. Why do this? Because we can block out the management control flow if the service is currently being accessed by the application control flow. Conversely if the management flow get's the lock first it will have cascaded the service chain apart by the time it releases the lock. The application flow can than proceed with a check to see if the service is available.
Unfortunately it is plain to see this kind of safety is impossible. Imagine some management control flow kicks in and stops a bundle two hops removed from the current position of the business control flow. Since the business flow has not yet entered the stopped bundle it will not be able to block the management flow from taking down it's services. As a result our thread will run into a wall. Obviously no amount of "local" synchronization by each individual bundle along the path will guarantee the integrity of the entire path. What is needed is a third party - a transaction manager of sorts, to lock the entire path before the business flow starts traversing it. Since such a manager does not currently exist we can conclude that service flickering can't prevent errors caused by disappearing services. We simply must accept that we need to handle such errors and try to develop and effective scheme to do so.
This brings on the question if there is some other benefit to justify the complexity caused by service flickering. We could argue that although we can't guarantee that a service call will succeed at least service flickering can tell us the precise moment after which a service call is guaranteed to fail. This allows us to perform various auxiliary reactions right after a required service goes down. For example if a bundle draws buttons in your IDE and a direct or transitive dependency goes away it can pop a dialog or hide the buttons from the toolbar. Without the cascading destruction of the service chain the buttons will be right there on the toolbar and the user will get exceptions every time they are clicked. This is a dubious return that hardly justifies the boilerplate investment. This becomes even less attractive if we consider the additional complications. Why should we blow the horn loudly during a routine bundle update that lasts 2 seconds? Maybe we should just "flicker" the buttons on the toolbar and postpone the dialog until the failure persist for more than 10 seconds. Should this period be configurable? Also who should react - only active bundles or every bundle along the service chain? Since we don't want to get flooded by dialogs (or other reactions in general) we must introduce some application-wide policy. In short we have payed a lot to get back a dubious benefit and as a side effect have introduced a brand new crosscutting concern in our modular application.
Lazy
Having seen how the extreme dynamics cause more problems than it solves let's try to reduce the service tracking behavior to the essential minimum. Because most of the complexity of the Eager model was a consequence of the overly strong service export policy we will begin by relaxing it:
To export a service is to declare an entry point into the bundle
Since the export is merely a declaration it does not require any dynamic flickering. We simply accept that calling a service can cause an exception because of a missing direct or transitive service dependency. We call this model "lazy" because here we do not learn about a missing service unless we try to call it. The complete dynamics doctrine than becomes:
- Explicit registration is used only during bundle startup.
Generally a bundle should follow this sequence in BundleActivator.start():
Import
- Construct
Build the bundle internal structure from imports and implementation classes. Store it's roots in non-final fields in the activator.
- Activate
If this is an active bundle start it's threads.
- Export
If there are objects to export register them now and store their ServiceRegistrations in non-final fields in the activator.
How to do this in an easy way is described below.
- Importers fail fastEvery imported service must be tracked. When an attempt is made to use a missing service a
- Service errors are handled like regular
RuntimeExceptions(faults)
We handle any unchecked exceptions (including the SUE) thrown when using service objects by the classical fault scheme: propagate to a top-level catch block (fault barrier), do cleanup in
try/finallyblocks as the stack unrolls or when we arrive at the catch block. Finally complete the crashed activity in some rational way. In detail:
- If the service is optional we just catch, handle and proceed.
If the service is not critical for the job at hand there's no need to crash. Runtime exceptions are caught on the spot and logged. Any appropriate fail-over actions are taken and the execution happily proceeds. I.e. we convert a fault to a contingency. Whether a service is optional depends on the concrete application. We can even imagine partially optional services where only some of the methods calls are wrapped in
try/catchfault barriers while others lead to more comprehensive crashes.
- If the service is required and we are a passive bundle we clean up our own resources and let the exception propagate.
Passive bundles don't drive business logic and therefore don't own the activities that call into them. As such they have no right to decide how these activities are completed and should let the exception propagate to the owning active bundle. They still must clean up any internal resources associated with the service call from
try/finallyblocks. Because good coding style requires such cleanup to be implemented anyway it turns out that for passive bundles lazy service dynamics coast nothing.
- If the service is required and we are an active bundle we declare the current activity as crashed, log, clean up, try contingency actions.
If we are the bundle who drives the crashed activity it's our responsibility to complete it one way or another. Good design requires that we wrap a fault barrier around the business logic code to absorb crashes. If there is need of resource cleanup we do it as usual. Than we do whatever the application logic dictates: display an error dialog, send an error response, etc.
- Explicit service unregistration is used only during bundle shutdown.
All bundles should execute the following sequence in
BundleActivator.stop():
- Unexport
Bring down all exported services by calling
unregister()on the previously stored
ServiceRegistrationobjects. This is an announcement to all current clients to start dropping their references and to the OSGi framework to stop letting new clients obtain a reference to the service. Doing this in the beginning of shutdown is a courtesy move since all services will be unregistered automatically right after
BundleActivator.stop()completes.
- Deactivate
If we are an active bundle perform graceful shutdown to our threads. Release any non-heap resources we own: close sockets and files, release UI widgets etc. This has to be done in a threadsafe manner because legitimate client calls may still be in progress. The goal of this step is to transform the content of the bundle into a fail fast ball of objects. The function of this ball from here on will be to crash cleanly any business control flow that has been trapped inside our service at the moment of shutdown. Because deactivation is performed concurrently from the management control flow it is obvious some synchronization should be in place. This shows that every OSGi service implementation must be prepared for concurrent access at least in terms of graceful shutdown. Because most OSGi services are concurrent anyway so the coast of an additional
close()method is not too high. If the service is stateless deactivation could be free - trapped business control flows will crash as they try to hop into another bundle through a discontinued service import.
- Detach
This is done by explicitly nulling any fields contained in your
BundleActivator. At this point we detach the fail-fast ball we created in the previous step from our bundle. As soon as all business control flows trapped inside crash the ball will be garbage collected. After stop() completes the bundle should consume memory only for it's
BundleActivatorinstance and it's
ClassLoader. These are both managed directly by the OSGi runtime. The bundle will mushroom again into a runtime structure if some management control flow reaches through the OSGi core to call once more
BundleActivator.start()(e.g. a user clicks on "start bundle" in his JMX console).
This sequence is carefully arranged to not expose any part of the bundle to external calls before everything is fully setup. Upon completion of this sequence the bundle is started and hooked to the service registry. It's internal structure is spared from garbage collection because it is referenced from within the activator and the activator in turn is referenced from the OSGi service layer. Now the management control flow can leave the activator and go about it's business. If the bundle has started some threads to execute the business flow they can continue doing their work after the activator is no longer being executed.
RuntimeExceptionis thrown. This exception is typically called
ServiceUnavailableException(or SUE).
The goal of the shutdown policy is to maintain the bundle services in a consistent "work correctly or crash cleanly" state right up to the moment when it is garbage collected. In the start up sequence we do not expose objects to control flow before they become consistent and in the shutdown sequence we maintain them consistent until garbage collected. This "be consistent at all times" policy can be observed in non-OSGi concurrent Java as well. E.g. the ususal way to shutdown a thread is to touch a boolean flag (call
unregister), destroy all resources the thread uses (discontinue imports, close sockets etc.) and leave the thread expire from natural causes.
The beauty of the Lazy doctrine is that we manage to almost completely fold the hard problem of service dynamics into the easier problem of dealing with exceptions properly . We achieve this by directing crashes caused by inconsistent services into the error handling pathways built into every non-dynamic Java application. Turns out dynamics are not so horrible, they mostly force us to have a good error handling and cleanup design. I.e. service dynamics are all about crashing safely.
Fighting code distortion
There is a substantial wrinkle in our smooth plan - the service consuming code is still hard to write and quite disruptive to the rest of our application code. Let's go back and examine how Concurrency and Direct Service References conspire to create a maintenance nightmare. In one sentence:
At any time (concurrency), we can be required to flush out all references to the service object (direct references).
This means we must at all times keep under strict control each and every reference - something akin to the resource cleanup problems faced by C++ programmers. As with any object in the JVM a service object can be referred in two ways:
- Heap
These references are stored in object fields. They must be explicitly managed by our code. The management control flow touches the heap references from the ServiceListener we use to track service availability. Therefore code in the listener must be synchronized with all other code that touches the heap reference.
- Stack
These references reside on the stacks of active threads and are automatically cleaned when their call frame expires. The management control flow can't touch the stack references so no synchronization is required
To keep things manageable developers shift the balance sharply in favor of the self-cleaning stack references. Usually the entire bundle contains a single heap reference per service. From there the service can be propagated as a method parameter to it's usage sites. When this is not possible long paths of
get() methods are built to pull the service to the respective usage site. Soon developers become overwhelmed and apply the Singleton pattern to this service reference. This replaces one flavor of code distortion for another, arguably worse one.
An alternative way to achieve correct lazy import behavior is to encapsulate the service reference in a holder object. All required synchronization, event handling, and cleanup will be encapsulated in the holder. Then we can propagate this holder to all service usage sites in place of the actual service. Here is a simple lazy holder:
import static org.osgi.framework.Constants.OBJECTCLASS; import static org.osgi.framework.ServiceEvent.UNREGISTERING; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; public class ServiceHolder<T> implements ServiceListener { private final BundleContext bc; private final Class<T> type; private ServiceReference ref; private T service; /** * Called from BundleActivator.start(). * * (management control flow) */ public ServiceHolder(Class<T> type, BundleContext bc) { this.type = type; this.bc = bc; /* Track events for services of type T */ try { bc.addServiceListener(this, "(" + OBJECTCLASS + "=" + type.getName() + ")"); } catch (InvalidSyntaxException e) { throw new RuntimeException("Unexpected: filter is correct", e); } } /** * Called by the app when it needs the service. * * (application control flow) */ @SuppressWarnings("unchecked") public synchronized T get() { /* Lazy-bind to a suitable service */ if (service == null) { ref = bc.getServiceReference(type.getName()); /* Can't find a service - fail fast */ if (ref == null) { throw new RuntimeException("Service " + type + " unavailable."); } service = (T) bc.getService(ref); } return service; } /** * Called by the container when services come and go. * * (management control flow) */ public synchronized void serviceChanged(ServiceEvent e) { /* Is a service going away? */ if (UNREGISTERING == e.getType()) { /* Is this the service we hold? */ if (ref == e.getServiceReference()) { /* Release the service */ service = null; ref = null; } } } }
There! Now this looks like a real programmer article. Let's imagine we want to import the following mission critical service.
interface Hello { void greet(String who); } In BundleActivator.start() we must setup a ServiceHolder. public Activator implements BundleActivator { private ServiceHolder<Hello> helloHolder; ... public void start(BundleContext bc) { helloHolder = new ServiceHolder<Hello>(Hello.class, bc); ... } ...
The service consuming code would look something like:
... private final ServiceHolder<Hello> holder; ... void salutations() { /* Pop the service into a self-cleaning reference */ Hello hello = holder.get(); hello.greet("InfoQ"); hello.greet("OSGi"); } ...
Or if we shorten a bit:
... void salutations() { holder.get().greet("InfoQ"); holder.get().greet("OSGi"); } ...
This extra level of indirection is still far from optimal. Having our code packed with these holders causes loss of clarity, hinders testing and becomes a refactoring nightmare if we decide to migrate a local class to another bundle and consume it as a service. But it's the only way to be correct. Or is it?
If we squint at the code it becomes obvious we are moving towards the classical Proxy design pattern. Let's complete the proxy by wrapping our holder in the original service interface:
class HelloProxy implements Hello { private final ServiceHolder<Hello> holder; public HelloProxy(ServiceHolder<Hello> holder) { this.holder = holder; } public void greet(String who) { holder.get().hello(who); } }
Now we can create a single
HelloProxy in the activator and use it everywhere through
Hello-typed references as if it was the original service. Except now we can store the "service" in final fields and pass it to constructors. Combine this with the rest of the Lazy doctrine and we get a clean separation between the dynamics boilerplate, locked inside proxies an the activator, and the business logic code. Also the business code now looks like a regular non-dynamic Java program:
... private final Hello hello; ... void salutations() { hello.greet("InfoQ"); hello.greet("OSGi"); } ...
At this point we must make an important observation the eager and lazy models are not mutually exclusive.. As the code above illustrates in the core of every lazy bundle runs tracking code similar to the code that would support an eager bundle. A lazy bundle wraps this tracking core with a stable layer of proxies that shield the application code (and it's control flow) from all the movement happening below. Still if we need to we can plug code into the tracking layer and have a hybrid eager(pre-proxy)/lazy(post-proxy) bundle. For example the eager part can do decorations or even complete transformations to the services before they are wrapped in proxies and passed to the lazy part. Turns out that (excluding service flickering) the lazy model is really a natural evolution of the eager model to a higher level of abstraction.
Service Layer Runtimes
All would be great except for the fact that coding proxies by hand can get very tedious. Fortunately such proxy generation is quite easy to code as a library or even better as an active Service Layer Runtime bundle.
Since OSGi 4.1 it became possible to implement a special type of bundle that can drive the service interactions of other bundles. Let's call these frameworks Service Layer Runtimes (or SLR) because they hide the raw OSGi service layer from the application developers. Although SLRs come in all shapes and sizes they inevitably include a dependency injection component. This is because DI is a natural match for services, which typically enter the bundle from a single point like the activator and need to be propagated all over the bundle internals. Using tons of singletons instead creates problems and organizing "fire brigades" of getters is tedious. Delegating this task to DI is a huge relief.
Below are very brief reviews of the most popular current day SLRs. Lost of features are omitted since a comprehensive side-by-side comparison would require at least two more articles.
Peaberry
Peaberry is a pure Java extension to the ever more popular Guice framework. Discovering an effective way to use Peaberry was the main inspiration for this article. The framework feels largely like using pure Guice. All we need to do to get a service proxy is to bind the interface of the service to a special Peaberry provider:
bind(Hello.class).toProvider(Peaberry.service(Hello.class).single());
The proxies are than generated on the fly using ASM. From there normal Guice takes over and injects them as it would any other object. Code written in this way looks a lot like plain old Java SE, with dynamic proxies practically indistinguishable from local objects. Peaberry supports eager/lazy hybrids by allowing us to hook code to the tracking layer and if required do decorations to the service objects before they are wrapped in proxies. A unique feature of Peaberry is it's ability to seamlessly mix services from different sources - for example objects from the Eclipse registry can be mixed transparently with OSGi services.
Alas Peaberry is not yet perfect. One area where it lags behind the other SLRs is dynamic configuration. The user has to import the ConfigurationAdmin service to mutate configurations or to export a ManagedService to receive dynamic configuration. Another drawback of Peaberry is that it still requires the user to code a minimalistic
BundleActivator where the Guice
Injector gets setup. The good new is that Peaberry is currently under active development and these gaps are sure to be plugged soon.
Spring Dynamic Modules
Dynamics are supported through transparently generated service proxies. Spring DM relies on the Spring component model to do Dependency Injection. Components have dynamic (de)activation lifecycles aligned with the Eager model. While Peaberry inclines the coder to use Lazy by default and go Eager if required Spring DM seems to default to a 50/50 Eager/Lazy style. Although it seems to provide more features than Peaberry, Spring DM feels much more heavyweight to use.
Spring DM will soon continue it's life as an OSGi standard called the Blueprint Service. Much more than a simple change of names the Blueprint Service is carefully evolved from Spring DM to integrate better with the OSGi runtime.
Declarative Services
This is the only SLR standardized by OSGi so it deserves a bit more attention. OSGi DS tries to solve the dynamics problem with traditional Java means. It is high level in that it has a component model with setter dependency injection. It is low level in that it exposes the components to more of the service dynamic (no proxies). A dependency can either be defined as "dynamic" or "static".
For dynamic dependencies a component must provide a pair of
bind()/unbind() callbacks. OSGi DS will do the tracking and call the respective callback. The component than takes over to performs all the swapping and synchronization on it's own. In this case OSGi DS saves the developer only the tracking code.
By default a dependency is "static" and the component only needs to provide a
bind()/set() method. Now the component does not have to worry about synchronization or release of the service object. Instead OSGi DS will re-create the entire component whenever the dependency changes. Alas this is the only way to make sure the old service object is released. Because it is so expensive the use of static dependencies is discouraged.
OSGi DS also follows the Eager service export policy: if a component is exposed as a service and some of it's required dependencies go away the component is unregistered. The consequence is also the cascading deactivation of dependent components. As we saw this lifecycle scheme can not prevent exceptions from failing transitive dependencies. The user code must still have proper error handling in place.
OSGi DS also supports the non Dependency Injection "lookup" style where your components receive a ComponentContext from which to pull out services.
OSGi DS will get a nice facelift in the soon to be released OSGi 4.2 specification. The improvements concentrate on allowing OSGi DS code to be pure POJO. It will become possible to truly never see any element of the OSGi service API unless we want to.
iPojo
Architecturally iPojo seems to be "OSGi DS but done right". Here as well we deploy components as bundles with each component having it's dependencies managed by a central SLR bundle. As with OSGi DS a component can be exposed as a service to the OSGi registry. From here however iPojo starts to significantly depart from OSGi DS. Most importantly it is highly modular allowing a component to specify a different pluggable handler for each type of dependency. Unlike OSGi DS, iPojo does a thorough job of protecting the user code from service dynamics. Rather than within proxies services are stored in a common
ThreadLocal cache. The cache is populated when a thread enters the component and flushed when it leaves. All of this is achieved through bytecode weaving magic. This makes iPojo usable on resource constrained devices.
Acknowledgments
The author would like to thank Roman Roelofsen for providing input and critical reviews throughout the long evolution of this article.
About the Author
Todor Boev has been involved with OSGi technology for the past eight years as an employee at ProSyst. During that time he had the opportunity to apply OSGi in a variety of environments ranging from embedded devices to scalable backend servers. He is passionate about developing OSGi as a user friendly, general purpose programming environment for the JVM. Currently he explores the integration between cutting edge Java and OSGi both professionally and as a contributor to the Peaberry project. He also maintains use the OSGi ServiceTracker instead of the ServiceHolder?
by
Raymond Feng
One comment on the ServiceHolder: OSGi already provides the ServiceTracker API that allows us to get instances of services by the filter. Why do you introduce the ServiceHolder?
Re: Why not use the OSGi ServiceTracker instead of the ServiceHolder?
by
Todor Boev
The ServiceTracker picks up services as soon as they appear and holds on to them all the time. The ServiceHolder picks up services lazily and switches between stale and working services on demand. This matches the lazy model better. You can make it even nicer by adding code to release the cached service object if it not been used for a while. At this point the ServiceHolder will become substantially different from ServiceTracker. The holder uses a lazy service caching policy while the tracker uses an eager one. The holder picks up services in the application control flow while the tracker does so in the management control flow (e.g. in the listener).
BTW Peaberry and iPojo already do this kind of lazy service caching so I recommend you use one of them rather than try to develop my toy code further :) | https://www.infoq.com/articles/service-dynamics-todor-boev/ | CC-MAIN-2016-44 | refinedweb | 5,569 | 54.63 |
In this tutorial you'll learn how to create draggable windows using Flash and AS3. I'll cover the basics of drag&drop, window bounds, adding content, and how to minimize the window.
Final Result Preview
Let's take a look at the final result we will be working towards:
Step 1: Create a New File
Okey, let's gooo! Create a new document by hitting CTRL+N and selecting Flash File (ActionScript 3). Set the stage size to 600x400 px and the background color to #EEE. In the Properties window, set the class to windows and save your file as windows.fla.
Step 2: Design the windowArea
Select the Rectangle Tool (R) and draw a rectangle with 280x90 px. Select your shape, go to the Color palette (Window > Color) and create a gradient from #FFF to #CCC.
Hit F for the Gradient Tool, select your gradient, rotate it 90 degrees (by holding the Shift button while you rotate) and shorten it so it adapts the rectangle.
Select all the shape, hit F8 to Convert to Symbol, name it windowArea and set the registration point to the top left.
Select the symbol and in the Properties window set the instance name to windowArea.
For the border, use the Glow filter, with a 2px blur, strength 500%, color #666666. I used a glow because if you use a stroke, when you resize the Window the stroke will also resize.
Step 3: Design the windowBar Button
Select the Rectangle Tool (R) again and draw a rectangle with 280x22 px and a 1px stroke with the color #666. Create another rectangle on top of this, but this time in the Rectangle Options set the Rectangle corner radius to 5.
Now, eliminate the necessary corners like on the image below.
Then, paint your shape, select it, go to the Color palette (Window > Color) and create a gradient from #999 to #333. Rotate the gradient 90 degrees, like we did on the previous step.
Select the all shape, hit F8. Name: windowBar; Type: Button; Registration: top left.
Select the symbol and in the Properties window set the instance name to windowBar.
Double click the shape, create keyframes for the Over and Down states. Now change the colors for each one.
I've chosen:
- Over: gradient from #FF9900 to #CC6633
- Down: gradient from #9933CC to #660099
Step 4: Create the Minimize Button
Create a round rectangle with 14x11 px, 5px radius, and change it so it looks something like below.
The minus sign you do by creating a rectangle 5x2 px with the color #999. Set the instance name to minimizeBtn.
I used the same colors from the windowBar, but the UP State with a 40% alpha for the gradient.
Step 5: Create the Window
Arrange all shapes in form of a window, hit F8 and create a MovieClip with the name window and registration: top left.
In the Library, right click the Window and go to Properties. Set the class to window. This way the window will be assigned to the class we'll be creating later.
Select the symbol and in the Properties window set the instance name to window. In the Filters, click Add filter (the circled button in the image below), and add a Drop Shadow with the color #333 like below:
Double-click the symbol to edit it. Select all (CTRL+A), Right Click > Distribute to layers.
In a new layer, write the text for the window's title with Arial, 11pt, color #CCC, letter-spacing: 1. Set it to Dynamic Text and name it windowTitle.
Step 6: Create the ActionScript File
Now that the design is complete, let's start coding our scene. The first thing we'll do is create our ActionScript file.
Hit Ctrl+N or go to File > New and select ActionScript File. Save it in the same directory and with the same name (windows.as) of your FLA file.
Now let's create our package and import the necessary classes:
package { import flash.display.MovieClip; import flash.events.Event; import flash.events.MouseEvent; import flash.events.KeyboardEvent; import flash.events.ContextMenuEvent; import flash.geom.Rectangle; import flash.filters.DropShadowFilter; import flash.text.TextFormat; import fl.transitions.Tween; import fl.transitions.easing.*; import fl.transitions.TweenEvent; public class window extends MovieClip { } }
Step 7: Add Event Listeners
Now you need to assign functions to our buttons. You'll need a function to when we start to drag the windowBar, another to stop the drag, one to bring the window to top when you click it, and another to minimize it.
Add these Event Listeners to the
public function Window() in our code:
public class window extends MovieClip { // variables public var title:String; public function Window() { // set windowTitle title = windowTitle.text; windowTitle.mouseEnabled = false; // windows functions this.addEventListener(MouseEvent.MOUSE_UP, onWindowClick); this.windowBar.addEventListener(MouseEvent.MOUSE_DOWN, onWindowStartDrag); this.windowBar.addEventListener(MouseEvent.MOUSE_UP, onWindowStopDrag); this.minimizeBtn.addEventListener(MouseEvent.MOUSE_UP, minimizeWindow); } }
The public var
title is used for the window's title. We'll be using this later.
Since the
windowTitle is a dynamic text we disable its mouse functions so that they won't affect the dragging area of the
windowBar.
Step 8: onWindowStartDrag Function
This is where we start having fun! Copy the following code after the
public function Window():
/* START DRAG **********************************************************/ private function onWindowStartDrag(e:MouseEvent):void { var windowWidth = this.width; var windowHeight = this.height; var windowBarWidth = e.target.width; var windowBarHeight = e.target.height; var boundsRect:Rectangle; // window's draggable boundaries if (windowArea.visible) { boundsRect = new Rectangle(0, 0, stage.stageWidth-windowWidth, stage.stageHeight-windowHeight); } else { boundsRect = new Rectangle(0, 0, stage.stageWidth-windowBarWidth, stage.stageHeight-windowBarHeight); } //trace(boundsRect); this.startDrag(false, boundsRect); // bring window to front stage.addChild(this); }
The first thing we do here is create variables to the widths and heights of the Window and the
windowBar.
Next, the window's boundaries. We'll create two boundaries: one when the window is normal (if windowArea is visible) and another when it is minimized. You do this by creating a rectangle with the size of the stage. The rectangle supports four attributes (x, y, width, height). It'll start in the corner of the screen (x: 0; y: 0) and extend to the other corner of the screen. Because the bounds are related to the registration point of the window, we'll need to subtract the window width and height (or the windowBar's in case the window is minimized).
After the bounds have been set, we'll set the window to drag. We'll drag this, the Window class. In other words, the whole window.
this.startDrag(false, boundsRect);
The
startDrag function supports two attributes: lockCenter and bounds. If you don't want any bounds just write this:
this.startDrag(false);
If we have several windows we'll need to bring the current window to the top of the display. We do this with the addChild by adding it again to stage:
// bring window to front stage.addChild(this);
Step 9: onWindowStopDrag Function
This one is really simple. We'll use the
stopDrag function here. Just copy the following to your code after the previous
onWindowStartDrag function:
/* STOP DRAG **********************************************************/ private function onWindowStopDrag(e:MouseEvent):void { this.stopDrag(); }
Step 10: Bring Window to Front
Again, really simple. When we click the window we'll bring it to front using
addChild.
/* WINDOW CLICK **********************************************************/ private function onWindowClick(e:MouseEvent):void { // bring window to front stage.addChild(this); }
Step 11: minimizeWindow Function
To minimize/show the window, we'll toggle the visibility of the
windowArea like this:
/* MINIMIZE WINDOW **********************************************************/ private function minimizeWindow(e:MouseEvent):void { windowArea.visible = !windowArea.visible; }
You can improve this by fading out the window and hiding it, and vice-versa:
/* MINIMIZE WINDOW **********************************************************/ private function minimizeWindow(e:MouseEvent):void { var fade:Tween; if (windowArea; } fade.start(); function fadeFinish(e:TweenEvent):void { windowArea.visible = !windowArea.visible; } }
The Tween supports the following values:
Tween(object, "property", EasingType, begin, end, duration, useSeconds);
For more extensive reading, use the LiveDocs.
In our case, what we're doing is, if the
windowArea is visible (meaning: not minimized), it will fade out the
windowArea and when the tween finishes (
TweenEvent.MOTION_FINISH), it will hide the
windowArea. Vice versa if it's minimized.
Step 12: Set the Title
We'll use the variable
t to change the
windowTitle. The other two lines are just to resolve a letter spacing issue. If you don't write them Flash will reset the letter spacing to zero.
/* SET WINDOW'S TITLE **********************************************************/ public function Title(t:String):void { var fmt:TextFormat = windowTitle.getTextFormat(); windowTitle.text = t; windowTitle.setTextFormat(fmt); // letter spacing issue title = t; }
This function will be used later like this:
YourWindowName.Title("Name of your window");
Step 13: Set the Size
This function will receive two attributes: the Width and Height of the window. If neither is filled, it will be set to the default size (280x112 px)
What we do here is change the width of the
windowBar, the
windowArea and the
windowTitle. For the height we just change the
windowArea's, leaving the height of the Window to its default size, just like a normal window.
When resizing we'll have to reset the position of the Minimize Button. Which is equal to the window's width minus the button's width and 6px.
/* SET WINDOW'S SIZE **********************************************************/ public function Size(Width:int = 280, Height:int = 112):void { // change width windowBar.width = Width; windowArea.width = Width; windowTitle.width = Width - 45; // change content height windowArea.height = Height; // reset minimizeBtn scale/position minimizeBtn.x = Width - minimizeBtn.width - 6; }
This function will be used later like this:
YourWindowName.Size(350,200);
Step 14: Give it a Nice Shadow
Remember when we placed a Drop Shadow under the Window? Well, if you place the window by code you'll need to add the drop shadow by code as well.
All of the above attributes can be set by code. Copy the function and change the values according to your own taste:
/* SET FILTER: DROP SHADOW **********************************************************/ public function DropShadow(color:String = "333333"):void { var dropShadow:DropShadowFilter = new DropShadowFilter(); dropShadow.blurX = 5; dropShadow.blurY = 5; dropShadow.strength = 1; dropShadow.quality = 1; // 1- low; 2- medium; 3- high (max: 15) dropShadow.angle = 45; dropShadow.distance = 1; dropShadow.alpha = 1; dropShadow.knockout = false; dropShadow.inner = false; dropShadow.hideObject = false; dropShadow.color = int("0x" + color); this.filters = new Array(dropShadow); // add filter to the window }
This function will receive a String with the color's hexadecimal code. If this is not filled, the default color value will be #333333.
The
quality can go from 1 to 15, being 1 2 3 - low, medium and high. We used low, here.
The
color must be converted from a String to an int.
After defining the attributes we must add the filter to the window like in the last line. This will create an Array of filters. Which means you could add other filters to the Window as well.
this.filters = new Array(dropShadow);
This function will be used later like this:
YourWindowName.DropShadow("FF0000"); // adds a red shadow
Step 15: Adding a Window by Code
Now change to your Flash file, create a new layer, name it as3 and hit F9 for the ActionScript (or go to Window > Actions).
Adding a Window is very simple. All you need to do is create a variable (let's call it
myWindow), assigning it to the
Window class and the add the Window to stage:
var myWindow:window = new window; addChild(myWindow);
This will produce a Window with its default values.
Step 16: Changing the Values
You can change several attributes of the Window:
- Title
- Shadow
- Size
- X and Y position
- Content
Again, the first thing to do is to create the variable assigned by the Window class:
var myWindow:window = new window;
Then you can start changing the attributes:
Changing the Title:
myWindow.Title("Cabo Verde");
Changing the Shadow:
myWindow.DropShadow("66CC00"); // adds a nice lime shadow
Changing the Size:
myWindow.Size(350,200);
Changing the Position:
myWindow.x = 20; myWindow.y = 20;
Adding the window to stage:
addChild(myWindow);
The all code will be like this:
var myWindow:window = new window; myWindow.Title("Cabo Verde"); myWindow.DropShadow("66CC00"); myWindow.Size(350,200); myWindow.x = 20; myWindow.y = 20; addChild(myWindow);
Step 17: Using Additional Windows
Here's another example with two windows added by code and a default one in the stage:
var janela:window = new window; var janela02:window = new window; janela.Title("Cabo Verde"); janela.DropShadow("66CC00"); janela.Size(350,200); janela.x = 20; janela.y = 20; janela02.Title("Ninjas!"); janela02.DropShadow("FF0000"); janela02.Size(250,200); janela02.x = 40; janela02.y = 150; addChild(janela); addChild(janela02);
If you need to know the window's title, you can use this:
trace(janela.title);
Milestone
Well done for following so far! You should now have achieved a result similar to what we looked at in the beginning:
Step 18: Different Content in the Windows
If you notice by now, you can change all the window's attributes but the content remains the same. So let's create the content.
Open the Window's MovieClip, create a new layer for the content and go to Insert > New Symbol (CTRL+F8). Choose MovieClip, name it content and hit OK. Now place it at X:0, Y:22.
Select the new content symbol you just created, and set its instance name to
CONTENT.
Double-click the content, name the existing layer content and create another one named as3. In the latter, hit F9 and write:
stop();
This will be our default content. Meaning, nothing!
Now create another keyframe and place an image for example. Bear in mind the size of the window you'll be using. Add another keyframe and write some text in it. Now we have 3 keyframes: 1. no content, 2. image, 3. text.
As for the code, add this to your class file:
/* CHANGE CONTENT **********************************************************/ public function Content(c:int):void { CONTENT.gotoAndStop(c); }
Really simple. We'll just say which keyframe we'll want to go to.
You'll also need to change the
minimizeWindow function to this:
/* MINIMIZE WINDOW **********************************************************/ private function minimizeWindow(e:MouseEvent):void { var fade:Tween; if (windowArea.visible) { CONTENT.visible = !CONTENT; CONTENT.visible = !CONTENT.visible; } fade.start(); function fadeFinish(e:TweenEvent):void { windowArea.visible = !windowArea.visible; } }
Step 19: Changing the Content in the Code
In the previous example, add this to the code:
janela.Content(2); // goes to the image keyframe
Here is the complete code:
var janela:window = new window; var janela02:window = new window; janela.Title("Cabo Verde"); janela.DropShadow("66CC00"); janela.Size(350,240); janela.Content(2); // goes to the image keyframe janela.x = 20; janela.y = 20; janela02.Title("Ninjas!"); janela02.DropShadow("FF0000"); janela02.Size(250,200); janela02.Content(3); // goes to the text keyframe janela02.x = 40; janela02.y = 150; addChild(janela); addChild(janela02);
Conclusion
So, there's a simple way to create a draggable window (much like we see on Windows). If you want to go further, you can change the content MovieClip, adding text, buttons, images, etc. You could add scrollbars, call content through XML, or whatever you can think of. The possibilities are endless!
Here's another awesome example:
This is eXOTRik, and I hope you found this useful. It's my first tutorial, hope to bring you some more ninja tricks. Ayaaaa!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
Envato Market has a range of items for sale to help get you started. | http://code.tutsplus.com/tutorials/enhance-your-flash-layouts-with-draggable-windows--active-4868 | CC-MAIN-2016-22 | refinedweb | 2,598 | 59.4 |
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 1997,2007 Oracle. All rights reserved. * * $Id: os_sleep.c,v 12.14 2007/05/17 15:15:46 bostic Exp $ */ #include "db_config.h" #define __INCLUDE_SELECT_H 1 #include "db_int.h" /* * __os_sleep -- * Yield the processor for a period of time. * * PUBLIC: void __os_sleep __P((DB_ENV *, u_long, u_long)); */ void __os_sleep(dbenv, secs, usecs) DB_ENV *dbenv; u_long secs, usecs; /* Seconds and microseconds. */ { struct timeval t; int ret; /* Don't require that the values be normalized. */ for (; usecs >= US_PER_SEC; usecs -= US_PER_SEC) ++secs; if (DB_GLOBAL(j_sleep) != NULL) { (void)DB_GLOBAL(j_sleep)(secs, usecs); return; } /* * It's important we yield the processor here so other processes or * threads can run. * * XXX * VxWorks doesn't yield the processor on select. This isn't really * an infinite loop, even though __os_yield can call __os_sleep, and * we'll fix this when the tree isn't frozen. [#15037] */ #ifdef HAVE_VXWORKS __os_yield(dbenv); #endif /* * Sheer raving paranoia -- don't select for 0 time, in case some * implementation doesn't yield the processor in that case. */ t.tv_sec = (long)secs; if (secs == 0 && usecs == 0) t.tv_usec = 1; else t.tv_usec = (long)usecs; /* * We don't catch interrupts and restart the system call here, unlike * other Berkeley DB system calls. This may be a user attempting to * interrupt a sleeping DB utility (for example, db_checkpoint), and * we want the utility to see the signal and quit. This assumes it's * always OK for DB to sleep for less time than originally scheduled. */ if (select(0, NULL, NULL, NULL, &t) == -1) { ret = __os_get_syserr(); if (__os_posix_err(ret) != EINTR) __db_syserr(dbenv, ret, "select"); } } | http://opensource.apple.com/source/BerkeleyDB/BerkeleyDB-18/db/os/os_sleep.c | CC-MAIN-2014-42 | refinedweb | 265 | 68.26 |
def factorial(x): f=1 if x==0: return 0 else: while x!=0: f=x*factorial(x-1) return f
What is happening wrong here? Can't figure out! Any type of help will be highly appreciated
def factorial(x): f=1 if x==0: return 0 else: while x!=0: f=x*factorial(x-1) return f
What is happening wrong here? Can't figure out! Any type of help will be highly appreciated
Your code causes an infinite loop because x will never become 0. Your code keeps running the while loop because x != 0 all the time. If it was, your code returns 0.
This is the code I used:
def factorial(x): result = 1 for integer in range(1,x+1): result *= integer return result
Plus, you got some recursion going on in the while loop. I suggest either just doing a loop or a recursion but not both (due to optimisation purposes). Even if the recursion finishes, your while loop still runs because x will never become 0 if x != 0 as an input.
I have
factorial calling itself, then return the factorial of the number,
factorial (x - 1), while multiplying the returning the integer (
x) with it.
@casz146 and @datfatcat explained what's going on in your code. I think if you took out the
f=1 and put the 1 in your if statement, you can go from there and simplify your code to where I got mine.
This is what I had that passed.
def factorial(x): if x == 1: return 1 else: return x * factorial(x - 1)
Thanks man!
I think one more condition on if should have been added perhaps? That is when x==0?
Thanks for helping out! | https://discuss.codecademy.com/t/factorial-infinite-loop-starting/54960 | CC-MAIN-2018-26 | refinedweb | 290 | 76.22 |
Quick links
Comment is non-executable line in source code used to describe a piece of code or program. Comments provides inline documentation of source code and enhances readability of the code. It describes what a piece of code does.
Comments are for readers not for compilers. They make source code more developer friendly.
The compiler has nothing to do with comments, it is non-executable piece of code. Therefore, during the compilation process, pre-processor removes all comments from the source code.
C programming supports two types of commenting style.
- Single line comments
- Multi-line comments
Single line comments
Single line comments begin with
// double forward slash character. Characters following
// is treated as comment and is not executed by the compiler. Single line comments are best suited when you want to add short detail about a complex code that can be described in a line.
Example program to demonstrate single line comments
#include <stdio.h> // Include header file // Starting point of program int main() { // Print hello message printf("Hello, Codeforwin!"); return 0; }
Multi line comments
Single line comment provide support to add short description about the code in one line. However, most often it is required to add long description about working of the code spanning across multiple lines. Definitely in such situation you can add multiple single line comments. But it is recommended to use multi-line comments.
Multi-line comments are used to add a detailed description about the code. It begins with
/* character and ends with
*/. Characters between
/*
*/ are treated as comments.
Multi-line comments can span upto multiple lines. In addition, you can use multi-line comments for both single as well as multiple line commenting.
Example program to demonstrate multi line comments
/** * @author Pankaj Prakash * @description C program to add two numbers. * Program reads two numbers from user and * displays the sum of two numbers. */ #include <stdio.h> int main() { /* Variable declarations */ int num1, num2, sum; /* Reads two number from user */ printf("Enter two number: "); scanf("%d%d", &num1, &num2); /* Calculate the sum */ sum = num1 + num2; /* Finally display sum to user */ printf("Sum = %d", sum); return 0; }
Advantages of commenting a program
Every developer must have a habit of commenting source code. It is as important as cleaning your bathroom. I already mentioned a well commented program is easy to read and maintain.
Let us consider the following piece of code.
void strcpy(char *src, char * dest) { while(*(src++) = *(dest++)); }
At this point with little knowledge of programming. Do you have any idea what the above piece of code will do? Now consider the same code again.
/** * Function to copy one string to another. * @src Pointer to source string * @dest Pointer to destination string */ void strcpy(char * src, char * dest) { /* * Copy one by one characters from src to dest string. * The loop terminates after assigning NULL * character to src string. */ while(*(src++) = *(dest++)); }
The above commented program gives you a basic idea about the code. Which is where comments are useful. The second program is more cleaner and readable for developers.
Let me add my story to the picture. In my early days of programming. I was a mad over developing small applications. I used to spend all my time on computers. Then, in my fourth semester of graduation I developed a Remote Administration Tool (in C#). Which was pretty cool tool, but lacks comments. After one year when I looked at the code, I got puzzled where to start and where to end due insufficiency of comments. For a moment I thought, did I developed this?
Being a programmer develop a good habit to comment your code. So that not only others but you can also understand your code after ages.
<pre><code> ----Your Source Code---- </code></pre> | http://codeforwin.org/2017/08/comments-in-c-programming.html | CC-MAIN-2017-47 | refinedweb | 625 | 67.15 |
I have a model with a property QtyIn which is an Int32. It's bound to an Entry in Xamarin Forms using this binding in XAML:
<Entry Text="{Binding Path=Source.QtyIn, Mode=TwoWay, Converter={StaticResource intToStringConverter}}" />
Without using my own IValueConverter, pressing the minus key on the keyboard simply does nothing (the binder has trouble converting '-' to an Int32). I get this error in my stdout:
05-03 15:19:27.923 I/mono-stdout(19384): Binding: - can not be converted to type 'System.Int32'
This is the code in my IValueConverter which tries to just return the string '-' if it can't be converted to a valid Int32.
public class IntToStringConverter : IValueConverter { // from Int32 to String public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString(); } // String to Int public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { int parsedInt = 0; if (int.TryParse(value.ToString(), out parsedInt)) { return parsedInt; } return value; } }
The problem is that Xamarin Forms is missing the UpdateSourceTrigger property on the Binding, so I can't set this to LostFocus. Right now it's try to convert the Entry text to an integer character-for-character which obviously doesn't work because '-' cannot be converted to a valid integer.
Does anyone know how to bind an Int32 to an Entry Text which allows negative numbers?
Thanks.
I had this code in my property binding and it wasn't checking for the '-' character. Just the '.' in a decimal. Added the check for '-' and now it's working.
public static bool IsNumberString(string numberString) { // Null check if (String.IsNullOrEmpty(numberString)) return false; char[] ca = numberString.ToString().ToCharArray(); for (int i = 0; i < ca.Length; i++) { if (!char.IsNumber(ca[i])) if (ca[i] != '.' && ca[i] != '-') // Decimal or negative return false; } return true; }
Answers
@JonHunt
When parsing a negative number you need to use the other overload with the correct NumberStyles:
TryParse( string s, NumberStyles style, IFormatProvider provider, out int result)
For details please see:
Hope this helps,
Tim
I have done that using:
and it still removes the '-' character after I press '-'. There is no way to type -123 because the - can never be converted to an integer. I get the error:
05-03 15:19:27.923 I/mono-stdout(19384): Binding: - can not be converted to type 'System.Int32'
@JonHunt
Hi Jon,
That is strange. I use similar code within a framework under development, and it functions fine.
Though that code is not in a ValueConvertor.
What was the outcome when you used the CultureInfo as the format provider?
Tim
I haven't tried using the CultureInfo but I'll see what that does. Basically it needs to convert only when you leave the focus but Xamarin Forms doesn't have that feature that WPF has
I had this code in my property binding and it wasn't checking for the '-' character. Just the '.' in a decimal. Added the check for '-' and now it's working.
Turns out that this issue was because the property that Entry was bound to had some Key checking and was undo'ing the '-' character. | https://forums.xamarin.com/discussion/comment/195518/ | CC-MAIN-2019-26 | refinedweb | 522 | 56.55 |
PEP 280 -- Optimizing access to globals
Deferral
While this PEP is a nice idea, no-one has yet emerged to do the work of hashing out the differences between this PEP, PEP 266 and PEP 267. Hence, it is being deferred.
Abstract
This PEP describes yet another approach to optimizing access to module globals, providing an alternative to PEP 266 (Optimizing Global Variable/Attribute Access by Skip Montanaro) and PEP 267 (Optimized Access to Module Namespaces by Jeremy Hylton).
The expectation is that eventually one approach will be picked and implemented; possibly multiple approaches will be prototyped first.
Description
(Note: Jason Orendorff writes: "".""" Reference:)
Let a cell be a really simple Python object, containing a pointer to a Python object and a pointer to a cell. Both pointers may be NULL. A Python implementation could be:
class cell(object): def __init__(self): self.objptr = NULL self.cellptr = NULL
The cellptr attribute is used for chaining cells together for searching built-ins; this will be explained later.
Let a celldict be a mapping from strings (the names of a module's globals) to objects (the values of those globals), implemented using a dict of cells. A Python implementation could be:
class celldict(object): def __init__(self): self.__dict = {} # dict of cells def getcell(self, key): c = self.__dict.get(key) if c is None: c = cell() self.__dict[key] = c return c def cellkeys(self): return self.__dict.keys() def __getitem__(self, key): c = self.__dict.get(key) if c is None: raise KeyError, key value = c.objptr if value is NULL: raise KeyError, key else: return value def __setitem__(self, key, value): c = self.__dict.get(key) if c is None: c = cell() self.__dict[key] = c c.objptr = value def __delitem__(self, key): c = self.__dict.get(key) if c is None or c.objptr is NULL: raise KeyError, key c.objptr = NULL def keys(self): return [k for k, c in self.__dict.iteritems() if c.objptr is not NULL] def items(self): return [k, c.objptr for k, c in self.__dict.iteritems() if c.objptr is not NULL] def values(self): preturn [c.objptr for c in self.__dict.itervalues() if c.objptr is not NULL] def clear(self): for c in self.__dict.values(): c.objptr = NULL # Etc.
It is possible that a cell exists corresponding to a given key, but the cell's objptr is NULL; let's call such a cell empty. When the celldict is used as a mapping, it is as if empty cells don't exist. However, once added, a cell is never deleted from a celldict, and it is possible to get at empty cells using the getcell() method.
The celldict implementation never uses the cellptr attribute of cells.
We change the module implementation to use a celldict for its __dict__. The module's getattr, setattr and delattr operations now map to getitem, setitem and delitem on the celldict. The type of <module>.__dict__ and globals() is probably the only backwards incompatibility.
When a module is initialized, its __builtins__ is initialized from the __builtin__ module's __dict__, which is itself a celldict. For each cell in __builtins__, the new module's __dict__ adds a cell with a NULL objptr, whose cellptr points to the corresponding cell of __builtins__. Python pseudo-code (ignoring rexec):
import __builtin__ class module(object): def __init__(self): self.__dict__ = d = celldict() d['__builtins__'] = bd = __builtin__.__dict__ for k in bd.cellkeys(): c = self.__dict__.getcell(k) c.cellptr = bd.getcell(k) def __getattr__(self, k): try: return self.__dict__[k] except KeyError: raise IndexError, k def __setattr__(self, k, v): self.__dict__[k] = v def __delattr__(self, k): del self.__dict__[k]
The compiler generates LOAD_GLOBAL_CELL <i> (and STORE_GLOBAL_CELL <i> etc.) opcodes for references to globals, where <i> is a small index with meaning only within one code object like the const index in LOAD_CONST. The code object has a new tuple, co_globals, giving the names of the globals referenced by the code indexed by <i>. No new analysis is required to be able to do this.
When a function object is created from a code object and a celldict, the function object creates an array of cell pointers by asking the celldict for cells corresponding to the names in the code object's co_globals. If the celldict doesn't already have a cell for a particular name, it creates and an empty one. This array of cell pointers is stored on the function object as func_cells. When a function object is created from a regular dict instead of a celldict, func_cells is a NULL pointer.
When the VM executes a LOAD_GLOBAL_CELL <i> instruction, it gets cell number <i> from func_cells. It then looks in the cell's PyObject pointer, and if not NULL, that's the global value. If it is NULL, it follows the cell's cell pointer to the next cell, if it is not NULL, and looks in the PyObject pointer in that cell. If that's also NULL, or if there is no second cell, NameError is raised. (It could follow the chain of cell pointers until a NULL cell pointer is found; but I have no use for this.) Similar for STORE_GLOBAL_CELL <i>, except it doesn't follow the cell pointer chain -- it always stores in the first cell.
There are fallbacks in the VM for the case where the function's globals aren't a celldict, and hence func_cells is NULL. In that case, the code object's co_globals is indexed with <i> to find the name of the corresponding global and this name is used to index the function's globals dict.
Additional Ideas
Never make func_cell a NULL pointer; instead, make up an array of empty cells, so that LOAD_GLOBAL_CELL can index func_cells without a NULL check.
Make c.cellptr equal to c when a cell is created, so that LOAD_GLOBAL_CELL can always dereference c.cellptr without a NULL check.
With these two additional ideas added, here's Python pseudo-code for LOAD_GLOBAL_CELL:
def LOAD_GLOBAL_CELL(self, i): # self is the frame c = self.func_cells[i] obj = c.objptr if obj is not NULL: return obj # Existing global return c.cellptr.objptr # Built-in or NULL
Be more aggressive: put the actual values of builtins into module dicts, not just pointers to cells containing the actual values.
There are two points to this: (1) Simplify and speed access, which is the most common operation. (2) Support faithful emulation of extreme existing corner cases.
WRT #2, the set of builtins in the scheme above is captured at the time a module dict is first created. Mutations to the set of builtin names following that don't get reflected in the module dicts. Example: consider files main.py and cheater.py:
[main.py] import cheater def f(): cheater.cheat() return pachinko() print f() [cheater.py] def cheat(): import __builtin__ __builtin__.pachinko = lambda: 666
If main.py is run under Python 2.2 (or before), 666 is printed. But under the proposal, __builtin__.pachinko doesn't exist at the time main's __dict__ is initialized. When the function object for f is created, main.__dict__ grows a pachinko cell mapping to two NULLs. When cheat() is called, __builtin__.__dict__ grows a pachinko cell too, but main.__dict__ doesn't know-- and will never know --about that. When f's return stmt references pachinko, in will still find the double-NULLs in main.__dict__'s pachinko cell, and so raise NameError.
A similar (in cause) break in compatibility can occur if a module global foo is del'ed, but a builtin foo was created prior to that but after the module dict was first created. Then the builtin foo becomes visible in the module under 2.2 and before, but remains invisible under the proposal.
Mutating builtins is extremely rare (most programs never mutate the builtins, and it's hard to imagine a plausible use for frequent mutation of the builtins -- I've never seen or heard of one), so it doesn't matter how expensive mutating the builtins becomes. OTOH, referencing globals and builtins is very common. Combining those observations suggests a more aggressive caching of builtins in module globals, speeding access at the expense of making mutations of the builtins (potentially much) more expensive to keep the caches in synch.
Much of the scheme above remains the same, and most of the rest is just a little different. A cell changes to:
class cell(object): def __init__(self, obj=NULL, builtin=0): self.objptr = obj self.builtinflag = builtin
and a celldict maps strings to this version of cells. builtinflag is true when and only when objptr contains a value obtained from the builtins; in other words, it's true when and only when a cell is acting as a cached value. When builtinflag is false, objptr is the value of a module global (possibly NULL). celldict changes to:
class celldict(object): def __init__(self, builtindict=()): self.basedict = builtindict self.__dict = d = {} for k, v in builtindict.items(): d[k] = cell(v, 1) def __getitem__(self, key): c = self.__dict.get(key) if c is None or c.objptr is NULL or c.builtinflag: raise KeyError, key return c.objptr def __setitem__(self, key, value): c = self.__dict.get(key) if c is None: c = cell() self.__dict[key] = c c.objptr = value c.builtinflag = 0 def __delitem__(self, key): c = self.__dict.get(key) if c is None or c.objptr is NULL or c.builtinflag: raise KeyError, key c.objptr = NULL # We may have unmasked a builtin. Note that because # we're checking the builtin dict for that *now*, this # still works if the builtin first came into existence # after we were constructed. Note too that del on # namespace dicts is rare, so the expensse of this check # shouldn't matter. if key in self.basedict: c.objptr = self.basedict[key] assert c.objptr is not NULL # else "in" lied c.builtinflag = 1 else: # There is no builtin with the same name. assert not c.builtinflag def keys(self): return [k for k, c in self.__dict.iteritems() if c.objptr is not NULL and not c.builtinflag] def items(self): return [k, c.objptr for k, c in self.__dict.iteritems() if c.objptr is not NULL and not c.builtinflag] def values(self): preturn [c.objptr for c in self.__dict.itervalues() if c.objptr is not NULL and not c.builtinflag] def clear(self): for c in self.__dict.values(): if not c.builtinflag: c.objptr = NULL # Etc.
The speed benefit comes from simplifying LOAD_GLOBAL_CELL, which I expect is executed more frequently than all other namespace operations combined:
def LOAD_GLOBAL_CELL(self, i): # self is the frame c = self.func_cells[i] return c.objptr # may be NULL (also true before)
That is, accessing builtins and accessing module globals are equally fast. For module globals, a NULL-pointer test+branch is saved. For builtins, an additional pointer chase is also saved.
The other part needed to make this fly is expensive, propagating mutations of builtins into the module dicts that were initialized from the builtins. This is much like, in 2.2, propagating changes in new-style base classes to their descendants: the builtins need to maintain a list of weakrefs to the modules (or module dicts) initialized from the builtin's dict. Given a mutation to the builtin dict (adding a new key, changing the value associated with an existing key, or deleting a key), traverse the list of module dicts and make corresponding mutations to them. This is straightforward; for example, if a key is deleted from builtins, execute reflect_bltin_del in each module:
def reflect_bltin_del(self, key): c = self.__dict.get(key) assert c is not None # else we were already out of synch if c.builtinflag: # Put us back in synch. c.objptr = NULL c.builtinflag = 0 # Else we're shadowing the builtin, so don't care that # the builtin went away.
Note that c.builtinflag protects from us erroneously deleting a module global of the same name. Adding a new (key, value) builtin pair is similar:
def reflect_bltin_new(self, key, value): c = self.__dict.get(key) if c is None: # Never heard of it before: cache the builtin value. self.__dict[key] = cell(value, 1) elif c.objptr is NULL: # This used to exist in the module or the builtins, # but doesn't anymore; rehabilitate it. assert not c.builtinflag c.objptr = value c.builtinflag = 1 else: # We're shadowing it already. assert not c.builtinflag
Changing the value of an existing builtin:
def reflect_bltin_change(self, key, newvalue): c = self.__dict.get(key) assert c is not None # else we were already out of synch if c.builtinflag: # Put us back in synch. c.objptr = newvalue # Else we're shadowing the builtin, so don't care that # the builtin changed.
FAQs
Q: Will it still be possible to:
a) install new builtins in the __builtin__ namespace and have them available in all already loaded modules right away ?
b) override builtins (e.g. open()) with my own copies (e.g. to increase security) in a way that makes these new copies override the previous ones in all modules ?
A: Yes, this is the whole point of this design. In the original approach, when LOAD_GLOBAL_CELL finds a NULL in the second cell, it should go back to see if the __builtins__ dict has been modified (the pseudo code doesn't have this yet). Tim's "more aggressive" alternative also takes care of this.
Q: How does the new scheme get along with the restricted execution model?
A: It is intended to support that fully.
Q: What happens when a global is deleted?
A: The module's celldict would have a cell with a NULL objptr for that key. This is true in both variations, but the "aggressive" variation goes on to see whether this unmasks a builtin of the same name, and if so copies its value (just a pointer-copy of the ultimate PyObject*) into the cell's objptr and sets the cell's builtinflag to true.
Q: What would the C code for LOAD_GLOBAL_CELL look like?
A: The first version, with the first two bullets under "Additional ideas" incorporated, could look like this:
case LOAD_GLOBAL_CELL: cell = func_cells[oparg]; x = cell->objptr; if (x == NULL) { x = cell->cellptr->objptr; if (x == NULL) { ... error recovery ... break; } } Py_INCREF(x); PUSH(x); continue;
We could even write it like this (idea courtesy of Ka-Ping Yee):
case LOAD_GLOBAL_CELL: cell = func_cells[oparg]; x = cell->cellptr->objptr; if (x != NULL) { Py_INCREF(x); PUSH(x); continue; } ... error recovery ... break;
In modern CPU architectures, this reduces the number of branches taken for built-ins, which might be a really good thing, while any decent memory cache should realize that cell->cellptr is the same as cell for regular globals and hence this should be very fast in that case too.
For the aggressive variant:
case LOAD_GLOBAL_CELL: cell = func_cells[oparg]; x = cell->objptr; if (x != NULL) { Py_INCREF(x); PUSH(x); continue; } ... error recovery ... break;
Q: What happens in the module's top-level code where there is presumably no func_cells array?
A: We could do some code analysis and create a func_cells array, or we could use LOAD_NAME which should use PyMapping_GetItem on the globals dict.
Graphics
Ka-Ping Yee supplied a drawing of the state of things after "import spam", where spam.py contains:
import eggs i = -2 max = 3 def foo(n): y = abs(i) + max return eggs.ham(y + n)
The drawing is at; a larger version is at; the source is at.
Comparison
XXX Here, a comparison of the three approaches could be added. | https://www.python.org/dev/peps/pep-0280/ | CC-MAIN-2018-30 | refinedweb | 2,616 | 67.86 |
.
bool)
char)
double)
float)
int)
long)
long long)
unsigned)
unsigned long)
unsigned long long)
ator
size) follow the STL naming convention instead of the ROOT naming convention in order to make RVec a drop-in replacement for
std::vector. convenience,:
The ROOT::RVec class has additional features in Python, which allow to adopt memory from Numpy arrays and vice versa. The purpose of these features is the copyless interfacing of Python and C++ using their most common data containers, Numpy arrays and RVec with a std::vector interface.
RVecs of fundamental types (int, float, ...) have in Python the
__array_interface__ attribute attached. This information allows Numpy to adopt the memory of RVecs without copying the content. You can find further documentation regarding the Numpy array interface here. The following code example demonstrates the memory adoption mechanism using
numpy.asarray.
Data owned by Numpy arrays with fundamental types (int, float, ...) can be adopted by RVecs. To create an RVec from a Numpy array, ROOT offers the facility ROOT.VecOps.AsRVec, which performs a similar operation to
numpy.asarray, but vice versa. A code example demonstrating the feature and the adoption of the data owned by the Numpy array is shown below.
Definition at line 1425 of file RVec.hxx.
#include <ROOT/RVec.hxx> | https://root.cern/doc/master/classROOT_1_1VecOps_1_1RVec.html | CC-MAIN-2021-49 | refinedweb | 211 | 57.98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.